first commit
Go quality gates / test (push) Waiting to run

This commit is contained in:
Mateusz Gruszczyński committed 2026-11-30 11:37:40 +01:00
commit 8c4d463f1e
96 files changed
+3319

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
*.png binary
*.svg text
*.go text eol=lf
*.sh text eol=lf
*.gohtml text eol=lf
*.css text eol=lf
*.js text eol=lf
+15
View File
@@ -0,0 +1,15 @@
name: Go quality gates
on:
push:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- run: go test -race ./...
- run: go vet ./...
- run: go build ./cmd/easydns-ui
+15
View File
@@ -0,0 +1,15 @@
name: Go quality gates
on:
push:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- run: go test -race ./...
- run: go vet ./...
- run: go build ./cmd/easydns-ui
+14
View File
@@ -0,0 +1,14 @@
/bin/
/dist/
/.idea/
/.vscode/
.DS_Store
*.log
*.swp
*.tmp
*.deb
*.zip
*.key
*.token
panel.password
session.key
+30
View File
@@ -0,0 +1,30 @@
# API-GAPS — brakujące funkcje, których UI nie udaje
Sprawdzono rzeczywisty kod EasyDNS Rust 0.1.4, nie roadmapę. Oryginalne referencyjne obrazy z projektu UI zawierały niektóre hipotetyczne metryki i oznaczenia — działający panel **nie pokazuje ich jako danych z serwera**.
| Brak / ograniczenie | Rzeczywisty stan API i zachowanie panelu |
|---|---|
| Query Log | Brak REST endpointu do listy historii zapytań DNS. Lookup to tylko jednorazowe `GET /query`. Nie ma strony Query Log. |
| Klaster, node health, 3/3 nodes | `GET /status` nie zwraca członków klastra. Panel pokazuje stan **pojedynczego** EasyDNS, bez wymyślania „Connected to cluster”. |
| 24-godzinne historyczne dane i wybór dowolnej daty | `/stats` zwraca migawkę/liczniki. Go zbiera tylko realne próbki co 15 s (do 6 godzin w pamięci), bez fikcyjnego 24h. Po restarcie historia znika. |
| Wykres QPS przypisany do konkretnej strefy | API nie zwraca per-zone QPS. Nie ma takiego wykresu w działającym Zone Details. |
| Transfer queue z `progress 64%`, ETA, pending list | `/zones/{zone}/transfers` zwraca **historię** AXFR/IXFR; nie udostępnia kolejki/progresu procentowego. Panel pokazuje tabelę realnej historii. |
| Dowolna edycja ZoneConfig | REST umożliwia utworzenie primary, podmianę tekstu strefy oraz usunięcie overlay-zone, ale nie pozwala zmieniać transfer ACL / NOTIFY / TSIG na istniejącej strefie. Konfiguracja read-only. |
| Tworzenie secondary przez REST | `/zones` POST tworzy tylko primary. Secondary może zostać zsynchronizowana, jeśli już istnieje w konfiguracji. |
| Pobranie źródłowego zone-file do edytora | Brak `GET zone_file`. Formularz replace wymaga samodzielnego podania **całego** pliku. |
| Indywidualny endpoint GET record | Brak `GET /zones/{zone}/records/{id}`. Panel szuka ID na paginowanej liście (limit 100 stron po 1000 rekordów). |
| SOA edytowany jako zwykły rekord | EasyDNS odrzuca SOA w CRUD rekordów. Panel zarządza SOA tylko przez pełną podmianę zone-file. |
| Pełny CRUD Views | `/policies` GET wystawia widoki, lecz brak REST zapisu tych struktur. Widok read-only. |
| Pełny CRUD ACL | Nazwane ACL i API/recursion client ACL wystawione do odczytu, brak odpowiednich PUT/POST/DELETE. Widok read-only. |
| Edycja Rate Limiting | `/policies` GET i `/stats.rate_limited` są dostępne, ale brak REST aktualizacji limitów. Widok read-only. |
| Pełna edycja polityk | `/policies` PUT obsługuje wyłącznie `allowlist` i `block_action`. Pozostałe ustawienia tylko do odczytu. |
| DNSSEC lifecycle, nowe klucze, signing | Status może być widoczny w GET zone, nie ma REST zarządzania kluczami. Tylko odczyt. |
| Lista konkretnych reguł Blocklist | GET `/blocklists` zwraca źródła i sumę reguł, nie każdy element. POST dodaje regułę; brak CRUD reguł. |
| Edit/Delete Upstream | `GET /upstreams`, `POST /upstreams` są faktyczne; brak aktualizacji/usunięcia. |
| Key browser / delete pojedynczego cache entry | `/cache` daje liczniki i flush całości lub domeny, nie listę kluczy cache. |
| Restart/stop server, zmiana portów z UI | REST udostępnia hot-reload konfiguracji, nie start/stop serwera ani pełny edytor `config.yaml`. |
| Rotacja tokenów API | Lokalny auto-token jest generowany przez EasyDNS i weryfikowany w jego kodzie; brak REST endpointu do rotacji. UI nie pozwala go edytować ani wyświetlić. |
| CPU, RAM, disk / host load przez `/stats` | Odpowiedź EasyDNS `stats` nie zawiera pełnych metryk OS. UI nie rysuje CPU/RAM/disk na podstawie fikcyjnych danych. |
| Serwerowy eksport CSV/report z /stats | Brak odpowiedniego export endpointu w REST. Panel umożliwia przeglądanie liczników, bez fikcyjnego raportu. |
Priorytet: zgodność API przed dekoracyjną zgodnością z koncepcyjnym obrazem. Gdy wyświetlanie danych jest niemożliwe, panel pokazuje tekst informacyjny lub brak widoku; nie generuje fałszywych wartości.
+48
View File
@@ -0,0 +1,48 @@
# API-MAPPING — ekran → EasyDNS REST
Źródło prawdy: dostarczone EasyDNS **v0.1.4**: `docs/api.md`, `crates/dns-api/src/handlers.rs`, `crates/dns-api/src/lib.rs`. Poniższe ścieżki **po prawej stronie** należą wyłącznie do EasyDNS, prefiks REST `/api/v1` (z wyjątkiem `/readyz`). Panel pod spodem ma własne strony `/zones`, `/metrics` itd., które nie są nowymi endpointami backendu DNS.
| Widok panelu | EasyDNS REST endpoint | Metoda | Odczytywane/wysyłane pola JSON | Działania i ograniczenia |
|---|---|---|---|---|
| Overview | `/status`, `/stats`, `/health`, `/audit?n=6` | GET | `version,mode,uptime_seconds,roles.{primary,secondary,recursive,forwarder},queries_total,responses,cache_hit_rate,blocked,rate_limited,latency_p95_s,status,expired_zones,items` | Odczyt, bez fikcyjnego stanu klastra / 24h serwera |
| Zones | `/zones?page=&per_page=&name=&kind=` | GET | `items[]:{name,kind,serial,loaded,expired,records,status},pagination:{page,per_page,total}` | Filtracja i stronicowanie, bez fikcyjnego sortowania po stronie serwera |
| Create Zone | `/zones` | POST | `{name,ns[],hostmaster?,transfer_acl[],notify[]}` | Tworzenie tylko stref primary; HTTP 400/409/422 |
| Import Zone File | `/zones` | POST | `{name,zone_file,transfer_acl[],notify[]}` | Wysyłka treści całego pliku strefy (jako JSON); brak odczytu istniejących zone files |
| Zone Details | `/zones/{zone}` | GET | `name,kind,serial,loaded,expired,records,status,config,journal_entries,dnssec`, `ETag` | Szczegóły strefy, konfiguracja i stan; `config` tylko odczyt |
| Records | `/zones/{zone}/records?name=&type=&page=&per_page=` | GET | `items[]:{id,name,type,ttl,data},pagination,serial`, `ETag` | Tabela, filtry, odczyt tylko primary/secondary; brak endpointu `GET /records/{id}` |
| Add Record | `/zones/{zone}/records` | POST | `{name,type,ttl,data}`, nagłówek `If-Match: "serial"` | Tylko primary, SOA wykluczone; 412 przy konflikcie seriala |
| Edit Record | `/zones/{zone}/records/{id}` | PUT | `{name,type,ttl,data}`, `If-Match` | Aktualizacja całego rekordu; ID wcześniej z listy; 400/404/409/412/422 |
| Delete Record | `/zones/{zone}/records/{id}` | DELETE | `If-Match`; identyfikator rekordu w URL | Potwierdzenie DELETE, bez usuwania SOA |
| Replace Zone | `/zones/{zone}` | PUT | `{zone_file}`, `If-Match` | Pełna podmiana, ETag 412, 422 dla błędu treści, brak GET tekstu pliku |
| Delete Zone | `/zones/{zone}` | DELETE | identyfikator strefy z URL | Tylko strefy API-overlay; 409 dla plikowych; potwierdzenie nazwy |
| Transfer History | `/zones/{zone}/transfers` | GET | `items[]:{time_unix,direction,kind,peer,serial,records,ok,error,duration_ms}` | Historia, **nie** żywa kolejka lub procentowy progres |
| Secondary Sync | `/zones/{zone}/sync` | POST | zwrot `result,serial` | Wyłącznie secondary; 409 jeśli inny typ; 502 przy błędzie transferu |
| DNS Notify | `/zones/{zone}/notify` | POST | zwrot `targets` | Tylko gdy skonfigurowano cele; HTTP 202 oznacza akceptację wysyłki |
| DNSSEC Status | `/zones/{zone}` | GET | `dnssec` / `config.dnssec` | Stan i parametry tylko do odczytu; brak REST API do generowania/rotacji kluczy |
| DNS Lookup | `/query?name=&type=` | GET | `rcode,aa,answers[],authority[],elapsed_ms` | Jedno bieżące zapytanie; API nie daje historii zapytań klientów |
| Upstreams | `/upstreams` | GET | `items[]:{group,strategy,servers[]:{address,stats:{queries,failures,healthy,ewma_rtt_ms,...}}}` | Bieżące grupy i zdrowie serwerów, bez edit/delete upstream |
| Add Upstream | `/upstreams` | POST | `{address}` | Dodaje do overlay i przeładowuje konfigurację |
| Policies | `/policies` | GET | `policy,rate_limit,views,acls,api_allowed_clients,recursion_allowed_clients` | Odczyt aktywnych ustawień |
| Policies Settings | `/policies` | PUT | `{allowlist:[],block_action}` | Tylko te dwa pola zapisywalne; pozostałe nie mają REST CRUD |
| Views | `/policies` | GET | `views[]` | **Read-only**; brak create/edit/delete views |
| ACL | `/policies` | GET | `acls,recursion_allowed_clients,api_allowed_clients` | **Read-only**; brak edycji nazwanych ACL i client ACL |
| Rate Limiting | `/policies`, `/stats` | GET | `rate_limit,rate_limited` | **Read-only**; licznik zbiorczy, brak zmian limitera |
| Blocklists | `/blocklists` | GET | `lists[],loaded[],rules,update_interval,state` | Odczyt list, stan i liczba reguł; brak listy pojedynczych reguł z GET |
| Add Block Rule | `/blocklists` | POST | `{rule}` | Dodaje pojedynczą regułę; brak edit/delete per-rule |
| Cache | `/cache` | GET | `entries,capacity,hits,misses,inserts,evictions,expired,stale_served,prefetches` | Liczniki, bez listowania kluczy cache |
| Flush Cache | `/cache` / `/cache?domain=...` | DELETE | zwrot `removed` | Usuwa całość (potwierdzenie) albo wskazaną domenę |
| Metrics | `/stats` | GET | `queries_total,responses,sources,latency_p50_s,latency_p95_s,latency_p99_s,cache,blocked,rate_limited,uptime_seconds` | Statystyki bieżące; szereg czasowy wyliczany z odczytów w pamięci Go |
| Audit Log | `/audit?n=` | GET | `items[]:{time_unix,actor,action,target,result,detail}` | Ostatnie zdarzenia administracyjne; brak filtrowania czasu / Query Log |
| Server Status | `/status`, `/health`, `/readyz` | GET | `listeners,roles,zones,version,mode,uptime_seconds,expired_zones`, plaintext `/readyz` | Odczyt, brak akcji start/stop usługi |
| Configuration | `/status`, `/policies` | GET | `mode,version,roles.default_resolution,dnssec_validation,policy.block_action,...` | Odczyt wybranych parametrów, brak ogólnego edytora konfiguracji |
| Hot Reload | `/config/reload` | POST | raport / stan reload (serwerowy response) | Odświeża konfigurację z dysku, poprzednia pozostaje aktywna gdy błąd |
## Autoryzacja i odpowiedzi
- TCP: EasyDNS generuje sam `control.token` w `<data_dir>/control.token` przy włączonym API TCP. Go odczytuje token z pliku w backendzie i używa `Authorization: Bearer TOKEN` do EasyDNS. Token nie jest udostępniany w HTML ani JavaScript.
- Unix: `control.sock`, prawo dostępu wg właściciela/grupy, bez bearer tokenu; serwer audytuje UID/PID.
- Typowy błąd: `{"error":{"status":412,"message":"..."}}`; panel wyświetla serwerowy `message` i odpowiednie ostrzeżenie.
- Obsługiwane statusy: m.in. 400 nieprawidłowe parametry, 401/403 brak uprawnień, 404 brak zasobu, 409 konflikt, **412** niezgodność `If-Match`, **422** odrzucony zone file/RDATA, 502 problem secondary, 503 niedostępny stan, 500 błąd wewnętrzny.
- `ETag` (nazwa serial) pobierany z listy rekordów / szczegółów strefy i zachowywany przez Go w formularzu; przy zapisie wysyłany `If-Match`.
- Endpoint `GET /api/v1/openapi.json` istnieje, ale panel go nie wywołuje do generowania fikcyjnych formularzy.
- Lokalna trasa Go `GET /ui/telemetry` **nie jest endpointem EasyDNS**: zwraca tylko zmierzone sample JSON i wymaga zalogowania do panelu.
+11
View File
@@ -0,0 +1,11 @@
# Changelog
## 0.1.0
- Independent Go 1.23 web administration panel; OLED UI inspired by RustProxy control-room visual language.
- Complete read-only and writable screens mapped to EasyDNS Rust REST API v0.1.4; no backend endpoint inventions.
- Generated EasyDNS control token read server-side with Unix-socket fallback, CSRF-protected admin sessions.
- Zone/record operations with ETag conflict protection; DNS diagnostics, upstreams, policies, blocklist additions, cache operations and audit.
- Live 15-second sampling of authentic counters without synthetic historical data.
- Self-contained `go:embed` binary and independent Debian systemd packages for amd64/arm64.
- Visual reference PNG and 28 independently rendered DEMO UI screenshots (1920×1080).
+37
View File
@@ -0,0 +1,37 @@
# EasyDNS — OLED design system
Punktem odniesienia są dołączone do zadania przykłady z RustProxy 0.43.1 (stylistyka, nie kod ani funkcjonalność) oraz zatwierdzone makiety w `design/reference/`.
## Kolory (rzeczywiste zmienne CSS)
| Token | HEX | Użycie |
|---|---|---|
| `--bg` | `#050807` | Tło OLED |
| `--sidebar` | `#060908` | Lewa nawigacja |
| `--panel` | `#111614` | Tabele i panele |
| `--panel-alt` | `#151b17` | Powierzchnie drugiego planu |
| `--field` | `#0b100e` | Wypełnienie pól formularza |
| `--line` | `#323b37` | Cienkie obramowania |
| `--text` | `#eff3ed` | Główny tekst |
| `--muted` | `#a5b1aa` | Drugi poziom typografii |
| `--subtle` | `#7f9087` | Etykiety pomocnicze |
| `--green` | `#a6d79d` | OK, akcje podstawowe, aktywna karta |
| `--cyan` | `#6fcde0` | Pierwsza seria wykresu, focus |
| `--amber` | `#f2b42f` | Ostrzeżenie, druga seria wykresu |
| `--red` | `#e88a8a` | Błędy, operacje niebezpieczne |
Brak gradientów, glassmorphism, miękkich cieni i ozdobnego monogramu. Proste narożniki 2–3 px, obramowania 1 px, małe przyciski konturowe. Podstawowe akcje w kolorze zielonym, destrukcyjne czerwone i opisane tekstem; ikona nigdy nie jest jedynym oznaczeniem przycisku, jeśli wymaga jasnego potwierdzenia.
## Typografia / grid
`Inter` (jeśli dostępny w systemie), potem systemowy sans-serif. Dane liczbowe, DNS i etykiety tabel: systemowy monospace. Sidebar desktop 208 px, topbar 48 px; karta minimum ok. 185 px, gap 9–13 px, table row 38 px, typografia body 13 px. Układ wykresów 3 kolumny desktop, 2 tablet i 1 mobile. Wszystko w rozdzielczości desktop 1920×1080 z rzeczywistym przepływem dokumentu, bez sztucznego przycinania.
## Wykresy
Lekka, cienka linia 1.65 px, subtelna siatka przerywana, cyjan i bursztyn dla serii, minimalne legendy, oś X z czasami próbek. Żadne wartości statystyczne nie są animowane ani sztucznie uzupełniane. Unikamy mieszania licznika narastającego z QPS. Brak danych? Komunikat „Collecting live samples”.
## Przyciski / formularze
`btn-ui` (kontur), `btn-primary-ui` (zielony), `btn-danger-ui` (czerwony), `btn-small` (tabela). Pola mają wyraźny focus i tekstowy label, z gwiazdką dla wymaganych parametrów. `ETag` do konkurowania o serial, ostrzeżenie 412, osobne potwierdzenia operacji: delete/replace/cache flush/reload.
Źródłem implementacji jest `internal/server/web/static/app.css`. Zmiany design systemu należy wprowadzać tam, a nie w obrazach PNG.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 EasyDNS @linuxiarz.pl
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+19
View File
@@ -0,0 +1,19 @@
GO ?= go
VERSION ?= 0.1.0
GOARCH ?= amd64
ARCH ?= all
.PHONY: test vet build deb docker-deb clean
test:
GOPROXY=off GOTOOLCHAIN=local $(GO) test -count=1 ./...
vet:
GOPROXY=off GOTOOLCHAIN=local $(GO) vet ./...
build:
mkdir -p bin
GOPROXY=off GOTOOLCHAIN=local $(GO) build -trimpath -ldflags "-X main.version=$(VERSION)" -o bin/easydns-ui ./cmd/easydns-ui
deb:
GOARCH=$(GOARCH) VERSION=$(VERSION) ./scripts/build-deb.sh
docker-deb:
./scripts/build_deb.sh --arch $(ARCH) --version $(VERSION)
clean:
rm -rf bin dist
+165
View File
@@ -0,0 +1,165 @@
# EasyDNS Web
**Samodzielny panel administracyjny WWW dla EasyDNS**, napisany w Go. Panel jest osobnym projektem i osobną usługą `easydns-ui.service`; **nie zastępuje serwera DNS**, nie jest dodawany do pakietu Rust EasyDNS i nie zmienia jego REST API.
![EasyDNS OLED operator dashboard — render działającego UI na danych DEMO](design/screenshots/overview-demo.png)
## Zakres i wygląd
Wygląd bazuje na zaakceptowanych makietach RustProxy-inspired / **OLED**: niemal czarne tło, grafitowe panele, niewidoczne gradienty (brak), cienkie obramowania, kompaktowe tabele, płaskie przyciski, linie telemetryczne w cyjanie i bursztynie, oszczędne wskaźniki kolorów. Zamiast generowanego logotypu: **napis EasyDNS**. Bez `API v1` w górnym pasku, fikcyjnych klastrów ani ozdobników.
Dostarczone są **oryginalne, zaakceptowane makiety 5 głównych ekranów** w `design/reference/` oraz **28 zrzutów faktycznie wyrenderowanych stron** w `design/screenshots/*-demo.png`. Zrzuty przedstawiają wyłącznie dane testowe; rzeczywisty panel pokazuje to, co zwróci podłączony EasyDNS. Kształt widoków jest zgodny z kierunkiem makiet, ale nie jest odtwarzaniem fikcyjnych przycisków ani danych piksel w piksel.
Panel zawiera: Overview, Zones, Zone Details, Records (create/edit/delete + serial conflict), tworzenie stref z NS lub pełnego zone file, transfers history, secondary synchronization, NOTIFY, DNSSEC inspection, DNS lookup, upstreams, Policies, Views, ACL, Rate Limiting, Blocklists, Cache, Metrics, Audit Log, Server Status, Configuration, confirmations and errors. **Nie ma Query Log**, bo taki endpoint nie istnieje. Ograniczenia szczegółowo w [API-GAPS.md](API-GAPS.md).
## Technologia
- **Go 1.23+**: serwer HTTP, bezpośredni klient REST i backend sesji.
- **Go `html/template`** oraz **`go:embed`**: wszystkie szablony, CSS/JS i ikony w pojedynczym binarnym pliku.
- **Bootstrap 5.3.6**: dołączony lokalnie, bez zależności od CDN; autorski `app.css` definiuje wzorzec OLED.
- **Vanilla JS**: wykresy natywnym Canvas na prawdziwych próbkach, bez danych syntetycznych; formularze działają bez JavaScript.
- **Ikony SVG** w stylu Lucide, osadzone lokalnie. Nie ma zależności od hostowanego zestawu ikon.
HTMX i Chart.js były technologiami preferowanymi, nie obligatoryjnymi. Ten wariant świadomie używa formularzy HTML oraz małego lokalnego renderera Canvas, aby binarka była samowystarczalna. **Nie twierdzi, że wykorzystuje HTMX albo Chart.js.**
## Instalacja gotowego `.deb` (Debian / Ubuntu)
EasyDNS musi być osobno zainstalowany i uruchomiony. Dla Linux `amd64`:
```bash
sudo apt install ./easydns-ui_0.1.0_amd64.deb
sudo systemctl status easydns-ui
sudo cat /etc/easydns-ui/panel.password
```
Dla ARM64 analogicznie: `easydns-ui_0.1.0_arm64.deb`.
Następnie otwórz na serwerze `http://127.0.0.1:8088` (lub tunel SSH dla pracy z innego komputera):
```bash
ssh -L 8088:127.0.0.1:8088 user@dns-server
```
Zaloguj się użytkownikiem `admin` i hasłem z `/etc/easydns-ui/panel.password`. Hasło **jest automatycznie generowane podczas pierwszej instalacji** i nie jest zapisywane w logach. Po ręcznej zmianie pliku hasła zrestartuj usługę.
**Token EasyDNS jest inny niż hasło panelu.** EasyDNS tworzy token sam w `/etc/easydns/data/control.token`, kiedy jego TCP REST API jest włączone. Backend Go odczytuje ten plik na każde chronione żądanie, wysyłając `Authorization: Bearer ...` **wyłącznie do EasyDNS**. Nie tworzy, nie zastępuje ani nie wyświetla tokenu. Instalator `.deb` dodaje użytkownika serwisu `easydns-ui` do grupy `easydns` (jeżeli istnieje). Jeżeli uprawnienia katalogów nadal blokują odczyt, ustaw właściwe prawa zgodnie z instalacją EasyDNS, nie kopiuj tokenu do kodu lub HTML.
Konfiguracja panelu: `/etc/default/easydns-ui`.
```ini
EASYDNS_UI_LISTEN=127.0.0.1:8088
EASYDNS_API_URL=http://127.0.0.1:9953
EASYDNS_API_TOKEN_FILE=/etc/easydns/data/control.token
```
Alternatywa bez tokenu dla API działającego tylko przez Unix socket:
```ini
EASYDNS_API_SOCKET=/etc/easydns/data/control.sock
```
Restart panelu po zmianie konfiguracji:
```bash
sudo systemctl restart easydns-ui
sudo journalctl -u easydns-ui -f
```
### HTTPS i dostęp z sieci
Domyślnie panel nasłuchuje **tylko na 127.0.0.1**. Nie publikuj portu HTTP bez TLS. Użyj tunelu SSH lub reverse proxy z HTTPS i wtedy w `/etc/default/easydns-ui` ustaw `EASYDNS_UI_COOKIE_SECURE=true`. Autoryzacja administratora w panelu: sesja podpisana HMAC, ciasteczko `HttpOnly` i `SameSite=Strict`, token CSRF dla wszystkich operacji POST, ograniczenie prób logowania, CSP i `no-store` dla stron z danymi. API EasyDNS nie jest udostępnione przeglądarce.
## Budowanie z repozytorium
```bash
# Go 1.23+ i dpkg-deb na maszynie budującej
make test
make vet
make build
./bin/easydns-ui -version
make deb GOARCH=amd64
make deb GOARCH=arm64
```
Wyniki `.deb` w `dist/`. Wszystkie zasoby panelu są embedowane.
### Budowanie pakietów `.deb` przez Docker (zalecane)
Na komputerze budującym wystarczy **Docker Engine / Docker Desktop**. Nie musisz instalować Go, kompilatora ARM, QEMU ani `dpkg-deb` na hoście. Skrypt uruchamia obraz `golang:1.23-bookworm`, wykorzystuje istniejące `scripts/build-deb.sh` do pakowania i zapisuje pliki na hoście w `dist/`. Nie uruchamia ani nie pakuje serwera Rust EasyDNS.
```bash
# Z katalogu głównego repozytorium — domyślnie dwie architektury
./scripts/build_deb.sh
# Tylko AMD64 lub ARM64
./scripts/build_deb.sh --arch amd64
./scripts/build_deb.sh --arch arm64
# Wersja pakietu i opcjonalnie inny obraz Go (musi zawierać dpkg-deb)
./scripts/build_deb.sh --version 0.2.0
IMAGE=golang:1.23-bookworm ./scripts/build_deb.sh --arch all
# Równoważne wywołanie przez Makefile
make docker-deb ARCH=all VERSION=0.1.0
```
Pliki wynikowe: `dist/easydns-ui_0.1.0_amd64.deb` i `dist/easydns-ui_0.1.0_arm64.deb`. Docker pobiera obraz przy pierwszym wywołaniu, więc wtedy potrzebny jest dostęp do rejestru obrazów. **Sam kontener budujący nie ma dostępu do sieci** (`--network none`) i kompiluje z `GOPROXY=off`. Architektury są kompilowane krzyżowo (`CGO_ENABLED=0`) z jednego obrazu; nie potrzeba `buildx`. Pliki w `dist/` należą do użytkownika uruchamiającego skrypt.
Bez Dockera nadal działa `make deb GOARCH=amd64` / `GOARCH=arm64`, ale wymaga Go i `dpkg-deb` na hoście.
Lokalne uruchomienie z już istniejącymi plikami logowania i tokenem:
```bash
EASYDNS_UI_PASSWORD_FILE=/bezpieczna/sciezka/panel.password \
EASYDNS_UI_SESSION_KEY_FILE=/bezpieczna/sciezka/session.key \
EASYDNS_API_TOKEN_FILE=/etc/easydns/data/control.token \
EASYDNS_API_URL=http://127.0.0.1:9953 \
EASYDNS_UI_LISTEN=127.0.0.1:8088 \
./bin/easydns-ui
```
Plik `panel.password` powinien zawierać tajne hasło długości co najmniej 16 znaków, a `session.key` co najmniej 32 losowe bajty lub 64 znaki hex. Gotowy pakiet tworzy oba automatycznie. W kodzie **nie ma** żadnego API tokenu ani domyślnego hasła.
## Struktura repo
```text
EasyDNS-Web/
├── cmd/easydns-ui/main.go # Punkt wejścia Go
├── internal/config/ # Zmienne środowiskowe
├── internal/easydns/ # Typowany REST API client; token tylko backend
├── internal/server/ # Routing, HTML templates, sesje, walidacja
│ └── web/
│ ├── templates/ # Go HTML Templates
│ └── static/ # OLED CSS, JS, SVG, Bootstrap 5, go:embed
├── internal/telemetry/ # Polling rzeczywistych liczników /stats
├── packaging/ # systemd, Debian maintainer scripts, env
├── scripts/build_deb.sh # Docker: obie architektury (bez Go/dpkg na hoście)
├── scripts/build-deb.sh # Natomiast pakowanie .deb (Go + dpkg-deb)
├── design/
│ ├── reference/ # 5 zaakceptowanych obrazów referencyjnych
│ └── screenshots/ # 28 zrzutów UI z danych DEMO
├── API-MAPPING.md
├── API-GAPS.md
├── UI-STRUCTURE.md
├── DESIGN-SYSTEM.md
├── SECURITY.md
└── Makefile
```
## API i zgodność z backendem
Bazą do mapowania był dostarczony **EasyDNS v0.1.4** (załączony kod Rust `crates/dns-api/src/handlers.rs`, trasy w `lib.rs`, `docs/api.md`). Aktualnego zdalnego `master` nie potwierdzono na potrzeby tego wydania. Wdrożenie w nowszej wersji wymaga uruchomienia testów zgodności. Panel **nie definiuje nowych endpointów EasyDNS**. HTTP `/ui/telemetry` to **wewnętrzny endpoint Go**, udostępniający przeglądarce wyłącznie próbki statystyk panelu — nie jest endpointem serwera DNS.
- [API-MAPPING.md](API-MAPPING.md): szczegółowe mapowanie ekranów do oryginalnych endpointów i pól JSON.
- [UI-STRUCTURE.md](UI-STRUCTURE.md): menu, przepływy i zachowania formularzy.
- [API-GAPS.md](API-GAPS.md): nieobsługiwane funkcje i różnice wobec koncepcyjnych grafik.
- [DESIGN-SYSTEM.md](DESIGN-SYSTEM.md): paleta OLED, komponenty, typografia, wykresy.
- [SECURITY.md](SECURITY.md): model uwierzytelniania, token, TLS, uprawnienia.
### Ograniczenia danych telemetrycznych
`GET /api/v1/stats` zwraca liczniki bieżące i kwantyle opóźnień, **nie** pełną historię 24h. Go zbiera pomiary co 15 sekund i utrzymuje ostatnie 1440 próbek (**do 6 godzin**, w RAM). Na wykresach **nie pojawiają się sztuczne wartości**, a historia znika po restarcie panelu. Polityki / Views / ACL / Rate Limiting i DNSSEC mają ograniczoną możliwość edycji, zgodnie z `API-GAPS.md`.
## Licencje
Kod panelu: MIT (patrz `LICENSE`). Bootstrap CSS: MIT, informacje w `THIRD-PARTY-NOTICES.md`. RustProxy był **inspiracją stylistyczną**, nie jest komponentem tego projektu i nie jest dołączony do repozytorium.
+24
View File
@@ -0,0 +1,24 @@
# Security model
## Trust boundaries
Browser → session cookie (HMAC-SHA256, HttpOnly, SameSite=Strict, optional Secure) → Go backend → EasyDNS REST using generated `control.token` or local Unix socket. The EasyDNS bearer never reaches HTML, JavaScript, CSS, logs or browser requests.
The panel is highly privileged. The login password is generated by the `.deb` postinst into `/etc/easydns-ui/panel.password` (`root:easydns-ui`, `0640`, directory `0750`). The panel session key is independently generated into `/etc/easydns-ui/session.key`. Password files have no hardcoded defaults. The Go service account is added to the `easydns` Unix group, when available, so it can read the Rust server's **existing** token (`control.token`) or access its control socket.
All state-changing browser actions are POST and require a per-session HMAC CSRF token; browser Origin (if supplied) must match the current host. No generic API endpoint proxy is exposed. ETag/If-Match on record and zone replacement prevents silent serial conflict. Error messages are server-derived; no secrets logged. Data is escaped by Go `html/template`. The default listen address is `127.0.0.1:8088` only; never publish plaintext on the internet. Serve HTTPS through a trusted reverse proxy and set `EASYDNS_UI_COOKIE_SECURE=true`.
## Operational recommendations
- Keep EasyDNS API on loopback or Unix socket, and panel on loopback behind a TLS proxy, or access over SSH tunnel.
- Restrict who can read `/etc/easydns/data/control.token`: token is admin-level access to DNS.
- Avoid copying server token into config files or front-end. The panel reads it dynamically.
- Rotate panel session key to invalidate all current sessions after an incident; restart service.
- Rotate the panel password by replacing the password file and restarting the panel.
- Secure reverse proxy with IP allowlist or VPN and an additional authentication layer as appropriate.
- Audit privileges: Go service account has no write permission to Rust EasyDNS configuration or token file.
- Logging: `journalctl -u easydns-ui`; does not log credentials or API payloads.
## Scope / known limitations
Login lockout is per remote IP and in-memory (8 failed attempts / 15 minutes); multi-instance coordination is not supported. Session credentials are stateless: once issued they expire within 12 h; logout removes the browser cookie, but does not revoke a previously stolen copy. The panel does not implement additional user/role CRUD, SSO, TOTP or token rotation because EasyDNS REST does not expose these operations. For multi-user administration, add an upstream authenticated reverse proxy rather than inventing DNS API endpoints.
+28
View File
@@ -0,0 +1,28 @@
# Third-party notices
`internal/server/web/static/vendor/bootstrap.min.css` contains Bootstrap v5.3.6 CSS.
Bootstrap is licensed under the MIT License:
Copyright (c) 2011-2025 The Bootstrap Authors
Copyright (c) 2011-2025 Twitter, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
RustProxy: source archive provided solely as a **visual style reference**, not copied into this project. The delivered UI CSS, icons and chart renderer are authored in this repository.
+71
View File
@@ -0,0 +1,71 @@
# UI-STRUCTURE — nawigacja i przepływy
## Menu (spójne na każdej stronie)
```text
EasyDNS
DNS
Overview /
Zones /zones
Create primary zone /zones/new
Import zone file /zones/import
Zone details /zones/{zone}
Records /zones/{zone}/records
Add /zones/{zone}/records/new
Edit /zones/{zone}/records/{id}/edit
Delete /zones/{zone}/records/{id}/delete
Transfers / History /zones/{zone}/transfers
DNSSEC /zones/{zone}/dnssec (read only)
Operations /zones/{zone}/operations
Replace zone file /zones/{zone}/replace
Delete zone /zones/{zone}/delete
DNS lookup /query?name=&type=
RESOLUTION & POLICY
Upstreams /upstreams
Add upstream /upstreams/new
Policies /policies
Views /views (read only)
ACL /acl (read only)
Rate limiting /rate-limiting (read only)
Blocklists /blocklists
Add block rule /blocklists/new
MONITORING & SYSTEM
Cache /cache
Metrics /metrics
Audit log /audit
Server status /status
Configuration /configuration
```
Menu nie ma Query Log, restartu usługi ani mechanizmów, których EasyDNS API nie obsługuje. Aktywna sekcja podkreślona zielonym paskiem zgodnym z referencją OLED. W podstronach strefy zamiast nowych pozycji sidebar stosowane są zakładki. Wąskie ekrany mają wysuwany sidebar.
## Formularze i operacje
- Logowanie: lokalne hasło panelu i sesja HMAC. Bearer EasyDNS pozostaje w Go. Każdy mutujący formularz ma `POST` i CSRF. Panel przekłada formularz na dokładnie znaną metodę REST EasyDNS.
- Create Zone: wymagane `name` oraz `ns[]` lub pełny `zone_file`, opcjonalnie `hostmaster`, `transfer_acl`, `notify`; niezależne zakładki „From nameservers” i „From zone file”. API tworzy tylko primary.
- Add Record: wymagane `name`, `type`, `ttl`, `data`. `SOA` niedostępne. Go pobiera aktualny `ETag`, wysyła `If-Match`, wykrywa HTTP 412.
- Edit Record: brak osobnego API GET record; Go wyszukuje rekord po identyfikatorze w liście i wypełnia formularz. Dane wpisane użytkownika przechodzą walidację form i serwera EasyDNS.
- Delete Record: osobny ekran z dokładną nazwą i typem, potwierdzenie `DELETE`, `If-Match`. Przy konflikcie nie ma wymuszonego zapisu; użytkownik wraca do listy.
- Replace Zone: użytkownik wprowadza cały nowy zone file; oryginał **nie** jest pobierany, potwierdzenie `REPLACE` i `If-Match`. Gdy treść nie przejdzie walidacji Rust, wyświetlany jest komunikat 422.
- Delete Zone: wpisanie dokładnej nazwy. API może odmówić 409 dla stref spoza overlay; panel nie udaje, że można je skasować.
- NOTIFY / Sync: widoczne w kontekście strefy, zgodnie z rolą i `notify[]`. Stan wyniku i ewentualne błędy pochodzą z API.
- DNS lookup: formularz GET; `rcode`, `aa`, `answers[]`, `authority[]`, `elapsed_ms` z jednorazowej odpowiedzi. Brak „history log”.
- Upstream Add: wymagane `address`, backend autoryzuje `POST /upstreams`. Brak opcji edit/delete.
- Policies Save: tylko `allowlist` i `block_action`; komunikaty walidacji i odrzucenia z API. Views/ACL/Rate Limiting nie mają formularzy edycji.
- Block rule: pojedynczy `rule`, walidacja pustej linii, błędy 400/422.
- Cache: flush domeny po wpisaniu `domain`, albo flush całej pamięci po wpisaniu `FLUSH ALL`.
- Configuration: `POST /config/reload` po wpisaniu `RELOAD`. Brak edytora pełnego pliku.
## Metryki i odświeżanie
Go wykonuje 1 żądanie GET `/stats` co 15 sekund niezależnie od liczby podłączonych operatorów. Przechowuje maksymalnie 1440 próbek (do 6 godzin) w RAM. Frontend odczytuje `GET /ui/telemetry` panelu, wymagające sesji. Wykresy zaczynają się dopiero po drugiej poprawnej próbce; spadki liczników po restarcie EasyDNS nie powodują fałszywych ujemnych wartości.
Serwer nie udostępnia per-zone QPS, transfer progress ani pełnych historycznych wykresów. W design references dane te są koncepcyjne. Produkcyjny UI nie podaje ich jako rzeczywistych.
## Błędy / bezpieczeństwo / responsywność
Formularze pokazują zwrócone przez EasyDNS `error.message`, bez wypisywania bearer tokenu. Konflikt 412 ma dedykowaną stronę. Potwierdzenia destrukcyjnych operacji wymagają jawnego wpisania właściwej frazy. Domyślnie dostępny jest tylko loopback; publikacja wymaga TLS reverse proxy lub tunelu SSH. Breakpointy UI: `1570`, `1130`, `820`, `540` px. CSS bez gradientów i animacji; przewidziano `prefers-reduced-motion`.
## Różnica design-reference a działające widoki
Pięć referencyjnych makiet PNG (Overview, Zones, Zone Details, Records, Metrics) to akceptacja kierunku **estetycznego**, nie specyfikacja istniejących endpointów. Implementacja zachowuje wygląd OLED, paletę, strukturę nawigacji, gęste tabele, sposób rysowania wykresów i typologię przycisków; usuwa dane, których EasyDNS nie ma. `design/screenshots/*-demo.png` przedstawiają dokładnie wyrenderowane HTML z fixture, oznaczone jako DEMO.
+43
View File
@@ -0,0 +1,43 @@
package main
import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"syscall"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/config"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/server"
)
var version = "dev"
func main() {
showVersion := flag.Bool("version", false, "show panel version")
flag.Parse()
if *showVersion {
fmt.Printf("easydns-ui %s\n", version)
return
}
cfg, err := config.Load()
if err != nil {
fmt.Fprintln(os.Stderr, "configuration:", err)
os.Exit(1)
}
server.Version = version
svc, err := server.New(cfg)
if err != nil {
fmt.Fprintln(os.Stderr, "initialize:", err)
os.Exit(1)
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
if err = svc.Run(ctx); err != nil && !errors.Is(err, context.Canceled) {
slog.Error("server", "error", err)
os.Exit(1)
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

+3
View File
@@ -0,0 +1,3 @@
module git.linuxiarz.pl/gru/EasyDNS-Web
go 1.23
+52
View File
@@ -0,0 +1,52 @@
package config
import (
"errors"
"fmt"
"os"
"strconv"
"strings"
)
type Config struct {
Listen string
APIURL string
APISocket string
TokenFile string
PasswordFile string
SessionKeyFile string
CookieSecure bool
Username string
}
func env(key, fallback string) string {
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
return v
}
return fallback
}
func Load() (Config, error) {
c := Config{
Listen: env("EASYDNS_UI_LISTEN", "127.0.0.1:8088"),
APIURL: env("EASYDNS_API_URL", "http://127.0.0.1:9953"),
APISocket: os.Getenv("EASYDNS_API_SOCKET"),
TokenFile: env("EASYDNS_API_TOKEN_FILE", "/etc/easydns/data/control.token"),
PasswordFile: env("EASYDNS_UI_PASSWORD_FILE", "/etc/easydns-ui/panel.password"),
SessionKeyFile: env("EASYDNS_UI_SESSION_KEY_FILE", "/etc/easydns-ui/session.key"),
CookieSecure: env("EASYDNS_UI_COOKIE_SECURE", "false") == "true",
Username: env("EASYDNS_UI_USERNAME", "admin"),
}
if _, err := strconv.Atoi(strings.Split(c.Listen, ":")[len(strings.Split(c.Listen, ":"))-1]); err != nil {
return c, fmt.Errorf("invalid listen address: %w", err)
}
if c.APISocket == "" && !strings.HasPrefix(c.APIURL, "http://127.0.0.1:") && !strings.HasPrefix(c.APIURL, "http://[::1]:") && !strings.HasPrefix(c.APIURL, "https://") {
return c, errors.New("API URL must be loopback HTTP or HTTPS")
}
for _, path := range []string{c.PasswordFile, c.SessionKeyFile} {
if _, err := os.Stat(path); err != nil {
return c, fmt.Errorf("required credential file %s: %w", path, err)
}
}
return c, nil
}
+133
View File
@@ -0,0 +1,133 @@
package easydns
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
)
const maxResponse = 16 << 20
type Client struct {
base string
tokenFile string
useSocket bool
http *http.Client
}
func New(base, tokenFile, socket string) (*Client, error) {
tr := &http.Transport{MaxIdleConnsPerHost: 8, IdleConnTimeout: 30 * time.Second, ResponseHeaderTimeout: 30 * time.Second}
if socket != "" {
tr.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", socket)
}
base = "http://unix"
} else {
u, e := url.Parse(base)
if e != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
return nil, errors.New("invalid EasyDNS API URL")
}
base = strings.TrimSuffix(base, "/")
}
return &Client{base: base, tokenFile: tokenFile, useSocket: socket != "", http: &http.Client{Transport: tr, Timeout: 65 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
}
type Error struct {
Status int
Message string
}
func (e *Error) Error() string {
if e.Status == 0 {
return e.Message
}
return fmt.Sprintf("EasyDNS HTTP %d: %s", e.Status, e.Message)
}
// Do uses ONLY paths explicitly built in the panel routes. It does not expose a generic API proxy.
func (c *Client) Do(ctx context.Context, method, path string, body any, etag string, out any) (string, error) {
if !strings.HasPrefix(path, "/api/v1/") && path != "/readyz" && path != "/healthz" {
return "", &Error{Message: "endpoint is not permitted"}
}
var src io.Reader
if body != nil {
b, e := json.Marshal(body)
if e != nil {
return "", e
}
src = bytes.NewReader(b)
}
req, e := http.NewRequestWithContext(ctx, method, c.base+path, src)
if e != nil {
return "", e
}
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if etag != "" {
req.Header.Set("If-Match", etag)
}
if !c.useSocket && path != "/readyz" && path != "/healthz" && path != "/api/v1/health" {
secret, e := os.ReadFile(c.tokenFile)
if e != nil {
return "", &Error{Message: "Unable to read EasyDNS generated control token; check token file permissions or configure the Unix socket"}
}
token := strings.TrimSpace(string(secret))
if token == "" {
return "", &Error{Message: "EasyDNS control token file is empty"}
}
req.Header.Set("Authorization", "Bearer "+token)
}
resp, e := c.http.Do(req)
if e != nil {
return "", &Error{Message: "EasyDNS API unavailable: " + e.Error()}
}
defer resp.Body.Close()
raw, e := io.ReadAll(io.LimitReader(resp.Body, maxResponse+1))
if e != nil {
return "", e
}
if len(raw) > maxResponse {
return "", &Error{Message: "EasyDNS API response exceeds 16 MiB"}
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
var envelope struct {
Error struct {
Status int `json:"status"`
Message string `json:"message"`
} `json:"error"`
}
msg := http.StatusText(resp.StatusCode)
if json.Unmarshal(raw, &envelope) == nil && envelope.Error.Message != "" {
msg = envelope.Error.Message
}
if msg == "" {
msg = "Unexpected EasyDNS response"
}
return resp.Header.Get("ETag"), &Error{Status: resp.StatusCode, Message: msg}
}
if out != nil && len(raw) > 0 {
if e := json.Unmarshal(raw, out); e != nil {
return "", fmt.Errorf("decode EasyDNS response: %w", e)
}
}
return resp.Header.Get("ETag"), nil
}
func (c *Client) Get(ctx context.Context, path string, out any) (string, error) {
return c.Do(ctx, http.MethodGet, path, nil, "", out)
}
func (c *Client) Write(ctx context.Context, method, path string, payload any, etag string, out any) error {
_, e := c.Do(ctx, method, path, payload, etag, out)
return e
}
func Escape(v string) string { return url.PathEscape(v) }
+101
View File
@@ -0,0 +1,101 @@
package easydns
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestGeneratedTokenAndETag(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "control.token")
if e := os.WriteFile(file, []byte("generated-test-token\n"), 0600); e != nil {
t.Fatal(e)
}
var got string
var match string
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = r.Header.Get("Authorization")
match = r.Header.Get("If-Match")
if r.Method != http.MethodPut || r.URL.Path != "/api/v1/zones/example.com./records/record-id" {
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
}
if got != "Bearer generated-test-token" {
t.Errorf("wrong bearer token: %q", got)
}
if match != "\"2026113001\"" {
t.Errorf("missing serial guard: %q", match)
}
var body struct {
Name string `json:"name"`
Type string `json:"type"`
TTL int `json:"ttl"`
Data string `json:"data"`
}
if e := json.NewDecoder(r.Body).Decode(&body); e != nil {
t.Error(e)
}
if body.Name != "www" || body.Type != "A" || body.TTL != 300 || body.Data != "192.0.2.10" {
t.Errorf("wrong payload: %+v", body)
}
w.Header().Set("ETag", "\"2026113002\"")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"ok":true}`))
}))
defer ts.Close()
c, e := New(ts.URL, file, "")
if e != nil {
t.Fatal(e)
}
var out struct {
OK bool `json:"ok"`
}
e = c.Write(context.Background(), "PUT", "/api/v1/zones/example.com./records/record-id", map[string]any{"name": "www", "type": "A", "ttl": 300, "data": "192.0.2.10"}, "\"2026113001\"", &out)
if e != nil {
t.Fatal(e)
}
if !out.OK {
t.Fatal("response not decoded")
}
if got == "" || match == "" {
t.Fatal("request not received")
}
}
func TestErrorEnvelope(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "control.token")
_ = os.WriteFile(file, []byte("a"), 0600)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(412)
_, _ = w.Write([]byte(`{"error":{"status":412,"message":"zone serial changed"}}`))
}))
defer ts.Close()
c, _ := New(ts.URL, file, "")
_, e := c.Get(context.Background(), "/api/v1/zones/example.com.", nil)
apiErr, ok := e.(*Error)
if !ok || apiErr.Status != 412 || !strings.Contains(apiErr.Message, "zone serial changed") {
t.Fatalf("wrong REST error: %#v", e)
}
}
func TestNoUnknownAPIPaths(t *testing.T) {
c, e := New("http://127.0.0.1:9953", "/does/not/matter", "")
if e != nil {
t.Fatal(e)
}
_, e = c.Get(context.Background(), "/new-not-real-endpoint", nil)
if e == nil || !strings.Contains(e.Error(), "not permitted") {
t.Fatalf("unexpected: %v", e)
}
}
func TestInvalidBaseURL(t *testing.T) {
_, e := New("file:///etc/shadow", "/tmp/token", "")
if e == nil {
t.Fatal("invalid URL accepted")
}
}
+207
View File
@@ -0,0 +1,207 @@
package easydns
import (
"fmt"
"strings"
"time"
)
type Pagination struct {
Page int `json:"page"`
PerPage int `json:"per_page"`
Total int `json:"total"`
}
type Page[T any] struct {
Items []T `json:"items"`
Pagination Pagination `json:"pagination"`
Serial uint32 `json:"serial"`
}
type Health struct {
Status string `json:"status"`
ExpiredZones []string `json:"expired_zones"`
}
type Roles struct {
Primary int `json:"primary"`
Secondary int `json:"secondary"`
Recursive bool `json:"recursive"`
Forwarder bool `json:"forwarder"`
ForwardZones int `json:"forward_zones"`
DefaultResolution string `json:"default_resolution"`
}
type Status struct {
Version string `json:"version"`
Mode string `json:"mode"`
UptimeSeconds uint64 `json:"uptime_seconds"`
Roles Roles `json:"roles"`
Listeners map[string]any `json:"listeners"`
Zones []Zone `json:"zones"`
DNSSECValidation any `json:"dnssec_validation"`
}
type Cache struct {
Entries uint64 `json:"entries"`
Capacity uint64 `json:"capacity"`
Hits uint64 `json:"hits"`
Misses uint64 `json:"misses"`
Inserts uint64 `json:"inserts"`
Evictions uint64 `json:"evictions"`
Expired uint64 `json:"expired"`
StaleServed uint64 `json:"stale_served"`
Prefetches uint64 `json:"prefetches"`
}
type Stats struct {
QueriesTotal uint64 `json:"queries_total"`
Responses map[string]uint64 `json:"responses"`
Sources map[string]uint64 `json:"sources"`
LatencyP50S float64 `json:"latency_p50_s"`
LatencyP95S float64 `json:"latency_p95_s"`
LatencyP99S float64 `json:"latency_p99_s"`
Cache Cache `json:"cache"`
CacheHitRate float64 `json:"cache_hit_rate"`
Blocked uint64 `json:"blocked"`
RateLimited uint64 `json:"rate_limited"`
UptimeSeconds uint64 `json:"uptime_seconds"`
}
type ZoneState struct {
Serial *uint32 `json:"serial"`
Loaded bool `json:"loaded"`
Expired bool `json:"expired"`
Records int `json:"records"`
Source *string `json:"source"`
LastRefreshUnix *int64 `json:"last_refresh_unix"`
LastSuccessUnix *int64 `json:"last_success_unix"`
NextRefreshUnix *int64 `json:"next_refresh_unix"`
ExpiresAtUnix *int64 `json:"expires_at_unix"`
LastError *string `json:"last_error"`
NotifiesSent uint64 `json:"notifies_sent"`
NotifiesFailed uint64 `json:"notifies_failed"`
}
type Zone struct {
Name string `json:"name"`
Kind string `json:"kind"`
Views []string `json:"views"`
Serial *uint32 `json:"serial"`
Loaded bool `json:"loaded"`
Expired bool `json:"expired"`
Records int `json:"records"`
Status ZoneState `json:"status"`
Config ZoneConfig `json:"config"`
JournalEntries int `json:"journal_entries"`
DNSSEC map[string]any `json:"dnssec"`
}
type ZoneConfig struct {
Name string `json:"name"`
Type string `json:"type"`
Notify []string `json:"notify"`
TransferACL []string `json:"transfer_acl"`
Primaries []string `json:"primaries"`
File *string `json:"file"`
DNSSEC map[string]any `json:"dnssec"`
Transfer any `json:"transfer"`
Views []string `json:"views"`
}
func (z Zone) IsPrimary() bool { return strings.EqualFold(z.Kind, "primary") }
func (z Zone) IsSecondary() bool { return strings.EqualFold(z.Kind, "secondary") }
func (z Zone) StateText() string {
if z.Expired {
return "Expired"
}
if !z.Loaded {
return "Not loaded"
}
return "Loaded"
}
func (z Zone) SerialText() string {
if z.Serial == nil {
return "—"
}
return fmt.Sprint(*z.Serial)
}
func (z Zone) SyncText() string {
if z.IsPrimary() {
return "Not applicable"
}
if z.Expired {
return "Expired"
}
if z.Status.LastError != nil && *z.Status.LastError != "" {
return "Error"
}
if z.Status.LastSuccessUnix != nil {
return "Last sync OK"
}
return "Not yet synced"
}
func (z Zone) LastSync() string {
if z.Status.LastSuccessUnix == nil {
return "—"
}
return time.Unix(*z.Status.LastSuccessUnix, 0).UTC().Format("2006-01-02 15:04:05 UTC")
}
type Record struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
TTL uint32 `json:"ttl"`
Data string `json:"data"`
}
type Transfer struct {
TimeUnix int64 `json:"time_unix"`
Direction string `json:"direction"`
Kind string `json:"kind"`
Peer string `json:"peer"`
Serial *uint32 `json:"serial"`
Records int `json:"records"`
OK bool `json:"ok"`
Error *string `json:"error"`
DurationMS uint64 `json:"duration_ms"`
}
type UpstreamGroup struct {
Group string `json:"group"`
Strategy string `json:"strategy"`
Servers []Upstream `json:"servers"`
}
type Upstream struct {
Address string `json:"address"`
Stats UpstreamStats `json:"stats"`
}
type UpstreamStats struct {
Queries uint64 `json:"queries"`
Failures uint64 `json:"failures"`
ConsecutiveFailures uint32 `json:"consecutive_failures"`
EWMARTTMS *float64 `json:"ewma_rtt_ms"`
CircuitOpenForMS *uint64 `json:"circuit_open_for_ms"`
LastError *string `json:"last_error"`
Healthy bool `json:"healthy"`
}
type QueryResult struct {
RCode string `json:"rcode"`
AA bool `json:"aa"`
Answers []Record `json:"answers"`
Authority []Record `json:"authority"`
ElapsedMS float64 `json:"elapsed_ms"`
}
type AuditItem struct {
TimeUnix int64 `json:"time_unix"`
Actor string `json:"actor"`
Action string `json:"action"`
Target string `json:"target"`
Result string `json:"result"`
Detail string `json:"detail"`
}
type Blocklists struct {
Lists []map[string]any `json:"lists"`
Loaded []string `json:"loaded"`
Rules int `json:"rules"`
UpdateInterval string `json:"update_interval"`
State map[string]map[string]any `json:"state"`
}
type Policies struct {
RecursionAllowedClients []string `json:"recursion_allowed_clients"`
ACLs map[string]any `json:"acls"`
Views []map[string]any `json:"views"`
RateLimit map[string]any `json:"rate_limit"`
Policy map[string]any `json:"policy"`
APIAllowedClients []string `json:"api_allowed_clients"`
}
+157
View File
@@ -0,0 +1,157 @@
package server
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"errors"
"net"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/config"
)
const sessionCookie = "easydns_ui_session"
const sessionTTL = 12 * time.Hour
type auth struct {
key []byte
password []byte
username string
secure bool
mu sync.Mutex
fail map[string][]time.Time
}
func newAuth(cfg config.Config) (*auth, error) {
p, err := os.ReadFile(cfg.PasswordFile)
if err != nil {
return nil, err
}
secret := strings.TrimSpace(string(p))
if len(secret) < 16 {
return nil, errors.New("panel password must have at least 16 characters")
}
k, err := os.ReadFile(cfg.SessionKeyFile)
if err != nil {
return nil, err
}
k = bytesTrimSpace(k)
if decoded, e := hex.DecodeString(string(k)); e == nil && len(decoded) >= 32 {
k = decoded
}
if len(k) < 32 {
return nil, errors.New("session key must contain at least 32 bytes")
}
return &auth{key: k, password: []byte(secret), username: cfg.Username, secure: cfg.CookieSecure, fail: make(map[string][]time.Time)}, nil
}
func bytesTrimSpace(v []byte) []byte { return []byte(strings.TrimSpace(string(v))) }
func (a *auth) sign(v string) string {
mac := hmac.New(sha256.New, a.key)
mac.Write([]byte(v))
return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
}
func (a *auth) makeSession() string {
r := make([]byte, 24)
_, _ = rand.Read(r)
v := base64.RawURLEncoding.EncodeToString(r) + "." + time.Now().UTC().Format("20060102150405")
return v + "." + a.sign(v)
}
func (a *auth) parseSession(r *http.Request) (string, bool) {
c, err := r.Cookie(sessionCookie)
if err != nil {
return "", false
}
parts := strings.Split(c.Value, ".")
if len(parts) != 3 {
return "", false
}
v := parts[0] + "." + parts[1]
if subtle.ConstantTimeCompare([]byte(a.sign(v)), []byte(parts[2])) != 1 {
return "", false
}
t, err := time.Parse("20060102150405", parts[1])
if err != nil {
return "", false
}
if time.Since(t) > sessionTTL || time.Until(t) > time.Minute {
return "", false
}
return v, true
}
func (a *auth) csrf(session string) string { return a.sign("csrf:" + session) }
func (a *auth) checkCSRF(r *http.Request, session string) bool {
if !sameOrigin(r) {
return false
}
provided := r.FormValue("_csrf")
if provided == "" {
provided = r.Header.Get("X-CSRF-Token")
}
return subtle.ConstantTimeCompare([]byte(provided), []byte(a.csrf(session))) == 1
}
func sameOrigin(r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin == "" {
return true
} // non-browser tools still need valid CSRF
u, err := url.Parse(origin)
if err != nil {
return false
}
return strings.EqualFold(u.Host, r.Host) && (u.Scheme == "https" || u.Scheme == "http")
}
func (a *auth) setCookie(w http.ResponseWriter, value string, maxAge int) {
http.SetCookie(w, &http.Cookie{Name: sessionCookie, Value: value, Path: "/", HttpOnly: true, Secure: a.secure, SameSite: http.SameSiteStrictMode, MaxAge: maxAge})
}
func (a *auth) allowedLogin(ip string) bool {
a.mu.Lock()
defer a.mu.Unlock()
now := time.Now()
v := a.fail[ip][:0]
for _, t := range a.fail[ip] {
if now.Sub(t) < 15*time.Minute {
v = append(v, t)
}
}
a.fail[ip] = v
return len(v) < 8
}
func (a *auth) failLogin(ip string) {
a.mu.Lock()
defer a.mu.Unlock()
a.fail[ip] = append(a.fail[ip], time.Now())
}
func (a *auth) clearFailure(ip string) { a.mu.Lock(); defer a.mu.Unlock(); delete(a.fail, ip) }
func remoteIP(r *http.Request) string {
h, _, e := net.SplitHostPort(r.RemoteAddr)
if e != nil {
return r.RemoteAddr
}
return h
}
func (a *auth) verify(user, pass string) bool {
u := subtle.ConstantTimeCompare([]byte(user), []byte(a.username))
ph := sha256.Sum256([]byte(pass))
eh := sha256.Sum256(a.password)
p := subtle.ConstantTimeCompare(ph[:], eh[:])
return u == 1 && p == 1
}
func secureHeaders(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "same-origin")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; base-uri 'none'")
h.ServeHTTP(w, r)
})
}
+261
View File
@@ -0,0 +1,261 @@
package server
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns"
)
func (s *Server) query(w http.ResponseWriter, r *http.Request) {
d := PageData{Form: map[string]string{"name": r.URL.Query().Get("name"), "type": r.URL.Query().Get("type")}}
if d.Form["type"] == "" {
d.Form["type"] = "A"
}
if d.Form["name"] != "" {
q := url.Values{"name": {strings.TrimSpace(d.Form["name"])}, "type": {d.Form["type"]}}
var result easydns.QueryResult
if e := s.get(r.Context(), "/api/v1/query?"+q.Encode(), &result); e != nil {
d.Error = e.Error()
} else {
d.Query = &result
}
}
s.render(w, r, "query", "DNS lookup", "Resolve a name through the running EasyDNS server. No query history is stored.", "query", "DNS / LOOKUP", d)
}
func (s *Server) upstreams(w http.ResponseWriter, r *http.Request) {
d := PageData{}
var a struct {
Items []easydns.UpstreamGroup `json:"items"`
}
if e := s.get(r.Context(), "/api/v1/upstreams", &a); e != nil {
d.Error = e.Error()
} else {
d.Upstreams = a.Items
}
s.render(w, r, "upstreams", "Upstreams", "Live resolver groups and upstream health.", "upstreams", "RESOLUTION / UPSTREAMS", d)
}
func (s *Server) upstreamForm(w http.ResponseWriter, r *http.Request) {
d := PageData{Form: map[string]string{}}
s.render(w, r, "upstream-form", "Add upstream", "Add one resolver address to the API overlay.", "upstreams", "RESOLUTION / UPSTREAMS / ADD", d)
}
func (s *Server) upstreamCreate(w http.ResponseWriter, r *http.Request) {
d := PageData{Form: formValues(r, "address")}
address := strings.TrimSpace(d.Form["address"])
if address == "" {
d.Error = "Upstream address is required."
} else {
var out any
err := s.api.Write(r.Context(), "POST", "/api/v1/upstreams", map[string]string{"address": address}, "", &out)
if err == nil {
redirect(w, r, "/upstreams?notice=upstream-added")
return
}
d.Error = err.Error()
}
s.render(w, r, "upstream-form", "Add upstream", "Add one resolver address.", "upstreams", "RESOLUTION / UPSTREAMS / ADD", d)
}
func (s *Server) policies(w http.ResponseWriter, r *http.Request) {
d := PageData{}
if e := s.get(r.Context(), "/api/v1/policies", &d.Policies); e != nil {
d.Error = e.Error()
} else {
d.Form = map[string]string{"allowlist": joinStrings(d.Policies.Policy["allowlist"]), "block_action": fmt.Sprint(d.Policies.Policy["block_action"])}
}
s.render(w, r, "policies", "Policies", "Inspect DNS policy and edit only the two REST-writable fields.", "policies", "RESOLUTION / POLICIES", d)
}
func joinStrings(v any) string {
a, ok := v.([]any)
if !ok {
return ""
}
parts := make([]string, 0, len(a))
for _, x := range a {
parts = append(parts, fmt.Sprint(x))
}
return strings.Join(parts, "\n")
}
func (s *Server) policiesSave(w http.ResponseWriter, r *http.Request) {
d := PageData{Form: formValues(r, "allowlist", "block_action")}
action := strings.ToLower(strings.TrimSpace(d.Form["block_action"]))
allowed := map[string]bool{"nxdomain": true, "refused": true, "null": true, "address": true, "nodata": true}
if !allowed[action] {
d.Error = "Unsupported block action."
} else {
body := map[string]any{"allowlist": splitLines(d.Form["allowlist"]), "block_action": action}
var result easydns.Policies
if e := s.api.Write(r.Context(), "PUT", "/api/v1/policies", body, "", &result); e != nil {
d.Error = e.Error()
} else {
redirect(w, r, "/policies?notice=policy-updated")
return
}
}
if e := s.get(r.Context(), "/api/v1/policies", &d.Policies); e != nil && d.Error == "" {
d.Error = e.Error()
}
s.render(w, r, "policies", "Policies", "Edit supported policy fields.", "policies", "RESOLUTION / POLICIES", d)
}
func (s *Server) policiesReadOnly(w http.ResponseWriter, r *http.Request, which string) {
d := PageData{}
if e := s.get(r.Context(), "/api/v1/policies", &d.Policies); e != nil {
d.Error = e.Error()
}
title, subtitle := map[string]string{"views": "Views", "acl": "Access control lists", "rate": "Rate limiting"}[which], ""
switch which {
case "views":
subtitle = "Split-horizon view configuration (read-only REST)."
case "acl":
subtitle = "Named ACLs and allowed clients (read-only REST)."
case "rate":
subtitle = "DNS response rate limiting configuration (read-only REST)."
}
d.Tab = which
if which == "rate" {
var stats easydns.Stats
if e := s.get(r.Context(), "/api/v1/stats", &stats); e == nil {
d.Stats = stats
}
}
s.render(w, r, "policy-readonly", title, subtitle, map[string]string{"views": "views", "acl": "acl", "rate": "rate"}[which], "RESOLUTION / "+strings.ToUpper(title), d)
}
func (s *Server) blocklists(w http.ResponseWriter, r *http.Request) {
d := PageData{}
if e := s.get(r.Context(), "/api/v1/blocklists", &d.Blocklists); e != nil {
d.Error = e.Error()
}
s.render(w, r, "blocklists", "Blocklists", "Configured feeds, load state and aggregate rule count.", "blocklists", "RESOLUTION / BLOCKLISTS", d)
}
func (s *Server) blockForm(w http.ResponseWriter, r *http.Request) {
s.render(w, r, "block-form", "Add block rule", "Append one rule to the EasyDNS API overlay.", "blocklists", "RESOLUTION / BLOCKLISTS / NEW", PageData{Form: map[string]string{}})
}
func (s *Server) blockCreate(w http.ResponseWriter, r *http.Request) {
d := PageData{Form: formValues(r, "rule")}
rule := strings.TrimSpace(d.Form["rule"])
if rule == "" || strings.ContainsAny(rule, "\r\n") {
d.Error = "Enter exactly one non-empty rule on one line."
} else {
if e := s.api.Write(r.Context(), "POST", "/api/v1/blocklists", map[string]string{"rule": rule}, "", nil); e != nil {
d.Error = e.Error()
} else {
redirect(w, r, "/blocklists?notice=rule-added")
return
}
}
s.render(w, r, "block-form", "Add block rule", "Append one rule to the EasyDNS API overlay.", "blocklists", "RESOLUTION / BLOCKLISTS / NEW", d)
}
func (s *Server) cache(w http.ResponseWriter, r *http.Request) {
d := PageData{}
if e := s.get(r.Context(), "/api/v1/cache", &d.Cache); e != nil {
d.Error = e.Error()
}
s.render(w, r, "cache", "Cache", "Resolver cache counters and precise invalidation.", "cache", "MONITORING / CACHE", d)
}
func (s *Server) cacheFlush(w http.ResponseWriter, r *http.Request) {
d := PageData{}
scope := r.FormValue("scope")
domain := strings.TrimSpace(r.FormValue("domain"))
path := "/api/v1/cache"
if scope == "domain" {
if domain == "" {
d.Error = "A domain is required for targeted invalidation."
} else {
path += "?domain=" + url.QueryEscape(domain)
}
} else if scope == "all" {
if r.FormValue("confirm") != "FLUSH ALL" {
d.Error = "Type FLUSH ALL to confirm full cache invalidation."
}
} else {
d.Error = "Unknown cache scope."
}
if d.Error == "" {
var out struct {
Removed uint64 `json:"removed"`
}
if e := s.api.Write(r.Context(), "DELETE", path, nil, "", &out); e != nil {
d.Error = e.Error()
} else {
redirect(w, r, "/cache?notice=cache-flushed")
return
}
}
if e := s.get(r.Context(), "/api/v1/cache", &d.Cache); e != nil && d.Error == "" {
d.Error = e.Error()
}
s.render(w, r, "cache", "Cache", "Resolver cache counters and invalidation.", "cache", "MONITORING / CACHE", d)
}
func (s *Server) metrics(w http.ResponseWriter, r *http.Request) {
d := PageData{}
if e := s.get(r.Context(), "/api/v1/stats", &d.Stats); e != nil {
d.Error = e.Error()
}
sm, e, last := s.telemetry.Snapshot()
d.SamplingCount = len(sm)
d.SamplingTime = last
d.SamplingError = e
s.render(w, r, "metrics", "Metrics", "Real counters and live samples collected by this panel.", "metrics", "MONITORING / METRICS", d)
}
func (s *Server) audit(w http.ResponseWriter, r *http.Request) {
d := PageData{}
n := getInt(r.URL.Query().Get("n"), 100, 1, 10000)
d.Filter = map[string]string{"n": strconv.Itoa(n)}
var res struct {
Items []easydns.AuditItem `json:"items"`
}
if e := s.get(r.Context(), "/api/v1/audit?n="+strconv.Itoa(n), &res); e != nil {
d.Error = e.Error()
} else {
d.Audit = res.Items
}
s.render(w, r, "audit", "Audit log", "Management actions recorded by EasyDNS. Not DNS query history.", "audit", "MONITORING / AUDIT", d)
}
func (s *Server) status(w http.ResponseWriter, r *http.Request) {
d := PageData{}
if e := s.get(r.Context(), "/api/v1/status", &d.Status); e != nil {
d.Error = e.Error()
}
if e := s.get(r.Context(), "/api/v1/health", &d.Health); e != nil && d.Error == "" {
d.Error = e.Error()
}
// /readyz is plaintext and may return 503; record only the returned readiness result.
if _, e := s.api.Get(r.Context(), "/readyz", nil); e != nil {
d.Filter = map[string]string{"ready": "Not ready / unavailable"}
} else {
d.Filter = map[string]string{"ready": "Ready"}
}
s.render(w, r, "status", "Server status", "Service roles, listeners, health and readiness.", "status", "MONITORING / SERVER STATUS", d)
}
func (s *Server) configuration(w http.ResponseWriter, r *http.Request) {
d := PageData{}
if e := s.get(r.Context(), "/api/v1/status", &d.Status); e != nil {
d.Error = e.Error()
}
if e := s.get(r.Context(), "/api/v1/policies", &d.Policies); e != nil && d.Error == "" {
d.Error = e.Error()
}
s.render(w, r, "configuration", "Configuration", "Read visible runtime settings and request hot reload. File editing is not exposed by REST.", "configuration", "MONITORING / CONFIGURATION", d)
}
func (s *Server) reload(w http.ResponseWriter, r *http.Request) {
d := PageData{}
if r.FormValue("confirm") != "RELOAD" {
d.Error = "Type RELOAD to confirm."
} else {
var res any
if e := s.api.Write(r.Context(), "POST", "/api/v1/config/reload", nil, "", &res); e != nil {
d.Error = e.Error()
} else {
redirect(w, r, "/configuration?notice=reloaded")
return
}
}
_ = s.get(r.Context(), "/api/v1/status", &d.Status)
_ = s.get(r.Context(), "/api/v1/policies", &d.Policies)
s.render(w, r, "configuration", "Configuration", "Hot reload with rollback on failure.", "configuration", "MONITORING / CONFIGURATION", d)
}
var _ = time.Now
+473
View File
@@ -0,0 +1,473 @@
package server
import (
"context"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns"
)
func (s *Server) overview(w http.ResponseWriter, r *http.Request) {
var d PageData
errs := []string{}
if e := s.get(r.Context(), "/api/v1/status", &d.Status); e != nil {
errs = append(errs, callError(e))
}
if e := s.get(r.Context(), "/api/v1/stats", &d.Stats); e != nil {
errs = append(errs, callError(e))
}
if e := s.get(r.Context(), "/api/v1/health", &d.Health); e != nil {
errs = append(errs, callError(e))
}
var audits struct {
Items []easydns.AuditItem `json:"items"`
}
if s.get(r.Context(), "/api/v1/audit?n=6", &audits) == nil {
d.Audit = audits.Items
}
smp, e, last := s.telemetry.Snapshot()
d.SamplingCount = len(smp)
d.SamplingTime = last
d.SamplingError = e
if len(errs) > 0 {
d.Error = strings.Join(errs, "; ")
}
s.render(w, r, "overview", "Overview", "DNS health, authority and resolver operations.", "overview", "DNS / OVERVIEW", d)
}
func (s *Server) zones(w http.ResponseWriter, r *http.Request) {
var d PageData
v := r.URL.Query()
d.Filter = map[string]string{"name": v.Get("name"), "kind": v.Get("kind")}
page := getInt(v.Get("page"), 1, 1, 100000)
query := url.Values{"page": {strconv.Itoa(page)}, "per_page": {"25"}}
for _, k := range []string{"name", "kind"} {
if t := strings.TrimSpace(d.Filter[k]); t != "" {
query.Set(k, t)
}
}
var result easydns.Page[easydns.Zone]
if err := s.get(r.Context(), "/api/v1/zones?"+query.Encode(), &result); err != nil {
d.Error = err.Error()
} else {
d.Zones = result.Items
d.Pagination = result.Pagination
}
s.render(w, r, "zones", "Zones", "Inspect authoritative and secondary zones and their state.", "zones", "DNS / ZONES", d)
}
func (s *Server) zoneCreateForm(w http.ResponseWriter, r *http.Request, fromFile bool) {
d := PageData{Form: map[string]string{}, Action: "new"}
if fromFile {
d.Action = "import"
}
s.render(w, r, "zone-form", "Create primary zone", "Define a new primary zone on EasyDNS.", "zones", "DNS / ZONES / CREATE", d)
}
func (s *Server) zoneCreate(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 2<<20)
if err := r.ParseForm(); err != nil {
http.Error(w, "Invalid form", 400)
return
}
d := PageData{Form: formValues(r, "name", "ns", "hostmaster", "transfer_acl", "notify", "zone_file", "mode")}
name := strings.TrimSpace(d.Form["name"])
isFile := d.Form["mode"] == "import"
d.Action = "new"
if isFile {
d.Action = "import"
}
if name == "" {
d.Error = "Zone name is required."
s.render(w, r, "zone-form", "Create primary zone", "Define a new primary zone.", "zones", "DNS / ZONES / CREATE", d)
return
}
payload := map[string]any{"name": name, "transfer_acl": splitLines(d.Form["transfer_acl"]), "notify": splitLines(d.Form["notify"])}
if isFile {
if strings.TrimSpace(d.Form["zone_file"]) == "" {
d.Error = "Full zone file text is required."
} else {
payload["zone_file"] = d.Form["zone_file"]
}
} else {
ns := splitLines(d.Form["ns"])
if len(ns) == 0 {
d.Error = "At least one nameserver is required."
} else {
payload["ns"] = ns
}
if strings.TrimSpace(d.Form["hostmaster"]) != "" {
payload["hostmaster"] = strings.TrimSpace(d.Form["hostmaster"])
}
}
if d.Error != "" {
s.render(w, r, "zone-form", "Create primary zone", "Define a new primary zone.", "zones", "DNS / ZONES / CREATE", d)
return
}
var res struct {
Name string `json:"name"`
}
if err := s.api.Write(r.Context(), "POST", "/api/v1/zones", payload, "", &res); err != nil {
d.Error = err.Error()
s.render(w, r, "zone-form", "Create primary zone", "Define a new primary zone.", "zones", "DNS / ZONES / CREATE", d)
return
}
if res.Name == "" {
res.Name = name
}
redirect(w, r, "/zones/"+easydns.Escape(res.Name)+"?notice=zone-created")
}
func splitLines(s string) []string {
f := strings.FieldsFunc(s, func(r rune) bool { return r == '\n' || r == '\r' || r == ',' })
a := []string{}
for _, x := range f {
if x = strings.TrimSpace(x); x != "" {
a = append(a, x)
}
}
return a
}
func (s *Server) zoneRouter(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/zones/")
p := strings.Split(path, "/")
if len(p) == 0 || p[0] == "" {
http.NotFound(w, r)
return
}
zone, e := url.PathUnescape(p[0])
if e != nil || strings.ContainsAny(zone, "/\\\x00") || len(zone) > 255 {
http.Error(w, "Invalid zone name", 400)
return
}
rest := p[1:]
key := strings.Join(rest, "/")
switch {
case key == "" && r.Method == "GET":
s.zoneDetail(w, r, zone, "overview")
case key == "records" && r.Method == "GET":
s.zoneDetail(w, r, zone, "records")
case key == "records" && r.Method == "POST":
s.recordSave(w, r, zone, "")
case key == "records/new" && r.Method == "GET":
s.recordForm(w, r, zone, "")
case key == "transfers" && r.Method == "GET":
s.zoneDetail(w, r, zone, "transfers")
case key == "dnssec" && r.Method == "GET":
s.zoneDetail(w, r, zone, "dnssec")
case key == "operations" && r.Method == "GET":
s.zoneDetail(w, r, zone, "operations")
case key == "replace" && r.Method == "GET":
s.zoneReplaceForm(w, r, zone)
case key == "replace" && r.Method == "POST":
s.zoneReplace(w, r, zone)
case key == "delete" && r.Method == "GET":
s.zoneDeleteForm(w, r, zone)
case key == "delete" && r.Method == "POST":
s.zoneDelete(w, r, zone)
case key == "notify" && r.Method == "POST":
s.zoneAction(w, r, zone, "notify")
case key == "sync" && r.Method == "POST":
s.zoneAction(w, r, zone, "sync")
case len(rest) == 3 && rest[0] == "records" && rest[2] == "edit" && r.Method == "GET":
s.recordForm(w, r, zone, rest[1])
case len(rest) == 3 && rest[0] == "records" && rest[2] == "delete" && r.Method == "GET":
s.recordDeleteForm(w, r, zone, rest[1])
case len(rest) == 3 && rest[0] == "records" && rest[2] == "delete" && r.Method == "POST":
s.recordDelete(w, r, zone, rest[1])
case len(rest) == 2 && rest[0] == "records" && r.Method == "POST":
s.recordSave(w, r, zone, rest[1])
default:
http.NotFound(w, r)
}
}
func (s *Server) readZone(ctx context.Context, zone string) (easydns.Zone, string, error) {
var out easydns.Zone
etag, err := s.api.Get(ctx, "/api/v1/zones/"+easydns.Escape(zone), &out)
return out, etag, err
}
func (s *Server) zoneDetail(w http.ResponseWriter, r *http.Request, name, tab string) {
d := PageData{Tab: tab, ZoneURL: "/zones/" + easydns.Escape(name)}
zone, etag, err := s.readZone(r.Context(), name)
if err != nil {
d.Error = err.Error()
} else {
d.Zone = zone
d.ETag = etag
d.IsPrimary = zone.IsPrimary()
}
if tab == "records" {
v := r.URL.Query()
query := url.Values{"page": {strconv.Itoa(getInt(v.Get("page"), 1, 1, 100000))}, "per_page": {"50"}}
d.Filter = map[string]string{"name": v.Get("name"), "type": v.Get("type")}
for _, k := range []string{"name", "type"} {
if v := strings.TrimSpace(d.Filter[k]); v != "" {
query.Set(k, v)
}
}
var p easydns.Page[easydns.Record]
if e, er := s.api.Get(r.Context(), "/api/v1/zones/"+easydns.Escape(name)+"/records?"+query.Encode(), &p); er != nil {
if d.Error == "" {
d.Error = er.Error()
}
} else {
d.Records = p.Items
d.Pagination = p.Pagination
if e != "" {
d.ETag = e
}
}
}
if tab == "transfers" {
var a struct {
Items []easydns.Transfer `json:"items"`
}
if e := s.get(r.Context(), "/api/v1/zones/"+easydns.Escape(name)+"/transfers", &a); e != nil {
if d.Error == "" {
d.Error = e.Error()
}
} else {
d.Transfers = a.Items
}
}
s.render(w, r, "zone", "Zone · "+name, "Zone state, records, transfers and diagnostics.", "zones", "DNS / ZONES / "+name, d)
}
func (s *Server) findRecord(ctx context.Context, zone, id string, pageHint int) (easydns.Record, string, error) {
// There is no individual-record GET. Search the real paginated list by its stable ID.
page := pageHint
if page < 1 {
page = 1
}
for n := 0; n < 100; n++ {
var records easydns.Page[easydns.Record]
path := fmt.Sprintf("/api/v1/zones/%s/records?page=%d&per_page=1000", easydns.Escape(zone), page)
etag, err := s.api.Get(ctx, path, &records)
if err != nil {
return easydns.Record{}, "", err
}
for _, rec := range records.Items {
if rec.ID == id {
return rec, etag, nil
}
}
if page*1000 >= records.Pagination.Total {
break
}
page++
}
return easydns.Record{}, "", &easydns.Error{Status: 404, Message: "record not found in zone record listing"}
}
func (s *Server) recordForm(w http.ResponseWriter, r *http.Request, zone, id string) {
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), Form: map[string]string{"ttl": "3600"}, Action: "new"}
z, _, err := s.readZone(r.Context(), zone)
if err != nil {
d.Error = err.Error()
} else {
d.Zone = z
d.IsPrimary = z.IsPrimary()
}
if id != "" {
d.Action = "edit"
rec, etag, err := s.findRecord(r.Context(), zone, id, getInt(r.URL.Query().Get("page"), 1, 1, 100000))
if err != nil {
d.Error = err.Error()
} else {
d.Record = rec
d.ETag = etag
d.Form = map[string]string{"name": rec.Name, "type": rec.Type, "ttl": strconv.FormatUint(uint64(rec.TTL), 10), "data": rec.Data}
}
} else {
var p easydns.Page[easydns.Record]
etag, err := s.api.Get(r.Context(), "/api/v1/zones/"+easydns.Escape(zone)+"/records?per_page=1", &p)
if err != nil {
d.Error = err.Error()
} else {
d.ETag = etag
}
}
s.render(w, r, "record-form", map[bool]string{true: "Edit DNS record", false: "Add DNS record"}[id != ""], "Modify an authoritative zone with serial conflict protection.", "zones", "DNS / ZONES / "+zone+" / RECORDS", d)
}
func (s *Server) recordSave(w http.ResponseWriter, r *http.Request, zone, id string) {
r.Body = http.MaxBytesReader(w, r.Body, 16<<10)
if e := r.ParseForm(); e != nil {
http.Error(w, "Invalid form", 400)
return
}
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), Action: "new", Form: formValues(r, "name", "type", "ttl", "data"), ETag: r.FormValue("etag")}
if id != "" {
d.Action = "edit"
d.Record.ID = id
}
z, _, e := s.readZone(r.Context(), zone)
if e != nil {
d.Error = e.Error()
} else {
d.Zone = z
d.IsPrimary = z.IsPrimary()
}
if e == nil && !z.IsPrimary() {
d.Error = "Records may only be changed on primary zones."
}
ttl, parseErr := strconv.ParseUint(strings.TrimSpace(d.Form["ttl"]), 10, 32)
if parseErr != nil || d.Form["name"] == "" || d.Form["type"] == "" || strings.TrimSpace(d.Form["data"]) == "" {
d.Error = "Name, type and data are required; TTL must be an integer between 0 and 4294967295."
}
if strings.EqualFold(d.Form["type"], "SOA") {
d.Error = "SOA is managed by zone replacement, not record CRUD."
}
if d.ETag == "" {
d.Error = "No current ETag. Reload the record form to prevent overwriting concurrent changes."
}
if d.Error != "" {
s.render(w, r, "record-form", "DNS record", "Modify an authoritative zone.", "zones", "DNS / ZONES / RECORDS", d)
return
}
payload := map[string]any{"name": strings.TrimSpace(d.Form["name"]), "type": strings.ToUpper(d.Form["type"]), "ttl": ttl, "data": strings.TrimSpace(d.Form["data"])}
method, path, notice := "POST", "/api/v1/zones/"+easydns.Escape(zone)+"/records", "record-added"
if id != "" {
method = "PUT"
path += "/" + easydns.Escape(id)
notice = "record-updated"
}
var out any
e = s.api.Write(r.Context(), method, path, payload, d.ETag, &out)
if e != nil {
if ae, ok := e.(*easydns.Error); ok && ae.Status == 412 {
s.conflict(w, r, zone, e.Error())
return
}
d.Error = e.Error()
s.render(w, r, "record-form", "DNS record", "Modify an authoritative zone.", "zones", "DNS / ZONES / RECORDS", d)
return
}
redirect(w, r, "/zones/"+easydns.Escape(zone)+"/records?notice="+notice)
}
func (s *Server) conflict(w http.ResponseWriter, r *http.Request, zone, msg string) {
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), Error: msg}
s.render(w, r, "conflict", "Zone changed", "Another modification changed the zone serial. Reload records before editing again.", "zones", "DNS / ZONES / CONFLICT", d)
}
func (s *Server) recordDeleteForm(w http.ResponseWriter, r *http.Request, zone, id string) {
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), Action: "record"}
rec, etag, e := s.findRecord(r.Context(), zone, id, getInt(r.URL.Query().Get("page"), 1, 1, 100000))
if e != nil {
d.Error = e.Error()
} else {
d.Record = rec
d.ETag = etag
if strings.EqualFold(rec.Type, "SOA") {
d.Error = "SOA cannot be deleted using the record API."
}
}
s.render(w, r, "delete-confirm", "Delete DNS record", "Confirm permanent removal of a DNS record.", "zones", "DNS / ZONES / RECORDS / DELETE", d)
}
func (s *Server) recordDelete(w http.ResponseWriter, r *http.Request, zone, id string) {
if r.FormValue("confirm") != "DELETE" {
http.Error(w, "Type DELETE to confirm", 400)
return
}
etag := r.FormValue("etag")
if etag == "" {
http.Error(w, "Missing zone serial. Reload.", 409)
return
}
if e := s.api.Write(r.Context(), "DELETE", "/api/v1/zones/"+easydns.Escape(zone)+"/records/"+easydns.Escape(id), nil, etag, nil); e != nil {
if ae, ok := e.(*easydns.Error); ok && ae.Status == 412 {
s.conflict(w, r, zone, e.Error())
return
}
d := PageData{Error: e.Error(), Action: "record", Record: easydns.Record{ID: id}, ZoneURL: "/zones/" + easydns.Escape(zone), ETag: etag}
s.render(w, r, "delete-confirm", "Delete DNS record", "Delete operation failed.", "zones", "DNS / ZONES / DELETE", d)
return
}
redirect(w, r, "/zones/"+easydns.Escape(zone)+"/records?notice=record-deleted")
}
func (s *Server) zoneReplaceForm(w http.ResponseWriter, r *http.Request, zone string) {
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), Form: map[string]string{}}
z, etag, e := s.readZone(r.Context(), zone)
if e != nil {
d.Error = e.Error()
} else {
d.Zone = z
d.ETag = etag
d.IsPrimary = z.IsPrimary()
}
s.render(w, r, "replace-zone", "Replace zone file", "Submit a complete zone file. The original text cannot be retrieved from the API.", "zones", "DNS / ZONES / REPLACE", d)
}
func (s *Server) zoneReplace(w http.ResponseWriter, r *http.Request, zone string) {
r.Body = http.MaxBytesReader(w, r.Body, 2<<20)
if e := r.ParseForm(); e != nil {
http.Error(w, "Invalid form", 400)
return
}
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), ETag: r.FormValue("etag"), Form: formValues(r, "zone_file")}
if d.ETag == "" || d.Form["zone_file"] == "" || r.FormValue("confirm") != "REPLACE" {
d.Error = "Full zone file, current ETag and the word REPLACE are required."
} else {
e := s.api.Write(r.Context(), "PUT", "/api/v1/zones/"+easydns.Escape(zone), map[string]string{"zone_file": d.Form["zone_file"]}, d.ETag, nil)
if e == nil {
redirect(w, r, d.ZoneURL+"?notice=zone-replaced")
return
}
if ae, ok := e.(*easydns.Error); ok && ae.Status == 412 {
s.conflict(w, r, zone, e.Error())
return
}
d.Error = e.Error()
}
s.render(w, r, "replace-zone", "Replace zone file", "Submit a complete zone file.", "zones", "DNS / ZONES / REPLACE", d)
}
func (s *Server) zoneDeleteForm(w http.ResponseWriter, r *http.Request, zone string) {
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), Action: "zone"}
z, _, e := s.readZone(r.Context(), zone)
if e != nil {
d.Error = e.Error()
} else {
d.Zone = z
}
s.render(w, r, "delete-confirm", "Delete zone", "Only API-created zones can be deleted. File-configured zones return HTTP 409.", "zones", "DNS / ZONES / DELETE", d)
}
func (s *Server) zoneDelete(w http.ResponseWriter, r *http.Request, zone string) {
if r.FormValue("confirm") != zone {
d := PageData{Error: "Type the full zone name exactly to confirm.", ZoneURL: "/zones/" + easydns.Escape(zone), Zone: easydns.Zone{Name: zone}, Action: "zone"}
s.render(w, r, "delete-confirm", "Delete zone", "Confirm deletion.", "zones", "DNS / ZONES / DELETE", d)
return
}
e := s.api.Write(r.Context(), "DELETE", "/api/v1/zones/"+easydns.Escape(zone), nil, "", nil)
if e != nil {
d := PageData{Error: e.Error(), ZoneURL: "/zones/" + easydns.Escape(zone), Zone: easydns.Zone{Name: zone}, Action: "zone"}
s.render(w, r, "delete-confirm", "Delete zone", "Delete failed.", "zones", "DNS / ZONES / DELETE", d)
return
}
redirect(w, r, "/zones?notice=zone-deleted")
}
func (s *Server) zoneAction(w http.ResponseWriter, r *http.Request, zone, action string) {
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), Tab: "operations"}
z, _, e := s.readZone(r.Context(), zone)
if e != nil {
d.Error = e.Error()
} else {
d.Zone = z
d.IsPrimary = z.IsPrimary()
}
if e == nil && action == "sync" && !z.IsSecondary() {
d.Error = "Sync is only valid for a secondary zone."
}
if e == nil && action == "notify" && len(z.Config.Notify) == 0 {
d.Error = "No NOTIFY targets configured for this zone."
}
if d.Error == "" {
if r.FormValue("confirm") != "yes" {
d.Error = "Confirm the requested zone operation."
} else {
var result any
err := s.api.Write(r.Context(), "POST", "/api/v1/zones/"+easydns.Escape(zone)+"/"+action, nil, "", &result)
if err != nil {
d.Error = err.Error()
} else {
redirect(w, r, d.ZoneURL+"/operations?notice="+map[string]string{"sync": "synced", "notify": "notified"}[action])
return
}
}
}
s.render(w, r, "zone", "Zone · "+zone, "Zone operations.", "zones", "DNS / ZONES / "+zone, d)
}
+298
View File
@@ -0,0 +1,298 @@
package server
import (
"context"
"encoding/json"
"fmt"
"html/template"
"log/slog"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/config"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/telemetry"
)
var Version = "dev"
func New(cfg config.Config) (*Server, error) {
a, err := newAuth(cfg)
if err != nil {
return nil, fmt.Errorf("panel auth: %w", err)
}
client, err := easydns.New(cfg.APIURL, cfg.TokenFile, cfg.APISocket)
if err != nil {
return nil, err
}
ts, err := loadTemplates()
if err != nil {
return nil, err
}
return &Server{cfg: cfg, api: client, telemetry: telemetry.New(), auth: a, templates: ts}, nil
}
func (s *Server) Run(ctx context.Context) error {
go s.telemetry.Run(ctx, s.api)
httpServer := &http.Server{Addr: s.cfg.Listen, Handler: s.Handler(), ReadHeaderTimeout: 7 * time.Second, ReadTimeout: 20 * time.Second, WriteTimeout: 80 * time.Second, IdleTimeout: 90 * time.Second, MaxHeaderBytes: 1 << 20}
go func() {
<-ctx.Done()
down, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
_ = httpServer.Shutdown(down)
}()
slog.Info("EasyDNS UI started", "listen", s.cfg.Listen, "api_mode", func() string {
if s.cfg.APISocket != "" {
return "unix"
}
return "tcp"
}())
err := httpServer.ListenAndServe()
if err == http.ErrServerClosed {
return nil
}
return err
}
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.Handle("GET /static/", http.StripPrefix("/static/", staticHandler()))
mux.HandleFunc("GET /login", s.loginPage)
mux.HandleFunc("POST /login", s.loginPost)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, _ = w.Write([]byte("easydns-ui: ok\n"))
})
mux.HandleFunc("/", s.authorized)
return secureHeaders(mux)
}
func (s *Server) authorized(w http.ResponseWriter, r *http.Request) {
sess, ok := s.auth.parseSession(r)
if !ok {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
w.Header().Set("Cache-Control", "no-store")
if r.Method == "POST" && !s.auth.checkCSRF(r, sess) {
http.Error(w, "Invalid CSRF token or Origin", http.StatusForbidden)
return
}
if r.Method != "GET" && r.Method != "HEAD" && r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
csrf := s.auth.csrf(sess)
ctx := context.WithValue(r.Context(), csrfKey{}, csrf)
r = r.WithContext(ctx)
switch {
case r.URL.Path == "/logout" && r.Method == "POST":
s.auth.setCookie(w, "", -1)
http.Redirect(w, r, "/login", http.StatusSeeOther)
case r.URL.Path == "/" && r.Method == "GET":
s.overview(w, r)
case r.URL.Path == "/ui/telemetry" && r.Method == "GET":
s.telemetryJSON(w, r)
case r.URL.Path == "/zones" && r.Method == "GET":
s.zones(w, r)
case r.URL.Path == "/zones/new" && r.Method == "GET":
s.zoneCreateForm(w, r, false)
case r.URL.Path == "/zones/import" && r.Method == "GET":
s.zoneCreateForm(w, r, true)
case r.URL.Path == "/zones" && r.Method == "POST":
s.zoneCreate(w, r)
case r.URL.Path == "/query" && r.Method == "GET":
s.query(w, r)
case r.URL.Path == "/upstreams" && r.Method == "GET":
s.upstreams(w, r)
case r.URL.Path == "/upstreams/new" && r.Method == "GET":
s.upstreamForm(w, r)
case r.URL.Path == "/upstreams" && r.Method == "POST":
s.upstreamCreate(w, r)
case r.URL.Path == "/policies" && r.Method == "GET":
s.policies(w, r)
case r.URL.Path == "/policies" && r.Method == "POST":
s.policiesSave(w, r)
case r.URL.Path == "/views" && r.Method == "GET":
s.policiesReadOnly(w, r, "views")
case r.URL.Path == "/acl" && r.Method == "GET":
s.policiesReadOnly(w, r, "acl")
case r.URL.Path == "/rate-limiting" && r.Method == "GET":
s.policiesReadOnly(w, r, "rate")
case r.URL.Path == "/blocklists" && r.Method == "GET":
s.blocklists(w, r)
case r.URL.Path == "/blocklists/new" && r.Method == "GET":
s.blockForm(w, r)
case r.URL.Path == "/blocklists" && r.Method == "POST":
s.blockCreate(w, r)
case r.URL.Path == "/cache" && r.Method == "GET":
s.cache(w, r)
case r.URL.Path == "/cache/flush" && r.Method == "POST":
s.cacheFlush(w, r)
case r.URL.Path == "/metrics" && r.Method == "GET":
s.metrics(w, r)
case r.URL.Path == "/audit" && r.Method == "GET":
s.audit(w, r)
case r.URL.Path == "/status" && r.Method == "GET":
s.status(w, r)
case r.URL.Path == "/configuration" && r.Method == "GET":
s.configuration(w, r)
case r.URL.Path == "/configuration/reload" && r.Method == "POST":
s.reload(w, r)
case strings.HasPrefix(r.URL.Path, "/zones/"):
s.zoneRouter(w, r)
default:
http.NotFound(w, r)
}
}
type csrfKey struct{}
func csrf(r *http.Request) string {
if v, ok := r.Context().Value(csrfKey{}).(string); ok {
return v
}
return ""
}
func (s *Server) render(w http.ResponseWriter, r *http.Request, page, title, subtitle, active, breadcrumb string, d PageData) {
t, ok := s.templates[page]
if !ok {
http.Error(w, "Missing template", http.StatusInternalServerError)
return
}
alert, kind := notice(r.URL.Query().Get("notice"))
if d.Success != "" {
alert = d.Success
kind = "ok"
}
if d.Error != "" {
alert = d.Error
kind = "danger"
}
v := PageView{Page: page, Title: title, Subtitle: subtitle, Active: active, Breadcrumb: breadcrumb, User: s.cfg.Username, CSRF: csrf(r), Message: alert, MessageType: kind, Data: d, BuildVersion: Version}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := t.ExecuteTemplate(w, "base", v); err != nil {
slog.Error("render", "page", page, "err", err)
}
}
func notice(n string) (string, string) {
switch n {
case "zone-created":
return "Primary zone created successfully.", "ok"
case "zone-deleted":
return "API-managed zone deleted.", "ok"
case "zone-replaced":
return "Zone contents replaced; the zone serial was updated.", "ok"
case "record-added":
return "DNS record created.", "ok"
case "record-updated":
return "DNS record updated.", "ok"
case "record-deleted":
return "DNS record deleted.", "ok"
case "notified":
return "DNS NOTIFY accepted for configured targets. Delivery is not guaranteed.", "ok"
case "synced":
return "Secondary synchronization request completed.", "ok"
case "upstream-added":
return "Upstream added and configuration reloaded.", "ok"
case "policy-updated":
return "Supported policy settings saved.", "ok"
case "rule-added":
return "Block rule added.", "ok"
case "cache-flushed":
return "Cache invalidation completed.", "ok"
case "reloaded":
return "Configuration hot reload completed.", "ok"
case "session-ended":
return "Signed out.", "ok"
default:
return "", ""
}
}
func redirect(w http.ResponseWriter, r *http.Request, target string) {
http.Redirect(w, r, target, http.StatusSeeOther)
}
func (s *Server) get(ctx context.Context, path string, out any) error {
_, err := s.api.Get(ctx, path, out)
return err
}
func (s *Server) telemetryJSON(w http.ResponseWriter, _ *http.Request) {
smp, errText, last := s.telemetry.Snapshot()
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(map[string]any{"samples": smp, "error": errText, "lastPoll": last, "intervalSeconds": 15})
}
func (s *Server) loginPage(w http.ResponseWriter, r *http.Request) {
if _, ok := s.auth.parseSession(r); ok {
redirect(w, r, "/")
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
_ = s.templates["login"].ExecuteTemplate(w, "login", map[string]any{"Error": "", "Username": s.cfg.Username})
}
func (s *Server) loginPost(w http.ResponseWriter, r *http.Request) {
if !sameOrigin(r) {
http.Error(w, "Origin denied", http.StatusForbidden)
return
}
r.Body = http.MaxBytesReader(w, r.Body, 8<<10)
if err := r.ParseForm(); err != nil {
http.Error(w, "Invalid form", http.StatusBadRequest)
return
}
ip := remoteIP(r)
pass := r.Form.Get("password")
u := r.Form.Get("username")
if !s.auth.allowedLogin(ip) {
w.WriteHeader(http.StatusTooManyRequests)
_ = s.templates["login"].ExecuteTemplate(w, "login", map[string]any{"Error": "Too many attempts. Try again later.", "Username": s.cfg.Username})
return
}
if !s.auth.verify(u, pass) {
s.auth.failLogin(ip)
w.WriteHeader(http.StatusUnauthorized)
_ = s.templates["login"].ExecuteTemplate(w, "login", map[string]any{"Error": "Invalid credentials.", "Username": s.cfg.Username})
return
}
s.auth.clearFailure(ip)
s.auth.setCookie(w, s.auth.makeSession(), int(sessionTTL.Seconds()))
redirect(w, r, "/")
}
func getInt(v string, def, min, max int) int {
n, err := strconv.Atoi(v)
if err != nil || n < min {
return def
}
if n > max {
return max
}
return n
}
func formValues(r *http.Request, keys ...string) map[string]string {
m := make(map[string]string, len(keys))
for _, k := range keys {
m[k] = r.FormValue(k)
}
return m
}
func failAPI(d *PageData, err error) {
if err != nil {
d.Error = err.Error()
}
}
func encQ(values url.Values) string {
if len(values) == 0 {
return ""
}
return "?" + values.Encode()
}
func callError(err error) string {
if err == nil {
return ""
}
return err.Error()
}
func stringTrim(v string) string { return strings.TrimSpace(v) }
var _ = template.HTML("")
+122
View File
@@ -0,0 +1,122 @@
package server
import (
"fmt"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/config"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
)
func testPanel(t *testing.T, api http.Handler) *Server {
t.Helper()
dir := t.TempDir()
password := filepath.Join(dir, "password")
key := filepath.Join(dir, "session.key")
token := filepath.Join(dir, "control.token")
for f, v := range map[string]string{password: "admin-test-password-long", key: strings.Repeat("a", 64), token: "generated-admin-token"} {
if e := os.WriteFile(f, []byte(v), 0600); e != nil {
t.Fatal(e)
}
}
backend := httptest.NewServer(api)
t.Cleanup(backend.Close)
s, e := New(config.Config{Listen: "127.0.0.1:0", APIURL: backend.URL, TokenFile: token, PasswordFile: password, SessionKeyFile: key, Username: "admin"})
if e != nil {
t.Fatal(e)
}
return s
}
func TestLoginAndCSRF(t *testing.T) {
s := testPanel(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"status":"ok"}`)
}))
h := s.Handler()
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("GET", "http://example.test/zones", nil))
if w.Code != 303 || w.Header().Get("Location") != "/login" {
t.Fatalf("route without login=%d %s", w.Code, w.Header().Get("Location"))
}
form := url.Values{"username": {"admin"}, "password": {"admin-test-password-long"}}
w = httptest.NewRecorder()
r := httptest.NewRequest("POST", "http://example.test/login", strings.NewReader(form.Encode()))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
h.ServeHTTP(w, r)
if w.Code != 303 || len(w.Result().Cookies()) == 0 {
t.Fatalf("login failed: %d", w.Code)
}
cookie := w.Result().Cookies()[0]
r = httptest.NewRequest("POST", "http://example.test/policies", strings.NewReader("block_action=nxdomain"))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
r.AddCookie(cookie)
w = httptest.NewRecorder()
h.ServeHTTP(w, r)
if w.Code != 403 {
t.Fatalf("missing CSRF was accepted: %d", w.Code)
}
r = httptest.NewRequest("GET", "http://example.test/zones", nil)
r.AddCookie(cookie)
w = httptest.NewRecorder()
h.ServeHTTP(w, r)
if w.Code != 200 || !strings.Contains(w.Body.String(), "EasyDNS") {
t.Fatalf("authenticated GET failed: %d %s", w.Code, w.Body.String())
}
if strings.Contains(w.Body.String(), "API v1") {
t.Fatal("visual artifact API v1 reappeared")
}
}
func TestRecordEditConflictPreservesETag(t *testing.T) {
var captured bool
s := testPanel(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/records/111") && r.Method == "PUT":
captured = true
if r.Header.Get("If-Match") != "\"10\"" {
t.Error("missing ETag match")
}
w.WriteHeader(412)
_, _ = io.WriteString(w, `{"error":{"status":412,"message":"zone serial changed"}}`)
case strings.HasPrefix(r.URL.Path, "/api/v1/zones/") && !strings.Contains(r.URL.Path, "/records"):
_, _ = io.WriteString(w, `{"name":"example.com.","kind":"primary","serial":10,"loaded":true,"records":1}`)
default:
t.Logf("unexpected test request %s %s", r.Method, r.URL.Path)
w.WriteHeader(404)
}
}))
form := url.Values{"name": {"www"}, "type": {"A"}, "ttl": {"300"}, "data": {"192.0.2.10"}, "etag": {"\"10\""}}
r := httptest.NewRequest("POST", "http://example.test/zones/example.com./records/111", strings.NewReader(form.Encode()))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
sess := s.auth.makeSession()
r.AddCookie(&http.Cookie{Name: sessionCookie, Value: sess})
r.PostForm = form
form.Set("_csrf", s.auth.csrf(strings.Join(strings.Split(sess, ".")[:2], ".")))
r = httptest.NewRequest("POST", "http://example.test/zones/example.com./records/111", strings.NewReader(form.Encode()))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
r.AddCookie(&http.Cookie{Name: sessionCookie, Value: sess})
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
if !captured {
t.Fatal("no PUT operation reached EasyDNS")
}
if w.Code != 200 || !strings.Contains(w.Body.String(), "Zone changed") {
t.Fatalf("missing conflict UI: status=%d %s", w.Code, w.Body.String())
}
}
func TestNoAPISecretsInRenderedTemplates(t *testing.T) {
s := testPanel(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"status":"ok"}`) }))
sess := s.auth.makeSession()
r := httptest.NewRequest("GET", "http://example.test/", nil)
r.AddCookie(&http.Cookie{Name: sessionCookie, Value: sess})
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
if strings.Contains(w.Body.String(), "generated-admin-token") {
t.Fatal("generated API bearer leaked to browser")
}
}
+206
View File
@@ -0,0 +1,206 @@
package server
import (
"embed"
"encoding/json"
"fmt"
"html/template"
"io/fs"
"net/http"
"strconv"
"strings"
"time"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/config"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/telemetry"
)
//go:embed web/templates/*.gohtml web/templates/pages/*.gohtml web/static/* web/static/vendor/*
var assets embed.FS
type PageData struct {
Status easydns.Status
Health easydns.Health
Stats easydns.Stats
Cache easydns.Cache
Zone easydns.Zone
Zones []easydns.Zone
Records []easydns.Record
Record easydns.Record
Pagination easydns.Pagination
Transfers []easydns.Transfer
Upstreams []easydns.UpstreamGroup
Policies easydns.Policies
Blocklists easydns.Blocklists
Audit []easydns.AuditItem
Query *easydns.QueryResult
Form map[string]string
Filter map[string]string
ETag string
ZoneURL string
IsPrimary bool
Error string
Success string
Action string
Tab string
FieldErrors map[string]string
SamplingCount int
SamplingTime time.Time
SamplingError string
LastRate string
}
type PageView struct {
Title, Subtitle, Page, Active, Breadcrumb, User, CSRF, Message, MessageType string
Data PageData
Body template.HTML
BuildVersion string
}
type Server struct {
cfg config.Config
api *easydns.Client
telemetry *telemetry.History
auth *auth
templates map[string]*template.Template
}
func funcs() template.FuncMap {
return template.FuncMap{
"recordTypes": func() []string {
return []string{"A", "AAAA", "CNAME", "MX", "TXT", "NS", "PTR", "SRV", "CAA", "DS", "DNSKEY", "TLSA", "SSHFP", "NAPTR"}
},
"blockActions": func() []string { return []string{"nxdomain", "refused", "null", "address", "nodata"} },
"auditSizes": func() []int { return []int{25, 50, 100, 250, 500, 1000} },
"inc": func(v int) int { return v + 1 },
"dec": func(v int) int { return v - 1 },
"multiply": func(a, b int) int { return a * b },
"int": func(v any) string {
var n string
switch t := v.(type) {
case int:
n = strconv.Itoa(t)
case int64:
n = strconv.FormatInt(t, 10)
case uint32:
n = strconv.FormatUint(uint64(t), 10)
case uint64:
n = strconv.FormatUint(t, 10)
default:
n = fmt.Sprint(v)
}
neg := ""
if strings.HasPrefix(n, "-") {
neg = "-"
n = n[1:]
}
for i := len(n) - 3; i > 0; i -= 3 {
n = n[:i] + "," + n[i:]
}
return neg + n
},
"pct": func(v float64) string { return fmt.Sprintf("%.1f%%", v*100) },
"ms": func(v float64) string { return fmt.Sprintf("%.1f ms", v*1000) },
"float": func(v any) string {
switch x := v.(type) {
case float64:
return fmt.Sprintf("%.1f", x)
case *float64:
if x != nil {
return fmt.Sprintf("%.1f", *x)
}
}
return "—"
},
"uptime": func(v uint64) string {
d := v / 86400
h := (v % 86400) / 3600
m := (v % 3600) / 60
return fmt.Sprintf("%dd %dh %dm", d, h, m)
},
"when": func(unix int64) string {
if unix == 0 {
return "—"
}
return time.Unix(unix, 0).Local().Format("2006-01-02 15:04:05")
},
"zoneurl": func(v string) string { return "/zones/" + easydns.Escape(v) },
"join": strings.Join,
"get": func(m map[string]any, k string) any {
if m == nil {
return "—"
}
v, ok := m[k]
if !ok || v == nil {
return "—"
}
return v
},
"string": func(v any) string {
if v == nil {
return "—"
}
switch t := v.(type) {
case string:
return t
case []any:
parts := make([]string, 0, len(t))
for _, x := range t {
parts = append(parts, fmt.Sprint(x))
}
return strings.Join(parts, ", ")
case map[string]any:
raw, _ := json.Marshal(t)
return string(raw)
default:
return fmt.Sprint(t)
}
},
"asjson": func(v any) string { b, _ := json.MarshalIndent(v, "", " "); return string(b) },
"lower": strings.ToLower,
"eqkind": strings.EqualFold,
"selectval": func(m map[string]string, k string) string {
if m == nil {
return ""
}
return m[k]
},
"statusclass": func(v string) string {
v = strings.ToLower(v)
if v == "noerror" || v == "ok" || v == "healthy" || v == "loaded" {
return "ok"
}
if strings.Contains(v, "fail") || strings.Contains(v, "error") || strings.Contains(v, "expired") || strings.Contains(v, "not loaded") {
return "danger"
}
if strings.Contains(v, "pend") || strings.Contains(v, "degrad") || strings.Contains(v, "warning") {
return "warn"
}
return "ok"
},
"notempty": func(v string) bool { return strings.TrimSpace(v) != "" },
}
}
func loadTemplates() (map[string]*template.Template, error) {
names, err := fs.Glob(assets, "web/templates/pages/*.gohtml")
if err != nil {
return nil, err
}
result := make(map[string]*template.Template)
for _, name := range names {
page := strings.TrimSuffix(strings.TrimPrefix(name, "web/templates/pages/"), ".gohtml")
t, e := template.New("base").Funcs(funcs()).ParseFS(assets, "web/templates/base.gohtml", name)
if e != nil {
return nil, fmt.Errorf("template %s: %w", page, e)
}
result[page] = t
}
return result, nil
}
func staticHandler() http.Handler {
sub, err := fs.Sub(assets, "web/static")
if err != nil {
panic(err)
}
return http.FileServer(http.FS(sub))
}
+39
View File
@@ -0,0 +1,39 @@
/* EasyDNS operator UI — OLED palette inspired by the RustProxy control room.
Flat surfaces, no gradients, compact controls, measured chart emphasis. */
:root,[data-bs-theme=dark]{
color-scheme:dark;
--bg:#050807;--sidebar:#060908;--panel:#111614;--panel-alt:#151b17;--field:#0b100e;
--line:#323b37;--row:#29312d;--text:#eff3ed;--muted:#a5b1aa;--subtle:#7f9087;
--green:#a6d79d;--cyan:#6fcde0;--amber:#f2b42f;--red:#e88a8a;
--nav-active:#202b22;--sans:Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,"Segoe UI",Arial,sans-serif;
--mono:ui-monospace,"SFMono-Regular",Consolas,"Liberation Mono",monospace;
--bs-body-bg:var(--bg);--bs-body-color:var(--text);--bs-link-color:var(--text);
}
*{box-sizing:border-box}html{scroll-behavior:auto}body{margin:0;background:var(--bg);color:var(--text);font:13px/1.45 var(--sans);min-height:100vh;overflow-x:hidden}a{color:inherit;text-decoration:none}a:hover{color:var(--green)}button,input,select,textarea{font:inherit}h1,h2,h3,p{margin:0}h2{font-size:14px;font-weight:650;letter-spacing:-.1px}h3{font-size:13px;font-weight:620}.mono{font-family:var(--mono);font-size:.94em}.upper{text-transform:uppercase}.muted{color:var(--muted)}.subtle{color:var(--subtle)}.success,.ok{color:var(--green)!important}.warning,.warn{color:var(--amber)!important}.danger{color:var(--red)!important}.tiny{font-size:11px}.break-any{overflow-wrap:anywhere}.sr-only{position:absolute!important;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.inline{display:inline}.right{text-align:right!important}.ellipsis{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:380px}.small-text{font-size:12px!important}.w-100{width:100%}.mt-panel{margin-top:13px!important}.mt-3{margin-top:12px!important}.mt-4{margin-top:19px!important}.mb-3{margin-bottom:12px!important}.mb-4{margin-bottom:18px!important}
.shell{display:grid;grid-template-columns:208px minmax(0,1fr);min-height:100vh}
.sidebar{background:var(--sidebar);border-right:1px solid var(--line);position:sticky;top:0;height:100vh;display:flex;flex-direction:column;z-index:21;padding:0 12px 14px}
.brand{height:66px;display:flex;align-items:center;padding:0 12px;border-bottom:1px solid var(--line);flex-shrink:0}
.brand a{color:#f4f8f4;font-size:24px;font-weight:720;letter-spacing:-.8px}
.sidebar-content{padding-top:16px;overflow:auto;scrollbar-width:thin;scrollbar-color:#39453d transparent}
.nav-section{font:10px/1.4 var(--mono);letter-spacing:.55px;color:#a1b5ad;padding:8px 12px 10px;margin-top:18px}.nav-section:first-child{margin-top:0}
.sidenav{display:flex;flex-direction:column;gap:2px}.sidenav>a{min-height:33px;display:flex;align-items:center;padding:7px 12px 7px 14px;color:#dbe2dc;border-left:2px solid transparent;transition:none;font-size:13px}.sidenav>a:hover{background:#161e19;color:#fff}.sidenav>a.active{border-left-color:#aadd9b;background:var(--nav-active);color:#fff;font-weight:620}
.sidebar-foot{margin-top:auto;padding:15px 12px 4px;color:#bdcbc1;border-top:1px solid var(--line);font-size:11px}.sidebar-foot small{display:block;color:var(--subtle);padding-left:13px;margin-top:3px}.indicator,.dot{display:inline-block;width:7px;height:7px;background:var(--green);border-radius:100%;margin-right:7px;vertical-align:1px;flex-shrink:0}.dot.warn{background:var(--amber)}.dot.danger{background:var(--red)}.dot.ok{background:var(--green)}
.workspace{min-width:0}.topbar{height:48px;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;gap:16px;padding:0 22px;background:#080b0a}
.breadcrumbs{font:11px/1.2 var(--mono);color:#c7d3ca;letter-spacing:.35px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.top-actions{display:flex;align-items:center;gap:7px;flex-shrink:0}.tool-button,.btn-ui{background:transparent;border:1px solid #49534c;color:#e0e7e0;min-height:31px;display:inline-flex;align-items:center;justify-content:center;gap:7px;padding:6px 11px;border-radius:3px;font-size:12px;font-weight:510;text-decoration:none;line-height:1.2;cursor:pointer;white-space:nowrap;transition:none}.tool-button:hover,.btn-ui:hover{border-color:#97ada0;color:#fff;background:#1a211e}.tool-button:focus-visible,.btn-ui:focus-visible,.field:focus-visible,.sidenav a:focus-visible{outline:2px solid var(--cyan);outline-offset:2px}.ico{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}.btn-primary-ui{border-color:#94c488;background:var(--green);color:#10200e;font-weight:690}.btn-primary-ui:hover{background:#b2e6a9;border-color:#b2e6a9;color:#10200e}.btn-danger-ui{border-color:#955651;color:#ffb5ad;background:#251612}.btn-danger-ui:hover{background:#3c2420;border-color:#d18a85;color:#fff}.btn-small{min-height:25px;padding:3px 8px;font-size:11px}.icon-button{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;color:#d5dfd7;border:1px solid transparent;border-radius:2px}.icon-button:hover{background:#242f29;color:#fff;border-color:#556256}.icon-button.danger-hover:hover{color:var(--red);border-color:#9d5955}.row-actions{display:flex;gap:3px;justify-content:flex-end}.mobile-menu{display:none}
.content{padding:17px 25px 26px;max-width:2220px;margin:0 auto;min-width:0}.page-head{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:19px}.eyebrow{font:10px/1.4 var(--mono);color:#a4d291;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px}.page-head h1{font-size:27px;line-height:1.15;font-weight:660;letter-spacing:-.65px}.page-subtitle{font-size:12px;color:#aebdb2;margin-top:4px}.page-head-right{align-self:flex-start;margin-top:5px}.operator-label{font:10px var(--mono);color:#a2ada5;border:1px solid var(--line);padding:6px 9px;border-radius:2px}
.panel{background:var(--panel);border:1px solid var(--line);border-radius:3px;min-width:0;box-shadow:none}.panel-head{padding:12px 14px;border-bottom:1px solid var(--row);display:flex;align-items:center;justify-content:space-between;gap:12px;min-height:48px}.panel-head p{font-size:11px;color:var(--muted);margin-top:2px}.panel-body{padding:16px}.panel-body.compact{padding:12px 14px}.panel-head.border-top{border-top:1px solid var(--line)}.text-link{font-size:11px;color:#9bcce0}.text-link:hover{text-decoration:underline}
.status-strip{display:grid;grid-template-columns:1.65fr repeat(4,1fr);align-items:stretch;min-height:70px;padding:10px 0;gap:0}.status-main{display:flex;flex-direction:column;justify-content:center;padding:0 20px}.status-heading{font-size:15px;display:flex;align-items:center;gap:6px;margin-bottom:3px}.status-heading .dot{width:9px;height:9px;margin-right:2px}.strip-cell{display:flex;flex-direction:column;gap:4px;justify-content:center;padding:0 17px;border-left:1px solid var(--line);min-width:0}.strip-cell:first-child{border-left:none}.strip-cell>span:first-child,.metric-label{color:#a9b7ac;font:10px/1.3 var(--mono);text-transform:uppercase;letter-spacing:.3px}.strip-cell strong{font-size:13px;line-height:1.3;font-weight:580;overflow-wrap:anywhere}.strip-cell small{color:var(--subtle);font-size:10px}.compact-strip{grid-template-columns:repeat(4,minmax(0,1fr))}.compact-strip .strip-cell:first-child{border:none}.zone-strip{grid-template-columns:repeat(6,minmax(0,1fr));min-height:76px}.zone-strip .strip-cell:first-child{border:none}
.metrics-grid{display:grid;gap:9px;margin:13px 0}.metrics-grid.six{grid-template-columns:repeat(6,minmax(0,1fr))}.metrics-grid.four{grid-template-columns:repeat(4,minmax(0,1fr))}.metric{min-height:93px;display:flex;flex-direction:column;justify-content:center;padding:12px 14px}.metric strong{font-size:24px;font-weight:650;line-height:1.3;letter-spacing:.2px;margin-top:4px;white-space:nowrap}.metric small{font-size:11px;color:var(--muted);margin-top:3px}.metric-row{max-width:290px}
.chart-grid{display:grid;gap:10px;margin-top:12px}.chart-grid.triple{grid-template-columns:repeat(3,minmax(0,1fr))}.chart-card{padding-bottom:8px;min-height:256px}.chart-card .panel-head{border-bottom:none;padding:12px 14px 6px;align-items:flex-start}.chart-card canvas{display:block;width:calc(100% - 24px);height:169px;margin:7px 12px 0;image-rendering:auto}.chart-foot{padding:8px 14px 1px;font:10px var(--mono);color:#bdcbc0;display:flex;align-items:center;gap:7px;flex-wrap:wrap}.legend-dot{display:inline-block;width:13px;height:2px;background:#aaa;vertical-align:middle}.legend-dot.cyan{background:var(--cyan)}.legend-dot.amber{background:var(--amber)}.legend-dot.red{background:var(--red)}.live-mark{font:9px var(--mono);color:#789c83;white-space:nowrap}
.dashboard-lower{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;margin-top:12px}.dashboard-lower.three-cards{margin-top:14px}.dashboard-lower>.panel{min-height:185px}.data-row{display:flex;justify-content:space-between;align-items:center;gap:12px;border-bottom:1px solid var(--row);padding:9px 0;min-height:34px;font-size:12px}.data-row:first-child{padding-top:4px}.data-row:last-child{border-bottom:none}.data-row span{color:#bac4bc;flex-shrink:0}.data-row strong{font-weight:550;text-align:right;color:#ecf2ed;max-width:67%;min-width:0;word-break:break-word}.data-row.mono{justify-content:flex-start}.barline{display:grid;grid-template-columns:100px minmax(0,1fr) 90px;align-items:center;gap:12px;padding:8px 0;font-size:11px}.barline strong{text-align:right;font:11px var(--mono)}.bar-track{display:block;height:8px;background:#29352f;border-radius:0;overflow:hidden}.bar-fill{display:block;height:100%;background:var(--green);width:0}.bar-fill.warn{background:var(--amber)}.bar-fill.danger{background:var(--red)}.bars-large{margin-top:15px}.bars-large .barline{padding:10px 0}.notice-inline{font-size:11px;color:#adbfae;background:#14201a;border-left:2px solid #739c71;padding:11px 14px;line-height:1.5}.notice{padding:11px 15px;border:1px solid #576951;background:#1b281e;color:#ddf0d8;border-radius:2px;margin-bottom:14px;display:flex;align-items:center;justify-content:space-between;gap:10px;font-size:12px;line-height:1.5}.notice.danger{background:#2b1c1c;color:#ffd2cb;border-color:#855a56}.notice.warn{background:#2d2519;color:#efd1a2;border-color:#756346}.notice-dismiss{border:none;background:none;color:inherit;font-size:18px;line-height:1;cursor:pointer}.empty{padding:28px 16px;text-align:center;color:var(--muted);font-size:12px}
.table-scroll{overflow-x:auto;scrollbar-color:#425049 transparent;scrollbar-width:thin}.data-table{border-collapse:collapse;table-layout:auto;width:100%;white-space:nowrap;font-size:12px}.data-table th{background:#121915;color:#a8b6ab;font:10px/1.35 var(--mono);text-transform:uppercase;letter-spacing:.45px;font-weight:500;text-align:left;padding:12px 13px;border-bottom:1px solid #455149}.data-table td{padding:9px 13px;border-bottom:1px solid var(--row);color:#d9e1da;height:38px;vertical-align:middle;max-width:630px;overflow-wrap:anywhere}.data-table tbody tr:hover td{background:#17211b}.data-table tbody tr:last-child td{border-bottom:none}.data-table .empty{text-align:center;padding:26px;white-space:normal}.data-table .entity,.entity{color:#f1f7f1;font-weight:610}.entity:hover{color:var(--green)}.data-table td.rdata{max-width:560px;white-space:normal;word-break:break-word}.tag{display:inline-block;font:10px/1.35 var(--mono);border:1px solid #647b55;color:#bbddac;padding:2px 6px;border-radius:2px;text-transform:uppercase;letter-spacing:.2px}.tag.blue{border-color:#597e8d;color:#9ccfe1}.tag.red{border-color:#915c58;color:#eda9a2}.tag.amber{border-color:#917245;color:#f2cb84}.tag.muted-tag{border-color:#546158;color:#a3b0a5}.table-footer{border-top:1px solid var(--row);padding:12px 14px;display:flex;gap:10px;align-items:center;justify-content:space-between;color:var(--muted);font-size:11px;min-height:49px}.pagination-ui{display:flex;align-items:center;gap:6px}
.toolbar{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:13px 13px;border-bottom:1px solid var(--line);min-height:55px}.toolbar-form{display:flex;gap:9px;align-items:center;flex-wrap:wrap}.toolbar-end{display:flex;align-items:center;gap:8px;flex-shrink:0}.toolbar-title h2{margin-bottom:3px}.toolbar-title p{color:var(--muted);font-size:11px}.field{width:100%;min-height:33px;border:1px solid #48564c;border-radius:2px;color:#f0f4ed;background:var(--field);padding:7px 11px;outline:none;box-shadow:none}.field:focus{border-color:#a4c493;box-shadow:0 0 0 1px #456d51}.field::placeholder{color:#77857c;opacity:1}.field[type=number]{appearance:textfield}.field[type=number]::-webkit-inner-spin-button{-webkit-appearance:none}.field-search{width:290px}.field-select{width:145px;cursor:pointer;padding-right:20px}.toolbar .field{min-height:31px}.field-label{font-size:12px;font-weight:570;color:#cfd8cd;display:block;margin-bottom:7px}textarea.field{resize:vertical;line-height:1.6}select.field{background-color:#0d120f}.required{color:var(--amber)}
.form-layout{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(280px,.78fr);gap:13px;align-items:start}.policy-layout{grid-template-columns:minmax(0,1.5fr) minmax(270px,1fr)}.form-body{padding:18px}.form-columns{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.field-row{margin-bottom:18px}.field-row:last-child{margin-bottom:0}.field-row small{font-size:11px;color:var(--subtle);display:block;margin-top:6px}.form-actions{display:flex;gap:9px;align-items:center;justify-content:flex-end;padding-top:18px;margin-top:11px;border-top:1px solid var(--row)}.form-actions .btn-ui{min-width:90px}.readout{display:flex;align-items:center;background:#19211b;color:#c7d1c7}.guide .panel-body p{font-size:12px;line-height:1.6;color:#b6c3b8}.guide .panel-body .data-row{font-size:11px}.guide h3{font-size:12px;margin-bottom:9px}.mode-tabs{display:flex;border-bottom:1px solid var(--line);padding:0 14px}.code-input{min-height:250px;font:12px/1.65 var(--mono)}.code-block{background:#090f0b;border:1px solid #313f33;border-radius:2px;padding:13px;overflow:auto;max-width:100%}.code-block pre,pre.code-block{margin:0;color:#bfdbc7;font:11px/1.6 var(--mono);white-space:pre-wrap;overflow-wrap:anywhere}.code-example{padding:10px;background:#0e1711;border:1px solid #314138;font-size:11px;line-height:2!important;color:#cbe3cd!important}.target-summary{border:1px solid #465147;background:#151e16;padding:10px 15px;margin:15px 0 20px}.confirmation-box{max-width:720px;margin:12px auto}.confirmation-box .panel-body>p{color:#becabf;line-height:1.7;margin:8px 0 20px}.confirmation-box .field{max-width:100%}.border-top{border-top:1px solid var(--line)!important}.operations-grid{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(250px,.9fr);gap:13px;margin-top:14px}.operation{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:15px 4px;border-bottom:1px solid var(--row)}.operation:last-child{border:0}.operation strong{display:block;font-size:12px}.operation small{display:block;font-size:11px;color:#9eada3;margin-top:4px}.operation .btn-ui{flex-shrink:0}.tabs{display:flex;align-items:center;gap:5px;margin:12px 0 14px;border-bottom:1px solid #374039;overflow-x:auto;white-space:nowrap}.tab{padding:11px 18px;display:inline-block;border-bottom:2px solid transparent;color:#bfc9bf;font-size:12px}.tab:hover{color:#fff;background:#171f1a}.tab.active{border-bottom-color:var(--green);color:#f6fff2;font-weight:640}.section-actions{display:flex;gap:9px;margin-top:14px}.pool-head{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 15px;background:#171e19;border-bottom:1px solid var(--line)}.pool-head h3{margin-bottom:3px}.pool-head+.table-scroll{margin-bottom:5px}.response-summary{display:flex;padding:15px 0;border-top:1px solid var(--line);border-bottom:1px solid var(--line);margin:0 16px;gap:0}.response-summary .strip-cell{flex:1}.response-summary .strip-cell:first-child{border-left:none}.danger-panel{border-color:#65413d}
.footer{display:flex;gap:18px;justify-content:space-between;border-top:1px solid #202a23;color:#697b6e;font-size:10px;padding-top:17px;margin-top:22px}.footer span{color:#68766c}
.mobile-menu{border:1px solid var(--line);background:#142019;color:#fff;padding:5px 9px;border-radius:2px}.sidebar-overlay{display:none}
.login-body{display:grid;place-items:center;min-height:100vh;background:#060908;padding:20px}.login-panel{width:min(440px,100%);background:#111613;border:1px solid #354237;border-radius:3px;padding:32px}.login-brand{font-size:29px;letter-spacing:-1px;font-weight:750;padding-bottom:24px;border-bottom:1px solid var(--line)}.overline{font:10px var(--mono);letter-spacing:1px;color:var(--green);margin-top:23px;margin-bottom:9px}.login-panel h1{font-size:27px;margin-bottom:8px}.login-panel .muted{color:var(--muted);line-height:1.6}.login-help{font-size:11px;color:#829185;line-height:1.6;margin:23px 0 0}
@media(max-width:1570px){.metrics-grid.six{grid-template-columns:repeat(3,minmax(0,1fr))}.chart-card canvas{height:160px}.barline{grid-template-columns:75px minmax(0,1fr) 72px}.strip-cell{padding-left:12px;padding-right:12px}}
@media(max-width:1130px){.shell{grid-template-columns:190px minmax(0,1fr)}.dashboard-lower{grid-template-columns:repeat(2,minmax(0,1fr))}.chart-grid.triple{grid-template-columns:repeat(2,minmax(0,1fr))}.form-layout{grid-template-columns:1fr}.toolbar{flex-wrap:wrap}.status-strip{grid-template-columns:repeat(3,minmax(0,1fr))}.status-main{min-height:53px}.zone-strip{grid-template-columns:repeat(3,minmax(0,1fr))}.operations-grid{grid-template-columns:1fr}}
@media(max-width:820px){.shell{grid-template-columns:1fr}.sidebar{position:fixed;transform:translateX(-100%);width:235px;transition:transform .12s ease;box-shadow:0 0 0 transparent}.sidebar.open{transform:translateX(0)}.sidebar-overlay.open{display:block;position:fixed;inset:0;background:#000b;z-index:20}.mobile-menu{display:block}.top-actions .tool-button span{display:none}.tool-button{padding:6px}.topbar{padding:0 12px}.content{padding:16px 13px}.page-head-right{display:none}.metrics-grid.six{grid-template-columns:repeat(2,minmax(0,1fr))}.status-strip,.compact-strip{grid-template-columns:repeat(2,minmax(0,1fr))}.status-main{grid-column:span 2}.status-strip .strip-cell:nth-child(2n){border-left:0}.field-search{width:180px}.footer span{display:none}}
@media(max-width:540px){.page-head h1{font-size:23px}.dashboard-lower,.chart-grid.triple,.metrics-grid.four,.metrics-grid.six,.form-columns{grid-template-columns:1fr}.toolbar-form{width:100%}.field-search{flex:1;min-width:150px}.toolbar-end{width:100%;justify-content:flex-end}.status-strip{grid-template-columns:repeat(2,minmax(0,1fr))}.zone-strip{grid-template-columns:repeat(2,minmax(0,1fr))}.strip-cell{padding:9px 12px}.status-main{padding:8px 12px}.page-subtitle{font-size:11px}.operator-label,.desktop-only{display:none}.chart-card canvas{height:165px}}
@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}
+18
View File
@@ -0,0 +1,18 @@
/* EasyDNS UI progressive enhancements. No secrets, auth state or API tokens in JS. */
(() => {
'use strict';
const side = document.getElementById('sidebar');
const toggle = document.getElementById('menuToggle');
const cover = document.getElementById('sidebarOverlay');
const close = () => { side?.classList.remove('open'); cover?.classList.remove('open'); toggle?.setAttribute('aria-expanded', 'false'); };
toggle?.addEventListener('click', () => {const on = side.classList.toggle('open');cover?.classList.toggle('open', on);toggle.setAttribute('aria-expanded', String(on));});
cover?.addEventListener('click', close);
document.addEventListener('keydown', e => {if(e.key === 'Escape') close();});
document.querySelectorAll('.notice-dismiss').forEach(el => el.addEventListener('click', () => el.closest('.notice')?.remove()));
document.querySelectorAll('.bar-fill[data-count]').forEach(bar => {
const count = Number(bar.dataset.count), total = Number(bar.dataset.total);
const ratio = Number.isFinite(count) && Number.isFinite(total) && total > 0 ? 100 * count / total : 0;
bar.style.width = Math.max(0, Math.min(100, ratio)) + '%';
bar.title = ratio.toFixed(1) + '% of total';
});
})();
+55
View File
@@ -0,0 +1,55 @@
/* Small, dependency-free canvas telemetry renderer.
* Draws only measured, non-synthetic EasyDNS API sample history.
* A 15-second backend poll stores samples in process memory. */
(() => {
'use strict';
const COLORS={cyan:'#72cfe1',amber:'#f1b42b',red:'#ec8588',grid:'#303a34',muted:'#8d9d91',text:'#dce6df'};
const chartTypes={
queries:{series:[['queryRate','Queries / s','cyan']],unit:'/s'},
cache:{series:[['cacheHitRate','Cache hit %','cyan']],unit:'%',range:[0,100]},
latency:{series:[['p50ms','p50','cyan'],['p95ms','p95','amber'],['p99ms','p99','red']],unit:'ms'},
blocked:{series:[['blocked','Blocked / s','amber']],unit:'/s'},
responses:{series:[['noerror','NOERROR','cyan'],['nxdomain','NXDOMAIN','amber'],['servfail','SERVFAIL','red']],unit:'/s'}
};
let samples=[];let lastPoll='';
function render(c){
const type=chartTypes[c.dataset.dnsChart];if(!type)return;
const dpr=Math.min(2,window.devicePixelRatio||1);
const box=c.getBoundingClientRect();if(box.width<30)return;
const width=box.width,height=box.height;
c.width=Math.round(width*dpr);c.height=Math.round(height*dpr);
const ctx=c.getContext('2d');if(!ctx)return;ctx.setTransform(dpr,0,0,dpr,0,0);ctx.clearRect(0,0,width,height);
const pad={left:49,right:12,top:10,bottom:25};const pw=Math.max(5,width-pad.left-pad.right),ph=Math.max(5,height-pad.top-pad.bottom);
const series=type.series.map(([key,label,color])=>({key,label,color:COLORS[color],vals:samples.map(s=>typeof s[key]==='number'&&Number.isFinite(s[key])?s[key]:null)}));
const observed=series.flatMap(x=>x.vals.filter(v=>v!==null));
ctx.font='10px ui-monospace,Consolas,monospace';ctx.textBaseline='middle';
if(samples.length<2||observed.length<2){ctx.fillStyle=COLORS.muted;ctx.textAlign='center';ctx.fillText('Collecting live samples…',width/2,height/2-2);ctx.fillText('First rate after 2 successful polls',width/2,height/2+15);return;}
let min=type.range?type.range[0]:0,max=type.range?type.range[1]:Math.max(...observed,0.001)*1.16;
if(!Number.isFinite(max)||max===min)max=min+1;
const x=i=>pad.left+pw*(i/Math.max(1,samples.length-1));
const y=v=>pad.top+ph*(1-(v-min)/(max-min));
ctx.textAlign='right';ctx.lineWidth=1;for(let tick=0;tick<=4;tick++){
const value=min+(max-min)*tick/4,py=y(value);
ctx.strokeStyle=COLORS.grid;ctx.setLineDash([2,4]);ctx.beginPath();ctx.moveTo(pad.left,py);ctx.lineTo(width-pad.right,py);ctx.stroke();
ctx.fillStyle=COLORS.muted;const label=max<=10?value.toFixed(1):Math.round(value).toString();ctx.fillText(label+type.unit,pad.left-8,py);
}
ctx.setLineDash([]);ctx.textAlign='center';ctx.fillStyle=COLORS.muted;
[0,.25,.5,.75,1].forEach(p=>{const idx=Math.min(samples.length-1,Math.round(p*(samples.length-1)));const t=new Date(samples[idx].time);if(!Number.isNaN(t.getTime()))ctx.fillText(t.toLocaleTimeString(undefined,{hour:'2-digit',minute:'2-digit'}),x(idx),height-9);});
series.forEach(s=>{ctx.beginPath();ctx.strokeStyle=s.color;ctx.lineWidth=1.65;ctx.lineJoin='round';let connected=false;
s.vals.forEach((v,i)=>{if(v===null){connected=false;return;}const px=x(i),py=y(v);if(!connected){ctx.moveTo(px,py);connected=true;}else{ctx.lineTo(px,py);}});ctx.stroke();
});
}
async function poll(){
try{
const r=await fetch('/ui/telemetry',{credentials:'same-origin',cache:'no-store',headers:{Accept:'application/json'}});
if(!r.ok||!(r.headers.get('content-type')||'').includes('json'))return;
const data=await r.json();samples=Array.isArray(data.samples)?data.samples:[];lastPoll=data.lastPoll;
document.querySelectorAll('canvas[data-dns-chart]').forEach(render);
}catch(_){/* Missing data stays empty; never fabricate data. */}
}
document.addEventListener('DOMContentLoaded',()=>{
const canvases=document.querySelectorAll('canvas[data-dns-chart]');if(!canvases.length)return;
const observer=new ResizeObserver(()=>canvases.forEach(render));canvases.forEach(c=>observer.observe(c));
poll();setInterval(poll,15000);
});
})();
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="9" fill="#080b09"/><circle cx="32" cy="32" r="19" fill="none" stroke="#9bc992" stroke-width="3"/><circle cx="32" cy="32" r="5" fill="#b7d8a0"/><path d="M13 32h38M32 13v38" fill="none" stroke="#536f5a" stroke-width="2"/></svg>

After

Width:  |  Height:  |  Size: 319 B

+15
View File
@@ -0,0 +1,15 @@
<svg xmlns="http://www.w3.org/2000/svg"><defs>
<symbol id="book" viewBox="0 0 24 24"><path d="M4 4.5h5.5A2.5 2.5 0 0 1 12 7v13a3 3 0 0 0-3-3H4V4.5ZM20 4.5h-5.5A2.5 2.5 0 0 0 12 7v13a3 3 0 0 1 3-3h5V4.5Z"/></symbol>
<symbol id="list" viewBox="0 0 24 24"><path d="M9 6h11M9 12h11M9 18h11"/><circle cx="4.5" cy="6" r=".8"/><circle cx="4.5" cy="12" r=".8"/><circle cx="4.5" cy="18" r=".8"/></symbol>
<symbol id="settings" viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="m10 2-.5 2.5-2 .9-2-1.5L3 6.5 4.5 8l-1 2L1 11v3l2.5.5 1 2L3 18l2.5 2.5 2-1.5 2 .9.5 2.1h4l.5-2.1 2-.9 2 1.5L21 18l-1.5-2 1-2L23 13v-2l-2.5-.5-1-2 1.5-2L18.5 4l-2 1.5-2-.9L14 2Z"/></symbol>
<symbol id="logout" viewBox="0 0 24 24"><path d="M9 4H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h3M16 8l4 4-4 4M20 12H9"/></symbol>
<symbol id="search" viewBox="0 0 24 24"><circle cx="10.5" cy="10.5" r="6.5"/><path d="m15.5 15.5 5 5"/></symbol>
<symbol id="plus" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></symbol>
<symbol id="upload" viewBox="0 0 24 24"><path d="M12 16V4m0 0-4 4m4-4 4 4M4 20h16"/></symbol>
<symbol id="refresh" viewBox="0 0 24 24"><path d="M20 7v5h-5M4 17v-5h5M18.5 9A7 7 0 0 0 6 6M5.5 15a7 7 0 0 0 12 3"/></symbol>
<symbol id="edit" viewBox="0 0 24 24"><path d="M4 20h4l11-11-4-4L4 16v4ZM13.5 6.5l4 4"/></symbol>
<symbol id="trash" viewBox="0 0 24 24"><path d="M4 7h16M9 3h6l1 4H8l1-4ZM7 7l1 14h8l1-14M10 11v6M14 11v6"/></symbol>
<symbol id="save" viewBox="0 0 24 24"><path d="M5 4h12l2 2v14H5V4ZM8 4v6h8V4M8 20v-6h8v6"/></symbol>
<symbol id="bell" viewBox="0 0 24 24"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 8-3 9h18c0-1-3-2-3-9M10 20h4"/></symbol>
<symbol id="arrow-right" viewBox="0 0 24 24"><path d="M5 12h14m-6-6 6 6-6 6"/></symbol>
</defs></svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

+6
View File
@@ -0,0 +1,6 @@
@charset "UTF-8";/*!
* Bootstrap v5.3.6 (https://getbootstrap.com/)
* Copyright 2011-2025 The Bootstrap Authors
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
*/:root,[data-bs-theme=light]{--bs-blue:#0d6efd;--bs-indigo:#6610f2;--bs-purple:#6f42c1;--bs-pink:#d63384;--bs-red:#dc3545;--bs-orange:#fd7e14;--bs-yellow:#ffc107;--bs-green:#198754;--bs-teal:#20c997;--bs-cyan:#0dcaf0;--bs-black:#000;--bs-white:#fff;--bs-gray:#6c757d;--bs-gray-dark:#343a40;--bs-gray-100:#f8f9fa;--bs-gray-200:#e9ecef;--bs-gray-300:#dee2e6;--bs-gray-400:#ced4da;--bs-gray-500:#adb5bd;--bs-gray-600:#6c757d;--bs-gray-700:#495057;--bs-gray-800:#343a40;--bs-gray-900:#212529;--bs-primary:#0d6efd;--bs-secondary:#6c757d;--bs-success:#198754;--bs-info:#0dcaf0;--bs-warning:#ffc107;--bs-danger:#dc3545;--bs-light:#f8f9fa;--bs-dark:#212529;--bs-primary-rgb:13,110,253;--bs-secondary-rgb:108,117,125;--bs-success-rgb:25,135,84;--bs-info-rgb:13,202,240;--bs-warning-rgb:255,193,7;--bs-danger-rgb:220,53,69;--bs-light-rgb:248,249,250;--bs-dark-rgb:33,37,41;--bs-primary-text-emphasis:#052c65;--bs-secondary-text-emphasis:#2b2f32;--bs-success-text-emphasis:#0a3622;--bs-info-text-emphasis:#055160;--bs-warning-text-emphasis:#664d03;--bs-danger-text-emphasis:#58151c;--bs-light-text-emphasis:#495057;--bs-dark-text-emphasis:#495057;--bs-primary-bg-subtle:#cfe2ff;--bs-secondary-bg-subtle:#e2e3e5;--bs-success-bg-subtle:#d1e7dd;--bs-info-bg-subtle:#cff4fc;--bs-warning-bg-subtle:#fff3cd;--bs-danger-bg-subtle:#f8d7da;--bs-light-bg-subtle:#fcfcfd;--bs-dark-bg-subtle:#ced4da;--bs-primary-border-subtle:#9ec5fe;--bs-secondary-border-subtle:#c4c8cb;--bs-success-border-subtle:#a3cfbb;--bs-info-border-subtle:#9eeaf9;--bs-warning-border-subtle:#ffe69c;--bs-danger-border-subtle:#f1aeb5;--bs-light-border-subtle:#e9ecef;--bs-dark-border-subtle:#adb5bd;--bs-white-rgb:255,255,255;--bs-black-rgb:0,0,0;--bs-font-sans-serif:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue","Noto Sans","Liberation Sans",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--bs-font-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--bs-gradient:linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));--bs-body-font-family:var(--bs-font-sans-serif);--bs-body-font-size:1rem;--bs-body-font-weight:400;--bs-body-line-height:1.5;--bs-body-color:#212529;--bs-body-color-rgb:33,37,41;--bs-body-bg:#fff;--bs-body-bg-rgb:255,255,255;--bs-emphasis-color:#000;--bs-emphasis-color-rgb:0,0,0;--bs-secondary-color:rgba(33, 37, 41, 0.75);--bs-secondary-color-rgb:33,37,41;--bs-secondary-bg:#e9ecef;--bs-secondary-bg-rgb:233,236,239;--bs-tertiary-color:rgba(33, 37, 41, 0.5);--bs-tertiary-color-rgb:33,37,41;--bs-tertiary-bg:#f8f9fa;--bs-tertiary-bg-rgb:248,249,250;--bs-heading-color:inherit;--bs-link-color:#0d6efd;--bs-link-color-rgb:13,110,253;--bs-link-decoration:underline;--bs-link-hover-color:#0a58ca;--bs-link-hover-color-rgb:10,88,202;--bs-code-color:#d63384;--bs-highlight-color:#212529;--bs-highlight-bg:#fff3cd;--bs-border-width:1px;--bs-border-style:solid;--bs-border-color:#dee2e6;--bs-border-color-translucent:rgba(0, 0, 0, 0.175);--bs-border-radius:0.375rem;--bs-border-radius-sm:0.25rem;--bs-border-radius-lg:0.5rem;--bs-border-radius-xl:1rem;--bs-border-radius-xxl:2rem;--bs-border-radius-2xl:var(--bs-border-radius-xxl);--bs-border-radius-pill:50rem;--bs-box-shadow:0 0.5rem 1rem rgba(0, 0, 0, 0.15);--bs-box-shadow-sm:0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);--bs-box-shadow-lg:0 1rem 3rem rgba(0, 0, 0, 0.175);--bs-box-shadow-inset:inset 0 1px 2px rgba(0, 0, 0, 0.075);--bs-focus-ring-width:0.25rem;--bs-focus-ring-opacity:0.25;--bs-focus-ring-color:rgba(13, 110, 253, 0.25);--bs-form-valid-color:#198754;--bs-form-valid-border-color:#198754;--bs-form-invalid-color:#dc3545;--bs-form-invalid-border-color:#dc3545}[data-bs-theme=dark]{color-scheme:dark;--bs-body-color:#dee2e6;--bs-body-color-rgb:222,226,230;--bs-body-bg:#212529;--bs-body-bg-rgb:33,37,41;--bs-emphasis-color:#fff;--bs-emphasis-color-rgb:255,255,255;--bs-secondary-color:rgba(222, 226, 230, 0.75);--bs-secondary-color-rgb:222,226,230;--bs-secondary-bg:#343a40;--bs-secondary-bg-rgb:52,58,64;--bs-tertiary-color:rgba(222, 226, 230, 0.5);--bs-tertiary-color-rgb:222,226,230;--bs-tertiary-bg:#2b3035;--bs-tertiary-bg-rgb:43,48,53;--bs-primary-text-emphasis:#6ea8fe;--bs-secondary-text-emphasis:#a7acb1;--bs-success-text-emphasis:#75b798;--bs-info-text-emphasis:#6edff6;--bs-warning-text-emphasis:#ffda6a;--bs-danger-text-emphasis:#ea868f;--bs-light-text-emphasis:#f8f9fa;--bs-dark-text-emphasis:#dee2e6;--bs-primary-bg-subtle:#031633;--bs-secondary-bg-subtle:#161719;--bs-success-bg-subtle:#051b11;--bs-info-bg-subtle:#032830;--bs-warning-bg-subtle:#332701;--bs-danger-bg-subtle:#2c0b0e;--bs-light-bg-subtle:#343a40;--bs-dark-bg-subtle:#1a1d20;--bs-primary-border-subtle:#084298;--bs-secondary-border-subtle:#41464b;--bs-success-border-subtle:#0f5132;--bs-info-border-subtle:#087990;--bs-warning-border-subtle:#997404;--bs-danger-border-subtle:#842029;--bs-light-border-subtle:#495057;--bs-dark-border-subtle:#343a40;--bs-heading-color:inherLine truncated
/*# sourceMappingURL=bootstrap.min.css.map */
+36
View File
@@ -0,0 +1,36 @@
{{define "base"}}<!doctype html>
<html lang="en" data-bs-theme="dark"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="color-scheme" content="dark"><meta name="theme-color" content="#050706">
<title>{{.Title}} · EasyDNS</title>
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="/static/vendor/bootstrap.min.css"><link rel="stylesheet" href="/static/app.css">
<script defer src="/static/app.js"></script><script defer src="/static/charts.js"></script>
</head><body>
<div class="shell">
<aside class="sidebar" id="sidebar" aria-label="Primary navigation">
<div class="brand"><a href="/" aria-label="EasyDNS Overview">EasyDNS</a></div>
<div class="sidebar-content">
<div class="nav-section">DNS</div>
<nav class="sidenav" aria-label="DNS"><a {{if eq .Active "overview"}}class="active" aria-current="page"{{end}} href="/">Overview</a><a {{if eq .Active "zones"}}class="active" aria-current="page"{{end}} href="/zones">Zones</a><a {{if eq .Active "query"}}class="active" aria-current="page"{{end}} href="/query">DNS lookup</a></nav>
<div class="nav-section">RESOLUTION &amp; POLICY</div>
<nav class="sidenav" aria-label="Resolution and policy"><a {{if eq .Active "upstreams"}}class="active" aria-current="page"{{end}} href="/upstreams">Upstreams</a><a {{if eq .Active "policies"}}class="active" aria-current="page"{{end}} href="/policies">Policies</a><a {{if eq .Active "views"}}class="active" aria-current="page"{{end}} href="/views">Views</a><a {{if eq .Active "acl"}}class="active" aria-current="page"{{end}} href="/acl">ACL</a><a {{if eq .Active "rate"}}class="active" aria-current="page"{{end}} href="/rate-limiting">Rate limiting</a><a {{if eq .Active "blocklists"}}class="active" aria-current="page"{{end}} href="/blocklists">Blocklists</a></nav>
<div class="nav-section">MONITORING &amp; SYSTEM</div>
<nav class="sidenav" aria-label="Monitoring"><a {{if eq .Active "cache"}}class="active" aria-current="page"{{end}} href="/cache">Cache</a><a {{if eq .Active "metrics"}}class="active" aria-current="page"{{end}} href="/metrics">Metrics</a><a {{if eq .Active "audit"}}class="active" aria-current="page"{{end}} href="/audit">Audit log</a><a {{if eq .Active "status"}}class="active" aria-current="page"{{end}} href="/status">Server status</a><a {{if eq .Active "configuration"}}class="active" aria-current="page"{{end}} href="/configuration">Configuration</a></nav>
</div>
<div class="sidebar-foot"><span class="indicator"></span> Local control panel <small>EasyDNS API connection</small></div>
</aside>
<div class="workspace">
<header class="topbar"><button class="mobile-menu" type="button" id="menuToggle" aria-controls="sidebar" aria-expanded="false" aria-label="Open navigation">☰</button><div class="breadcrumbs">{{.Breadcrumb}}</div>
<div class="top-actions"><a href="https://git.linuxiarz.pl/gru/EasyDNS" target="_blank" rel="noopener noreferrer" class="tool-button"><svg class="ico"><use href="/static/icons.svg#book"/></svg><span>Documentation</span></a><a href="/audit" class="tool-button"><svg class="ico"><use href="/static/icons.svg#list"/></svg><span>Audit</span></a><a href="/configuration" class="tool-button"><svg class="ico"><use href="/static/icons.svg#settings"/></svg><span>Configuration</span></a><form method="post" action="/logout" class="inline"><input type="hidden" name="_csrf" value="{{.CSRF}}"><button type="submit" class="tool-button"><svg class="ico"><use href="/static/icons.svg#logout"/></svg><span>Sign out</span></button></form></div>
</header>
<main class="content" id="main">
<div class="page-head"><div class="page-head-left"><p class="eyebrow"><span class="indicator"></span> EasyDNS control room</p><h1>{{.Title}}</h1><p class="page-subtitle">{{.Subtitle}}</p></div><div class="page-head-right"><span class="operator-label">{{.User}}</span></div></div>
{{if .Message}}<div class="notice {{.MessageType}}" role="alert"><span>{{.Message}}</span><button class="notice-dismiss" type="button" aria-label="Dismiss notice">×</button></div>{{end}}
{{template "content" .}}
<footer class="footer">EasyDNS · independent management panel <span>Only verified EasyDNS API operations are available</span></footer>
</main>
</div>
</div>
<div id="sidebarOverlay" class="sidebar-overlay" aria-hidden="true"></div>
</body></html>{{end}}
@@ -0,0 +1,2 @@
{{define "content"}}<section class="panel"><div class="toolbar"><div class="toolbar-title"><h2>Administrative events</h2><p>Most recent administrative operations</p></div><form method="get" action="/audit" class="toolbar-form"><label class="field-label" for="auditN">Tail length</label><select class="field field-select" id="auditN" name="n">{{range auditSizes}}<option value="{{.}}" {{if eq (selectval $.Data.Filter "n") (string .)}}selected{{end}}>{{.}}</option>{{end}}</select><button type="submit" class="btn-ui">Load events</button></form></div>
<div class="table-scroll"><table class="data-table"><thead><tr><th>TIMESTAMP</th><th>ACTOR</th><th>ACTION</th><th>TARGET</th><th>RESULT</th><th>DETAILS</th></tr></thead><tbody>{{range .Data.Audit}}<tr><td class="mono subtle">{{when .TimeUnix}}</td><td class="mono">{{.Actor}}</td><td>{{.Action}}</td><td class="mono">{{.Target}}</td><td><span class="dot {{statusclass .Result}}"></span>{{.Result}}</td><td class="break-any">{{.Detail}}</td></tr>{{else}}<tr><td colspan="6" class="empty">No audit events returned by EasyDNS.</td></tr>{{end}}</tbody></table></div><div class="table-footer"><span>{{len .Data.Audit}} entries returned · maximum supported by API: 10,000</span></div></section><div class="notice-inline mt-panel">The audit endpoint records management operations. It is not a DNS query log and does not provide date-range filters or pagination.</div>{{end}}
@@ -0,0 +1 @@
{{define "content"}}<div class="form-layout"><section class="panel"><div class="panel-head"><div><h2>New block rule</h2><p>One validated policy rule per request.</p></div></div><form method="post" action="/blocklists" class="form-body"><input type="hidden" name="_csrf" value="{{.CSRF}}"><div class="field-row"><label class="field-label" for="blockRule">Rule <span class="required">*</span></label><input class="field mono" id="blockRule" name="rule" required value="{{selectval .Data.Form "rule"}}" placeholder="malware.example.org"><small>A single line. EasyDNS validates syntax and writes to its API overlay.</small></div><div class="form-actions"><a href="/blocklists" class="btn-ui">Cancel</a><button class="btn-ui btn-primary-ui" type="submit">Add rule</button></div></form></section><aside class="panel guide"><div class="panel-head"><h2>API boundaries</h2></div><div class="panel-body"><p>The REST API returns the number of loaded rules, but not their complete list. Editing or removing an individual rule is not supported.</p><div class="data-row"><span>Invalid rule</span><strong>400</strong></div><div class="data-row"><span>Rejected reload</span><strong>422</strong></div></div></aside></div>{{end}}
@@ -0,0 +1,3 @@
{{define "content"}}<div class="status-strip panel compact-strip"><div class="strip-cell"><span>CONFIGURED LISTS</span><strong>{{len .Data.Blocklists.Lists}}</strong></div><div class="strip-cell"><span>LOADED LISTS</span><strong>{{len .Data.Blocklists.Loaded}}</strong></div><div class="strip-cell"><span>ACTIVE RULES</span><strong>{{int .Data.Blocklists.Rules}}</strong></div><div class="strip-cell"><span>UPDATE INTERVAL</span><strong>{{.Data.Blocklists.UpdateInterval}}</strong></div></div>
<section class="panel mt-panel"><div class="toolbar"><div class="toolbar-title"><h2>Configured feeds</h2><p>Rule sources and their effective enablement.</p></div><a class="btn-ui btn-primary-ui" href="/blocklists/new"><svg class="ico"><use href="/static/icons.svg#plus"/></svg>Add rule</a></div><div class="table-scroll"><table class="data-table"><thead><tr><th>NAME</th><th>CATEGORY</th><th>SOURCE FILE</th><th>REMOTE URL</th><th>ENABLED</th><th>UPDATE INTERVAL</th></tr></thead><tbody>{{range .Data.Blocklists.Lists}}<tr><td class="entity">{{string (get . "name")}}</td><td>{{string (get . "category")}}</td><td class="mono">{{string (get . "file")}}</td><td class="mono break-any">{{string (get . "url")}}</td><td>{{string (get . "enabled")}}</td><td class="mono">{{string (get . "update_interval")}}</td></tr>{{else}}<tr><td class="empty" colspan="6">No blocklist feeds configured.</td></tr>{{end}}</tbody></table></div></section>
<section class="panel mt-panel"><div class="panel-head"><div><h2>Remote list sync state</h2><p>Read-only update and download results</p></div></div><div class="table-scroll"><table class="data-table"><thead><tr><th>NAME</th><th>LAST SUCCESS</th><th>LAST ATTEMPT</th><th>RESULT</th><th>MESSAGE</th></tr></thead><tbody>{{range $key,$v:=.Data.Blocklists.State}}<tr><td class="mono">{{$key}}</td><td class="mono">{{string (get $v "last_success")}}</td><td class="mono">{{string (get $v "last_attempt")}}</td><td>{{string (get $v "ok")}}</td><td>{{string (get $v "message")}}</td></tr>{{else}}<tr><td class="empty" colspan="5">No remote feed sync state available.</td></tr>{{end}}</tbody></table></div></section><div class="notice-inline mt-panel">REST can add individual block rules, but cannot list/remove them individually or force a remote feed download.</div>{{end}}
@@ -0,0 +1,4 @@
{{define "content"}}<div class="metrics-grid four"><div class="panel metric"><span class="metric-label">CACHE ENTRIES</span><strong>{{int .Data.Cache.Entries}}</strong><small>Capacity {{int .Data.Cache.Capacity}}</small></div><div class="panel metric"><span class="metric-label">HITS</span><strong>{{int .Data.Cache.Hits}}</strong><small>Cumulative hits</small></div><div class="panel metric"><span class="metric-label">MISSES</span><strong>{{int .Data.Cache.Misses}}</strong><small>Cumulative misses</small></div><div class="panel metric"><span class="metric-label">EVICTIONS</span><strong>{{int .Data.Cache.Evictions}}</strong><small>Cumulative evictions</small></div></div>
<div class="dashboard-lower mt-panel"><section class="panel"><div class="panel-head"><h2>Cache counters</h2></div><div class="panel-body compact"><div class="data-row"><span>Entries</span><strong>{{int .Data.Cache.Entries}}</strong></div><div class="data-row"><span>Inserts</span><strong>{{int .Data.Cache.Inserts}}</strong></div><div class="data-row"><span>Expired</span><strong>{{int .Data.Cache.Expired}}</strong></div><div class="data-row"><span>Stale served</span><strong>{{int .Data.Cache.StaleServed}}</strong></div><div class="data-row"><span>Prefetches</span><strong>{{int .Data.Cache.Prefetches}}</strong></div></div></section>
<section class="panel"><div class="panel-head"><h2>Flush domain suffix</h2></div><form method="post" action="/cache/flush" class="panel-body"><input type="hidden" name="_csrf" value="{{.CSRF}}"><input type="hidden" name="scope" value="domain"><p>Invalidate entries under a domain suffix. Cache contents cannot be enumerated over REST.</p><label class="field-label" for="flushDomain">Domain suffix</label><input class="field mono" id="flushDomain" name="domain" required placeholder="example.org"><button class="btn-ui mt-3" type="submit">Flush domain</button></form></section>
<section class="panel danger-panel"><div class="panel-head"><h2>Flush entire cache</h2></div><form method="post" action="/cache/flush" class="panel-body"><input type="hidden" name="_csrf" value="{{.CSRF}}"><input type="hidden" name="scope" value="all"><p>Remove all DNS cache entries. This is a destructive action without an undo endpoint.</p><label class="field-label" for="flushConfirm">Type FLUSH ALL to confirm</label><input class="field mono" name="confirm" id="flushConfirm" required pattern="FLUSH ALL" autocomplete="off" placeholder="FLUSH ALL"><button class="btn-ui btn-danger-ui mt-3" type="submit">Flush all cache entries</button></form></section></div>{{end}}
@@ -0,0 +1,4 @@
{{define "content"}}<div class="form-layout policy-layout"><section class="panel"><div class="panel-head"><div><h2>Visible runtime configuration</h2><p>Selected runtime parameters exposed by EasyDNS</p></div></div><div class="panel-body compact"><div class="data-row"><span>Server mode</span><strong>{{.Data.Status.Mode}}</strong></div><div class="data-row"><span>Version</span><strong>{{.Data.Status.Version}}</strong></div><div class="data-row"><span>Default resolution</span><strong>{{.Data.Status.Roles.DefaultResolution}}</strong></div><div class="data-row"><span>DNSSEC validation</span><strong>{{string .Data.Status.DNSSECValidation}}</strong></div><div class="data-row"><span>Block action</span><strong>{{string (get .Data.Policies.Policy "block_action")}}</strong></div><div class="data-row"><span>API allowed clients</span><strong>{{join .Data.Policies.APIAllowedClients ", "}}</strong></div><div class="data-row"><span>Recursion allowed clients</span><strong>{{join .Data.Policies.RecursionAllowedClients ", "}}</strong></div></div>
<div class="panel-head border-top"><div><h2>Hot reload</h2><p>Reload configuration from disk. EasyDNS reports errors and preserves prior active configuration.</p></div></div>
<form method="post" action="/configuration/reload" class="form-body"><input type="hidden" name="_csrf" value="{{.CSRF}}"><label class="field-label" for="reloadConfirm">Type RELOAD to confirm</label><input class="field mono" id="reloadConfirm" name="confirm" required pattern="RELOAD" autocomplete="off" placeholder="RELOAD"><div class="form-actions"><button class="btn-ui btn-primary-ui" type="submit"><svg class="ico"><use href="/static/icons.svg#refresh"/></svg>Reload EasyDNS configuration</button></div></form></section>
<aside class="panel guide"><div class="panel-head"><h2>What this panel cannot change</h2></div><div class="panel-body"><p>The REST API does not expose arbitrary configuration file editing, token rotation, server restarts, listener updates, ACL edits or rate limiter changes.</p><div class="notice-inline">EasyDNS creates <span class="mono">control.token</span> itself when its TCP API is enabled. The Go process reads that file server-side. It is never sent to your browser.</div><p class="mt-3 muted">This page never displays the token or pretends to modify local configuration.</p></div></aside></div>{{end}}
@@ -0,0 +1 @@
{{define "content"}}<div class="confirmation-box panel"><div class="panel-head"><div><h2>Stale zone serial</h2><p>The operation was not applied.</p></div><span class="tag amber">HTTP 412</span></div><div class="panel-body"><p>EasyDNS rejected the request because the zone changed after the form was opened. Review the latest records and start a new edit. This panel will not silently overwrite another administrator's modifications.</p><div class="form-actions"><a class="btn-ui btn-primary-ui" href="{{.Data.ZoneURL}}/records">Reload records</a><a class="btn-ui" href="{{.Data.ZoneURL}}">Zone details</a></div></div></div>{{end}}
@@ -0,0 +1,4 @@
{{define "content"}}<div class="confirmation-box panel"><div class="panel-head"><div><h2>Confirm permanent deletion</h2><p>This operation cannot be undone through EasyDNS REST.</p></div><span class="tag red">DESTRUCTIVE</span></div><div class="panel-body">
{{if eq .Data.Action "record"}}<p>You are about to remove the following DNS record:</p><div class="target-summary"><div class="data-row"><span>Name</span><strong class="mono">{{.Data.Record.Name}}</strong></div><div class="data-row"><span>Type</span><strong>{{.Data.Record.Type}}</strong></div><div class="data-row"><span>RDATA</span><strong class="mono">{{.Data.Record.Data}}</strong></div></div><form method="post" action="{{.Data.ZoneURL}}/records/{{.Data.Record.ID}}/delete"><input type="hidden" name="_csrf" value="{{.CSRF}}"><input type="hidden" name="etag" value="{{.Data.ETag}}"><label class="field-label" for="confirmDelete">Type DELETE <span class="required">*</span></label><input id="confirmDelete" class="field mono" name="confirm" required pattern="DELETE" autocomplete="off" placeholder="DELETE"><div class="form-actions"><a class="btn-ui" href="{{.Data.ZoneURL}}/records">Cancel</a><button type="submit" class="btn-ui btn-danger-ui">Delete record</button></div></form>
{{else}}<p>Zone <strong class="mono">{{.Data.Zone.Name}}</strong> will be removed if it was created via the REST API overlay. File-configured zones cannot be removed using this endpoint (409).</p><form method="post" action="{{.Data.ZoneURL}}/delete"><input type="hidden" name="_csrf" value="{{.CSRF}}"><label class="field-label" for="confirmZone">Type the complete zone name <span class="required">*</span></label><input id="confirmZone" class="field mono" name="confirm" required autocomplete="off" placeholder="{{.Data.Zone.Name}}"><div class="form-actions"><a class="btn-ui" href="{{.Data.ZoneURL}}">Cancel</a><button type="submit" class="btn-ui btn-danger-ui">Delete zone</button></div></form>{{end}}
</div></div>{{end}}
@@ -0,0 +1,4 @@
{{define "login"}}<!doctype html><html lang="en" data-bs-theme="dark"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sign in · EasyDNS</title><link rel="stylesheet" href="/static/vendor/bootstrap.min.css"><link rel="stylesheet" href="/static/app.css"></head>
<body class="login-body"><main class="login-panel"><div class="login-brand">EasyDNS</div><p class="overline">LOCAL CONTROL ROOM</p><h1>Sign in</h1><p class="muted mb-4">Access the EasyDNS administration panel. The EasyDNS bearer token stays on the server.</p>
{{with index . "Error"}}{{if .}}<div class="notice danger" role="alert">{{.}}</div>{{end}}{{end}}
<form method="post" action="/login" autocomplete="on"><label class="field-label" for="username">Username</label><input class="field" id="username" name="username" autocomplete="username" value="{{index . "Username"}}" required><label class="field-label mt-3" for="password">Password</label><input class="field" type="password" id="password" name="password" autocomplete="current-password" required><button class="btn-ui btn-primary-ui w-100 mt-4" type="submit">Sign in</button></form><p class="login-help">Panel authentication is separate from EasyDNS REST API credentials.</p></main></body></html>{{end}}
@@ -0,0 +1,11 @@
{{define "content"}}<div class="metrics-grid six"><div class="panel metric"><span class="metric-label">DNS QUERIES</span><strong>{{int .Data.Stats.QueriesTotal}}</strong><small>Cumulative counter</small></div><div class="panel metric"><span class="metric-label">CACHE HIT RATE</span><strong class="success">{{pct .Data.Stats.CacheHitRate}}</strong><small>Latest cache ratio</small></div><div class="panel metric"><span class="metric-label">P50 LATENCY</span><strong>{{ms .Data.Stats.LatencyP50S}}</strong><small>Live histogram</small></div><div class="panel metric"><span class="metric-label">P95 LATENCY</span><strong>{{ms .Data.Stats.LatencyP95S}}</strong><small>Live histogram</small></div><div class="panel metric"><span class="metric-label">P99 LATENCY</span><strong>{{ms .Data.Stats.LatencyP99S}}</strong><small>Live histogram</small></div><div class="panel metric"><span class="metric-label">RATE LIMITED</span><strong class="warning">{{int .Data.Stats.RateLimited}}</strong><small>Cumulative count</small></div></div>
<div class="chart-grid triple"><section class="panel chart-card"><div class="panel-head"><div><h2>DNS query throughput</h2><p>Measured requests per second</p></div></div><canvas data-dns-chart="queries" role="img" aria-label="DNS query rate"></canvas><div class="chart-foot"><span class="legend-dot cyan"></span> DNS queries / s</div></section>
<section class="panel chart-card"><div class="panel-head"><div><h2>Response codes</h2><p>Rates from cumulative result counters</p></div></div><canvas data-dns-chart="responses" role="img" aria-label="DNS responses over time"></canvas><div class="chart-foot"><span class="legend-dot cyan"></span> NOERROR <span class="legend-dot amber"></span> NXDOMAIN <span class="legend-dot red"></span> SERVFAIL</div></section>
<section class="panel chart-card"><div class="panel-head"><div><h2>Cache efficiency</h2><p>Hit share calculated per poll</p></div></div><canvas data-dns-chart="cache" role="img" aria-label="Cache hit ratio"></canvas><div class="chart-foot"><span class="legend-dot cyan"></span> Cache hit %</div></section></div>
<div class="chart-grid triple"><section class="panel chart-card"><div class="panel-head"><div><h2>Resolver latency</h2><p>p50 / p95 / p99 snapshot history</p></div></div><canvas data-dns-chart="latency" role="img" aria-label="Latency percentiles"></canvas><div class="chart-foot"><span class="legend-dot cyan"></span> p50 <span class="legend-dot amber"></span> p95 <span class="legend-dot red"></span> p99</div></section>
<section class="panel chart-card"><div class="panel-head"><div><h2>Blocked query rate</h2><p>Derived from blocked counter</p></div></div><canvas data-dns-chart="blocked" role="img" aria-label="Blocked DNS query rate"></canvas><div class="chart-foot"><span class="legend-dot amber"></span> Blocked / s</div></section>
<section class="panel chart-card"><div class="panel-head"><div><h2>Response count mix</h2><p>Actual cumulative EasyDNS counters</p></div></div><div class="panel-body compact bars-large">{{range $key,$v:=.Data.Stats.Responses}}<div class="barline"><span class="mono upper">{{$key}}</span><div class="bar-track"><span class="bar-fill {{statusclass $key}}" data-count="{{$v}}" data-total="{{$.Data.Stats.QueriesTotal}}"></span></div><strong>{{int $v}}</strong></div>{{else}}<div class="empty">No response counts available.</div>{{end}}</div></section></div>
<div class="dashboard-lower mt-panel"><section class="panel"><div class="panel-head"><h2>Query sources</h2></div><div class="table-scroll"><table class="data-table"><thead><tr><th>SOURCE</th><th>COUNT (CUMULATIVE)</th></tr></thead><tbody>{{range $key,$v:=.Data.Stats.Sources}}<tr><td class="mono">{{$key}}</td><td class="mono right">{{int $v}}</td></tr>{{else}}<tr><td class="empty" colspan="2">No query source counters.</td></tr>{{end}}</tbody></table></div></section>
<section class="panel"><div class="panel-head"><h2>Cache counters</h2></div><div class="panel-body compact"><div class="data-row"><span>Entries</span><strong>{{int .Data.Stats.Cache.Entries}}</strong></div><div class="data-row"><span>Hits</span><strong>{{int .Data.Stats.Cache.Hits}}</strong></div><div class="data-row"><span>Misses</span><strong>{{int .Data.Stats.Cache.Misses}}</strong></div><div class="data-row"><span>Evictions</span><strong>{{int .Data.Stats.Cache.Evictions}}</strong></div></div></section>
<section class="panel"><div class="panel-head"><h2>Telemetry sampling</h2></div><div class="panel-body compact"><div class="data-row"><span>Samples stored in UI memory</span><strong>{{.Data.SamplingCount}}</strong></div><div class="data-row"><span>Polling frequency</span><strong>15 s</strong></div><div class="data-row"><span>Last sample</span><strong>{{if .Data.SamplingTime.IsZero}}—{{else}}{{.Data.SamplingTime.Format "15:04:05"}}{{end}}</strong></div><div class="notice-inline">No artificial 24-hour chart data. Samples are collected only while the Go service runs, and reset on restart.</div></div></section></div>
{{end}}
@@ -0,0 +1,34 @@
{{define "content"}}
<div class="status-strip panel">
<div class="status-main"><div class="status-heading"><span class="dot {{statusclass .Data.Health.Status}}"></span><strong>{{if eq .Data.Health.Status "ok"}}DNS service operational{{else if eq .Data.Health.Status "degraded"}}DNS service degraded{{else}}Status unavailable{{end}}</strong></div><div class="tiny muted">Health: {{if .Data.Health.Status}}{{.Data.Health.Status}}{{else}}Unknown{{end}} · {{if .Data.Status.Roles.Recursive}}Resolver enabled{{else}}No recursive resolver{{end}}</div></div>
<div class="strip-cell"><span>SERVER MODE</span><strong>{{if .Data.Status.Mode}}{{.Data.Status.Mode}}{{else}}—{{end}}</strong></div>
<div class="strip-cell"><span>UPTIME</span><strong>{{uptime .Data.Status.UptimeSeconds}}</strong></div>
<div class="strip-cell"><span>ZONES</span><strong>{{int .Data.Status.Roles.Primary}} primary / {{int .Data.Status.Roles.Secondary}} secondary</strong></div>
<div class="strip-cell"><span>VERSION</span><strong>{{if .Data.Status.Version}}{{.Data.Status.Version}}{{else}}—{{end}}</strong></div>
</div>
<div class="metrics-grid six">
<div class="metric panel"><span class="metric-label">DNS QUERIES</span><strong>{{int .Data.Stats.QueriesTotal}}</strong><small>Cumulative since startup</small></div>
<div class="metric panel"><span class="metric-label">CACHE HIT RATIO</span><strong class="success">{{pct .Data.Stats.CacheHitRate}}</strong><small>Hits / (hits + misses)</small></div>
<div class="metric panel"><span class="metric-label">RESOLVER LATENCY P95</span><strong>{{ms .Data.Stats.LatencyP95S}}</strong><small>Latest API histogram</small></div>
<div class="metric panel"><span class="metric-label">BLOCKED QUERIES</span><strong class="warning">{{int .Data.Stats.Blocked}}</strong><small>Cumulative policy count</small></div>
<div class="metric panel"><span class="metric-label">RATE LIMITED</span><strong>{{int .Data.Stats.RateLimited}}</strong><small>Cumulative count</small></div>
<div class="metric panel"><span class="metric-label">ZONE HEALTH</span><strong class="{{statusclass .Data.Health.Status}}">{{if eq .Data.Health.Status "ok"}}Healthy{{else if eq .Data.Health.Status "degraded"}}Degraded{{else}}Unknown{{end}}</strong><small>{{len .Data.Health.ExpiredZones}} expired zones</small></div>
</div>
<div class="chart-grid triple">
<section class="panel chart-card"><div class="panel-head"><div><h2>Query rate</h2><p>Calculated from real /stats counter deltas.</p></div><span class="live-mark">PANEL SAMPLES</span></div><canvas data-dns-chart="queries" aria-label="Queries per second, measured by panel" role="img"></canvas><div class="chart-foot"><span class="legend-dot cyan"></span> Queries / s</div></section>
<section class="panel chart-card"><div class="panel-head"><div><h2>Cache hit ratio</h2><p>Derived from cache hit/miss deltas.</p></div></div><canvas data-dns-chart="cache" aria-label="Cache hit percentage" role="img"></canvas><div class="chart-foot"><span class="legend-dot cyan"></span> Hits / all lookups</div></section>
<section class="panel chart-card"><div class="panel-head"><div><h2>Resolver latency</h2><p>Live p50 and p95, milliseconds.</p></div></div><canvas data-dns-chart="latency" aria-label="Resolver latency p50 p95" role="img"></canvas><div class="chart-foot"><span class="legend-dot amber"></span> p95 <span class="legend-dot cyan"></span> p50</div></section>
</div>
<div class="dashboard-lower">
<section class="panel"><div class="panel-head"><div><h2>Response codes</h2><p>Cumulative DNS results since startup</p></div><a href="/metrics" class="text-link">Metrics →</a></div><div class="panel-body compact">
{{range $key,$v := .Data.Stats.Responses}}<div class="barline"><span class="mono upper">{{$key}}</span><div class="bar-track"><span class="bar-fill {{statusclass $key}}" style="width:0" data-count="{{$v}}" data-total="{{$.Data.Stats.QueriesTotal}}"></span></div><strong>{{int $v}}</strong></div>{{else}}<div class="empty">No response statistics available.</div>{{end}}
</div></section>
<section class="panel"><div class="panel-head"><div><h2>Zone state</h2><p>Reported by EasyDNS</p></div><a href="/zones" class="text-link">View zones →</a></div><div class="panel-body compact">
<div class="data-row"><span>Primary zones</span><strong>{{int .Data.Status.Roles.Primary}}</strong></div><div class="data-row"><span>Secondary zones</span><strong>{{int .Data.Status.Roles.Secondary}}</strong></div><div class="data-row"><span>Recursive resolver</span><strong>{{if .Data.Status.Roles.Recursive}}Enabled{{else}}Disabled{{end}}</strong></div><div class="data-row"><span>Forwarder</span><strong>{{if .Data.Status.Roles.Forwarder}}Enabled{{else}}Disabled{{end}}</strong></div><div class="data-row"><span>Expired zones</span><strong class="{{if .Data.Health.ExpiredZones}}danger{{else}}success{{end}}">{{len .Data.Health.ExpiredZones}}</strong></div>
</div></section>
<section class="panel"><div class="panel-head"><div><h2>Polling status</h2><p>UI sampling, not server-side history</p></div></div><div class="panel-body compact"><div class="data-row"><span>Samples</span><strong>{{.Data.SamplingCount}}</strong></div><div class="data-row"><span>Interval</span><strong>15 seconds</strong></div><div class="data-row"><span>Most recent</span><strong>{{if .Data.SamplingTime.IsZero}}No sample{{else}}{{.Data.SamplingTime.Format "15:04:05"}}{{end}}</strong></div><div class="notice-inline">Charts populate only after successful live polls.</div></div></section>
</div>
<section class="panel mt-panel"><div class="panel-head"><div><h2>Recent audit events</h2><p>Changes and administration activity</p></div><a class="text-link" href="/audit">Audit log →</a></div><div class="table-scroll"><table class="data-table"><thead><tr><th>TIME</th><th>ACTION</th><th>TARGET</th><th>RESULT</th><th>DETAIL</th></tr></thead><tbody>
{{range .Data.Audit}}<tr><td class="mono subtle">{{when .TimeUnix}}</td><td>{{.Action}}</td><td class="mono">{{.Target}}</td><td><span class="dot {{statusclass .Result}}"></span>{{.Result}}</td><td class="ellipsis">{{.Detail}}</td></tr>{{else}}<tr><td colspan="5" class="empty">No audit events returned by EasyDNS.</td></tr>{{end}}
</tbody></table></div></section>
{{end}}
@@ -0,0 +1,6 @@
{{define "content"}}<div class="form-layout policy-layout"><section class="panel"><div class="panel-head"><div><h2>Blocking policy</h2><p>Only allowlist and block action can be changed here.</p></div></div>
<form class="form-body" method="post" action="/policies"><input type="hidden" name="_csrf" value="{{.CSRF}}"><div class="field-row"><label for="blockAction" class="field-label">Block action <span class="required">*</span></label><select id="blockAction" name="block_action" class="field" required>{{range blockActions}}<option value="{{.}}" {{if eq . (selectval $.Data.Form "block_action")}}selected{{end}}>{{.}}</option>{{end}}</select><small>Configured action for matching block rules; NXDOMAIN/REFUSED/NULL/ADDRESS/NODATA.</small></div>
<div class="field-row"><label class="field-label" for="allowlist">Allowlist entries</label><textarea id="allowlist" name="allowlist" class="field mono" rows="10" placeholder="good.example.org">{{selectval .Data.Form "allowlist"}}</textarea><small>One entry per line. Empty list explicitly clears the allowlist.</small></div>
<div class="form-actions"><button type="reset" class="btn-ui">Discard local edits</button><button type="submit" class="btn-ui btn-primary-ui">Save supported settings</button></div></form></section>
<aside class="panel guide"><div class="panel-head"><h2>Other policy fields</h2></div><div class="panel-body"><p>All other fields are read-only in the REST API. View them here; edit the EasyDNS configuration file outside this panel.</p>
{{range $key,$v := .Data.Policies.Policy}}{{if and (ne $key "allowlist") (ne $key "block_action")}}<div class="data-row"><span>{{$key}}</span><strong class="break-any">{{string $v}}</strong></div>{{end}}{{end}}</div></aside></div>{{end}}
@@ -0,0 +1,5 @@
{{define "content"}}<div class="notice-inline mb-3"><strong>Read-only.</strong> EasyDNS REST API does not expose create/update/delete methods for {{if eq .Data.Tab "views"}}views{{else if eq .Data.Tab "acl"}}named ACLs{{else}}DNS rate limits{{end}}.</div>
{{if eq .Data.Tab "views"}}<section class="panel"><div class="panel-head"><div><h2>Configured split-horizon views</h2><p>Active split-horizon configuration</p></div></div><div class="table-scroll"><table class="data-table"><thead><tr><th>VIEW</th><th>CLIENTS</th><th>RESOLUTION</th><th>RECURSION</th><th>DETAILS</th></tr></thead><tbody>{{range .Data.Policies.Views}}<tr><td class="entity">{{string (get . "name")}}</td><td class="mono">{{string (get . "clients")}}</td><td>{{string (get . "resolution")}}</td><td>{{string (get . "recursion")}}</td><td><details><summary>Show config</summary><pre class="code-block">{{asjson .}}</pre></details></td></tr>{{else}}<tr><td class="empty" colspan="5">No views returned by the API.</td></tr>{{end}}</tbody></table></div></section>
{{else if eq .Data.Tab "acl"}}<div class="dashboard-lower"><section class="panel"><div class="panel-head"><h2>Named ACLs</h2></div><div class="table-scroll"><table class="data-table"><thead><tr><th>NAME</th><th>CLIENT NETWORKS / REFERENCES</th></tr></thead><tbody>{{range $key,$v:=.Data.Policies.ACLs}}<tr><td class="mono entity">{{$key}}</td><td class="mono">{{string $v}}</td></tr>{{else}}<tr><td colspan="2" class="empty">No named ACLs configured.</td></tr>{{end}}</tbody></table></div></section><section class="panel"><div class="panel-head"><h2>Allowed clients</h2></div><div class="panel-body compact"><h3>Recursion</h3>{{range .Data.Policies.RecursionAllowedClients}}<div class="data-row mono">{{.}}</div>{{else}}<p class="muted">No entries returned.</p>{{end}}<h3 class="mt-4">REST API</h3>{{range .Data.Policies.APIAllowedClients}}<div class="data-row mono">{{.}}</div>{{else}}<p class="muted">No entries returned.</p>{{end}}</div></section></div>
{{else}}<section class="panel"><div class="panel-head"><div><h2>DNS response rate limiting</h2><p>Not the TCP REST API request throttle.</p></div></div><div class="table-scroll"><table class="data-table"><thead><tr><th>PARAMETER</th><th>EFFECTIVE VALUE</th></tr></thead><tbody>{{range $key,$v:=.Data.Policies.RateLimit}}<tr><td class="mono">{{$key}}</td><td class="mono break-any">{{string $v}}</td></tr>{{else}}<tr><td colspan="2" class="empty">No rate limiting config returned.</td></tr>{{end}}</tbody></table></div></section><div class="metric-row mt-panel"><div class="panel metric"><span class="metric-label">RATE-LIMITED RESPONSES</span><strong>{{int .Data.Stats.RateLimited}}</strong><small>Cumulative /stats counter</small></div></div>{{end}}
{{end}}
@@ -0,0 +1,3 @@
{{define "content"}}<div class="form-layout"><section class="panel"><div class="panel-head"><div><h2>DNS resolver diagnostic</h2><p>One-shot DNS query through this EasyDNS server</p></div></div><form method="get" action="/query" class="form-body"><div class="form-columns"><div class="field-row"><label for="qname" class="field-label">Domain name <span class="required">*</span></label><input id="qname" class="field mono" name="name" value="{{selectval .Data.Form "name"}}" required placeholder="example.org"></div><div class="field-row"><label for="qtype" class="field-label">Record type</label><select id="qtype" class="field" name="type">{{range recordTypes}}<option value="{{.}}" {{if eq . (selectval $.Data.Form "type")}}selected{{end}}>{{.}}</option>{{end}}</select></div></div><div class="form-actions"><button class="btn-ui btn-primary-ui" type="submit"><svg class="ico"><use href="/static/icons.svg#search"/></svg>Run lookup</button></div></form>
{{if .Data.Query}}<div class="response-summary"><div class="strip-cell"><span>RESPONSE CODE</span><strong class="{{statusclass .Data.Query.RCode}}">{{.Data.Query.RCode}}</strong></div><div class="strip-cell"><span>AUTHORITATIVE</span><strong>{{if .Data.Query.AA}}Yes{{else}}No{{end}}</strong></div><div class="strip-cell"><span>TIME</span><strong>{{float .Data.Query.ElapsedMS}} ms</strong></div></div><div class="panel-head"><h2>Answer section</h2></div><div class="table-scroll"><table class="data-table"><thead><tr><th>NAME</th><th>TYPE</th><th>TTL</th><th>RDATA</th></tr></thead><tbody>{{range .Data.Query.Answers}}<tr><td class="mono">{{.Name}}</td><td><span class="tag green">{{.Type}}</span></td><td>{{.TTL}}</td><td class="mono">{{.Data}}</td></tr>{{else}}<tr><td class="empty" colspan="4">No answer records.</td></tr>{{end}}</tbody></table></div><div class="panel-head"><h2>Authority section</h2></div><div class="table-scroll"><table class="data-table"><thead><tr><th>NAME</th><th>TYPE</th><th>TTL</th><th>RDATA</th></tr></thead><tbody>{{range .Data.Query.Authority}}<tr><td class="mono">{{.Name}}</td><td><span class="tag blue">{{.Type}}</span></td><td>{{.TTL}}</td><td class="mono">{{.Data}}</td></tr>{{else}}<tr><td class="empty" colspan="4">No authority records returned.</td></tr>{{end}}</tbody></table></div>{{end}}</section>
<aside class="panel guide"><div class="panel-head"><h2>Diagnostics</h2></div><div class="panel-body"><p>The query is sent through the actual EasyDNS listener using the server API. It is not an external DNS testing service.</p><div class="data-row"><span>Query history</span><strong>Unavailable</strong></div><div class="data-row"><span>Live lookup</span><strong class="success">Supported</strong></div><div class="notice-inline mt-panel">The EasyDNS API defaults an unrecognized type to A. This UI limits the type selector to recognized values.</div></div></aside></div>{{end}}
@@ -0,0 +1,8 @@
{{define "content"}}<div class="form-layout"><section class="panel"><div class="panel-head"><div><h2>{{if eq .Data.Action "edit"}}Edit existing record{{else}}New DNS record{{end}}</h2><p>Zone <span class="mono">{{.Data.Zone.Name}}</span> · serial guarded by ETag</p></div><a href="{{.Data.ZoneURL}}/records" class="btn-ui btn-small">Back to records</a></div>
{{if .Data.IsPrimary}}<form class="form-body" method="post" action="{{if eq .Data.Action "edit"}}{{.Data.ZoneURL}}/records/{{.Data.Record.ID}}{{else}}{{.Data.ZoneURL}}/records{{end}}"><input type="hidden" name="_csrf" value="{{.CSRF}}"><input type="hidden" name="etag" value="{{.Data.ETag}}">
<div class="form-columns"><div class="field-row"><label class="field-label" for="recordName">Record name <span class="required">*</span></label><input class="field mono" id="recordName" name="name" required value="{{selectval .Data.Form "name"}}" placeholder="www or @"><small>@ for zone apex; relative names are allowed.</small></div><div class="field-row"><label class="field-label" for="recordType">Record type <span class="required">*</span></label><select class="field" name="type" id="recordType" required><option value="">Select record type</option>{{range recordTypes}}<option value="{{.}}" {{if eq (selectval $.Data.Form "type") .}}selected{{end}} {{if eq . "SOA"}}disabled{{end}}>{{.}}</option>{{end}}</select><small>SOA changes require whole-zone replacement.</small></div></div>
<div class="field-row"><label class="field-label" for="recordData">Record data (RDATA) <span class="required">*</span></label><textarea id="recordData" class="field mono" name="data" rows="4" required placeholder="192.0.2.10">{{selectval .Data.Form "data"}}</textarea><small>Use the syntax expected for the selected RR type; Rust validates exact RDATA format.</small></div>
<div class="form-columns"><div class="field-row"><label class="field-label" for="recordTTL">TTL in seconds <span class="required">*</span></label><input class="field mono" id="recordTTL" name="ttl" type="number" min="0" max="4294967295" required value="{{selectval .Data.Form "ttl"}}"><small>0–4,294,967,295. Default: 3600.</small></div><div class="field-row"><label class="field-label">Current zone serial</label><div class="field readout mono">{{.Data.Zone.SerialText}}</div><small>Changes to the serial may trigger HTTP 412.</small></div></div>
<div class="form-actions"><a href="{{.Data.ZoneURL}}/records" class="btn-ui">Cancel</a><button class="btn-ui btn-primary-ui" type="submit"><svg class="ico"><use href="/static/icons.svg#save"/></svg>{{if eq .Data.Action "edit"}}Save changes{{else}}Add record{{end}}</button></div></form>{{else}}<div class="panel-body"><div class="notice-inline">This zone is secondary or unavailable. Record modifications are not allowed.</div></div>{{end}}</section>
<aside class="panel guide"><div class="panel-head"><h2>Write behavior</h2></div><div class="panel-body"><p>This form uses an existing EasyDNS operation. There is no record-details endpoint; edits are populated from the record list.</p><div class="data-row"><span>Change conflict</span><strong>412</strong></div><div class="data-row"><span>Validation error</span><strong>400 / 422</strong></div><div class="data-row"><span>Secondary zone</span><strong>409</strong></div><div class="notice-inline mt-panel">The server may assign a different record ID after changing the name, type or value.</div></div></aside>
</div>{{end}}
@@ -0,0 +1,3 @@
{{define "content"}}<div class="form-layout"><section class="panel"><div class="panel-head"><div><h2>Full zone-file replacement</h2><p>{{.Data.Zone.Name}} · submit complete replacement content</p></div></div><div class="panel-body"><div class="notice danger"><strong>Destructive replacement.</strong> The EasyDNS API does not return original zone file text. Paste a complete replacement file that you already possess.</div></div>
<form class="form-body" method="post" action="{{.Data.ZoneURL}}/replace"><input type="hidden" name="_csrf" value="{{.CSRF}}"><input type="hidden" name="etag" value="{{.Data.ETag}}"><div class="field-row"><label class="field-label" for="zoneFull">Complete zone file <span class="required">*</span></label><textarea class="field code-input mono" id="zoneFull" rows="15" spellcheck="false" name="zone_file" required placeholder="Paste the full zone file here. Nothing is preloaded.">{{selectval .Data.Form "zone_file"}}</textarea></div><div class="field-row"><label class="field-label" for="replaceConfirm">Type REPLACE to confirm <span class="required">*</span></label><input id="replaceConfirm" name="confirm" class="field mono" required pattern="REPLACE" autocomplete="off" placeholder="REPLACE"></div><div class="form-actions"><a class="btn-ui" href="{{.Data.ZoneURL}}">Cancel</a><button class="btn-ui btn-danger-ui" type="submit">Replace zone contents</button></div></form></section>
<aside class="panel guide"><div class="panel-head"><h2>Before you continue</h2></div><div class="panel-body"><p>Back up the original zone from its source outside this panel. The API validates the full replacement, calculates the diff, updates the serial and sends NOTIFY where configured.</p><div class="data-row"><span>Current serial</span><strong class="mono">{{.Data.Zone.SerialText}}</strong></div><div class="data-row"><span>Conflict</span><strong>412</strong></div><div class="data-row"><span>Invalid content</span><strong>422</strong></div></div></aside></div>{{end}}
@@ -0,0 +1,5 @@
{{define "content"}}<div class="status-strip panel compact-strip"><div class="strip-cell"><span>HEALTH</span><strong class="{{statusclass .Data.Health.Status}}">{{if .Data.Health.Status}}{{.Data.Health.Status}}{{else}}Unavailable{{end}}</strong></div><div class="strip-cell"><span>READINESS</span><strong>{{selectval .Data.Filter "ready"}}</strong></div><div class="strip-cell"><span>MODE</span><strong>{{.Data.Status.Mode}}</strong></div><div class="strip-cell"><span>UPTIME</span><strong>{{uptime .Data.Status.UptimeSeconds}}</strong></div><div class="strip-cell"><span>VERSION</span><strong>{{.Data.Status.Version}}</strong></div></div>
<div class="dashboard-lower mt-panel"><section class="panel"><div class="panel-head"><h2>DNS roles</h2></div><div class="panel-body compact"><div class="data-row"><span>Primary zones</span><strong>{{int .Data.Status.Roles.Primary}}</strong></div><div class="data-row"><span>Secondary zones</span><strong>{{int .Data.Status.Roles.Secondary}}</strong></div><div class="data-row"><span>Recursive role</span><strong>{{.Data.Status.Roles.Recursive}}</strong></div><div class="data-row"><span>Forwarder role</span><strong>{{.Data.Status.Roles.Forwarder}}</strong></div><div class="data-row"><span>Forward zones</span><strong>{{.Data.Status.Roles.ForwardZones}}</strong></div><div class="data-row"><span>Default resolution</span><strong>{{.Data.Status.Roles.DefaultResolution}}</strong></div></div></section>
<section class="panel"><div class="panel-head"><h2>Bound listeners</h2></div><div class="panel-body compact">{{range $key,$v:=.Data.Status.Listeners}}<div class="data-row"><span>{{$key}}</span><strong class="mono break-any">{{string $v}}</strong></div>{{else}}<div class="empty">No listener information.</div>{{end}}</div></section>
<section class="panel"><div class="panel-head"><h2>Health / expired zones</h2></div><div class="panel-body compact"><div class="data-row"><span>Health</span><strong class="{{statusclass .Data.Health.Status}}">{{.Data.Health.Status}}</strong></div><div class="data-row"><span>Expired zones</span><strong>{{len .Data.Health.ExpiredZones}}</strong></div>{{range .Data.Health.ExpiredZones}}<div class="data-row mono danger">{{.}}</div>{{else}}<p class="muted mt-3">No expired zones returned.</p>{{end}}</div></section></div>
<section class="panel mt-panel"><div class="panel-head"><h2>Per-zone runtime state</h2></div><div class="table-scroll"><table class="data-table"><thead><tr><th>NAME</th><th>ROLE</th><th>LOADED</th><th>EXPIRED</th><th>SERIAL</th><th>RECORDS</th><th>LAST SYNC</th></tr></thead><tbody>{{range .Data.Status.Zones}}<tr><td><a class="entity mono" href="{{zoneurl .Name}}">{{.Name}}</a></td><td>{{.Kind}}</td><td>{{.Loaded}}</td><td>{{.Expired}}</td><td class="mono">{{.SerialText}}</td><td>{{.Records}}</td><td class="mono">{{.LastSync}}</td></tr>{{else}}<tr><td colspan="7" class="empty">No zones in status response.</td></tr>{{end}}</tbody></table></div></section>{{end}}
@@ -0,0 +1 @@
{{define "content"}}<div class="form-layout"><section class="panel"><div class="panel-head"><div><h2>New upstream server</h2><p>EasyDNS validates the transport URI and reloads its configuration.</p></div></div><form method="post" action="/upstreams" class="form-body"><input type="hidden" name="_csrf" value="{{.CSRF}}"><div class="field-row"><label class="field-label" for="address">Upstream address <span class="required">*</span></label><input class="field mono" id="address" name="address" required value="{{selectval .Data.Form "address"}}" placeholder="1.1.1.1"><small>IP address or IP:port. For encrypted transports use a protocol scheme and TLS server name.</small></div><div class="form-actions"><a class="btn-ui" href="/upstreams">Cancel</a><button class="btn-ui btn-primary-ui" type="submit">Add upstream</button></div></form></section><aside class="panel guide"><div class="panel-head"><h2>Accepted formats</h2></div><div class="panel-body"><p class="mono code-example">1.1.1.1<br>1.1.1.1:53<br>tcp://1.1.1.1<br>tls://1.1.1.1#cloudflare-dns.com<br>https://1.1.1.1/dns-query#cloudflare-dns.com</p><p>Encrypted transports require the certificate's DNS name. No server deletion endpoint exists.</p></div></aside></div>{{end}}
@@ -0,0 +1,4 @@
{{define "content"}}<section class="panel"><div class="toolbar"><div class="toolbar-title"><h2>Resolver pools</h2><p>Runtime upstream health and forwarding strategy.</p></div><a class="btn-ui btn-primary-ui" href="/upstreams/new"><svg class="ico"><use href="/static/icons.svg#plus"/></svg>Add upstream</a></div>
{{range .Data.Upstreams}}<div class="pool-head"><div><h3>{{.Group}}</h3><span class="subtle">Strategy: {{.Strategy}}</span></div><span class="tag blue">{{len .Servers}} servers</span></div><div class="table-scroll"><table class="data-table"><thead><tr><th>ADDRESS</th><th>HEALTH</th><th>QUERIES</th><th>FAILURES</th><th>EWMA RTT</th><th>CIRCUIT</th><th>LAST ERROR</th></tr></thead><tbody>
{{range .Servers}}<tr><td class="mono entity">{{.Address}}</td><td><span class="dot {{if .Stats.Healthy}}ok{{else}}warn{{end}}"></span>{{if .Stats.Healthy}}Healthy{{else}}Unavailable{{end}}</td><td class="mono">{{int .Stats.Queries}}</td><td class="mono">{{int .Stats.Failures}}</td><td class="mono">{{if .Stats.EWMARTTMS}}{{float .Stats.EWMARTTMS}} ms{{else}}—{{end}}</td><td class="mono">{{if .Stats.CircuitOpenForMS}}Open{{else}}Closed / unknown{{end}}</td><td class="muted">{{if .Stats.LastError}}{{.Stats.LastError}}{{else}}—{{end}}</td></tr>{{else}}<tr><td class="empty" colspan="7">No servers in this pool.</td></tr>{{end}}
</tbody></table></div>{{else}}<div class="empty">No upstream groups returned by EasyDNS.</div>{{end}}</section><div class="notice-inline mt-panel">The API supports adding an upstream address, but does not provide a REST method to edit or remove upstreams or reorder pools.</div>{{end}}
@@ -0,0 +1,9 @@
{{define "content"}}<div class="form-layout"><section class="panel"><div class="panel-head"><div><h2>{{if eq .Data.Action "import"}}Import complete zone file{{else}}Create from nameservers{{end}}</h2><p>Primary zones only · validated before activation</p></div></div>
<div class="mode-tabs"><a class="tab {{if ne .Data.Action "import"}}active{{end}}" href="/zones/new">From nameservers</a><a class="tab {{if eq .Data.Action "import"}}active{{end}}" href="/zones/import">From zone file</a></div>
<form method="post" action="/zones" class="form-body"><input type="hidden" name="_csrf" value="{{.CSRF}}"><input type="hidden" name="mode" value="{{.Data.Action}}">
<div class="field-row"><label class="field-label" for="zoneName">Zone name <span class="required">*</span></label><input id="zoneName" class="field" type="text" name="name" required placeholder="example.org" value="{{selectval .Data.Form "name"}}"><small>Use a full DNS zone name. Creating a secondary is not supported by this API.</small></div>
{{if eq .Data.Action "import"}}<div class="field-row"><label class="field-label" for="zoneFile">Complete zone file <span class="required">*</span></label><textarea id="zoneFile" class="field mono code-input" name="zone_file" rows="13" spellcheck="false" required placeholder="$TTL 3600&#10;@ IN SOA ns1.example.org. hostmaster.example.org. 1 3600 900 1209600 300&#10;@ IN NS ns1.example.org.">{{selectval .Data.Form "zone_file"}}</textarea><small>Paste original zone file content you own. EasyDNS does not expose zone files for download via REST.</small></div>
{{else}}<div class="field-row"><label class="field-label" for="zoneNS">Nameservers <span class="required">*</span></label><textarea id="zoneNS" class="field mono" name="ns" rows="4" placeholder="ns1.example.org.&#10;ns2.example.org." required>{{selectval .Data.Form "ns"}}</textarea><small>One FQDN per line; the API generates a minimal SOA/NS zone.</small></div><div class="field-row"><label class="field-label" for="hostmaster">SOA hostmaster</label><input id="hostmaster" class="field mono" name="hostmaster" value="{{selectval .Data.Form "hostmaster"}}" placeholder="hostmaster.example.org."></div>{{end}}
<div class="form-columns"><div class="field-row"><label class="field-label" for="transferAcl">Transfer ACL (optional)</label><textarea class="field mono" id="transferAcl" name="transfer_acl" rows="3" placeholder="192.0.2.0/24">{{selectval .Data.Form "transfer_acl"}}</textarea><small>Networks, one per line.</small></div><div class="field-row"><label class="field-label" for="notify">NOTIFY targets (optional)</label><textarea class="field mono" id="notify" name="notify" rows="3" placeholder="192.0.2.20:53">{{selectval .Data.Form "notify"}}</textarea><small>IP:port socket addresses, one per line.</small></div></div>
<div class="form-actions"><a href="/zones" class="btn-ui">Cancel</a><button class="btn-ui btn-primary-ui" type="submit"><svg class="ico"><use href="/static/icons.svg#plus"/></svg>Create primary zone</button></div>
</form></section><aside class="panel guide"><div class="panel-head"><h2>Creation details</h2></div><div class="panel-body"><p>This is a configuration-changing operation. EasyDNS validates the zone, persists it in the API overlay and reloads the runtime.</p><div class="data-row"><span>Already exists</span><strong>409</strong></div><div class="data-row"><span>Invalid zone file</span><strong>422</strong></div><div class="data-row"><span>Invalid request</span><strong>400</strong></div><div class="notice-inline mt-panel">The nameservers/hostmaster form does not create secondary zones.</div></div></aside></div>{{end}}
@@ -0,0 +1,44 @@
{{define "content"}}
<div class="status-strip panel zone-strip">
<div class="strip-cell"><span>ZONE STATE</span><strong><span class="dot {{statusclass .Data.Zone.StateText}}"></span>{{.Data.Zone.StateText}}</strong></div>
<div class="strip-cell"><span>SERIAL</span><strong class="mono">{{.Data.Zone.SerialText}}</strong></div>
<div class="strip-cell"><span>TYPE</span><strong>{{.Data.Zone.Kind}}</strong></div>
<div class="strip-cell"><span>RECORDS</span><strong>{{.Data.Zone.Records}}</strong></div>
<div class="strip-cell"><span>TRANSFER / SYNC</span><strong>{{if .Data.Zone.IsSecondary}}{{.Data.Zone.SyncText}}{{else}}—{{end}}</strong></div>
<div class="strip-cell"><span>LAST SYNC</span><strong class="small-text">{{.Data.Zone.LastSync}}</strong></div>
</div>
<div class="tabs" role="navigation" aria-label="Zone views">
<a {{if eq .Data.Tab "overview"}}class="tab active" aria-current="page"{{else}}class="tab"{{end}} href="{{.Data.ZoneURL}}">Overview</a>
<a {{if eq .Data.Tab "records"}}class="tab active" aria-current="page"{{else}}class="tab"{{end}} href="{{.Data.ZoneURL}}/records">Records</a>
<a {{if eq .Data.Tab "transfers"}}class="tab active" aria-current="page"{{else}}class="tab"{{end}} href="{{.Data.ZoneURL}}/transfers">Transfers / History</a>
<a {{if eq .Data.Tab "dnssec"}}class="tab active" aria-current="page"{{else}}class="tab"{{end}} href="{{.Data.ZoneURL}}/dnssec">DNSSEC</a>
<a {{if eq .Data.Tab "operations"}}class="tab active" aria-current="page"{{else}}class="tab"{{end}} href="{{.Data.ZoneURL}}/operations">Operations</a>
</div>
{{if eq .Data.Tab "overview"}}
<div class="dashboard-lower three-cards">
<section class="panel"><div class="panel-head"><div><h2>Zone status</h2><p>Live authoritative store state</p></div></div><div class="panel-body compact"><div class="data-row"><span>Zone name</span><strong class="mono">{{.Data.Zone.Name}}</strong></div><div class="data-row"><span>Loaded</span><strong>{{if .Data.Zone.Loaded}}Yes{{else}}No{{end}}</strong></div><div class="data-row"><span>Expired</span><strong class="{{if .Data.Zone.Expired}}danger{{else}}success{{end}}">{{if .Data.Zone.Expired}}Yes{{else}}No{{end}}</strong></div><div class="data-row"><span>Journal entries</span><strong>{{.Data.Zone.JournalEntries}}</strong></div><div class="data-row"><span>View associations</span><strong>{{if .Data.Zone.Views}}{{join .Data.Zone.Views ", "}}{{else}}Default{{end}}</strong></div></div></section>
<section class="panel"><div class="panel-head"><div><h2>Transfer &amp; notification</h2><p>Configured values from zone detail</p></div></div><div class="panel-body compact"><div class="data-row"><span>NOTIFY targets</span><strong>{{len .Data.Zone.Config.Notify}}</strong></div><div class="data-row"><span>Transfer ACL entries</span><strong>{{len .Data.Zone.Config.TransferACL}}</strong></div><div class="data-row"><span>Primaries</span><strong>{{len .Data.Zone.Config.Primaries}}</strong></div><div class="data-row"><span>NOTIFY sent</span><strong>{{int .Data.Zone.Status.NotifiesSent}}</strong></div><div class="data-row"><span>NOTIFY failed</span><strong>{{int .Data.Zone.Status.NotifiesFailed}}</strong></div></div></section>
<section class="panel"><div class="panel-head"><div><h2>Secondary refresh</h2><p>Only applicable to secondary zones</p></div></div><div class="panel-body compact"><div class="data-row"><span>Last successful</span><strong class="small-text">{{.Data.Zone.LastSync}}</strong></div><div class="data-row"><span>Last error</span><strong class="danger">{{if .Data.Zone.Status.LastError}}{{.Data.Zone.Status.LastError}}{{else}}—{{end}}</strong></div><div class="data-row"><span>Serial</span><strong>{{.Data.Zone.SerialText}}</strong></div></div></section>
</div>
<div class="section-actions"><a class="btn-ui btn-primary-ui" href="{{.Data.ZoneURL}}/records">View DNS records</a><a class="btn-ui" href="{{.Data.ZoneURL}}/transfers">Transfer history</a><a class="btn-ui" href="{{.Data.ZoneURL}}/operations">Zone operations</a></div>
{{else if eq .Data.Tab "records"}}
<section class="panel"><div class="toolbar"><form class="toolbar-form" method="get" action="{{.Data.ZoneURL}}/records"><input class="field field-search" name="name" placeholder="Record name begins with..." aria-label="Filter record names" value="{{selectval .Data.Filter "name"}}"><select class="field field-select" aria-label="Record type" name="type"><option value="">All types</option>{{range $type := recordTypes}}<option value="{{$type}}" {{if eq (selectval $.Data.Filter "type") $type}}selected{{end}}>{{$type}}</option>{{end}}</select><button type="submit" class="btn-ui"><svg class="ico"><use href="/static/icons.svg#search"/></svg>Filter</button></form>
<div class="toolbar-end"><span class="subtle desktop-only">{{.Data.Pagination.Total}} records</span>{{if .Data.IsPrimary}}<a class="btn-ui btn-primary-ui" href="{{.Data.ZoneURL}}/records/new"><svg class="ico"><use href="/static/icons.svg#plus"/></svg>Add record</a>{{else}}<span class="tag muted-tag">Secondary · read-only</span>{{end}}</div></div>
<div class="table-scroll"><table class="data-table"><thead><tr><th>NAME</th><th>TYPE</th><th>RDATA</th><th>TTL</th>{{if .Data.IsPrimary}}<th class="right">ACTIONS</th>{{end}}</tr></thead><tbody>
{{range .Data.Records}}<tr><td class="mono entity">{{.Name}}</td><td><span class="tag green">{{.Type}}</span></td><td class="mono rdata">{{.Data}}</td><td class="mono">{{.TTL}}</td>{{if $.Data.IsPrimary}}<td class="right">{{if ne .Type "SOA"}}<div class="row-actions"><a href="{{$.Data.ZoneURL}}/records/{{.ID}}/edit?page={{$.Data.Pagination.Page}}" class="icon-button" aria-label="Edit record {{.Name}}" title="Edit"><svg class="ico"><use href="/static/icons.svg#edit"/></svg></a><a href="{{$.Data.ZoneURL}}/records/{{.ID}}/delete?page={{$.Data.Pagination.Page}}" class="icon-button danger-hover" aria-label="Delete record {{.Name}}" title="Delete"><svg class="ico"><use href="/static/icons.svg#trash"/></svg></a></div>{{else}}<span class="subtle" title="SOA is managed by zone replacement">Managed</span>{{end}}</td>{{end}}</tr>{{else}}<tr><td class="empty" colspan="5">No records returned for this filter.</td></tr>{{end}}
</tbody></table></div><div class="table-footer"><span>{{len .Data.Records}} / {{.Data.Pagination.Total}} records · page {{.Data.Pagination.Page}}</span><div class="pagination-ui">{{if gt .Data.Pagination.Page 1}}<a class="btn-ui btn-small" href="{{.Data.ZoneURL}}/records?page={{dec .Data.Pagination.Page}}&amp;name={{selectval .Data.Filter "name"}}&amp;type={{selectval .Data.Filter "type"}}">Previous</a>{{end}}{{if lt (multiply .Data.Pagination.Page .Data.Pagination.PerPage) .Data.Pagination.Total}}<a class="btn-ui btn-small" href="{{.Data.ZoneURL}}/records?page={{inc .Data.Pagination.Page}}&amp;name={{selectval .Data.Filter "name"}}&amp;type={{selectval .Data.Filter "type"}}">Next</a>{{end}}</div></div></section>
<div class="notice-inline mt-panel">Writes are protected with the zone serial ETag. SOA records are managed through whole-zone replacement; secondaries are read-only.</div>
{{else if eq .Data.Tab "transfers"}}
<section class="panel"><div class="panel-head"><div><h2>Zone transfer history</h2><p>Recorded inbound and outbound AXFR / IXFR events</p></div></div><div class="table-scroll"><table class="data-table"><thead><tr><th>TIME</th><th>DIRECTION</th><th>TYPE</th><th>PEER</th><th>SERIAL</th><th>RECORDS</th><th>DURATION</th><th>RESULT</th></tr></thead><tbody>{{range .Data.Transfers}}<tr><td class="mono subtle">{{when .TimeUnix}}</td><td>{{.Direction}}</td><td><span class="tag green">{{.Kind}}</span></td><td class="mono">{{.Peer}}</td><td class="mono">{{if .Serial}}{{.Serial}}{{else}}—{{end}}</td><td>{{.Records}}</td><td class="mono">{{.DurationMS}} ms</td><td><span class="dot {{if .OK}}ok{{else}}danger{{end}}"></span>{{if .OK}}Completed{{else}}{{if .Error}}{{.Error}}{{else}}Failed{{end}}{{end}}</td></tr>{{else}}<tr><td class="empty" colspan="8">No recorded transfers. This API provides history, not a live transfer queue.</td></tr>{{end}}</tbody></table></div></section>
{{else if eq .Data.Tab "dnssec"}}
<section class="panel"><div class="panel-head"><div><h2>DNSSEC status</h2><p>Inspection only. Key lifecycle and signing changes are not exposed through REST.</p></div></div><div class="panel-body">{{if .Data.Zone.DNSSEC}}<div class="code-block"><pre>{{asjson .Data.Zone.DNSSEC}}</pre></div>{{else}}<div class="empty">No DNSSEC status returned for this zone.</div>{{end}}</div></section>
{{else if eq .Data.Tab "operations"}}
<div class="operations-grid"><section class="panel"><div class="panel-head"><div><h2>Supported zone actions</h2><p>Available operations depend on the zone role and configuration</p></div></div><div class="panel-body">
{{if .Data.Zone.IsSecondary}}<form method="post" action="{{.Data.ZoneURL}}/sync" class="operation"><input type="hidden" name="_csrf" value="{{.CSRF}}"><input type="hidden" name="confirm" value="yes"><div><strong>Synchronize secondary</strong><small>Request an immediate refresh from its primary.</small></div><button class="btn-ui" type="submit"><svg class="ico"><use href="/static/icons.svg#refresh"/></svg>Sync now</button></form>{{end}}
{{if .Data.Zone.Config.Notify}}<form method="post" action="{{.Data.ZoneURL}}/notify" class="operation"><input type="hidden" name="_csrf" value="{{.CSRF}}"><input type="hidden" name="confirm" value="yes"><div><strong>Send DNS NOTIFY</strong><small>{{len .Data.Zone.Config.Notify}} configured targets · HTTP 202 means accepted, not delivered</small></div><button class="btn-ui" type="submit"><svg class="ico"><use href="/static/icons.svg#bell"/></svg>Send NOTIFY</button></form>{{end}}
{{if .Data.Zone.IsPrimary}}<div class="operation"><div><strong>Replace zone contents</strong><small>Submit a complete operator-provided zone file. No original file download.</small></div><a href="{{.Data.ZoneURL}}/replace" class="btn-ui">Replace zone</a></div>{{end}}
<div class="operation"><div><strong>Delete API-created zone</strong><small>Only zones created in the API overlay are deletable; others return HTTP 409.</small></div><a href="{{.Data.ZoneURL}}/delete" class="btn-ui btn-danger-ui">Delete zone</a></div>
{{if and (not .Data.Zone.IsSecondary) (not .Data.Zone.IsPrimary)}}<div class="empty">Zone operations require a loaded zone.</div>{{end}}
</div></section><section class="panel"><div class="panel-head"><div><h2>Configured transfer access</h2><p>Read-only zone configuration</p></div></div><div class="panel-body"><h3>Transfer ACL</h3>{{range .Data.Zone.Config.TransferACL}}<div class="data-row mono">{{.}}</div>{{else}}<p class="muted">No transfer ACL entries.</p>{{end}}<h3 class="mt-4">NOTIFY targets</h3>{{range .Data.Zone.Config.Notify}}<div class="data-row mono">{{.}}</div>{{else}}<p class="muted">No NOTIFY targets.</p>{{end}}<h3 class="mt-4">Primary servers</h3>{{range .Data.Zone.Config.Primaries}}<div class="data-row mono">{{.}}</div>{{else}}<p class="muted">No primary servers in this zone configuration.</p>{{end}}</div></section></div>
{{end}}
{{end}}
@@ -0,0 +1,11 @@
{{define "content"}}
<div class="status-strip panel compact-strip"><div class="strip-cell"><span>TOTAL ZONES (CURRENT FILTER)</span><strong>{{int .Data.Pagination.Total}}</strong></div><div class="strip-cell"><span>ITEMS PER PAGE</span><strong>{{.Data.Pagination.PerPage}}</strong></div><div class="strip-cell"><span>CURRENT PAGE</span><strong>{{.Data.Pagination.Page}}</strong></div><div class="strip-cell"><span>ZONE TYPES</span><strong>Primary · Secondary</strong></div></div>
<section class="panel mt-panel"><div class="toolbar">
<form action="/zones" method="get" class="toolbar-form"><label class="sr-only" for="searchZones">Search zones</label><input class="field field-search" id="searchZones" name="name" placeholder="Search zones by name" value="{{selectval .Data.Filter "name"}}"><select class="field field-select" name="kind" aria-label="Zone type"><option value="">All types</option><option value="primary" {{if eq (selectval .Data.Filter "kind") "primary"}}selected{{end}}>Primary</option><option value="secondary" {{if eq (selectval .Data.Filter "kind") "secondary"}}selected{{end}}>Secondary</option></select><button class="btn-ui" type="submit"><svg class="ico"><use href="/static/icons.svg#search"/></svg> Search</button></form>
<div class="toolbar-end"><a class="btn-ui" href="/zones/import"><svg class="ico"><use href="/static/icons.svg#upload"/></svg> Import zone file</a><a class="btn-ui btn-primary-ui" href="/zones/new"><svg class="ico"><use href="/static/icons.svg#plus"/></svg> Add zone</a></div></div>
<div class="table-scroll"><table class="data-table"><thead><tr><th>ZONE NAME</th><th>TYPE</th><th>SERIAL</th><th>RECORDS</th><th>STATE</th><th>TRANSFER / SYNC</th><th>LAST SUCCESSFUL SYNC</th><th class="right">ACTION</th></tr></thead><tbody>
{{range .Data.Zones}}<tr><td><a class="entity" href="{{zoneurl .Name}}">{{.Name}}</a></td><td><span class="tag {{if .IsSecondary}}blue{{else}}green{{end}}">{{.Kind}}</span></td><td class="mono">{{.SerialText}}</td><td class="mono">{{.Records}}</td><td><span class="dot {{if .Loaded}}{{if .Expired}}danger{{else}}ok{{end}}{{else}}warn{{end}}"></span>{{.StateText}}</td><td>{{if .IsSecondary}}<span class="dot {{statusclass .SyncText}}"></span>{{.SyncText}}{{else}}<span class="subtle">—</span>{{end}}</td><td class="mono subtle">{{if .IsSecondary}}{{.LastSync}}{{else}}—{{end}}</td><td class="right"><a class="btn-ui btn-small" href="{{zoneurl .Name}}">Open <svg class="ico"><use href="/static/icons.svg#arrow-right"/></svg></a></td></tr>{{else}}<tr><td class="empty" colspan="8">No zones match the current filter, or the API is not available.</td></tr>{{end}}
</tbody></table></div>
<div class="table-footer"><span>Showing {{len .Data.Zones}} of {{int .Data.Pagination.Total}} zones · page {{.Data.Pagination.Page}}</span><div class="pagination-ui"><a class="btn-ui btn-small" href="/zones?page=1&amp;name={{selectval .Data.Filter "name"}}&amp;kind={{selectval .Data.Filter "kind"}}">First</a>{{if gt .Data.Pagination.Page 1}}<a class="btn-ui btn-small" href="/zones?page={{dec .Data.Pagination.Page}}&amp;name={{selectval .Data.Filter "name"}}&amp;kind={{selectval .Data.Filter "kind"}}">Previous</a>{{end}}{{if lt (multiply .Data.Pagination.Page .Data.Pagination.PerPage) .Data.Pagination.Total}}<a class="btn-ui btn-small" href="/zones?page={{inc .Data.Pagination.Page}}&amp;name={{selectval .Data.Filter "name"}}&amp;kind={{selectval .Data.Filter "kind"}}">Next</a>{{end}}</div></div>
</section><div class="notice-inline mt-panel">Primary zones can be created through REST. Secondary zone creation and general zone configuration editing are not exposed by EasyDNS.</div>
{{end}}
+111
View File
@@ -0,0 +1,111 @@
// Package telemetry derives time series from real EasyDNS counter polls.
// EasyDNS REST does not expose history; no datapoints are synthesized.
package telemetry
import (
"context"
"sync"
"time"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns"
)
const maxSamples = 1440 // six hours at a fifteen-second sampling interval
type Sample struct {
Time time.Time `json:"time"`
QueriesTotal uint64 `json:"-"`
NoError uint64 `json:"-"`
NXDomain uint64 `json:"-"`
ServFail uint64 `json:"-"`
Refused uint64 `json:"-"`
Blocked uint64 `json:"-"`
RateLimited uint64 `json:"-"`
CacheHits uint64 `json:"-"`
CacheMisses uint64 `json:"-"`
QueryRate *float64 `json:"queryRate"`
NoErrorRate *float64 `json:"noerror"`
NXDomainRate *float64 `json:"nxdomain"`
ServFailRate *float64 `json:"servfail"`
RefusedRate *float64 `json:"refused"`
BlockedRate *float64 `json:"blocked"`
CacheHitRate *float64 `json:"cacheHitRate"`
P50MS float64 `json:"p50ms"`
P95MS float64 `json:"p95ms"`
P99MS float64 `json:"p99ms"`
}
type History struct {
mu sync.RWMutex
samples []Sample
lastErr string
lastPoll time.Time
}
func New() *History { return &History{samples: make([]Sample, 0, maxSamples)} }
func delta(a, b uint64, secs float64) *float64 {
if secs <= 0 || b < a {
return nil
}
v := float64(b-a) / secs
return &v
}
func (h *History) Record(t time.Time, s easydns.Stats) {
p := Sample{Time: t, QueriesTotal: s.QueriesTotal, NoError: s.Responses["noerror"], NXDomain: s.Responses["nxdomain"], ServFail: s.Responses["servfail"], Refused: s.Responses["refused"], Blocked: s.Blocked, RateLimited: s.RateLimited, CacheHits: s.Cache.Hits, CacheMisses: s.Cache.Misses, P50MS: s.LatencyP50S * 1000, P95MS: s.LatencyP95S * 1000, P99MS: s.LatencyP99S * 1000}
h.mu.Lock()
defer h.mu.Unlock()
if len(h.samples) > 0 {
prev := h.samples[len(h.samples)-1]
secs := t.Sub(prev.Time).Seconds()
p.QueryRate = delta(prev.QueriesTotal, p.QueriesTotal, secs)
p.NoErrorRate = delta(prev.NoError, p.NoError, secs)
p.NXDomainRate = delta(prev.NXDomain, p.NXDomain, secs)
p.ServFailRate = delta(prev.ServFail, p.ServFail, secs)
p.RefusedRate = delta(prev.Refused, p.Refused, secs)
p.BlockedRate = delta(prev.Blocked, p.Blocked, secs)
if p.CacheHits >= prev.CacheHits && p.CacheMisses >= prev.CacheMisses {
hits := p.CacheHits - prev.CacheHits
misses := p.CacheMisses - prev.CacheMisses
if hits+misses > 0 {
v := 100 * float64(hits) / float64(hits+misses)
p.CacheHitRate = &v
}
}
}
h.samples = append(h.samples, p)
if len(h.samples) > maxSamples {
h.samples = append([]Sample(nil), h.samples[len(h.samples)-maxSamples:]...)
}
h.lastPoll = t
h.lastErr = ""
}
func (h *History) Failed(msg string) { h.mu.Lock(); defer h.mu.Unlock(); h.lastErr = msg }
func (h *History) Snapshot() ([]Sample, string, time.Time) {
h.mu.RLock()
defer h.mu.RUnlock()
v := append([]Sample(nil), h.samples...)
return v, h.lastErr, h.lastPoll
}
func (h *History) Run(ctx context.Context, c *easydns.Client) {
poll := func() {
var stats easydns.Stats
ctxReq, cancel := context.WithTimeout(ctx, 8*time.Second)
defer cancel()
if _, err := c.Get(ctxReq, "/api/v1/stats", &stats); err != nil {
h.Failed("API sampling unavailable")
return
}
h.Record(time.Now().UTC(), stats)
}
poll()
ticker := time.NewTicker(15 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
poll()
}
}
}
+33
View File
@@ -0,0 +1,33 @@
package telemetry
import (
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns"
"testing"
"time"
)
func TestSamplesAreMeasuredOnly(t *testing.T) {
h := New()
t0 := time.Unix(1000000, 0)
h.Record(t0, easydns.Stats{QueriesTotal: 100, Responses: map[string]uint64{"noerror": 90}, Cache: easydns.Cache{Hits: 50, Misses: 10}, LatencyP95S: 0.014})
sm, _, _ := h.Snapshot()
if len(sm) != 1 || sm[0].QueryRate != nil {
t.Fatal("must not fake initial rate")
}
h.Record(t0.Add(10*time.Second), easydns.Stats{QueriesTotal: 150, Responses: map[string]uint64{"noerror": 136}, Cache: easydns.Cache{Hits: 90, Misses: 20}, LatencyP95S: 0.010})
sm, _, _ = h.Snapshot()
if len(sm) != 2 || sm[1].QueryRate == nil || *sm[1].QueryRate != 5 {
t.Fatalf("bad query rate: %+v", sm)
}
if sm[1].CacheHitRate == nil || *sm[1].CacheHitRate != 80 {
t.Fatalf("bad cache ratio: %+v", sm[1].CacheHitRate)
}
if sm[1].P95MS != 10 {
t.Fatalf("bad latency: %v", sm[1].P95MS)
}
h.Record(t0.Add(20*time.Second), easydns.Stats{QueriesTotal: 0, Responses: map[string]uint64{}, Cache: easydns.Cache{Hits: 0, Misses: 0}})
sm, _, _ = h.Snapshot()
if sm[2].QueryRate != nil || sm[2].CacheHitRate != nil {
t.Fatal("counter reset must not produce negative/wrong rates")
}
}
+40
View File
@@ -0,0 +1,40 @@
#!/bin/sh
set -e
case "$1" in
configure)
if ! getent group easydns-ui >/dev/null 2>&1; then
addgroup --system easydns-ui
fi
if ! id easydns-ui >/dev/null 2>&1; then
adduser --system --ingroup easydns-ui --home /nonexistent --no-create-home --disabled-login --gecos 'EasyDNS web UI' easydns-ui
fi
if getent group easydns >/dev/null 2>&1; then
usermod -a -G easydns easydns-ui
fi
mkdir -p /etc/easydns-ui
chown root:easydns-ui /etc/easydns-ui
chmod 0750 /etc/easydns-ui
if [ ! -s /etc/easydns-ui/panel.password ]; then
umask 077
head -c 24 /dev/urandom | base64 | tr -d '\n' > /etc/easydns-ui/panel.password
printf '\n' >> /etc/easydns-ui/panel.password
fi
if [ ! -s /etc/easydns-ui/session.key ]; then
umask 077
head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n' > /etc/easydns-ui/session.key
printf '\n' >> /etc/easydns-ui/session.key
fi
chown root:easydns-ui /etc/easydns-ui/panel.password /etc/easydns-ui/session.key
chmod 0640 /etc/easydns-ui/panel.password /etc/easydns-ui/session.key
if [ -f /etc/default/easydns-ui ]; then
chown root:easydns-ui /etc/default/easydns-ui
chmod 0640 /etc/default/easydns-ui
fi
if [ -d /run/systemd/system ]; then
systemctl daemon-reload
systemctl enable easydns-ui.service >/dev/null 2>&1 || true
systemctl restart easydns-ui.service >/dev/null 2>&1 || true
fi
;;
esac
exit 0
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
set -e
if [ "$1" = purge ]; then
rm -f /etc/easydns-ui/panel.password /etc/easydns-ui/session.key
rmdir /etc/easydns-ui 2>/dev/null || true
fi
if [ -d /run/systemd/system ]; then
systemctl daemon-reload >/dev/null 2>&1 || true
fi
exit 0
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -e
if [ "$1" = remove ] || [ "$1" = deconfigure ]; then
if [ -d /run/systemd/system ]; then
systemctl stop easydns-ui.service >/dev/null 2>&1 || true
systemctl disable easydns-ui.service >/dev/null 2>&1 || true
fi
fi
exit 0
+12
View File
@@ -0,0 +1,12 @@
# EasyDNS-Web: independent Go admin panel. No token values are stored here.
EASYDNS_UI_LISTEN=127.0.0.1:8088
# Option 1: local TCP EasyDNS API; reads its already-generated control.token
EASYDNS_API_URL=http://127.0.0.1:9953
EASYDNS_API_TOKEN_FILE=/etc/easydns/data/control.token
# Option 2: uncomment to use the local control socket; this needs easydns group rights.
# EASYDNS_API_SOCKET=/etc/easydns/data/control.sock
EASYDNS_UI_PASSWORD_FILE=/etc/easydns-ui/panel.password
EASYDNS_UI_SESSION_KEY_FILE=/etc/easydns-ui/session.key
EASYDNS_UI_USERNAME=admin
# Set to true only if users access the browser over HTTPS (e.g. behind a TLS proxy).
EASYDNS_UI_COOKIE_SECURE=false
+33
View File
@@ -0,0 +1,33 @@
[Unit]
Description=EasyDNS Web Administration Panel
Documentation=https://git.linuxiarz.pl/gru/EasyDNS
Wants=network-online.target
After=network-online.target easydns.service
[Service]
Type=simple
User=easydns-ui
Group=easydns-ui
# Installer adds easydns-ui to the easydns group, if it exists.
# Unix socket or generated control.token must be accessible to this user.
EnvironmentFile=-/etc/default/easydns-ui
ExecStart=/usr/bin/easydns-ui
Restart=on-failure
RestartSec=4s
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
PrivateDevices=true
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
RestrictSUIDSGID=true
LockPersonality=true
UMask=0077
CapabilityBoundingSet=
AmbientCapabilities=
[Install]
WantedBy=multi-user.target
+44
View File
@@ -0,0 +1,44 @@
#!/bin/sh
# Build a standalone EasyDNS UI Debian package; never packages the DNS server.
set -eu
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
ARCH=${GOARCH:-amd64}
VERSION=${VERSION:-0.1.0}
case "$ARCH" in
amd64|arm64) ;;
*) echo "Unsupported architecture: $ARCH (use amd64 or arm64)" >&2; exit 1 ;;
esac
case "$VERSION" in
*[!a-zA-Z0-9.+~:-]*|'') echo 'Invalid version' >&2; exit 1 ;;
esac
STAGING=$(mktemp -d)
trap 'rm -rf "$STAGING"' EXIT HUP INT TERM
chmod 0755 "$STAGING"
mkdir -p "$STAGING/DEBIAN" "$STAGING/usr/bin" "$STAGING/lib/systemd/system" "$STAGING/etc/default" "$ROOT/dist"
cd "$ROOT"
GOOS=linux GOARCH="$ARCH" CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=$VERSION" -o "$STAGING/usr/bin/easydns-ui" ./cmd/easydns-ui
chmod 0755 "$STAGING/usr/bin/easydns-ui"
cp packaging/easydns-ui.service "$STAGING/lib/systemd/system/easydns-ui.service"
cp packaging/easydns-ui.default "$STAGING/etc/default/easydns-ui"
chmod 0644 "$STAGING/etc/default/easydns-ui"
cp packaging/debian/postinst packaging/debian/prerm packaging/debian/postrm "$STAGING/DEBIAN/"
cat > "$STAGING/DEBIAN/control" <<CONTROL
Package: easydns-ui
Version: $VERSION
Section: admin
Priority: optional
Architecture: $ARCH
Depends: adduser, coreutils, passwd
Maintainer: EasyDNS UI maintainers
Description: EasyDNS standalone OLED administration panel
A Go web UI for an existing EasyDNS server. Uses the server's
autogenerated control.token or local Unix control socket.
It does not install or replace the Rust DNS service.
CONTROL
cat > "$STAGING/DEBIAN/conffiles" <<CONF
/etc/default/easydns-ui
CONF
# The parent may be non-root while dpkg-deb is available.
OUT="$ROOT/dist/easydns-ui_${VERSION}_${ARCH}.deb"
dpkg-deb --build --root-owner-group "$STAGING" "$OUT" >/dev/null
printf '%s\n' "$OUT"
+129
View File
@@ -0,0 +1,129 @@
#!/bin/sh
# Build standalone EasyDNS UI .deb packages using Docker (no Go or dpkg on host).
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
IMAGE=${IMAGE:-golang:1.23-bookworm}
VERSION=${VERSION:-0.1.0}
ARCH=${ARCH:-${GOARCH:-all}}
usage() {
cat <<'HELP'
Usage: ./scripts/build_deb.sh [--arch all|amd64|arm64] [--version VERSION] [--image IMAGE]
Build Linux Debian packages inside a Docker container. Only Docker is required
on the host; Go, dpkg-deb, and cross-compilation tools run in the container.
Options:
--arch Architectures to build (default: all = amd64 + arm64)
--version Debian package version (default: 0.1.0)
--image Debian-based Go image (default: golang:1.23-bookworm)
-h, --help Show this message
Environment alternatives: ARCH, GOARCH, VERSION, IMAGE.
Packages are written to ./dist/easydns-ui_VERSION_ARCH.deb.
Examples:
./scripts/build_deb.sh
./scripts/build_deb.sh --arch amd64 --version 0.2.0
IMAGE=golang:1.23-bookworm ./scripts/build_deb.sh --arch arm64
HELP
}
while [ "$#" -gt 0 ]; do
case "$1" in
--arch|--version|--image)
option=$1
shift
if [ "$#" -eq 0 ]; then
printf 'Missing value for %s\n' "$option" >&2
usage >&2
exit 2
fi
case "$option" in
--arch) ARCH=$1 ;;
--version) VERSION=$1 ;;
--image) IMAGE=$1 ;;
esac
;;
-h|--help) usage; exit 0 ;;
*) printf 'Unknown argument: %s\n' "$1" >&2; usage >&2; exit 2 ;;
esac
shift
done
case "$ARCH" in
all) ARCHES='amd64 arm64' ;;
amd64|arm64) ARCHES=$ARCH ;;
*) printf 'Unsupported architecture: %s (use all, amd64 or arm64)\n' "$ARCH" >&2; exit 2 ;;
esac
# Debian requires a digit at the start of the version. Reject shell metacharacters,
# path separators, whitespace and newlines; the native builder validates it too.
case "$VERSION" in
''|[!0-9]*|*[!A-Za-z0-9.+~:-]*)
printf 'Invalid Debian package version: %s\n' "$VERSION" >&2
exit 2
;;
esac
case "$IMAGE" in
''|*[!A-Za-z0-9._:/@-]*)
printf 'Invalid Docker image reference: %s\n' "$IMAGE" >&2
exit 2
;;
esac
if ! command -v docker >/dev/null 2>&1; then
printf 'Docker is not installed or not in PATH. Install Docker Engine/Desktop first.\n' >&2
exit 1
fi
if ! docker info >/dev/null 2>&1; then
printf 'Cannot connect to Docker daemon (is Docker running and your user authorized?).\n' >&2
exit 1
fi
# Pre-create as host user: output files will not be owned by container root.
mkdir -p "$ROOT/dist"
uid=$(id -u)
gid=$(id -g)
printf 'Building EasyDNS UI %s for %s using Docker image %s\n' "$VERSION" "$ARCHES" "$IMAGE"
# Native Debian packaging script is the single source of truth for package
# contents, scripts, systemd unit, config, and control metadata. Running one
# normal Docker platform with CGO disabled builds both Linux architectures
# without QEMU, multiarch buildx or a compiler installed on the host.
docker run --rm \
--network none \
--user "$uid:$gid" \
--volume "$ROOT:/workspace:rw" \
--workdir /workspace \
--env "VERSION=$VERSION" \
--env "ARCHES=$ARCHES" \
--env GOOS=linux \
--env CGO_ENABLED=0 \
--env GOPROXY=off \
--env GOTOOLCHAIN=local \
--env GOFLAGS=-buildvcs=false \
--env HOME=/tmp \
--env GOCACHE=/tmp/easydns-go-cache \
--env GOPATH=/tmp/easydns-go-path \
"$IMAGE" sh -ec '
command -v go >/dev/null 2>&1 || { echo "Docker image does not contain Go" >&2; exit 1; }
command -v dpkg-deb >/dev/null 2>&1 || { echo "Docker image does not contain dpkg-deb (use a Debian-based Go image)" >&2; exit 1; }
for arch in $ARCHES; do
echo "==> Building linux/$arch"
GOARCH="$arch" VERSION="$VERSION" ./scripts/build-deb.sh
file="dist/easydns-ui_${VERSION}_${arch}.deb"
test -s "$file"
test "$(dpkg-deb -f "$file" Architecture)" = "$arch"
test "$(dpkg-deb -f "$file" Version)" = "$VERSION"
echo "==> Valid package: $file"
done
'
printf '\nCompleted. Packages:\n'
for arch in $ARCHES; do
output="$ROOT/dist/easydns-ui_${VERSION}_${arch}.deb"
[ -s "$output" ] || { printf 'Missing package: %s\n' "$output" >&2; exit 1; }
printf ' %s\n' "$output"
done