Replace state blob with resource-oriented API endpoints
Split /api/v1/state into dedicated resource endpoints: - /api/v1/operator, /api/v1/central-domain - /api/v1/ddns/config, /api/v1/dns/settings - /api/v1/dhcp/config (moved from /dnsmasq/dhcp/) - /api/v1/nftables/config, /api/v1/haproxy/routes Each page now talks to its own resource instead of deep-merging a blob. Removes useConfig hook, CentralState type, and legacy config methods.
This commit is contained in:
@@ -1,7 +1,6 @@
|
|||||||
package v1
|
package v1
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
@@ -28,7 +27,6 @@ import (
|
|||||||
"github.com/wild-cloud/wild-central/internal/secrets"
|
"github.com/wild-cloud/wild-central/internal/secrets"
|
||||||
"github.com/wild-cloud/wild-central/internal/domains"
|
"github.com/wild-cloud/wild-central/internal/domains"
|
||||||
"github.com/wild-cloud/wild-central/internal/sse"
|
"github.com/wild-cloud/wild-central/internal/sse"
|
||||||
"github.com/wild-cloud/wild-central/internal/storage"
|
|
||||||
"github.com/wild-cloud/wild-central/internal/wireguard"
|
"github.com/wild-cloud/wild-central/internal/wireguard"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -171,9 +169,11 @@ func (api *API) StartCentralStatusBroadcaster(startTime time.Time) {
|
|||||||
func (api *API) RegisterRoutes(r *mux.Router) {
|
func (api *API) RegisterRoutes(r *mux.Router) {
|
||||||
r.Use(RequestLoggingMiddleware)
|
r.Use(RequestLoggingMiddleware)
|
||||||
|
|
||||||
// Global State (runtime settings — operator, DDNS, DHCP, etc.)
|
// Resource-oriented settings (persisted in state.yaml)
|
||||||
r.HandleFunc("/api/v1/state", api.GetState).Methods("GET")
|
r.HandleFunc("/api/v1/operator", api.GetOperator).Methods("GET")
|
||||||
r.HandleFunc("/api/v1/state", api.UpdateState).Methods("PUT")
|
r.HandleFunc("/api/v1/operator", api.UpdateOperator).Methods("PUT")
|
||||||
|
r.HandleFunc("/api/v1/central-domain", api.GetCentralDomain).Methods("GET")
|
||||||
|
r.HandleFunc("/api/v1/central-domain", api.UpdateCentralDomain).Methods("PUT")
|
||||||
|
|
||||||
// Global Secrets
|
// Global Secrets
|
||||||
r.HandleFunc("/api/v1/secrets", api.GetGlobalSecrets).Methods("GET")
|
r.HandleFunc("/api/v1/secrets", api.GetGlobalSecrets).Methods("GET")
|
||||||
@@ -186,28 +186,44 @@ func (api *API) RegisterRoutes(r *mux.Router) {
|
|||||||
r.HandleFunc("/api/v1/network/info", api.NetworkInfoHandler).Methods("GET")
|
r.HandleFunc("/api/v1/network/info", api.NetworkInfoHandler).Methods("GET")
|
||||||
r.HandleFunc("/api/v1/network/resolve", api.NetworkResolveHandler).Methods("GET")
|
r.HandleFunc("/api/v1/network/resolve", api.NetworkResolveHandler).Methods("GET")
|
||||||
|
|
||||||
// dnsmasq management
|
// DNS (dnsmasq daemon)
|
||||||
|
r.HandleFunc("/api/v1/dns/settings", api.GetDNSSettings).Methods("GET")
|
||||||
|
r.HandleFunc("/api/v1/dns/settings", api.UpdateDNSSettings).Methods("PUT")
|
||||||
r.HandleFunc("/api/v1/dnsmasq/status", api.DnsmasqStatus).Methods("GET")
|
r.HandleFunc("/api/v1/dnsmasq/status", api.DnsmasqStatus).Methods("GET")
|
||||||
r.HandleFunc("/api/v1/dnsmasq/config", api.DnsmasqGetConfig).Methods("GET")
|
r.HandleFunc("/api/v1/dnsmasq/config", api.DnsmasqGetConfig).Methods("GET")
|
||||||
r.HandleFunc("/api/v1/dnsmasq/config", api.DnsmasqWriteConfig).Methods("PUT")
|
r.HandleFunc("/api/v1/dnsmasq/config", api.DnsmasqWriteConfig).Methods("PUT")
|
||||||
r.HandleFunc("/api/v1/dnsmasq/restart", api.DnsmasqRestart).Methods("POST")
|
r.HandleFunc("/api/v1/dnsmasq/restart", api.DnsmasqRestart).Methods("POST")
|
||||||
r.HandleFunc("/api/v1/dnsmasq/generate", api.DnsmasqGenerate).Methods("POST")
|
r.HandleFunc("/api/v1/dnsmasq/generate", api.DnsmasqGenerate).Methods("POST")
|
||||||
r.HandleFunc("/api/v1/dnsmasq/dhcp/leases", api.DnsmasqDHCPLeases).Methods("GET")
|
|
||||||
r.HandleFunc("/api/v1/dnsmasq/dhcp/static", api.DnsmasqDHCPAddStatic).Methods("POST")
|
|
||||||
r.HandleFunc("/api/v1/dnsmasq/dhcp/static/{mac}", api.DnsmasqDHCPDeleteStatic).Methods("DELETE")
|
|
||||||
|
|
||||||
// HAProxy ingress management
|
// DHCP (feature, backed by dnsmasq)
|
||||||
|
r.HandleFunc("/api/v1/dhcp/config", api.GetDHCPConfig).Methods("GET")
|
||||||
|
r.HandleFunc("/api/v1/dhcp/config", api.UpdateDHCPConfig).Methods("PUT")
|
||||||
|
r.HandleFunc("/api/v1/dhcp/leases", api.DnsmasqDHCPLeases).Methods("GET")
|
||||||
|
r.HandleFunc("/api/v1/dhcp/static", api.DnsmasqDHCPAddStatic).Methods("POST")
|
||||||
|
r.HandleFunc("/api/v1/dhcp/static/{mac}", api.DnsmasqDHCPDeleteStatic).Methods("DELETE")
|
||||||
|
|
||||||
|
// HAProxy gateway management
|
||||||
r.HandleFunc("/api/v1/haproxy/status", api.HaproxyStatus).Methods("GET")
|
r.HandleFunc("/api/v1/haproxy/status", api.HaproxyStatus).Methods("GET")
|
||||||
r.HandleFunc("/api/v1/haproxy/config", api.HaproxyGetConfig).Methods("GET")
|
r.HandleFunc("/api/v1/haproxy/config", api.HaproxyGetConfig).Methods("GET")
|
||||||
r.HandleFunc("/api/v1/haproxy/generate", api.HaproxyGenerate).Methods("POST")
|
r.HandleFunc("/api/v1/haproxy/generate", api.HaproxyGenerate).Methods("POST")
|
||||||
r.HandleFunc("/api/v1/haproxy/restart", api.HaproxyRestart).Methods("POST")
|
r.HandleFunc("/api/v1/haproxy/restart", api.HaproxyRestart).Methods("POST")
|
||||||
r.HandleFunc("/api/v1/haproxy/stats", api.HaproxyStats).Methods("GET")
|
r.HandleFunc("/api/v1/haproxy/stats", api.HaproxyStats).Methods("GET")
|
||||||
|
r.HandleFunc("/api/v1/haproxy/routes", api.GetHAProxyRoutes).Methods("GET")
|
||||||
|
r.HandleFunc("/api/v1/haproxy/routes", api.UpdateHAProxyRoutes).Methods("PUT")
|
||||||
|
|
||||||
// nftables firewall management
|
// nftables firewall management
|
||||||
r.HandleFunc("/api/v1/nftables/status", api.NftablesStatus).Methods("GET")
|
r.HandleFunc("/api/v1/nftables/status", api.NftablesStatus).Methods("GET")
|
||||||
|
r.HandleFunc("/api/v1/nftables/config", api.GetNftablesConfig).Methods("GET")
|
||||||
|
r.HandleFunc("/api/v1/nftables/config", api.UpdateNftablesConfig).Methods("PUT")
|
||||||
r.HandleFunc("/api/v1/nftables/apply", api.NftablesApply).Methods("POST")
|
r.HandleFunc("/api/v1/nftables/apply", api.NftablesApply).Methods("POST")
|
||||||
r.HandleFunc("/api/v1/nftables/interfaces", api.NftablesGetInterfaces).Methods("GET")
|
r.HandleFunc("/api/v1/nftables/interfaces", api.NftablesGetInterfaces).Methods("GET")
|
||||||
|
|
||||||
|
// DDNS management
|
||||||
|
r.HandleFunc("/api/v1/ddns/config", api.GetDDNSConfig).Methods("GET")
|
||||||
|
r.HandleFunc("/api/v1/ddns/config", api.UpdateDDNSConfig).Methods("PUT")
|
||||||
|
r.HandleFunc("/api/v1/ddns/status", api.DDNSStatus).Methods("GET")
|
||||||
|
r.HandleFunc("/api/v1/ddns/trigger", api.DDNSTrigger).Methods("POST")
|
||||||
|
|
||||||
// WireGuard VPN management
|
// WireGuard VPN management
|
||||||
r.HandleFunc("/api/v1/vpn/status", api.VpnStatus).Methods("GET")
|
r.HandleFunc("/api/v1/vpn/status", api.VpnStatus).Methods("GET")
|
||||||
r.HandleFunc("/api/v1/vpn/config", api.VpnGetConfig).Methods("GET")
|
r.HandleFunc("/api/v1/vpn/config", api.VpnGetConfig).Methods("GET")
|
||||||
@@ -260,89 +276,7 @@ func (api *API) RegisterRoutes(r *mux.Router) {
|
|||||||
r.HandleFunc("/api/v1/events", api.GlobalEventStream).Methods("GET")
|
r.HandleFunc("/api/v1/events", api.GlobalEventStream).Methods("GET")
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Global Config/Secrets handlers ---
|
// --- Secrets handlers ---
|
||||||
|
|
||||||
// GetState returns the global state wrapped in { configured, state }.
|
|
||||||
func (api *API) GetState(w http.ResponseWriter, r *http.Request) {
|
|
||||||
data, err := os.ReadFile(api.statePath())
|
|
||||||
if err != nil {
|
|
||||||
respondJSON(w, http.StatusOK, map[string]any{
|
|
||||||
"configured": false,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var stateMap map[string]any
|
|
||||||
if err := yaml.Unmarshal(data, &stateMap); err != nil {
|
|
||||||
respondError(w, http.StatusInternalServerError, "Failed to parse state")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
respondJSON(w, http.StatusOK, map[string]any{
|
|
||||||
"configured": true,
|
|
||||||
"state": stateMap,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateState updates the global state
|
|
||||||
func (api *API) UpdateState(w http.ResponseWriter, r *http.Request) {
|
|
||||||
configPath := api.statePath()
|
|
||||||
|
|
||||||
body, err := io.ReadAll(r.Body)
|
|
||||||
if err != nil {
|
|
||||||
respondError(w, http.StatusBadRequest, "Failed to read request body")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var updates map[string]any
|
|
||||||
if err := yaml.Unmarshal(body, &updates); err != nil {
|
|
||||||
respondError(w, http.StatusBadRequest, "Invalid YAML format")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read existing state (may not exist yet)
|
|
||||||
existingContent, err := storage.ReadFile(configPath)
|
|
||||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
|
||||||
respondError(w, http.StatusInternalServerError, "Failed to read existing state")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var existingConfig map[string]any
|
|
||||||
if len(existingContent) > 0 {
|
|
||||||
if err := yaml.Unmarshal(existingContent, &existingConfig); err != nil {
|
|
||||||
respondError(w, http.StatusBadRequest, "Failed to parse existing config")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
existingConfig = make(map[string]any)
|
|
||||||
}
|
|
||||||
|
|
||||||
for key, value := range updates {
|
|
||||||
existingConfig[key] = value
|
|
||||||
}
|
|
||||||
|
|
||||||
yamlContent, err := yaml.Marshal(existingConfig)
|
|
||||||
if err != nil {
|
|
||||||
respondError(w, http.StatusInternalServerError, "Failed to marshal YAML")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
lockPath := configPath + ".lock"
|
|
||||||
if err := storage.WithLock(lockPath, func() error {
|
|
||||||
return storage.WriteFile(configPath, yamlContent, 0644)
|
|
||||||
}); err != nil {
|
|
||||||
respondError(w, http.StatusInternalServerError, "Failed to write config")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
slog.Info("global config updated")
|
|
||||||
|
|
||||||
// Reload DDNS and re-register Central's service if config changed
|
|
||||||
go api.reloadDDNSIfEnabled()
|
|
||||||
go api.EnsureCentralDomain()
|
|
||||||
|
|
||||||
respondMessage(w, http.StatusOK, "Config updated successfully")
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetGlobalSecrets returns the global secrets (redacted by default)
|
// GetGlobalSecrets returns the global secrets (redacted by default)
|
||||||
func (api *API) GetGlobalSecrets(w http.ResponseWriter, r *http.Request) {
|
func (api *API) GetGlobalSecrets(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|||||||
@@ -9,31 +9,22 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/wild-cloud/wild-central/internal/storage"
|
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestGetState_ReturnsWrappedResponse(t *testing.T) {
|
func TestGetOperator(t *testing.T) {
|
||||||
api, tmpDir := setupTestAPI(t)
|
api, tmpDir := setupTestAPI(t)
|
||||||
|
|
||||||
// Write a config with a central domain
|
// Write state with operator email
|
||||||
cfg := map[string]any{
|
state := map[string]any{
|
||||||
"cloud": map[string]any{
|
"operator": map[string]any{"email": "test@example.com"},
|
||||||
"central": map[string]any{
|
|
||||||
"domain": "central.example.com",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"operator": map[string]any{
|
|
||||||
"email": "test@example.com",
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
data, _ := yaml.Marshal(cfg)
|
data, _ := yaml.Marshal(state)
|
||||||
storage.WriteFile(filepath.Join(tmpDir, "state.yaml"), data, 0644)
|
os.WriteFile(filepath.Join(tmpDir, "state.yaml"), data, 0644)
|
||||||
|
|
||||||
req := httptest.NewRequest("GET", "/api/v1/state", nil)
|
req := httptest.NewRequest("GET", "/api/v1/operator", nil)
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
|
api.GetOperator(w, req)
|
||||||
api.GetState(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusOK {
|
if w.Code != http.StatusOK {
|
||||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||||
@@ -41,34 +32,47 @@ func TestGetState_ReturnsWrappedResponse(t *testing.T) {
|
|||||||
|
|
||||||
var resp map[string]any
|
var resp map[string]any
|
||||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||||
|
if resp["email"] != "test@example.com" {
|
||||||
// Must have "configured" and "state" keys
|
t.Errorf("expected email test@example.com, got %v", resp["email"])
|
||||||
if resp["configured"] != true {
|
|
||||||
t.Errorf("expected configured=true, got %v", resp["configured"])
|
|
||||||
}
|
|
||||||
state, ok := resp["state"].(map[string]any)
|
|
||||||
if !ok {
|
|
||||||
t.Fatalf("expected state to be a map, got %T", resp["state"])
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify nested structure is preserved
|
|
||||||
cloud, _ := state["cloud"].(map[string]any)
|
|
||||||
central, _ := cloud["central"].(map[string]any)
|
|
||||||
if central["domain"] != "central.example.com" {
|
|
||||||
t.Errorf("expected domain central.example.com, got %v", central["domain"])
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetState_EmptyReturnsNotConfigured(t *testing.T) {
|
func TestUpdateOperator(t *testing.T) {
|
||||||
api, tmpDir := setupTestAPI(t)
|
api, tmpDir := setupTestAPI(t)
|
||||||
|
|
||||||
// Ensure no state file exists
|
body, _ := json.Marshal(map[string]string{"email": "new@example.com"})
|
||||||
os.Remove(filepath.Join(tmpDir, "state.yaml"))
|
req := httptest.NewRequest("PUT", "/api/v1/operator", bytes.NewReader(body))
|
||||||
|
|
||||||
req := httptest.NewRequest("GET", "/api/v1/state", nil)
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
|
api.UpdateOperator(w, req)
|
||||||
|
|
||||||
api.GetState(w, req)
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify persisted
|
||||||
|
data, _ := os.ReadFile(filepath.Join(tmpDir, "state.yaml"))
|
||||||
|
var state map[string]any
|
||||||
|
yaml.Unmarshal(data, &state)
|
||||||
|
op := state["operator"].(map[string]any)
|
||||||
|
if op["email"] != "new@example.com" {
|
||||||
|
t.Errorf("expected email new@example.com, got %v", op["email"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetCentralDomain(t *testing.T) {
|
||||||
|
api, tmpDir := setupTestAPI(t)
|
||||||
|
|
||||||
|
state := map[string]any{
|
||||||
|
"cloud": map[string]any{
|
||||||
|
"central": map[string]any{"domain": "central.example.com"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
data, _ := yaml.Marshal(state)
|
||||||
|
os.WriteFile(filepath.Join(tmpDir, "state.yaml"), data, 0644)
|
||||||
|
|
||||||
|
req := httptest.NewRequest("GET", "/api/v1/central-domain", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
api.GetCentralDomain(w, req)
|
||||||
|
|
||||||
if w.Code != http.StatusOK {
|
if w.Code != http.StatusOK {
|
||||||
t.Fatalf("expected 200, got %d", w.Code)
|
t.Fatalf("expected 200, got %d", w.Code)
|
||||||
@@ -76,9 +80,27 @@ func TestGetState_EmptyReturnsNotConfigured(t *testing.T) {
|
|||||||
|
|
||||||
var resp map[string]any
|
var resp map[string]any
|
||||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||||
|
if resp["domain"] != "central.example.com" {
|
||||||
|
t.Errorf("expected domain central.example.com, got %v", resp["domain"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if resp["configured"] != false {
|
func TestUpdateCentralDomain(t *testing.T) {
|
||||||
t.Errorf("expected configured=false, got %v", resp["configured"])
|
api, _ := setupTestAPI(t)
|
||||||
|
|
||||||
|
body, _ := json.Marshal(map[string]string{"domain": "new.example.com"})
|
||||||
|
req := httptest.NewRequest("PUT", "/api/v1/central-domain", bytes.NewReader(body))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
api.UpdateCentralDomain(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var resp map[string]any
|
||||||
|
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||||
|
if resp["domain"] != "new.example.com" {
|
||||||
|
t.Errorf("expected domain new.example.com, got %v", resp["domain"])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,12 +125,10 @@ func TestGetGlobalSecrets_RedactsLeafValues(t *testing.T) {
|
|||||||
var resp map[string]any
|
var resp map[string]any
|
||||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||||
|
|
||||||
// Top-level leaf should be redacted
|
|
||||||
if resp["topLevelSecret"] != "********" {
|
if resp["topLevelSecret"] != "********" {
|
||||||
t.Errorf("expected topLevelSecret redacted, got %v", resp["topLevelSecret"])
|
t.Errorf("expected topLevelSecret redacted, got %v", resp["topLevelSecret"])
|
||||||
}
|
}
|
||||||
|
|
||||||
// Nested map structure should be preserved
|
|
||||||
cf, ok := resp["cloudflare"].(map[string]any)
|
cf, ok := resp["cloudflare"].(map[string]any)
|
||||||
if !ok {
|
if !ok {
|
||||||
t.Fatalf("expected cloudflare to be a map, got %T", resp["cloudflare"])
|
t.Fatalf("expected cloudflare to be a map, got %T", resp["cloudflare"])
|
||||||
@@ -116,9 +136,6 @@ func TestGetGlobalSecrets_RedactsLeafValues(t *testing.T) {
|
|||||||
if cf["apiToken"] != "********" {
|
if cf["apiToken"] != "********" {
|
||||||
t.Errorf("expected apiToken redacted, got %v", cf["apiToken"])
|
t.Errorf("expected apiToken redacted, got %v", cf["apiToken"])
|
||||||
}
|
}
|
||||||
if cf["zoneId"] != "********" {
|
|
||||||
t.Errorf("expected zoneId redacted, got %v", cf["zoneId"])
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetGlobalSecrets_RawShowsValues(t *testing.T) {
|
func TestGetGlobalSecrets_RawShowsValues(t *testing.T) {
|
||||||
@@ -146,39 +163,6 @@ func TestGetGlobalSecrets_RawShowsValues(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestUpdateState(t *testing.T) {
|
|
||||||
api, tmpDir := setupTestAPI(t)
|
|
||||||
|
|
||||||
update := map[string]any{
|
|
||||||
"cloud": map[string]any{
|
|
||||||
"central": map[string]any{
|
|
||||||
"domain": "new.example.com",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
body, _ := json.Marshal(update)
|
|
||||||
|
|
||||||
req := httptest.NewRequest("PUT", "/api/v1/state", bytes.NewReader(body))
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
api.UpdateState(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusOK {
|
|
||||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify file was written
|
|
||||||
data, _ := os.ReadFile(filepath.Join(tmpDir, "state.yaml"))
|
|
||||||
var cfg map[string]any
|
|
||||||
yaml.Unmarshal(data, &cfg)
|
|
||||||
|
|
||||||
cloud := cfg["cloud"].(map[string]any)
|
|
||||||
central := cloud["central"].(map[string]any)
|
|
||||||
if central["domain"] != "new.example.com" {
|
|
||||||
t.Errorf("expected domain new.example.com, got %v", central["domain"])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCloudflareVerify_NoToken(t *testing.T) {
|
func TestCloudflareVerify_NoToken(t *testing.T) {
|
||||||
api, _ := setupTestAPI(t)
|
api, _ := setupTestAPI(t)
|
||||||
|
|
||||||
|
|||||||
267
internal/api/v1/handlers_settings.go
Normal file
267
internal/api/v1/handlers_settings.go
Normal file
@@ -0,0 +1,267 @@
|
|||||||
|
package v1
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/wild-cloud/wild-central/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// loadState loads state from disk, returning an empty state if the file doesn't exist.
|
||||||
|
func (api *API) loadState() *config.State {
|
||||||
|
state, err := config.LoadState(api.statePath())
|
||||||
|
if err != nil {
|
||||||
|
return &config.State{}
|
||||||
|
}
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
|
||||||
|
// saveState writes state to disk and returns an error suitable for HTTP responses.
|
||||||
|
func (api *API) saveState(state *config.State) error {
|
||||||
|
return config.SaveState(state, api.statePath())
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Operator ---
|
||||||
|
|
||||||
|
func (api *API) GetOperator(w http.ResponseWriter, r *http.Request) {
|
||||||
|
respondJSON(w, http.StatusOK, api.loadState().Operator)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) UpdateOperator(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var updates struct {
|
||||||
|
Email string `json:"email"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&updates); err != nil {
|
||||||
|
respondError(w, http.StatusBadRequest, "Invalid request body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
state := api.loadState()
|
||||||
|
state.Operator.Email = updates.Email
|
||||||
|
if err := api.saveState(state); err != nil {
|
||||||
|
respondError(w, http.StatusInternalServerError, "Failed to save state")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info("operator updated", "email", updates.Email)
|
||||||
|
respondJSON(w, http.StatusOK, state.Operator)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Central Domain ---
|
||||||
|
|
||||||
|
func (api *API) GetCentralDomain(w http.ResponseWriter, r *http.Request) {
|
||||||
|
respondJSON(w, http.StatusOK, map[string]string{
|
||||||
|
"domain": api.loadState().Cloud.Central.Domain,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) UpdateCentralDomain(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var updates struct {
|
||||||
|
Domain string `json:"domain"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&updates); err != nil {
|
||||||
|
respondError(w, http.StatusBadRequest, "Invalid request body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
state := api.loadState()
|
||||||
|
state.Cloud.Central.Domain = updates.Domain
|
||||||
|
if err := api.saveState(state); err != nil {
|
||||||
|
respondError(w, http.StatusInternalServerError, "Failed to save state")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
go api.EnsureCentralDomain()
|
||||||
|
|
||||||
|
slog.Info("central domain updated", "domain", updates.Domain)
|
||||||
|
respondJSON(w, http.StatusOK, map[string]string{"domain": updates.Domain})
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- DDNS Config ---
|
||||||
|
|
||||||
|
func (api *API) GetDDNSConfig(w http.ResponseWriter, r *http.Request) {
|
||||||
|
respondJSON(w, http.StatusOK, api.loadState().Cloud.DDNS)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) UpdateDDNSConfig(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var updates struct {
|
||||||
|
Enabled *bool `json:"enabled,omitempty"`
|
||||||
|
Provider string `json:"provider,omitempty"`
|
||||||
|
IntervalMinutes *int `json:"intervalMinutes,omitempty"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&updates); err != nil {
|
||||||
|
respondError(w, http.StatusBadRequest, "Invalid request body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
state := api.loadState()
|
||||||
|
if updates.Enabled != nil {
|
||||||
|
state.Cloud.DDNS.Enabled = *updates.Enabled
|
||||||
|
}
|
||||||
|
if updates.Provider != "" {
|
||||||
|
state.Cloud.DDNS.Provider = updates.Provider
|
||||||
|
}
|
||||||
|
if updates.IntervalMinutes != nil {
|
||||||
|
state.Cloud.DDNS.IntervalMinutes = *updates.IntervalMinutes
|
||||||
|
}
|
||||||
|
if err := api.saveState(state); err != nil {
|
||||||
|
respondError(w, http.StatusInternalServerError, "Failed to save state")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
go api.reloadDDNSIfEnabled()
|
||||||
|
|
||||||
|
slog.Info("DDNS config updated", "enabled", state.Cloud.DDNS.Enabled)
|
||||||
|
respondJSON(w, http.StatusOK, state.Cloud.DDNS)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- DNS Settings (dnsmasq IP/interface) ---
|
||||||
|
|
||||||
|
func (api *API) GetDNSSettings(w http.ResponseWriter, r *http.Request) {
|
||||||
|
d := api.loadState().Cloud.Dnsmasq
|
||||||
|
respondJSON(w, http.StatusOK, map[string]string{
|
||||||
|
"ip": d.IP,
|
||||||
|
"interface": d.Interface,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) UpdateDNSSettings(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var updates struct {
|
||||||
|
IP string `json:"ip,omitempty"`
|
||||||
|
Interface string `json:"interface,omitempty"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&updates); err != nil {
|
||||||
|
respondError(w, http.StatusBadRequest, "Invalid request body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
state := api.loadState()
|
||||||
|
if updates.IP != "" {
|
||||||
|
state.Cloud.Dnsmasq.IP = updates.IP
|
||||||
|
}
|
||||||
|
if updates.Interface != "" {
|
||||||
|
state.Cloud.Dnsmasq.Interface = updates.Interface
|
||||||
|
}
|
||||||
|
if err := api.saveState(state); err != nil {
|
||||||
|
respondError(w, http.StatusInternalServerError, "Failed to save state")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info("DNS settings updated", "ip", state.Cloud.Dnsmasq.IP)
|
||||||
|
respondJSON(w, http.StatusOK, map[string]string{
|
||||||
|
"ip": state.Cloud.Dnsmasq.IP,
|
||||||
|
"interface": state.Cloud.Dnsmasq.Interface,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- DHCP Config ---
|
||||||
|
|
||||||
|
func (api *API) GetDHCPConfig(w http.ResponseWriter, r *http.Request) {
|
||||||
|
respondJSON(w, http.StatusOK, api.loadState().Cloud.Dnsmasq.DHCP)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) UpdateDHCPConfig(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var updates struct {
|
||||||
|
Enabled *bool `json:"enabled,omitempty"`
|
||||||
|
RangeStart string `json:"rangeStart,omitempty"`
|
||||||
|
RangeEnd string `json:"rangeEnd,omitempty"`
|
||||||
|
LeaseTime string `json:"leaseTime,omitempty"`
|
||||||
|
Gateway string `json:"gateway,omitempty"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&updates); err != nil {
|
||||||
|
respondError(w, http.StatusBadRequest, "Invalid request body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
state := api.loadState()
|
||||||
|
dhcp := &state.Cloud.Dnsmasq.DHCP
|
||||||
|
if updates.Enabled != nil {
|
||||||
|
dhcp.Enabled = *updates.Enabled
|
||||||
|
}
|
||||||
|
if updates.RangeStart != "" {
|
||||||
|
dhcp.RangeStart = updates.RangeStart
|
||||||
|
}
|
||||||
|
if updates.RangeEnd != "" {
|
||||||
|
dhcp.RangeEnd = updates.RangeEnd
|
||||||
|
}
|
||||||
|
if updates.LeaseTime != "" {
|
||||||
|
dhcp.LeaseTime = updates.LeaseTime
|
||||||
|
}
|
||||||
|
if updates.Gateway != "" {
|
||||||
|
dhcp.Gateway = updates.Gateway
|
||||||
|
}
|
||||||
|
if err := api.saveState(state); err != nil {
|
||||||
|
respondError(w, http.StatusInternalServerError, "Failed to save state")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info("DHCP config updated", "enabled", dhcp.Enabled)
|
||||||
|
respondJSON(w, http.StatusOK, state.Cloud.Dnsmasq.DHCP)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- nftables Config ---
|
||||||
|
|
||||||
|
func (api *API) GetNftablesConfig(w http.ResponseWriter, r *http.Request) {
|
||||||
|
respondJSON(w, http.StatusOK, api.loadState().Cloud.Nftables)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) UpdateNftablesConfig(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var updates struct {
|
||||||
|
Enabled *bool `json:"enabled,omitempty"`
|
||||||
|
WANInterface string `json:"wanInterface,omitempty"`
|
||||||
|
ExtraPorts []config.ExtraPort `json:"extraPorts,omitempty"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&updates); err != nil {
|
||||||
|
respondError(w, http.StatusBadRequest, "Invalid request body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
state := api.loadState()
|
||||||
|
if updates.Enabled != nil {
|
||||||
|
state.Cloud.Nftables.Enabled = updates.Enabled
|
||||||
|
}
|
||||||
|
if updates.WANInterface != "" {
|
||||||
|
state.Cloud.Nftables.WANInterface = updates.WANInterface
|
||||||
|
}
|
||||||
|
if updates.ExtraPorts != nil {
|
||||||
|
state.Cloud.Nftables.ExtraPorts = updates.ExtraPorts
|
||||||
|
}
|
||||||
|
if err := api.saveState(state); err != nil {
|
||||||
|
respondError(w, http.StatusInternalServerError, "Failed to save state")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info("nftables config updated")
|
||||||
|
respondJSON(w, http.StatusOK, state.Cloud.Nftables)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- HAProxy Custom Routes ---
|
||||||
|
|
||||||
|
func (api *API) GetHAProxyRoutes(w http.ResponseWriter, r *http.Request) {
|
||||||
|
respondJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"customRoutes": api.loadState().Cloud.HAProxy.CustomRoutes,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) UpdateHAProxyRoutes(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var updates struct {
|
||||||
|
CustomRoutes []config.HAProxyCustomRoute `json:"customRoutes"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&updates); err != nil {
|
||||||
|
respondError(w, http.StatusBadRequest, "Invalid request body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
state := api.loadState()
|
||||||
|
state.Cloud.HAProxy.CustomRoutes = updates.CustomRoutes
|
||||||
|
if err := api.saveState(state); err != nil {
|
||||||
|
respondError(w, http.StatusInternalServerError, "Failed to save state")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info("HAProxy custom routes updated", "count", len(updates.CustomRoutes))
|
||||||
|
respondJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"customRoutes": state.Cloud.HAProxy.CustomRoutes,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -12,9 +12,8 @@ import {
|
|||||||
import { useCloudflare } from '../hooks/useCloudflare';
|
import { useCloudflare } from '../hooks/useCloudflare';
|
||||||
import { useDdns } from '../hooks/useDdns';
|
import { useDdns } from '../hooks/useDdns';
|
||||||
import { useCentralStatus } from '../hooks/useCentralStatus';
|
import { useCentralStatus } from '../hooks/useCentralStatus';
|
||||||
import { useConfig } from '../hooks';
|
|
||||||
import { useVpn } from '../hooks/useVpn';
|
import { useVpn } from '../hooks/useVpn';
|
||||||
import { secretsApi } from '../services/api';
|
import { secretsApi, dnsSettingsApi, nftablesConfigApi } from '../services/api';
|
||||||
import { usePageHelp } from '../hooks/usePageHelp';
|
import { usePageHelp } from '../hooks/usePageHelp';
|
||||||
import type { DdnsRecordStatus } from '../services/api/networking';
|
import type { DdnsRecordStatus } from '../services/api/networking';
|
||||||
|
|
||||||
@@ -22,8 +21,9 @@ export function DashboardComponent() {
|
|||||||
const { data: centralStatus, isLoading: statusLoading, restart: restartDaemon, isRestarting } = useCentralStatus();
|
const { data: centralStatus, isLoading: statusLoading, restart: restartDaemon, isRestarting } = useCentralStatus();
|
||||||
const { verification, isLoading: cfLoading } = useCloudflare();
|
const { verification, isLoading: cfLoading } = useCloudflare();
|
||||||
const { status: ddnsStatus, isLoadingStatus: ddnsLoading, trigger: triggerDdns, isTriggering } = useDdns();
|
const { status: ddnsStatus, isLoadingStatus: ddnsLoading, trigger: triggerDdns, isTriggering } = useDdns();
|
||||||
const { config: globalConfig } = useConfig();
|
|
||||||
const { config: vpnConfig } = useVpn();
|
const { config: vpnConfig } = useVpn();
|
||||||
|
const { data: dnsSettings } = useQuery({ queryKey: ['dns', 'settings'], queryFn: () => dnsSettingsApi.get() });
|
||||||
|
const { data: nftConfig } = useQuery({ queryKey: ['nftables', 'config'], queryFn: () => nftablesConfigApi.get() });
|
||||||
|
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { data: globalSecrets } = useQuery({
|
const { data: globalSecrets } = useQuery({
|
||||||
@@ -379,9 +379,9 @@ export function DashboardComponent() {
|
|||||||
<ul className="list-disc list-inside space-y-1 text-xs">
|
<ul className="list-disc list-inside space-y-1 text-xs">
|
||||||
<li>
|
<li>
|
||||||
Set the router's DNS server to Wild Central
|
Set the router's DNS server to Wild Central
|
||||||
{globalConfig?.cloud?.dnsmasq?.ip && (
|
{dnsSettings?.ip && (
|
||||||
<span className="font-mono bg-muted px-1.5 py-0.5 rounded ml-1">
|
<span className="font-mono bg-muted px-1.5 py-0.5 rounded ml-1">
|
||||||
{globalConfig.cloud.dnsmasq.ip}
|
{dnsSettings.ip}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</li>
|
</li>
|
||||||
@@ -391,7 +391,7 @@ export function DashboardComponent() {
|
|||||||
{ port: 443, proto: 'TCP', label: 'HTTPS' },
|
{ port: 443, proto: 'TCP', label: 'HTTPS' },
|
||||||
{ port: 80, proto: 'TCP', label: 'HTTP' },
|
{ port: 80, proto: 'TCP', label: 'HTTP' },
|
||||||
...(vpnConfig?.enabled ? [{ port: vpnConfig.listenPort || 51820, proto: 'UDP', label: 'VPN' }] : []),
|
...(vpnConfig?.enabled ? [{ port: vpnConfig.listenPort || 51820, proto: 'UDP', label: 'VPN' }] : []),
|
||||||
...((globalConfig?.cloud?.nftables?.extraPorts ?? []) as { port: number; protocol?: string; label?: string }[])
|
...((nftConfig?.extraPorts ?? []) as { port: number; protocol?: string; label?: string }[])
|
||||||
.map(ep => ({ port: ep.port, proto: (ep.protocol || 'tcp').toUpperCase(), label: ep.label || '' })),
|
.map(ep => ({ port: ep.port, proto: (ep.protocol || 'tcp').toUpperCase(), label: ep.label || '' })),
|
||||||
].map((p, i) => (
|
].map((p, i) => (
|
||||||
<span key={i}>
|
<span key={i}>
|
||||||
|
|||||||
@@ -5,13 +5,20 @@ import { Input, Label } from './ui';
|
|||||||
import { Alert, AlertDescription } from './ui/alert';
|
import { Alert, AlertDescription } from './ui/alert';
|
||||||
import { Wifi, Loader2, Edit2, Check, X, Trash2, Plus, RotateCw, CheckCircle, AlertCircle } from 'lucide-react';
|
import { Wifi, Loader2, Edit2, Check, X, Trash2, Plus, RotateCw, CheckCircle, AlertCircle } from 'lucide-react';
|
||||||
import { Badge } from './ui/badge';
|
import { Badge } from './ui/badge';
|
||||||
import { useConfig } from '../hooks';
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
import { useDhcp } from '../hooks/useDhcp';
|
import { useDhcp } from '../hooks/useDhcp';
|
||||||
import { useDnsmasq } from '../hooks/useDnsmasq';
|
import { useDnsmasq } from '../hooks/useDnsmasq';
|
||||||
|
import { dhcpConfigApi, type DHCPConfig } from '../services/api/settings';
|
||||||
import type { DhcpStaticLease } from '../services/api/networking';
|
import type { DhcpStaticLease } from '../services/api/networking';
|
||||||
|
|
||||||
export function DhcpComponent() {
|
export function DhcpComponent() {
|
||||||
const { config: globalConfig, updateConfig, isUpdating } = useConfig();
|
const queryClient = useQueryClient();
|
||||||
|
const { data: dhcpConfig } = useQuery({ queryKey: ['dhcp', 'config'], queryFn: () => dhcpConfigApi.get() });
|
||||||
|
const dhcpMutation = useMutation({
|
||||||
|
mutationFn: (data: Partial<DHCPConfig>) => dhcpConfigApi.update(data),
|
||||||
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['dhcp', 'config'] }),
|
||||||
|
});
|
||||||
|
const isUpdating = dhcpMutation.isPending;
|
||||||
const { leases, isLoadingLeases, refetchLeases, addStatic, isAddingStatic, deleteStatic } = useDhcp();
|
const { leases, isLoadingLeases, refetchLeases, addStatic, isAddingStatic, deleteStatic } = useDhcp();
|
||||||
const { generateConfig: generateDnsConfig } = useDnsmasq();
|
const { generateConfig: generateDnsConfig } = useDnsmasq();
|
||||||
|
|
||||||
@@ -36,33 +43,23 @@ export function DhcpComponent() {
|
|||||||
|
|
||||||
const handleDhcpConfigEdit = () => {
|
const handleDhcpConfigEdit = () => {
|
||||||
setDhcpConfigForm({
|
setDhcpConfigForm({
|
||||||
enabled: globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ?? false,
|
enabled: dhcpConfig?.enabled ?? false,
|
||||||
rangeStart: globalConfig?.cloud?.dnsmasq?.dhcp?.rangeStart ?? '',
|
rangeStart: dhcpConfig?.rangeStart ?? '',
|
||||||
rangeEnd: globalConfig?.cloud?.dnsmasq?.dhcp?.rangeEnd ?? '',
|
rangeEnd: dhcpConfig?.rangeEnd ?? '',
|
||||||
leaseTime: globalConfig?.cloud?.dnsmasq?.dhcp?.leaseTime ?? '24h',
|
leaseTime: dhcpConfig?.leaseTime ?? '24h',
|
||||||
gateway: globalConfig?.cloud?.dnsmasq?.dhcp?.gateway ?? '',
|
gateway: dhcpConfig?.gateway ?? '',
|
||||||
});
|
});
|
||||||
setEditingDhcpConfig(true);
|
setEditingDhcpConfig(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDhcpConfigSave = async () => {
|
const handleDhcpConfigSave = async () => {
|
||||||
if (!globalConfig) return;
|
|
||||||
try {
|
try {
|
||||||
await updateConfig({
|
await dhcpMutation.mutateAsync({
|
||||||
...globalConfig,
|
|
||||||
cloud: {
|
|
||||||
...globalConfig.cloud,
|
|
||||||
dnsmasq: {
|
|
||||||
...globalConfig.cloud?.dnsmasq,
|
|
||||||
dhcp: {
|
|
||||||
enabled: dhcpConfigForm.enabled,
|
enabled: dhcpConfigForm.enabled,
|
||||||
rangeStart: dhcpConfigForm.rangeStart,
|
rangeStart: dhcpConfigForm.rangeStart,
|
||||||
rangeEnd: dhcpConfigForm.rangeEnd,
|
rangeEnd: dhcpConfigForm.rangeEnd,
|
||||||
leaseTime: dhcpConfigForm.leaseTime,
|
leaseTime: dhcpConfigForm.leaseTime,
|
||||||
gateway: dhcpConfigForm.gateway || undefined,
|
gateway: dhcpConfigForm.gateway || undefined,
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
setEditingDhcpConfig(false);
|
setEditingDhcpConfig(false);
|
||||||
if (dhcpConfigForm.enabled) {
|
if (dhcpConfigForm.enabled) {
|
||||||
@@ -104,9 +101,9 @@ export function DhcpComponent() {
|
|||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<CardTitle>Configuration</CardTitle>
|
<CardTitle>Configuration</CardTitle>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Badge variant={globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ? 'success' : 'secondary'} className="gap-1">
|
<Badge variant={dhcpConfig?.enabled ? 'success' : 'secondary'} className="gap-1">
|
||||||
{globalConfig?.cloud?.dnsmasq?.dhcp?.enabled && <CheckCircle className="h-3 w-3" />}
|
{dhcpConfig?.enabled && <CheckCircle className="h-3 w-3" />}
|
||||||
{globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ? 'Enabled' : 'Disabled'}
|
{dhcpConfig?.enabled ? 'Enabled' : 'Disabled'}
|
||||||
</Badge>
|
</Badge>
|
||||||
{!editingDhcpConfig && (
|
{!editingDhcpConfig && (
|
||||||
<Button variant="outline" size="sm" onClick={handleDhcpConfigEdit} className="gap-1 h-7 text-xs">
|
<Button variant="outline" size="sm" onClick={handleDhcpConfigEdit} className="gap-1 h-7 text-xs">
|
||||||
@@ -189,24 +186,24 @@ export function DhcpComponent() {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-2 text-sm">
|
<div className="space-y-2 text-sm">
|
||||||
{globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ? (
|
{dhcpConfig?.enabled ? (
|
||||||
<>
|
<>
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
<div>
|
<div>
|
||||||
<span className="text-muted-foreground">Range: </span>
|
<span className="text-muted-foreground">Range: </span>
|
||||||
<span className="font-mono">
|
<span className="font-mono">
|
||||||
{globalConfig.cloud.dnsmasq.dhcp.rangeStart} – {globalConfig.cloud.dnsmasq.dhcp.rangeEnd}
|
{dhcpConfig!.rangeStart} – {dhcpConfig!.rangeEnd}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<span className="text-muted-foreground">Lease: </span>
|
<span className="text-muted-foreground">Lease: </span>
|
||||||
<span className="font-mono">{globalConfig.cloud.dnsmasq.dhcp.leaseTime || '24h'}</span>
|
<span className="font-mono">{dhcpConfig!.leaseTime || '24h'}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{globalConfig.cloud.dnsmasq.dhcp.gateway && (
|
{dhcpConfig!.gateway && (
|
||||||
<div>
|
<div>
|
||||||
<span className="text-muted-foreground">Gateway: </span>
|
<span className="text-muted-foreground">Gateway: </span>
|
||||||
<span className="font-mono">{globalConfig.cloud.dnsmasq.dhcp.gateway}</span>
|
<span className="font-mono">{dhcpConfig!.gateway}</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -7,9 +7,10 @@ import { Alert, AlertDescription } from './ui/alert';
|
|||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
|
||||||
import { Shield, Loader2, AlertCircle, CheckCircle, Check, X, Plus, Trash2, BookOpen, ChevronDown, ChevronUp, Lock } from 'lucide-react';
|
import { Shield, Loader2, AlertCircle, CheckCircle, Check, X, Plus, Trash2, BookOpen, ChevronDown, ChevronUp, Lock } from 'lucide-react';
|
||||||
import { Badge } from './ui/badge';
|
import { Badge } from './ui/badge';
|
||||||
import { useConfig } from '../hooks';
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
import { useNftables } from '../hooks/useNftables';
|
import { useNftables } from '../hooks/useNftables';
|
||||||
import { useVpn } from '../hooks/useVpn';
|
import { useVpn } from '../hooks/useVpn';
|
||||||
|
import { nftablesConfigApi, haproxyRoutesApi } from '../services/api/settings';
|
||||||
|
|
||||||
type ExtraPort = { port: number; protocol?: string; label?: string };
|
type ExtraPort = { port: number; protocol?: string; label?: string };
|
||||||
|
|
||||||
@@ -38,15 +39,20 @@ interface PortEntry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function FirewallComponent() {
|
export function FirewallComponent() {
|
||||||
const { config: globalConfig, updateConfig } = useConfig();
|
const queryClient = useQueryClient();
|
||||||
|
const { data: nftCfg } = useQuery({ queryKey: ['nftables', 'config'], queryFn: () => nftablesConfigApi.get() });
|
||||||
|
const { data: haproxyRoutes } = useQuery({ queryKey: ['haproxy', 'routes'], queryFn: () => haproxyRoutesApi.get() });
|
||||||
|
const nftMutation = useMutation({
|
||||||
|
mutationFn: (data: Parameters<typeof nftablesConfigApi.update>[0]) => nftablesConfigApi.update(data),
|
||||||
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['nftables', 'config'] }),
|
||||||
|
});
|
||||||
const { status: nftablesStatus, isLoadingStatus: isNftablesLoading, interfaces, refetchStatus } = useNftables();
|
const { status: nftablesStatus, isLoadingStatus: isNftablesLoading, interfaces, refetchStatus } = useNftables();
|
||||||
const { config: vpnConfig } = useVpn();
|
const { config: vpnConfig } = useVpn();
|
||||||
|
|
||||||
const nftCfg = globalConfig?.cloud?.nftables;
|
|
||||||
const isEnabled = nftCfg?.enabled !== false;
|
const isEnabled = nftCfg?.enabled !== false;
|
||||||
const currentWan = nftCfg?.wanInterface ?? '';
|
const currentWan = nftCfg?.wanInterface ?? '';
|
||||||
const currentExtraPorts: ExtraPort[] = nftCfg?.extraPorts ?? [];
|
const currentExtraPorts: ExtraPort[] = nftCfg?.extraPorts ?? [];
|
||||||
const customRoutes = globalConfig?.cloud?.haproxy?.customRoutes ?? [];
|
const customRoutes = haproxyRoutes?.customRoutes ?? [];
|
||||||
|
|
||||||
const [editingWan, setEditingWan] = useState(false);
|
const [editingWan, setEditingWan] = useState(false);
|
||||||
const [wanValue, setWanValue] = useState('');
|
const [wanValue, setWanValue] = useState('');
|
||||||
@@ -121,15 +127,8 @@ export function FirewallComponent() {
|
|||||||
const tcpPorts = allPorts.filter(p => p.protocol === 'tcp');
|
const tcpPorts = allPorts.filter(p => p.protocol === 'tcp');
|
||||||
const udpPorts = allPorts.filter(p => p.protocol === 'udp');
|
const udpPorts = allPorts.filter(p => p.protocol === 'udp');
|
||||||
|
|
||||||
async function saveNftConfig(patch: NonNullable<NonNullable<typeof globalConfig>['cloud']>['nftables']) {
|
async function saveNftConfig(patch: Partial<NonNullable<typeof nftCfg>>) {
|
||||||
if (!globalConfig) return;
|
await nftMutation.mutateAsync(patch);
|
||||||
await updateConfig({
|
|
||||||
...globalConfig,
|
|
||||||
cloud: {
|
|
||||||
...globalConfig.cloud,
|
|
||||||
nftables: { ...nftCfg, ...patch },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
refetchStatus();
|
refetchStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
export { useMessages } from './useMessages';
|
export { useMessages } from './useMessages';
|
||||||
export { useStatus } from './useStatus';
|
export { useStatus } from './useStatus';
|
||||||
export { useHealth } from './useHealth';
|
export { useHealth } from './useHealth';
|
||||||
export { useConfig } from './useConfig';
|
|
||||||
export { useDnsmasq } from './useDnsmasq';
|
export { useDnsmasq } from './useDnsmasq';
|
||||||
export { useCentralStatus } from './useCentralStatus';
|
export { useCentralStatus } from './useCentralStatus';
|
||||||
export { useCloudflare } from './useCloudflare';
|
export { useCloudflare } from './useCloudflare';
|
||||||
|
|||||||
@@ -1,61 +0,0 @@
|
|||||||
import { useState, useEffect } from 'react';
|
|
||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
||||||
import { apiService } from '../services/api-legacy';
|
|
||||||
import type { CentralState, CentralStateResponse } from '../types';
|
|
||||||
|
|
||||||
interface CreateConfigResponse {
|
|
||||||
status: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hook for managing Wild Central runtime state
|
|
||||||
* Endpoint: /api/v1/state
|
|
||||||
* File: {dataDir}/state.yaml
|
|
||||||
*/
|
|
||||||
export const useConfig = () => {
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const [showConfigSetup, setShowConfigSetup] = useState(false);
|
|
||||||
|
|
||||||
const stateQuery = useQuery<CentralStateResponse>({
|
|
||||||
queryKey: ['state'],
|
|
||||||
queryFn: () => apiService.getConfig(),
|
|
||||||
});
|
|
||||||
|
|
||||||
// Update showConfigSetup based on query data
|
|
||||||
useEffect(() => {
|
|
||||||
if (stateQuery.data) {
|
|
||||||
setShowConfigSetup(stateQuery.data.configured === false);
|
|
||||||
}
|
|
||||||
}, [stateQuery.data]);
|
|
||||||
|
|
||||||
const createStateMutation = useMutation<CreateConfigResponse, Error, CentralState>({
|
|
||||||
mutationFn: (state) => apiService.createConfig(state),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['state'] });
|
|
||||||
setShowConfigSetup(false);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const updateStateMutation = useMutation<CreateConfigResponse, Error, CentralState>({
|
|
||||||
mutationFn: (state) => apiService.updateConfig(state),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['state'] });
|
|
||||||
// Immediately re-check daemon status so the pending-restart banner appears
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['central', 'status'] });
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
config: stateQuery.data?.state || null,
|
|
||||||
isConfigured: stateQuery.data?.configured || false,
|
|
||||||
showConfigSetup,
|
|
||||||
setShowConfigSetup,
|
|
||||||
isLoading: stateQuery.isLoading,
|
|
||||||
isCreating: createStateMutation.isPending,
|
|
||||||
isUpdating: updateStateMutation.isPending,
|
|
||||||
error: stateQuery.error || createStateMutation.error || updateStateMutation.error,
|
|
||||||
createConfig: createStateMutation.mutate,
|
|
||||||
updateConfig: updateStateMutation.mutateAsync,
|
|
||||||
refetch: stateQuery.refetch,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
import type {
|
import type {
|
||||||
Status,
|
Status,
|
||||||
CentralState,
|
|
||||||
CentralStateResponse,
|
|
||||||
HealthResponse,
|
HealthResponse,
|
||||||
StatusResponse,
|
StatusResponse,
|
||||||
NetworkInfo,
|
NetworkInfo,
|
||||||
@@ -30,16 +28,6 @@ class ApiService {
|
|||||||
return response.json();
|
return response.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
private async requestText(endpoint: string, options?: RequestInit): Promise<string> {
|
|
||||||
const url = `${this.baseUrl}${endpoint}`;
|
|
||||||
const response = await fetch(url, options);
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`HTTP error! status: ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return response.text();
|
|
||||||
}
|
|
||||||
|
|
||||||
async getStatus(): Promise<Status> {
|
async getStatus(): Promise<Status> {
|
||||||
return this.request<Status>('/api/status');
|
return this.request<Status>('/api/status');
|
||||||
@@ -49,43 +37,6 @@ class ApiService {
|
|||||||
return this.request<HealthResponse>('/api/v1/health');
|
return this.request<HealthResponse>('/api/v1/health');
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========================================
|
|
||||||
// Global Config APIs (Wild Central level)
|
|
||||||
// Endpoint: /api/v1/state
|
|
||||||
// ========================================
|
|
||||||
|
|
||||||
async getConfig(): Promise<CentralStateResponse> {
|
|
||||||
return this.request<CentralStateResponse>('/api/v1/state');
|
|
||||||
}
|
|
||||||
|
|
||||||
async getConfigYaml(): Promise<string> {
|
|
||||||
return this.requestText('/api/v1/state/yaml');
|
|
||||||
}
|
|
||||||
|
|
||||||
async updateConfigYaml(yamlContent: string): Promise<StatusResponse> {
|
|
||||||
return this.request<StatusResponse>('/api/v1/state/yaml', {
|
|
||||||
method: 'PUT',
|
|
||||||
headers: { 'Content-Type': 'text/plain' },
|
|
||||||
body: yamlContent
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async createConfig(config: CentralState): Promise<StatusResponse> {
|
|
||||||
return this.request<StatusResponse>('/api/v1/state', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify(config)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async updateConfig(config: CentralState): Promise<StatusResponse> {
|
|
||||||
return this.request<StatusResponse>('/api/v1/state', {
|
|
||||||
method: 'PUT',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify(config)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async getDnsmasqStatus(): Promise<DnsmasqStatus> {
|
async getDnsmasqStatus(): Promise<DnsmasqStatus> {
|
||||||
return this.request<DnsmasqStatus>('/api/v1/dnsmasq/status');
|
return this.request<DnsmasqStatus>('/api/v1/dnsmasq/status');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,3 +9,5 @@ export { certApi } from './cert';
|
|||||||
export type { CertStatusResponse, CertInfo } from './cert';
|
export type { CertStatusResponse, CertInfo } from './cert';
|
||||||
export { cloudflareApi } from './cloudflare';
|
export { cloudflareApi } from './cloudflare';
|
||||||
export type { CloudflareVerifyResponse, CloudflareZone } from './cloudflare';
|
export type { CloudflareVerifyResponse, CloudflareZone } from './cloudflare';
|
||||||
|
export { operatorApi, centralDomainApi, dnsSettingsApi, ddnsConfigApi, dhcpConfigApi, nftablesConfigApi, haproxyRoutesApi } from './settings';
|
||||||
|
export type { OperatorSettings, CentralDomainSettings, DNSSettings, DDNSConfig, DHCPConfig, NftablesConfig, HAProxyCustomRoute, HAProxyRoutes } from './settings';
|
||||||
|
|||||||
@@ -144,15 +144,15 @@ export interface DhcpStaticLease {
|
|||||||
|
|
||||||
export const dhcpApi = {
|
export const dhcpApi = {
|
||||||
async getLeases(): Promise<{ leases: DhcpLease[] }> {
|
async getLeases(): Promise<{ leases: DhcpLease[] }> {
|
||||||
return apiClient.get('/api/v1/dnsmasq/dhcp/leases');
|
return apiClient.get('/api/v1/dhcp/leases');
|
||||||
},
|
},
|
||||||
|
|
||||||
async addStatic(lease: DhcpStaticLease): Promise<{ message: string }> {
|
async addStatic(lease: DhcpStaticLease): Promise<{ message: string }> {
|
||||||
return apiClient.post('/api/v1/dnsmasq/dhcp/static', lease);
|
return apiClient.post('/api/v1/dhcp/static', lease);
|
||||||
},
|
},
|
||||||
|
|
||||||
async deleteStatic(mac: string): Promise<{ message: string }> {
|
async deleteStatic(mac: string): Promise<{ message: string }> {
|
||||||
return apiClient.delete(`/api/v1/dnsmasq/dhcp/static/${encodeURIComponent(mac)}`);
|
return apiClient.delete(`/api/v1/dhcp/static/${encodeURIComponent(mac)}`);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
121
web/src/services/api/settings.ts
Normal file
121
web/src/services/api/settings.ts
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
import { apiClient } from './client';
|
||||||
|
|
||||||
|
// Operator
|
||||||
|
|
||||||
|
export interface OperatorSettings {
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const operatorApi = {
|
||||||
|
async get(): Promise<OperatorSettings> {
|
||||||
|
return apiClient.get('/api/v1/operator');
|
||||||
|
},
|
||||||
|
async update(data: Partial<OperatorSettings>): Promise<OperatorSettings> {
|
||||||
|
return apiClient.put('/api/v1/operator', data);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Central Domain
|
||||||
|
|
||||||
|
export interface CentralDomainSettings {
|
||||||
|
domain: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const centralDomainApi = {
|
||||||
|
async get(): Promise<CentralDomainSettings> {
|
||||||
|
return apiClient.get('/api/v1/central-domain');
|
||||||
|
},
|
||||||
|
async update(data: CentralDomainSettings): Promise<CentralDomainSettings> {
|
||||||
|
return apiClient.put('/api/v1/central-domain', data);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// DNS Settings
|
||||||
|
|
||||||
|
export interface DNSSettings {
|
||||||
|
ip: string;
|
||||||
|
interface: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const dnsSettingsApi = {
|
||||||
|
async get(): Promise<DNSSettings> {
|
||||||
|
return apiClient.get('/api/v1/dns/settings');
|
||||||
|
},
|
||||||
|
async update(data: Partial<DNSSettings>): Promise<DNSSettings> {
|
||||||
|
return apiClient.put('/api/v1/dns/settings', data);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// DDNS Config
|
||||||
|
|
||||||
|
export interface DDNSConfig {
|
||||||
|
enabled: boolean;
|
||||||
|
provider?: string;
|
||||||
|
intervalMinutes?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ddnsConfigApi = {
|
||||||
|
async get(): Promise<DDNSConfig> {
|
||||||
|
return apiClient.get('/api/v1/ddns/config');
|
||||||
|
},
|
||||||
|
async update(data: Partial<DDNSConfig>): Promise<DDNSConfig> {
|
||||||
|
return apiClient.put('/api/v1/ddns/config', data);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// DHCP Config
|
||||||
|
|
||||||
|
export interface DHCPConfig {
|
||||||
|
enabled: boolean;
|
||||||
|
rangeStart?: string;
|
||||||
|
rangeEnd?: string;
|
||||||
|
leaseTime?: string;
|
||||||
|
gateway?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const dhcpConfigApi = {
|
||||||
|
async get(): Promise<DHCPConfig> {
|
||||||
|
return apiClient.get('/api/v1/dhcp/config');
|
||||||
|
},
|
||||||
|
async update(data: Partial<DHCPConfig>): Promise<DHCPConfig> {
|
||||||
|
return apiClient.put('/api/v1/dhcp/config', data);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// nftables Config
|
||||||
|
|
||||||
|
export interface NftablesConfig {
|
||||||
|
enabled?: boolean;
|
||||||
|
wanInterface?: string;
|
||||||
|
extraPorts?: Array<{ port: number; protocol?: string; label?: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const nftablesConfigApi = {
|
||||||
|
async get(): Promise<NftablesConfig> {
|
||||||
|
return apiClient.get('/api/v1/nftables/config');
|
||||||
|
},
|
||||||
|
async update(data: Partial<NftablesConfig>): Promise<NftablesConfig> {
|
||||||
|
return apiClient.put('/api/v1/nftables/config', data);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// HAProxy Custom Routes
|
||||||
|
|
||||||
|
export interface HAProxyCustomRoute {
|
||||||
|
name: string;
|
||||||
|
port: number;
|
||||||
|
backend: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HAProxyRoutes {
|
||||||
|
customRoutes: HAProxyCustomRoute[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const haproxyRoutesApi = {
|
||||||
|
async get(): Promise<HAProxyRoutes> {
|
||||||
|
return apiClient.get('/api/v1/haproxy/routes');
|
||||||
|
},
|
||||||
|
async update(data: HAProxyRoutes): Promise<HAProxyRoutes> {
|
||||||
|
return apiClient.put('/api/v1/haproxy/routes', data);
|
||||||
|
},
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user