Scaffold ipswap: tray-driven Windows IP preset switcher
Implements the design in claude.md as a building skeleton: pure Go, no cgo, cross-compiles to a single Windows .exe from Linux. Architecture follows the spec's deliberate split. The fast path is native — tray icon, grouped submenus, a Win32 MessageBox showing a live before/after diff, then netsh. The slow path is an embedded web editor served on a random loopback port and opened in the default browser. Two decisions worth recording: Reads use GetAdaptersAddresses, writes use netsh. The spec left the enumeration mechanism open; parsing `netsh show config` breaks on a non-English Windows because the output is localised. DNS static-vs-DHCP origin is not exposed by that API, so it comes from one registry read. The netsh command plan is built in portable code. That puts the delete-every- existing-address step — the one that stops secondary addresses leaking across switches — under test without needing a Windows box. The editor requires the session token in a header for mutations, not just the cookie: any page in the browser can make it POST to 127.0.0.1 with the cookie attached, but it cannot set a header. The updater refuses to install a release that publishes no SHA256. Not yet done: no group picker for export (the API supports it), no single-instance guard, and internal/server/web/app.css is reconstructed from the description in claude.md rather than the canonical apointless.css. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,439 @@
|
||||
// Package server is the "slow path": a local HTTP server hosting the preset
|
||||
// editor, opened in the user's default browser.
|
||||
//
|
||||
// It exists because the fast path must not involve a browser and the editor
|
||||
// must not involve a MessageBox. Switching a preset is two clicks in the tray;
|
||||
// managing fifty of them needs a real UI, and an embedded web app is the only
|
||||
// way to get one without linking a GUI toolkit and giving up cross-compilation.
|
||||
//
|
||||
// The server is not running most of the time. The tray starts it on demand and
|
||||
// it shuts itself down once the browser stops sending heartbeats.
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"embed"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitea.apointless.space/bsncubed/ipswap/internal/config"
|
||||
"gitea.apointless.space/bsncubed/ipswap/internal/netcfg"
|
||||
"gitea.apointless.space/bsncubed/ipswap/internal/preset"
|
||||
)
|
||||
|
||||
//go:embed web
|
||||
var webFS embed.FS
|
||||
|
||||
const (
|
||||
// idleTimeout is how long the server survives without a heartbeat. The
|
||||
// browser beats every 30s, so this tolerates a few missed beats before
|
||||
// concluding the tab is gone.
|
||||
idleTimeout = 5 * time.Minute
|
||||
// tokenHeader carries the session token on mutating requests.
|
||||
tokenHeader = "X-Ipswap-Token"
|
||||
)
|
||||
|
||||
// Server hosts the editor.
|
||||
type Server struct {
|
||||
store *preset.Store
|
||||
mgr netcfg.Manager
|
||||
paths config.Paths
|
||||
|
||||
// onSettingsChange lets the tray react to a settings save, e.g. to
|
||||
// rewrite the Run key when start-with-Windows is toggled.
|
||||
onSettingsChange func(config.Settings)
|
||||
// onPresetsChange asks the tray to rebuild its menu.
|
||||
onPresetsChange func()
|
||||
|
||||
mu sync.Mutex
|
||||
settings config.Settings
|
||||
token string
|
||||
srv *http.Server
|
||||
ln net.Listener
|
||||
lastBeat time.Time
|
||||
stop chan struct{}
|
||||
}
|
||||
|
||||
// New builds a server. It does not listen until Start is called.
|
||||
func New(store *preset.Store, mgr netcfg.Manager, paths config.Paths, settings config.Settings) *Server {
|
||||
return &Server{store: store, mgr: mgr, paths: paths, settings: settings}
|
||||
}
|
||||
|
||||
// OnSettingsChange registers a callback fired after settings are saved.
|
||||
func (s *Server) OnSettingsChange(f func(config.Settings)) { s.onSettingsChange = f }
|
||||
|
||||
// OnPresetsChange registers a callback fired after any preset mutation.
|
||||
func (s *Server) OnPresetsChange(f func()) { s.onPresetsChange = f }
|
||||
|
||||
// URL returns the address to open, including the session token. It is empty
|
||||
// when the server is not running.
|
||||
func (s *Server) URL() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.ln == nil {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("http://127.0.0.1:%d/?t=%s", s.ln.Addr().(*net.TCPAddr).Port, s.token)
|
||||
}
|
||||
|
||||
// Start binds a random loopback port and serves until Stop or an idle timeout.
|
||||
// Calling it while already running just returns the existing URL, so clicking
|
||||
// "Manage presets…" twice reuses the one session.
|
||||
func (s *Server) Start() (string, error) {
|
||||
s.mu.Lock()
|
||||
if s.ln != nil {
|
||||
url := fmt.Sprintf("http://127.0.0.1:%d/?t=%s", s.ln.Addr().(*net.TCPAddr).Port, s.token)
|
||||
s.lastBeat = time.Now()
|
||||
s.mu.Unlock()
|
||||
return url, nil
|
||||
}
|
||||
|
||||
// Loopback only. This binds no external interface at any point, which
|
||||
// matters given the app spends its life on customer networks.
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
s.mu.Unlock()
|
||||
return "", fmt.Errorf("binding a local port: %w", err)
|
||||
}
|
||||
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
ln.Close()
|
||||
s.mu.Unlock()
|
||||
return "", err
|
||||
}
|
||||
|
||||
s.ln = ln
|
||||
s.token = token
|
||||
s.lastBeat = time.Now()
|
||||
s.stop = make(chan struct{})
|
||||
s.srv = &http.Server{
|
||||
Handler: s.routes(),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
}
|
||||
stop := s.stop
|
||||
srv := s.srv
|
||||
port := ln.Addr().(*net.TCPAddr).Port
|
||||
s.mu.Unlock()
|
||||
|
||||
go func() {
|
||||
if err := srv.Serve(ln); err != nil && err != http.ErrServerClosed {
|
||||
log.Printf("editor server stopped: %v", err)
|
||||
}
|
||||
}()
|
||||
go s.watchIdle(stop)
|
||||
|
||||
log.Printf("editor server listening on 127.0.0.1:%d", port)
|
||||
return fmt.Sprintf("http://127.0.0.1:%d/?t=%s", port, token), nil
|
||||
}
|
||||
|
||||
// Stop shuts the server down. It is safe to call when not running.
|
||||
func (s *Server) Stop() {
|
||||
s.mu.Lock()
|
||||
srv, stop := s.srv, s.stop
|
||||
s.srv, s.ln, s.stop, s.token = nil, nil, nil, ""
|
||||
s.mu.Unlock()
|
||||
|
||||
if stop != nil {
|
||||
close(stop)
|
||||
}
|
||||
if srv == nil {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
_ = srv.Shutdown(ctx)
|
||||
log.Printf("editor server shut down")
|
||||
}
|
||||
|
||||
func (s *Server) watchIdle(stop <-chan struct{}) {
|
||||
t := time.NewTicker(30 * time.Second)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-t.C:
|
||||
s.mu.Lock()
|
||||
idle := time.Since(s.lastBeat)
|
||||
s.mu.Unlock()
|
||||
if idle > idleTimeout {
|
||||
log.Printf("editor server idle for %s, shutting down", idle.Round(time.Second))
|
||||
s.Stop()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newToken() (string, error) {
|
||||
var b [32]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", fmt.Errorf("generating a session token: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(b[:]), nil
|
||||
}
|
||||
|
||||
// Settings returns the current settings.
|
||||
func (s *Server) Settings() config.Settings {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.settings
|
||||
}
|
||||
|
||||
// SetSettings replaces the settings the server serves, for when something
|
||||
// outside the editor changes them.
|
||||
func (s *Server) SetSettings(c config.Settings) {
|
||||
s.mu.Lock()
|
||||
s.settings = c
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Server) beat() {
|
||||
s.mu.Lock()
|
||||
s.lastBeat = time.Now()
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// --- routing ---
|
||||
|
||||
func (s *Server) routes() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
assets, err := fs.Sub(webFS, "web")
|
||||
if err != nil {
|
||||
// Only reachable if the embed directive and the directory disagree,
|
||||
// which is a build-time mistake, not a runtime condition.
|
||||
panic(err)
|
||||
}
|
||||
mux.Handle("GET /", http.FileServer(http.FS(assets)))
|
||||
|
||||
mux.HandleFunc("POST /api/heartbeat", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
})
|
||||
|
||||
mux.HandleFunc("GET /api/presets", s.handleListPresets)
|
||||
mux.HandleFunc("POST /api/presets", s.handlePutPreset)
|
||||
mux.HandleFunc("PUT /api/presets/{id}", s.handlePutPreset)
|
||||
mux.HandleFunc("DELETE /api/presets/{id}", s.handleDeletePreset)
|
||||
|
||||
mux.HandleFunc("GET /api/adapters", s.handleAdapters)
|
||||
mux.HandleFunc("GET /api/settings", s.handleGetSettings)
|
||||
mux.HandleFunc("PUT /api/settings", s.handlePutSettings)
|
||||
|
||||
mux.HandleFunc("GET /api/export", s.handleExport)
|
||||
mux.HandleFunc("POST /api/import", s.handleImport)
|
||||
|
||||
return s.withAuth(mux)
|
||||
}
|
||||
|
||||
// withAuth gates every request on the session token and refreshes the idle
|
||||
// timer.
|
||||
//
|
||||
// The token arrives once in the URL and is then stored in a SameSite=Strict
|
||||
// cookie. Mutating requests additionally require the token in a header, which
|
||||
// a cross-site page cannot set: a cookie alone would let any website in the
|
||||
// browser POST to this port and rewrite the user's presets.
|
||||
func (s *Server) withAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
s.mu.Lock()
|
||||
token := s.token
|
||||
s.mu.Unlock()
|
||||
if token == "" {
|
||||
http.Error(w, "server is shutting down", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
if q := r.URL.Query().Get("t"); q != "" && tokenEqual(q, token) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "ipswap_session",
|
||||
Value: token,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
})
|
||||
s.beat()
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
c, err := r.Cookie("ipswap_session")
|
||||
if err != nil || !tokenEqual(c.Value, token) {
|
||||
http.Error(w, "unauthorised: reopen the editor from the tray menu", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
if !tokenEqual(r.Header.Get(tokenHeader), token) {
|
||||
http.Error(w, "missing session header", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
s.beat()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func tokenEqual(got, want string) bool {
|
||||
return subtle.ConstantTimeCompare([]byte(got), []byte(want)) == 1
|
||||
}
|
||||
|
||||
// --- handlers ---
|
||||
|
||||
func (s *Server) handleListPresets(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"presets": s.store.All(),
|
||||
"groups": s.store.Groups(),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handlePutPreset(w http.ResponseWriter, r *http.Request) {
|
||||
var p preset.Preset
|
||||
if err := readJSON(r, &p); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
if id := r.PathValue("id"); id != "" {
|
||||
p.ID = id
|
||||
}
|
||||
|
||||
saved, err := s.store.Put(p)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
s.notifyPresets()
|
||||
writeJSON(w, http.StatusOK, saved)
|
||||
}
|
||||
|
||||
func (s *Server) handleDeletePreset(w http.ResponseWriter, r *http.Request) {
|
||||
if err := s.store.Delete(r.PathValue("id")); err != nil {
|
||||
writeErr(w, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
s.notifyPresets()
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleAdapters(w http.ResponseWriter, r *http.Request) {
|
||||
adapters, err := s.mgr.Adapters()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
type row struct {
|
||||
netcfg.Adapter
|
||||
Current string `json:"current"`
|
||||
}
|
||||
out := make([]row, 0, len(adapters))
|
||||
for _, a := range adapters {
|
||||
r := row{Adapter: a}
|
||||
if live, err := s.mgr.Current(a.Name); err == nil {
|
||||
r.Current = live.Summary()
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"adapters": out})
|
||||
}
|
||||
|
||||
func (s *Server) handleGetSettings(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, s.Settings())
|
||||
}
|
||||
|
||||
func (s *Server) handlePutSettings(w http.ResponseWriter, r *http.Request) {
|
||||
c := s.Settings()
|
||||
if err := readJSON(r, &c); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
if err := c.Save(s.paths.Config); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
s.SetSettings(c)
|
||||
if s.onSettingsChange != nil {
|
||||
s.onSettingsChange(c)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, c)
|
||||
}
|
||||
|
||||
func (s *Server) handleExport(w http.ResponseWriter, r *http.Request) {
|
||||
var groups []string
|
||||
if g := strings.TrimSpace(r.URL.Query().Get("groups")); g != "" {
|
||||
groups = strings.Split(g, ",")
|
||||
}
|
||||
|
||||
b, err := s.store.Export(groups...)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="ipswap-presets.json"`)
|
||||
w.Write(b)
|
||||
}
|
||||
|
||||
func (s *Server) handleImport(w http.ResponseWriter, r *http.Request) {
|
||||
mode := preset.ImportMode(r.URL.Query().Get("mode"))
|
||||
if mode == "" {
|
||||
mode = preset.ImportMerge
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 8<<20))
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := s.store.Import(body, mode)
|
||||
if err != nil {
|
||||
// Import validates the whole file first, so a rejection here means
|
||||
// nothing on disk changed.
|
||||
writeErr(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
s.notifyPresets()
|
||||
writeJSON(w, http.StatusOK, res)
|
||||
}
|
||||
|
||||
func (s *Server) notifyPresets() {
|
||||
if s.onPresetsChange != nil {
|
||||
s.onPresetsChange()
|
||||
}
|
||||
}
|
||||
|
||||
// --- helpers ---
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if err := json.NewEncoder(w).Encode(v); err != nil {
|
||||
log.Printf("writing response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func writeErr(w http.ResponseWriter, status int, err error) {
|
||||
writeJSON(w, status, map[string]string{"error": err.Error()})
|
||||
}
|
||||
|
||||
func readJSON(r *http.Request, v any) error {
|
||||
dec := json.NewDecoder(io.LimitReader(r.Body, 1<<20))
|
||||
if err := dec.Decode(v); err != nil {
|
||||
return fmt.Errorf("invalid request body: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.apointless.space/bsncubed/ipswap/internal/config"
|
||||
"gitea.apointless.space/bsncubed/ipswap/internal/netcfg"
|
||||
"gitea.apointless.space/bsncubed/ipswap/internal/preset"
|
||||
)
|
||||
|
||||
func newTestServer(t *testing.T) (*Server, string, string) {
|
||||
t.Helper()
|
||||
|
||||
dir := t.TempDir()
|
||||
store, err := preset.NewStore(filepath.Join(dir, "presets.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paths := config.Paths{Dir: dir, Presets: filepath.Join(dir, "presets.json"), Config: filepath.Join(dir, "config.json")}
|
||||
|
||||
s := New(store, netcfg.New(), paths, config.Default())
|
||||
raw, err := s.Start()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(s.Stop)
|
||||
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s, "http://" + u.Host, u.Query().Get("t")
|
||||
}
|
||||
|
||||
// do issues a request with no cookie jar, so each call is judged purely on
|
||||
// what it carries.
|
||||
func do(t *testing.T, method, url, token, header, body string) *http.Response {
|
||||
t.Helper()
|
||||
var r io.Reader
|
||||
if body != "" {
|
||||
r = strings.NewReader(body)
|
||||
}
|
||||
req, err := http.NewRequest(method, url, r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if token != "" {
|
||||
req.AddCookie(&http.Cookie{Name: "ipswap_session", Value: token})
|
||||
}
|
||||
if header != "" {
|
||||
req.Header.Set(tokenHeader, header)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func TestServesOnLoopbackOnly(t *testing.T) {
|
||||
_, base, _ := newTestServer(t)
|
||||
if !strings.HasPrefix(base, "http://127.0.0.1:") {
|
||||
t.Errorf("editor must bind loopback only, got %s", base)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRejectsMissingToken(t *testing.T) {
|
||||
_, base, _ := newTestServer(t)
|
||||
|
||||
resp := do(t, "GET", base+"/api/presets", "", "", "")
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Errorf("no token should be 401, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRejectsWrongToken(t *testing.T) {
|
||||
_, base, _ := newTestServer(t)
|
||||
|
||||
resp := do(t, "GET", base+"/api/presets", strings.Repeat("a", 64), "", "")
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Errorf("a wrong token should be 401, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryTokenSetsCookie(t *testing.T) {
|
||||
_, base, token := newTestServer(t)
|
||||
|
||||
resp := do(t, "GET", base+"/api/presets?t="+token, "", "", "")
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("query token should authenticate, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var found bool
|
||||
for _, c := range resp.Cookies() {
|
||||
if c.Name == "ipswap_session" {
|
||||
found = true
|
||||
if c.SameSite != http.SameSiteStrictMode {
|
||||
t.Error("session cookie must be SameSite=Strict")
|
||||
}
|
||||
if !c.HttpOnly {
|
||||
t.Error("session cookie must be HttpOnly")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("expected a session cookie to be set")
|
||||
}
|
||||
}
|
||||
|
||||
// A cookie alone must not be enough to mutate: any page in the browser can
|
||||
// make the browser send this cookie to 127.0.0.1, but it cannot set a header.
|
||||
func TestMutationRequiresHeaderNotJustCookie(t *testing.T) {
|
||||
_, base, token := newTestServer(t)
|
||||
|
||||
body := `{"name":"x","adapter":"Ethernet","mode":"dhcp","dns":{"mode":"dhcp"}}`
|
||||
|
||||
resp := do(t, "POST", base+"/api/presets", token, "", body)
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusForbidden {
|
||||
t.Errorf("cookie-only mutation should be 403, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
resp2 := do(t, "POST", base+"/api/presets", token, token, body)
|
||||
defer resp2.Body.Close()
|
||||
if resp2.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(resp2.Body)
|
||||
t.Errorf("cookie plus header should succeed, got %d: %s", resp2.StatusCode, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPresetCRUD(t *testing.T) {
|
||||
_, base, token := newTestServer(t)
|
||||
|
||||
body := `{"name":"Control","group":"Riedel","adapter":"Ethernet","mode":"static",
|
||||
"primary":{"address":"192.168.42.100","prefix":24,"gateway":"192.168.42.1"},
|
||||
"dns":{"mode":"static","servers":["192.168.42.1"]}}`
|
||||
|
||||
resp := do(t, "POST", base+"/api/presets", token, token, body)
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("create failed: %d %s", resp.StatusCode, b)
|
||||
}
|
||||
|
||||
var created preset.Preset
|
||||
if err := json.NewDecoder(resp.Body).Decode(&created); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if created.ID == "" {
|
||||
t.Fatal("server should assign an id")
|
||||
}
|
||||
|
||||
list := do(t, "GET", base+"/api/presets", token, "", "")
|
||||
defer list.Body.Close()
|
||||
var got struct {
|
||||
Presets []preset.Preset `json:"presets"`
|
||||
Groups []string `json:"groups"`
|
||||
}
|
||||
if err := json.NewDecoder(list.Body).Decode(&got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Presets) != 1 || got.Presets[0].Name != "Control" {
|
||||
t.Fatalf("list returned %+v", got.Presets)
|
||||
}
|
||||
|
||||
del := do(t, "DELETE", base+"/api/presets/"+created.ID, token, token, "")
|
||||
defer del.Body.Close()
|
||||
if del.StatusCode != http.StatusOK {
|
||||
t.Errorf("delete failed: %d", del.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidPresetIsRejected(t *testing.T) {
|
||||
_, base, token := newTestServer(t)
|
||||
|
||||
body := `{"name":"bad","adapter":"Ethernet","mode":"static","dns":{"mode":"dhcp"}}`
|
||||
resp := do(t, "POST", base+"/api/presets", token, token, body)
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("a static preset with no primary should be 400, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStopRejectsSubsequentRequests(t *testing.T) {
|
||||
s, base, token := newTestServer(t)
|
||||
s.Stop()
|
||||
|
||||
if _, err := http.Get(base + "/api/presets?t=" + token); err == nil {
|
||||
t.Error("expected the listener to be closed after Stop")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIndexIsServed(t *testing.T) {
|
||||
_, base, token := newTestServer(t)
|
||||
|
||||
resp := do(t, "GET", base+"/?t="+token, "", "", "")
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("index should be served, got %d", resp.StatusCode)
|
||||
}
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
if !strings.Contains(string(b), "ipswap") {
|
||||
t.Error("index.html does not look like the editor")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
/*
|
||||
* apointless.css — reconstructed from the description in claude.md.
|
||||
*
|
||||
* If you have the canonical apointless.css, drop it in over this file: the
|
||||
* markup below only uses the components the spec lists (cards, stat cards,
|
||||
* badges, pills, buttons, inputs, tables, alerts, code blocks, spinners), so a
|
||||
* real copy should be a straight swap.
|
||||
*
|
||||
* Fonts are declared as stacks with system fallbacks rather than pulled from a
|
||||
* CDN: ipswap runs on laptops sitting on customer networks with no route to
|
||||
* the internet, and a webfont that 404s would leave the editor unstyled.
|
||||
*/
|
||||
|
||||
:root {
|
||||
--bg: #0b0d11;
|
||||
--surface-1: #12151b;
|
||||
--surface-2: #1a1e28;
|
||||
--surface-3: #232838;
|
||||
|
||||
--text: #e6e9ef;
|
||||
--text-muted: #9aa3b2;
|
||||
--text-dim: #6b7382;
|
||||
|
||||
--accent: #3b82f6;
|
||||
--accent-hover: #60a5fa;
|
||||
--accent-dim: rgba(59, 130, 246, 0.15);
|
||||
|
||||
--ok: #22c55e;
|
||||
--warn: #f59e0b;
|
||||
--danger: #ef4444;
|
||||
--info: #38bdf8;
|
||||
|
||||
--border: #232838;
|
||||
--border-strong: #2f3648;
|
||||
|
||||
--mono: "JetBrains Mono", ui-monospace, "Cascadia Mono", "Consolas", monospace;
|
||||
--sans: "DM Sans", ui-sans-serif, system-ui, "Segoe UI", sans-serif;
|
||||
|
||||
--radius: 10px;
|
||||
--radius-sm: 6px;
|
||||
--gap: 16px;
|
||||
}
|
||||
|
||||
html.light {
|
||||
--bg: #f6f7f9;
|
||||
--surface-1: #ffffff;
|
||||
--surface-2: #f0f2f5;
|
||||
--surface-3: #e4e7ec;
|
||||
|
||||
--text: #12151b;
|
||||
--text-muted: #4b5563;
|
||||
--text-dim: #6b7382;
|
||||
|
||||
--accent-dim: rgba(59, 130, 246, 0.12);
|
||||
--border: #dfe3e9;
|
||||
--border-strong: #c8ced8;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: var(--sans);
|
||||
font-size: 15px;
|
||||
line-height: 1.55;
|
||||
min-height: 100vh;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* Subtle blue grid behind everything. */
|
||||
body::before {
|
||||
content: "";
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
background-image:
|
||||
linear-gradient(to right, rgba(59, 130, 246, 0.05) 1px, transparent 1px),
|
||||
linear-gradient(to bottom, rgba(59, 130, 246, 0.05) 1px, transparent 1px);
|
||||
background-size: 40px 40px;
|
||||
}
|
||||
|
||||
.wrap {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
max-width: 1100px;
|
||||
margin: 0 auto;
|
||||
padding: 28px 20px 64px;
|
||||
}
|
||||
|
||||
/* --- typography --- */
|
||||
|
||||
h1, h2, h3 { font-weight: 600; line-height: 1.25; margin: 0 0 8px; }
|
||||
h1 { font-size: 24px; letter-spacing: -0.02em; }
|
||||
h2 { font-size: 18px; }
|
||||
h3 { font-size: 15px; color: var(--text-muted); }
|
||||
|
||||
.mono { font-family: var(--mono); }
|
||||
.muted { color: var(--text-muted); }
|
||||
.dim { color: var(--text-dim); font-size: 13px; }
|
||||
|
||||
header.top {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--gap);
|
||||
margin-bottom: 24px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* --- cards --- */
|
||||
|
||||
.card {
|
||||
background: var(--surface-1);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 18px;
|
||||
margin-bottom: var(--gap);
|
||||
}
|
||||
|
||||
.card > h2 { margin-bottom: 12px; }
|
||||
|
||||
.stat-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
gap: 12px;
|
||||
margin-bottom: var(--gap);
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: var(--surface-1);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 14px 16px;
|
||||
}
|
||||
|
||||
.stat-card .label {
|
||||
font-size: 12px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.stat-card .value {
|
||||
font-family: var(--mono);
|
||||
font-size: 18px;
|
||||
margin-top: 4px;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
/* --- badges and pills --- */
|
||||
|
||||
.badge, .pill {
|
||||
display: inline-block;
|
||||
font-size: 12px;
|
||||
font-family: var(--mono);
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--border-strong);
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.badge.accent { background: var(--accent-dim); border-color: var(--accent); color: var(--accent-hover); }
|
||||
.badge.ok { background: rgba(34, 197, 94, 0.12); border-color: var(--ok); color: var(--ok); }
|
||||
.badge.warn { background: rgba(245, 158, 11, 0.12); border-color: var(--warn); color: var(--warn); }
|
||||
.badge.danger { background: rgba(239, 68, 68, 0.12); border-color: var(--danger); color: var(--danger); }
|
||||
|
||||
.pill { background: var(--surface-2); }
|
||||
|
||||
/* --- buttons --- */
|
||||
|
||||
button, .btn {
|
||||
font-family: var(--sans);
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
padding: 7px 14px;
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--surface-2);
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
transition: background 0.12s ease, border-color 0.12s ease;
|
||||
}
|
||||
|
||||
button:hover, .btn:hover { background: var(--surface-3); border-color: var(--accent); }
|
||||
button:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
button:disabled:hover { background: var(--surface-2); border-color: var(--border-strong); }
|
||||
|
||||
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
|
||||
button.primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }
|
||||
button.danger { border-color: var(--danger); color: var(--danger); }
|
||||
button.danger:hover { background: rgba(239, 68, 68, 0.12); }
|
||||
button.ghost { background: transparent; border-color: transparent; color: var(--text-muted); }
|
||||
button.ghost:hover { background: var(--surface-2); border-color: var(--border); }
|
||||
button.small { font-size: 12px; padding: 4px 9px; }
|
||||
|
||||
.btn-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
|
||||
|
||||
/* --- inputs --- */
|
||||
|
||||
label { display: block; font-size: 13px; color: var(--text-muted); margin-bottom: 4px; }
|
||||
|
||||
input, select, textarea {
|
||||
width: 100%;
|
||||
font-family: var(--mono);
|
||||
font-size: 14px;
|
||||
padding: 7px 10px;
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--surface-2);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
input:focus, select:focus, textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-dim);
|
||||
}
|
||||
|
||||
input[type="checkbox"] { width: auto; accent-color: var(--accent); }
|
||||
|
||||
.field { margin-bottom: 12px; }
|
||||
.field-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.check { display: flex; align-items: center; gap: 8px; }
|
||||
.check label { margin: 0; }
|
||||
|
||||
/* --- tables --- */
|
||||
|
||||
table { width: 100%; border-collapse: collapse; font-size: 14px; }
|
||||
|
||||
th {
|
||||
text-align: left;
|
||||
font-size: 12px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--text-dim);
|
||||
font-weight: 500;
|
||||
padding: 8px 10px;
|
||||
border-bottom: 1px solid var(--border-strong);
|
||||
}
|
||||
|
||||
td { padding: 9px 10px; border-bottom: 1px solid var(--border); vertical-align: middle; }
|
||||
tbody tr:hover { background: var(--surface-2); }
|
||||
td.mono, .table-scroll td.addr { font-family: var(--mono); font-size: 13px; }
|
||||
.table-scroll { overflow-x: auto; }
|
||||
|
||||
/* --- alerts --- */
|
||||
|
||||
.alert {
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--surface-2);
|
||||
padding: 10px 14px;
|
||||
margin-bottom: 12px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.alert.ok { border-color: var(--ok); background: rgba(34, 197, 94, 0.10); }
|
||||
.alert.warn { border-color: var(--warn); background: rgba(245, 158, 11, 0.10); }
|
||||
.alert.danger { border-color: var(--danger); background: rgba(239, 68, 68, 0.10); }
|
||||
.alert.info { border-color: var(--info); background: rgba(56, 189, 248, 0.10); }
|
||||
|
||||
/* --- code --- */
|
||||
|
||||
pre, code {
|
||||
font-family: var(--mono);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
pre {
|
||||
background: var(--surface-2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 12px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
/* --- spinner --- */
|
||||
|
||||
.spinner {
|
||||
display: inline-block;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border: 2px solid var(--border-strong);
|
||||
border-top-color: var(--accent);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.7s linear infinite;
|
||||
vertical-align: -2px;
|
||||
}
|
||||
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
/* --- layout odds and ends --- */
|
||||
|
||||
.group-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin: 20px 0 8px;
|
||||
}
|
||||
|
||||
.group-head h2 { margin: 0; }
|
||||
|
||||
.empty {
|
||||
text-align: center;
|
||||
color: var(--text-dim);
|
||||
padding: 32px 16px;
|
||||
}
|
||||
|
||||
dialog {
|
||||
background: var(--surface-1);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
padding: 20px;
|
||||
width: min(680px, 92vw);
|
||||
}
|
||||
|
||||
dialog::backdrop { background: rgba(0, 0, 0, 0.6); }
|
||||
|
||||
.sec-list { display: flex; flex-direction: column; gap: 8px; }
|
||||
.sec-row { display: flex; gap: 8px; align-items: center; }
|
||||
.sec-row input { flex: 1; }
|
||||
|
||||
.hidden { display: none !important; }
|
||||
@@ -0,0 +1,435 @@
|
||||
/*
|
||||
* ipswap preset editor.
|
||||
*
|
||||
* Plain ES modules-free JavaScript on purpose: the whole app is served from an
|
||||
* embed.FS inside a single .exe, and a build step for the front end would mean
|
||||
* a Node toolchain in CI for a few hundred lines of DOM code.
|
||||
*/
|
||||
|
||||
// The token arrives once in the query string. The server also sets it as a
|
||||
// SameSite=Strict cookie, but mutations additionally require it as a header —
|
||||
// a cookie alone would let any page in the browser POST to this port.
|
||||
const TOKEN = new URLSearchParams(location.search).get("t") || "";
|
||||
|
||||
const state = {
|
||||
presets: [],
|
||||
groups: [],
|
||||
adapters: [],
|
||||
settings: null,
|
||||
editing: null,
|
||||
};
|
||||
|
||||
// --- theme ---
|
||||
|
||||
const themeToggle = document.getElementById("theme-toggle");
|
||||
|
||||
function applyTheme(light) {
|
||||
document.documentElement.classList.toggle("light", light);
|
||||
themeToggle.textContent = light ? "Dark" : "Light";
|
||||
localStorage.setItem("ipswap-theme", light ? "light" : "dark");
|
||||
}
|
||||
|
||||
applyTheme(localStorage.getItem("ipswap-theme") === "light");
|
||||
themeToggle.addEventListener("click", () =>
|
||||
applyTheme(!document.documentElement.classList.contains("light"))
|
||||
);
|
||||
|
||||
// --- api ---
|
||||
|
||||
async function api(path, opts = {}) {
|
||||
const headers = Object.assign({}, opts.headers);
|
||||
if (opts.method && opts.method !== "GET") {
|
||||
headers["X-Ipswap-Token"] = TOKEN;
|
||||
if (opts.body && !headers["Content-Type"]) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
}
|
||||
}
|
||||
|
||||
const res = await fetch(path, Object.assign({}, opts, { headers }));
|
||||
const text = await res.text();
|
||||
let data = null;
|
||||
try {
|
||||
data = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
// Non-JSON bodies come from the auth middleware, which writes plain text.
|
||||
if (!res.ok) throw new Error(text || res.statusText);
|
||||
}
|
||||
if (!res.ok) throw new Error((data && data.error) || text || res.statusText);
|
||||
return data;
|
||||
}
|
||||
|
||||
// The server shuts down after five minutes without one of these.
|
||||
setInterval(() => {
|
||||
api("/api/heartbeat", { method: "POST" }).catch(() => {});
|
||||
}, 30_000);
|
||||
|
||||
// --- alerts ---
|
||||
|
||||
function alertBox(kind, message, container = "alerts") {
|
||||
const host = document.getElementById(container);
|
||||
host.innerHTML = `<div class="alert ${kind}">${escapeHTML(message)}</div>`;
|
||||
if (kind === "ok") setTimeout(() => (host.innerHTML = ""), 4000);
|
||||
}
|
||||
|
||||
function escapeHTML(s) {
|
||||
return String(s).replace(/[&<>"']/g, (c) =>
|
||||
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]
|
||||
);
|
||||
}
|
||||
|
||||
// --- rendering ---
|
||||
|
||||
function maskOf(prefix) {
|
||||
if (state.settings && state.settings.mask_style === "dotted") {
|
||||
let m = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;
|
||||
return [m >>> 24, (m >>> 16) & 255, (m >>> 8) & 255, m & 255].join(".");
|
||||
}
|
||||
return "/" + prefix;
|
||||
}
|
||||
|
||||
function addrText(a) {
|
||||
return a.address + maskOf(a.prefix).replace(/^(?!\/)/, " ");
|
||||
}
|
||||
|
||||
function renderStats() {
|
||||
const adapters = new Set(state.presets.map((p) => p.adapter));
|
||||
document.getElementById("stats").innerHTML = `
|
||||
<div class="stat-card"><div class="label">Presets</div><div class="value">${state.presets.length}</div></div>
|
||||
<div class="stat-card"><div class="label">Groups</div><div class="value">${state.groups.length}</div></div>
|
||||
<div class="stat-card"><div class="label">Adapters in use</div><div class="value">${adapters.size}</div></div>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderPresets() {
|
||||
const host = document.getElementById("groups");
|
||||
if (!state.presets.length) {
|
||||
host.innerHTML = `<div class="card"><div class="empty">No presets yet. Create one, or import a pack from a colleague.</div></div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const byGroup = new Map();
|
||||
for (const p of state.presets) {
|
||||
const g = p.group && p.group.trim() ? p.group : "Ungrouped";
|
||||
if (!byGroup.has(g)) byGroup.set(g, []);
|
||||
byGroup.get(g).push(p);
|
||||
}
|
||||
|
||||
let html = "";
|
||||
for (const [group, presets] of byGroup) {
|
||||
html += `
|
||||
<div class="group-head">
|
||||
<h2>${escapeHTML(group)}</h2>
|
||||
<span class="pill">${presets.length}</span>
|
||||
</div>
|
||||
<div class="card" style="padding:0">
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr>
|
||||
<th>Name</th><th>Adapter</th><th>Address</th><th>Gateway</th><th>DNS</th><th></th>
|
||||
</tr></thead>
|
||||
<tbody>`;
|
||||
|
||||
for (const p of presets) {
|
||||
const isDHCP = p.mode === "dhcp";
|
||||
const addr = isDHCP
|
||||
? `<span class="badge accent">DHCP</span>`
|
||||
: escapeHTML(addrText(p.primary)) +
|
||||
(p.secondary && p.secondary.length
|
||||
? ` <span class="pill">+${p.secondary.length}</span>`
|
||||
: "");
|
||||
const dns =
|
||||
p.dns.mode === "dhcp"
|
||||
? `<span class="badge">from DHCP</span>`
|
||||
: escapeHTML((p.dns.servers || []).join(", "));
|
||||
|
||||
html += `<tr>
|
||||
<td>${escapeHTML(p.name)}${p.notes ? `<div class="dim">${escapeHTML(p.notes)}</div>` : ""}</td>
|
||||
<td class="mono">${escapeHTML(p.adapter)}</td>
|
||||
<td class="addr">${addr}</td>
|
||||
<td class="addr">${isDHCP ? "" : escapeHTML(p.primary.gateway || "—")}</td>
|
||||
<td class="addr">${dns}</td>
|
||||
<td style="text-align:right; white-space:nowrap">
|
||||
<button class="small" data-edit="${escapeHTML(p.id)}">Edit</button>
|
||||
<button class="small danger" data-del="${escapeHTML(p.id)}">Delete</button>
|
||||
</td>
|
||||
</tr>`;
|
||||
}
|
||||
html += `</tbody></table></div></div>`;
|
||||
}
|
||||
host.innerHTML = html;
|
||||
|
||||
host.querySelectorAll("[data-edit]").forEach((b) =>
|
||||
b.addEventListener("click", () => openEditor(b.dataset.edit))
|
||||
);
|
||||
host.querySelectorAll("[data-del]").forEach((b) =>
|
||||
b.addEventListener("click", () => deletePreset(b.dataset.del))
|
||||
);
|
||||
}
|
||||
|
||||
function renderAdapters() {
|
||||
const body = document.getElementById("adapters");
|
||||
if (!state.adapters.length) {
|
||||
body.innerHTML = `<tr><td colspan="4" class="dim">No adapters found.</td></tr>`;
|
||||
return;
|
||||
}
|
||||
body.innerHTML = state.adapters
|
||||
.map(
|
||||
(a) => `<tr>
|
||||
<td class="mono">${escapeHTML(a.name)}</td>
|
||||
<td class="dim">${escapeHTML(a.description || "")}</td>
|
||||
<td class="addr">${escapeHTML(a.current || "—")}</td>
|
||||
<td>${a.up ? '<span class="badge ok">up</span>' : '<span class="badge">down</span>'}</td>
|
||||
</tr>`
|
||||
)
|
||||
.join("");
|
||||
}
|
||||
|
||||
// --- loading ---
|
||||
|
||||
async function loadAll() {
|
||||
const [presets, adapters, settings] = await Promise.all([
|
||||
api("/api/presets"),
|
||||
api("/api/adapters"),
|
||||
api("/api/settings"),
|
||||
]);
|
||||
state.presets = presets.presets || [];
|
||||
state.groups = presets.groups || [];
|
||||
state.adapters = adapters.adapters || [];
|
||||
state.settings = settings;
|
||||
|
||||
renderStats();
|
||||
renderPresets();
|
||||
renderAdapters();
|
||||
|
||||
document.getElementById("group-list").innerHTML = state.groups
|
||||
.map((g) => `<option value="${escapeHTML(g)}">`)
|
||||
.join("");
|
||||
document.getElementById("f-adapter").innerHTML = state.adapters
|
||||
.map((a) => `<option value="${escapeHTML(a.name)}">${escapeHTML(a.name)}</option>`)
|
||||
.join("");
|
||||
}
|
||||
|
||||
// --- editor ---
|
||||
|
||||
const editor = document.getElementById("editor");
|
||||
|
||||
function secondaryRow(addr = "", prefix = "") {
|
||||
const div = document.createElement("div");
|
||||
div.className = "sec-row";
|
||||
div.innerHTML = `
|
||||
<input class="sec-addr" placeholder="10.0.10.50" value="${escapeHTML(addr)}">
|
||||
<input class="sec-prefix" placeholder="/24" value="${escapeHTML(prefix)}" style="max-width:150px">
|
||||
<button type="button" class="small ghost sec-del">✕</button>`;
|
||||
div.querySelector(".sec-del").addEventListener("click", () => div.remove());
|
||||
return div;
|
||||
}
|
||||
|
||||
function openEditor(id) {
|
||||
const p = id ? state.presets.find((x) => x.id === id) : null;
|
||||
state.editing = p ? p.id : null;
|
||||
|
||||
document.getElementById("editor-title").textContent = p ? "Edit preset" : "New preset";
|
||||
document.getElementById("editor-error").innerHTML = "";
|
||||
document.getElementById("f-name").value = p ? p.name : "";
|
||||
document.getElementById("f-group").value = p ? p.group || "" : "";
|
||||
document.getElementById("f-adapter").value = p ? p.adapter : (state.adapters[0] || {}).name || "";
|
||||
document.getElementById("f-mode").value = p ? p.mode : "static";
|
||||
document.getElementById("f-notes").value = p ? p.notes || "" : "";
|
||||
|
||||
const prim = (p && p.primary) || {};
|
||||
document.getElementById("f-address").value = prim.address || "";
|
||||
document.getElementById("f-prefix").value = prim.prefix !== undefined ? maskOf(prim.prefix) : "";
|
||||
document.getElementById("f-gateway").value = prim.gateway || "";
|
||||
document.getElementById("f-metric").value = prim.gateway_metric || 0;
|
||||
|
||||
const secs = document.getElementById("secondaries");
|
||||
secs.innerHTML = "";
|
||||
for (const s of (p && p.secondary) || []) secs.appendChild(secondaryRow(s.address, maskOf(s.prefix)));
|
||||
|
||||
document.getElementById("f-dns-mode").value = p ? p.dns.mode : "static";
|
||||
document.getElementById("f-dns").value = p ? (p.dns.servers || []).join(", ") : "";
|
||||
|
||||
syncModeVisibility();
|
||||
editor.showModal();
|
||||
}
|
||||
|
||||
function syncModeVisibility() {
|
||||
const isDHCP = document.getElementById("f-mode").value === "dhcp";
|
||||
document.getElementById("static-fields").classList.toggle("hidden", isDHCP);
|
||||
const dnsStatic = document.getElementById("f-dns-mode").value === "static";
|
||||
document.getElementById("dns-servers-field").classList.toggle("hidden", !dnsStatic);
|
||||
}
|
||||
|
||||
document.getElementById("f-mode").addEventListener("change", syncModeVisibility);
|
||||
document.getElementById("f-dns-mode").addEventListener("change", syncModeVisibility);
|
||||
document.getElementById("btn-add-sec").addEventListener("click", () =>
|
||||
document.getElementById("secondaries").appendChild(secondaryRow())
|
||||
);
|
||||
document.getElementById("btn-new").addEventListener("click", () => openEditor(null));
|
||||
document.getElementById("btn-cancel").addEventListener("click", () => editor.close());
|
||||
|
||||
// Masks are parsed here so the editor accepts both spellings, matching the Go
|
||||
// side's ParsePrefix. Anything malformed is reported before the request goes
|
||||
// out rather than coming back as a server-side validation error.
|
||||
function parsePrefix(s) {
|
||||
s = (s || "").trim().replace(/^\//, "");
|
||||
if (!s) throw new Error("mask is required");
|
||||
if (s.includes(".")) {
|
||||
const parts = s.split(".").map(Number);
|
||||
if (parts.length !== 4 || parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) {
|
||||
throw new Error(`"${s}" is not a dotted-quad netmask`);
|
||||
}
|
||||
const m = ((parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]) >>> 0;
|
||||
let ones = 0;
|
||||
while (ones < 32 && m & (1 << (31 - ones))) ones++;
|
||||
if (ones < 32 && (m << ones) >>> 0) throw new Error(`"${s}" is not a contiguous netmask`);
|
||||
return ones;
|
||||
}
|
||||
const n = Number(s);
|
||||
if (!Number.isInteger(n) || n < 0 || n > 32) throw new Error(`"${s}" is not a prefix length`);
|
||||
return n;
|
||||
}
|
||||
|
||||
async function savePreset() {
|
||||
const mode = document.getElementById("f-mode").value;
|
||||
const dnsMode = document.getElementById("f-dns-mode").value;
|
||||
|
||||
let body;
|
||||
try {
|
||||
body = {
|
||||
id: state.editing || "",
|
||||
name: document.getElementById("f-name").value.trim(),
|
||||
group: document.getElementById("f-group").value.trim(),
|
||||
adapter: document.getElementById("f-adapter").value,
|
||||
mode,
|
||||
notes: document.getElementById("f-notes").value.trim(),
|
||||
dns: {
|
||||
mode: dnsMode,
|
||||
servers:
|
||||
dnsMode === "static"
|
||||
? document.getElementById("f-dns").value.split(",").map((s) => s.trim()).filter(Boolean)
|
||||
: undefined,
|
||||
},
|
||||
};
|
||||
|
||||
if (mode === "static") {
|
||||
body.primary = {
|
||||
address: document.getElementById("f-address").value.trim(),
|
||||
prefix: parsePrefix(document.getElementById("f-prefix").value),
|
||||
gateway: document.getElementById("f-gateway").value.trim() || undefined,
|
||||
gateway_metric: Number(document.getElementById("f-metric").value) || undefined,
|
||||
};
|
||||
const secs = [];
|
||||
for (const row of document.querySelectorAll("#secondaries .sec-row")) {
|
||||
const a = row.querySelector(".sec-addr").value.trim();
|
||||
if (!a) continue;
|
||||
secs.push({ address: a, prefix: parsePrefix(row.querySelector(".sec-prefix").value) });
|
||||
}
|
||||
if (secs.length) body.secondary = secs;
|
||||
}
|
||||
} catch (e) {
|
||||
alertBox("danger", e.message, "editor-error");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const path = state.editing ? `/api/presets/${encodeURIComponent(state.editing)}` : "/api/presets";
|
||||
await api(path, { method: state.editing ? "PUT" : "POST", body: JSON.stringify(body) });
|
||||
editor.close();
|
||||
await loadAll();
|
||||
alertBox("ok", "Preset saved.");
|
||||
} catch (e) {
|
||||
alertBox("danger", e.message, "editor-error");
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById("btn-save").addEventListener("click", savePreset);
|
||||
|
||||
async function deletePreset(id) {
|
||||
const p = state.presets.find((x) => x.id === id);
|
||||
if (!confirm(`Delete preset "${p ? p.name : id}"?`)) return;
|
||||
try {
|
||||
await api(`/api/presets/${encodeURIComponent(id)}`, { method: "DELETE" });
|
||||
await loadAll();
|
||||
alertBox("ok", "Preset deleted.");
|
||||
} catch (e) {
|
||||
alertBox("danger", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
// --- settings ---
|
||||
|
||||
const settingsDlg = document.getElementById("settings");
|
||||
|
||||
document.getElementById("btn-settings").addEventListener("click", () => {
|
||||
const s = state.settings || {};
|
||||
document.getElementById("s-mask").value = s.mask_style || "prefix";
|
||||
document.getElementById("s-startup").checked = !!s.start_with_windows;
|
||||
document.getElementById("s-updates").checked = !!s.check_updates;
|
||||
document.getElementById("s-repo").value = s.update_repo || "";
|
||||
settingsDlg.showModal();
|
||||
});
|
||||
|
||||
document.getElementById("btn-settings-cancel").addEventListener("click", () => settingsDlg.close());
|
||||
|
||||
document.getElementById("btn-settings-save").addEventListener("click", async () => {
|
||||
try {
|
||||
await api("/api/settings", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({
|
||||
mask_style: document.getElementById("s-mask").value,
|
||||
start_with_windows: document.getElementById("s-startup").checked,
|
||||
check_updates: document.getElementById("s-updates").checked,
|
||||
update_repo: document.getElementById("s-repo").value.trim(),
|
||||
}),
|
||||
});
|
||||
settingsDlg.close();
|
||||
await loadAll();
|
||||
alertBox("ok", "Settings saved.");
|
||||
} catch (e) {
|
||||
alertBox("danger", e.message);
|
||||
}
|
||||
});
|
||||
|
||||
// --- import / export ---
|
||||
|
||||
document.getElementById("btn-export").addEventListener("click", () => {
|
||||
// A plain navigation, so the browser's own download UI picks the location.
|
||||
location.href = "/api/export";
|
||||
});
|
||||
|
||||
const importDlg = document.getElementById("import");
|
||||
document.getElementById("btn-import").addEventListener("click", () => {
|
||||
document.getElementById("import-error").innerHTML = "";
|
||||
importDlg.showModal();
|
||||
});
|
||||
document.getElementById("btn-import-cancel").addEventListener("click", () => importDlg.close());
|
||||
|
||||
document.getElementById("btn-import-go").addEventListener("click", async () => {
|
||||
const file = document.getElementById("i-file").files[0];
|
||||
if (!file) {
|
||||
alertBox("danger", "Choose a file first.", "import-error");
|
||||
return;
|
||||
}
|
||||
const mode = document.getElementById("i-mode").value;
|
||||
if (mode === "replace" && !confirm("Replace discards every preset you currently have. Continue?")) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await api(`/api/import?mode=${mode}`, { method: "POST", body: await file.text() });
|
||||
importDlg.close();
|
||||
await loadAll();
|
||||
let msg = `Imported ${res.added} preset${res.added === 1 ? "" : "s"}.`;
|
||||
if (res.renamed && res.renamed.length) {
|
||||
msg += ` ${res.renamed.length} had an id collision and were kept alongside the originals.`;
|
||||
}
|
||||
alertBox("ok", msg);
|
||||
} catch (e) {
|
||||
alertBox("danger", e.message, "import-error");
|
||||
}
|
||||
});
|
||||
|
||||
// --- go ---
|
||||
|
||||
loadAll().catch((e) => alertBox("danger", `Could not load: ${e.message}`));
|
||||
@@ -0,0 +1,193 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>ipswap — presets</title>
|
||||
<link rel="stylesheet" href="/app.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<header class="top">
|
||||
<div>
|
||||
<h1>ipswap</h1>
|
||||
<div class="dim">Preset editor · this page closes itself when you stop using it</div>
|
||||
</div>
|
||||
<div class="btn-row">
|
||||
<button id="theme-toggle" class="ghost small">Light</button>
|
||||
<button id="btn-settings" class="ghost small">Settings</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div id="alerts"></div>
|
||||
|
||||
<div class="stat-row" id="stats"></div>
|
||||
|
||||
<div class="card">
|
||||
<div class="btn-row" style="justify-content: space-between;">
|
||||
<h2 style="margin:0">Presets</h2>
|
||||
<div class="btn-row">
|
||||
<button id="btn-import">Import…</button>
|
||||
<button id="btn-export">Export</button>
|
||||
<button id="btn-new" class="primary">New preset</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="groups"></div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Adapters on this machine</h2>
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Name</th><th>Description</th><th>Current IPv4</th><th>State</th></tr>
|
||||
</thead>
|
||||
<tbody id="adapters"><tr><td colspan="4"><span class="spinner"></span></td></tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- preset editor -->
|
||||
<dialog id="editor">
|
||||
<form method="dialog" id="editor-form">
|
||||
<h2 id="editor-title">New preset</h2>
|
||||
<div id="editor-error"></div>
|
||||
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="f-name">Name</label>
|
||||
<input id="f-name" required placeholder="Artist frame — control">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="f-group">Group</label>
|
||||
<input id="f-group" list="group-list" placeholder="Riedel">
|
||||
<datalist id="group-list"></datalist>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="f-adapter">Adapter</label>
|
||||
<select id="f-adapter"></select>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="f-mode">Mode</label>
|
||||
<select id="f-mode">
|
||||
<option value="static">Static</option>
|
||||
<option value="dhcp">DHCP</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="static-fields">
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="f-address">Address</label>
|
||||
<input id="f-address" placeholder="192.168.42.100">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="f-prefix">Mask <span class="dim">(/24 or 255.255.255.0)</span></label>
|
||||
<input id="f-prefix" placeholder="/24">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="f-gateway">Gateway <span class="dim">(optional)</span></label>
|
||||
<input id="f-gateway" placeholder="192.168.42.1">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="f-metric">Gateway metric <span class="dim">(0 = automatic)</span></label>
|
||||
<input id="f-metric" type="number" min="0" value="0">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label>Secondary addresses</label>
|
||||
<div class="sec-list" id="secondaries"></div>
|
||||
<button type="button" id="btn-add-sec" class="small" style="margin-top:8px">Add secondary</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="f-dns-mode">DNS</label>
|
||||
<select id="f-dns-mode">
|
||||
<option value="static">Static</option>
|
||||
<option value="dhcp">From DHCP</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="field" id="dns-servers-field">
|
||||
<label for="f-dns">DNS servers <span class="dim">(comma separated, order matters)</span></label>
|
||||
<input id="f-dns" placeholder="192.168.42.1, 1.1.1.1">
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="f-notes">Notes</label>
|
||||
<input id="f-notes" placeholder="Frame A, rack 3">
|
||||
</div>
|
||||
|
||||
<div class="btn-row" style="justify-content: flex-end; margin-top: 16px;">
|
||||
<button type="button" id="btn-cancel" class="ghost">Cancel</button>
|
||||
<button type="button" id="btn-save" class="primary">Save</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<!-- settings -->
|
||||
<dialog id="settings">
|
||||
<h2>Settings</h2>
|
||||
<div class="field">
|
||||
<label for="s-mask">Mask display</label>
|
||||
<select id="s-mask">
|
||||
<option value="prefix">Prefix (/24)</option>
|
||||
<option value="dotted">Dotted (255.255.255.0)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="field check">
|
||||
<input type="checkbox" id="s-startup">
|
||||
<label for="s-startup">Start ipswap when Windows starts</label>
|
||||
</div>
|
||||
<div class="field check">
|
||||
<input type="checkbox" id="s-updates">
|
||||
<label for="s-updates">Check for updates on startup</label>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="s-repo">Update repository <span class="dim">(https://host/owner/repo — blank disables)</span></label>
|
||||
<input id="s-repo" placeholder="https://gitea.apointless.space/bsncubed/ipswap">
|
||||
</div>
|
||||
<div class="btn-row" style="justify-content: flex-end; margin-top: 16px;">
|
||||
<button type="button" id="btn-settings-cancel" class="ghost">Cancel</button>
|
||||
<button type="button" id="btn-settings-save" class="primary">Save</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- import -->
|
||||
<dialog id="import">
|
||||
<h2>Import presets</h2>
|
||||
<div class="alert info">
|
||||
The file is validated in full before anything is written. If it is rejected, nothing changes.
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="i-file">Preset pack (.json)</label>
|
||||
<input type="file" id="i-file" accept="application/json,.json">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="i-mode">Mode</label>
|
||||
<select id="i-mode">
|
||||
<option value="merge">Merge — keep what I have, add these</option>
|
||||
<option value="replace">Replace — discard my existing presets</option>
|
||||
</select>
|
||||
</div>
|
||||
<div id="import-error"></div>
|
||||
<div class="btn-row" style="justify-content: flex-end; margin-top: 16px;">
|
||||
<button type="button" id="btn-import-cancel" class="ghost">Cancel</button>
|
||||
<button type="button" id="btn-import-go" class="primary">Import</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<script src="/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user