forked from cbuijs/sdproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebui.go
More file actions
843 lines (755 loc) · 26.6 KB
/
webui.go
File metadata and controls
843 lines (755 loc) · 26.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
/*
File: webui.go
Version: 1.4.0
Updated: 2026-03-24 22:00 CET
Description:
Password-protected single-page web admin interface for sdproxy.
Lets you flip per-group override modes at runtime — no restart needed.
Four override modes per group:
DEFAULT — normal operation; schedule + budget apply as configured.
ALLOW — gate wide open; no schedule, no budget, no blocks at all.
FREE — suspend schedule and budget; everything else stays normal.
BLOCK — cut internet; every DNS query from the group is blocked.
Fully responsive layout:
≥640px — standard table with columns for each override mode.
<640px — card-per-group layout; radio buttons become a 2×2 button grid.
Budget/detail panels scroll horizontally rather than overflowing.
Enable in config.yaml:
webui:
listen: "0.0.0.0:8088" # IP:port — default 127.0.0.1:8080
password: "secret" # required; leave empty to keep UI disabled
Session: one active session at a time, 8-hour cookie TTL.
No TLS — intended for LAN admin use only.
Changes:
1.4.0 - [FEAT] Responsive design: card layout on mobile (<640px), compact
table on tablet/desktop. Radio buttons become a 2×2 grid on mobile.
Budget tables wrapped in overflow-x:auto. Meta row uses flex-wrap.
Touch-friendly tap targets (min 44px).
1.3.0 - [FEAT] Live status badge per group/device mirroring CheckParental
priority chain.
1.2.0 - [FEAT] Live budget-remaining table, per-device sub-sections.
1.1.0 - [FEAT] Collapsible detail panel, centred login page.
1.0.0 - Initial implementation.
... Older commit-information removed for brevity.
*/
package main
import (
"crypto/rand"
"encoding/hex"
"fmt"
"log"
"net/http"
"sort"
"strings"
"sync"
"time"
)
// ---------------------------------------------------------------------------
// Group override state
// ---------------------------------------------------------------------------
var (
groupOverride = make(map[string]string)
groupOverrideMu sync.RWMutex
)
// GetGroupOverride returns the current override for a group ("DEFAULT" when
// none set). Called from CheckParental on every DNS query — must be cheap.
func GetGroupOverride(name string) string {
groupOverrideMu.RLock()
v := groupOverride[name]
groupOverrideMu.RUnlock()
if v == "" {
return "DEFAULT"
}
return v
}
// SetGroupOverride sets the runtime override mode for a group.
func SetGroupOverride(name, mode string) {
groupOverrideMu.Lock()
groupOverride[name] = mode
groupOverrideMu.Unlock()
}
// ---------------------------------------------------------------------------
// Session — single active session, 8-hour TTL
// ---------------------------------------------------------------------------
var (
sessMu sync.Mutex
sessToken string
sessExp time.Time
)
func newSession() string {
b := make([]byte, 16)
_, _ = rand.Read(b)
tok := hex.EncodeToString(b)
sessMu.Lock()
sessToken = tok
sessExp = time.Now().Add(8 * time.Hour)
sessMu.Unlock()
return tok
}
func validSession(tok string) bool {
sessMu.Lock()
defer sessMu.Unlock()
return tok != "" && tok == sessToken && time.Now().Before(sessExp)
}
const cookieName = "sdp_sess"
func isAuthed(r *http.Request) bool {
c, err := r.Cookie(cookieName)
return err == nil && validSession(c.Value)
}
// ---------------------------------------------------------------------------
// Startup
// ---------------------------------------------------------------------------
// StartWebUI launches the admin HTTP server.
// No-op when cfg.WebUI.Password is empty.
func StartWebUI() {
if cfg.WebUI.Password == "" {
log.Println("[WEBUI] No password configured — web UI disabled.")
return
}
addr := cfg.WebUI.Listen
if addr == "" {
addr = "127.0.0.1:8080"
}
mux := http.NewServeMux()
mux.HandleFunc("/", handleRoot)
mux.HandleFunc("/login", handleLogin)
mux.HandleFunc("/logout", handleLogout)
mux.HandleFunc("/set", handleSet)
srv := &http.Server{
Addr: addr,
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
IdleTimeout: 30 * time.Second,
MaxHeaderBytes: 4096,
}
go func() {
log.Printf("[WEBUI] Admin UI at http://%s", addr)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Printf("[WEBUI] Server error: %v", err)
}
}()
}
// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------
func handleRoot(w http.ResponseWriter, r *http.Request) {
if !isAuthed(r) {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
names := make([]string, 0, len(cfg.Groups))
for n := range cfg.Groups {
names = append(names, n)
}
sort.Strings(names)
macCount := make(map[string]int, len(cfg.Groups))
for _, route := range cfg.Routes {
if route.Group != "" {
macCount[route.Group]++
}
}
// ── Desktop table rows ──────────────────────────────────────────────────
var tableRows strings.Builder
// ── Mobile cards ────────────────────────────────────────────────────────
var mobileCards strings.Builder
if len(names) == 0 {
tableRows.WriteString(`<tr><td colspan="5" class="empty">` +
`No groups configured in config.yaml.</td></tr>`)
mobileCards.WriteString(`<div class="empty">` +
`No groups configured in config.yaml.</div>`)
}
for _, name := range names {
grp := cfg.Groups[name]
cur := GetGroupOverride(name)
detail := buildGroupDetail(name, grp, macCount[name])
// Desktop: one <tr> with four radio columns.
var radios strings.Builder
for _, mode := range []string{"DEFAULT", "ALLOW", "FREE", "BLOCK"} {
chk := ""
if cur == mode {
chk = " checked"
}
radios.WriteString(
`<td><label class="mode-` + strings.ToLower(mode) + `">` +
`<input type="radio" name="` + esc(name) +
`" value="` + mode + `"` + chk + `> ` + mode +
`</label></td>`)
}
tableRows.WriteString(
`<tr class="group-row">` +
`<td class="name-cell">` +
`<details><summary class="group-name">` + esc(name) + `</summary>` +
detail + `</details>` +
`</td>` + radios.String() + `</tr>`)
// Mobile: one card with a 2×2 radio grid.
mobileCards.WriteString(buildMobileCard(name, cur, grp, macCount[name], detail))
}
body := `<div class="header">` +
`<h2>sdproxy <span class="sub">group overrides</span></h2>` +
`<a href="/logout" class="logout">logout</a>` +
`</div>` +
// Desktop table (hidden on small screens via CSS).
`<form method="post" action="/set" id="desk-form">` +
`<div class="table-wrap">` +
`<table>` +
`<thead><tr>` +
`<th>Group <span class="th-hint">(click to expand)</span></th>` +
`<th>DEFAULT</th><th>ALLOW</th><th>FREE</th><th>BLOCK</th>` +
`</tr></thead>` +
`<tbody>` + tableRows.String() + `</tbody>` +
`</table></div>` +
`<div class="actions">` +
`<button type="submit">Apply changes</button>` +
`<span class="legend">` +
`<b>DEFAULT</b> normal · ` +
`<b class="c-allow">ALLOW</b> open gate · ` +
`<b class="c-free">FREE</b> no schedule/budget · ` +
`<b class="c-block">BLOCK</b> cut internet` +
`</span></div>` +
`</form>` +
// Mobile card stack (hidden on large screens via CSS).
`<form method="post" action="/set" id="mob-form">` +
`<div class="cards">` + mobileCards.String() + `</div>` +
`<div class="actions">` +
`<button type="submit">Apply changes</button>` +
`</div>` +
`</form>`
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(mainPage("sdproxy — group overrides", body)))
}
// buildMobileCard renders a full-width card for one group on narrow screens.
func buildMobileCard(name, cur string, grp GroupConfig, macs int, detail string) string {
var b strings.Builder
b.WriteString(`<div class="card">`)
// Card header: group name + status badge.
isDeviceTracking := strings.ToLower(grp.BudgetTracking) == "device"
sk := ""
if !isDeviceTracking {
sk = name
}
status := computeStatus(name, sk, grp)
b.WriteString(`<div class="card-header">` +
`<span class="card-name">` + esc(name) + `</span>` +
renderBadge(status) +
`</div>`)
// 2×2 radio grid.
b.WriteString(`<div class="radio-grid">`)
for _, mode := range []string{"DEFAULT", "ALLOW", "FREE", "BLOCK"} {
chk := ""
if cur == mode {
chk = " checked"
}
b.WriteString(
`<label class="radio-btn mode-` + strings.ToLower(mode) + `">` +
`<input type="radio" name="` + esc(name) +
`" value="` + mode + `"` + chk + `> ` + mode +
`</label>`)
}
b.WriteString(`</div>`)
// Collapsible detail.
b.WriteString(`<details><summary class="detail-toggle">Details</summary>` +
detail + `</details>`)
b.WriteString(`</div>`) // .card
return b.String()
}
func handleLogin(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
_ = r.ParseForm()
if r.FormValue("pw") == cfg.WebUI.Password {
tok := newSession()
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Value: tok,
Path: "/",
MaxAge: 8 * 3600,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(loginPage(`<p class="err">Wrong password.</p>`)))
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(loginPage("")))
}
func handleLogout(w http.ResponseWriter, r *http.Request) {
sessMu.Lock()
sessToken = ""
sessMu.Unlock()
http.SetCookie(w, &http.Cookie{Name: cookieName, Value: "", MaxAge: -1, Path: "/"})
http.Redirect(w, r, "/login", http.StatusSeeOther)
}
func handleSet(w http.ResponseWriter, r *http.Request) {
if !isAuthed(r) {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
if r.Method == http.MethodPost {
if err := r.ParseForm(); err == nil {
for name := range cfg.Groups {
mode := strings.ToUpper(r.FormValue(name))
switch mode {
case "DEFAULT", "ALLOW", "FREE", "BLOCK":
old := GetGroupOverride(name)
if old != mode {
SetGroupOverride(name, mode)
log.Printf("[WEBUI] Group %q override: %s → %s", name, old, mode)
}
}
}
}
}
http.Redirect(w, r, "/", http.StatusSeeOther)
}
// ---------------------------------------------------------------------------
// Status computation
// ---------------------------------------------------------------------------
type statusResult struct {
text string
cls string
}
// computeStatus derives the current effective status for a group/device.
// Mirrors the CheckParental priority chain: override → schedule → budget.
// Pass sk="" to skip the budget check (device-tracking meta rows).
func computeStatus(groupName, sk string, grp GroupConfig) statusResult {
switch GetGroupOverride(groupName) {
case "ALLOW":
return statusResult{"Override: ALLOW — gate open", "st-allow"}
case "BLOCK":
return statusResult{"Override: BLOCK — internet cut", "st-block"}
case "FREE":
return statusResult{"Override: FREE — schedule & budget suspended", "st-free"}
}
if len(grp.Schedule) > 0 && !inAnyScheduleWindow(grp.Schedule) {
return statusResult{"Blocked: outside schedule", "st-block"}
}
if sk == "" {
return statusResult{"Schedule: active", "st-ok"}
}
return budgetStatus(sk)
}
// budgetStatus reads the live groupState for sk and returns the first
// blocking condition or "Allowed".
func budgetStatus(sk string) statusResult {
if groupStates == nil {
return statusResult{"Allowed", "st-ok"}
}
gs, ok := groupStates[sk]
if !ok {
return statusResult{"No data yet", "st-muted"}
}
gs.mu.Lock()
defer gs.mu.Unlock()
if gs.hardBlocked["total"] {
return statusResult{"Blocked: total (config)", "st-block"}
}
if rem, limited := gs.remaining["total"]; limited && rem <= 0 {
return statusResult{"Blocked: total budget exhausted", "st-block"}
}
// Collect and deduplicate category keys.
seen := make(map[string]bool)
var cats []string
for c := range gs.remaining {
if c != "total" && !seen[c] {
seen[c] = true
cats = append(cats, c)
}
}
for c := range gs.hardBlocked {
if c != "total" && !seen[c] {
seen[c] = true
cats = append(cats, c)
}
}
sort.Strings(cats)
for _, cat := range cats {
if gs.hardBlocked[cat] {
return statusResult{fmt.Sprintf("Blocked: %s (config)", esc(cat)), "st-block"}
}
if rem, ok := gs.remaining[cat]; ok && rem <= 0 {
return statusResult{fmt.Sprintf("Blocked: %s budget exhausted", esc(cat)), "st-block"}
}
}
return statusResult{"Allowed", "st-ok"}
}
func renderBadge(sr statusResult) string {
if sr.text == "" {
return ""
}
return `<span class="sbadge ` + sr.cls + `">` + sr.text + `</span>`
}
// ---------------------------------------------------------------------------
// Detail panel
// ---------------------------------------------------------------------------
func buildGroupDetail(name string, grp GroupConfig, macs int) string {
var b strings.Builder
b.WriteString(`<div class="detail">`)
isDeviceTracking := strings.ToLower(grp.BudgetTracking) == "device"
sk := ""
if !isDeviceTracking {
sk = name
}
status := computeStatus(name, sk, grp)
upstream := grp.Upstream
if upstream == "" {
upstream = `<span class="muted">inherited</span>`
} else {
upstream = esc(upstream)
}
tracking := grp.BudgetTracking
if tracking == "" {
tracking = "group"
}
b.WriteString(`<div class="meta">`)
b.WriteString(`<span>Upstream: <b>` + upstream + `</b></span>`)
b.WriteString(`<span>Tracking: <b>` + esc(tracking) + `</b></span>`)
b.WriteString(fmt.Sprintf(`<span>Devices: <b>%d</b></span>`, macs))
b.WriteString(`<span>` + renderBadge(status) + `</span>`)
b.WriteString(`</div>`)
b.WriteString(`<div class="section-label">Schedule</div>`)
if len(grp.Schedule) > 0 {
b.WriteString(`<div class="pills">`)
for _, s := range grp.Schedule {
b.WriteString(`<span class="pill pill-sched">` + esc(s) + `</span>`)
}
b.WriteString(`</div>`)
} else {
b.WriteString(`<div class="muted-line">no schedule — always allowed</div>`)
}
b.WriteString(`<div class="section-label">Budget</div>`)
if len(grp.Budget) == 0 {
b.WriteString(`<div class="muted-line">no budget configured</div>`)
} else if isDeviceTracking {
b.WriteString(buildDeviceBudgetSection(name, grp))
} else {
rows := readBudgetRows(name, grp)
b.WriteString(`<div class="btable-wrap">` + renderBudgetTable(rows) + `</div>`)
}
b.WriteString(`</div>`)
return b.String()
}
func buildDeviceBudgetSection(groupName string, grp GroupConfig) string {
type devEntry struct {
sk string
label string
}
var devs []devEntry
if groupStates != nil {
for sk, gn := range stateToGroup {
if gn != groupName {
continue
}
mac := ""
if idx := strings.IndexByte(sk, '/'); idx >= 0 {
mac = sk[idx+1:]
}
label := LookupNameByMACOrIP(mac, "")
if label == "" {
if mac != "" {
label = mac
} else {
label = sk
}
}
devs = append(devs, devEntry{sk: sk, label: label})
}
}
if len(devs) == 0 {
return `<div class="muted-line">no devices active yet</div>`
}
sort.Slice(devs, func(i, j int) bool { return devs[i].label < devs[j].label })
var b strings.Builder
for _, d := range devs {
devStatus := computeStatus(groupName, d.sk, grp)
b.WriteString(`<div class="dev-section">`)
b.WriteString(`<div class="dev-label">` +
esc(d.label) + ` ` + renderBadge(devStatus) +
`</div>`)
rows := readBudgetRows(d.sk, grp)
b.WriteString(`<div class="btable-wrap">` + renderBudgetTable(rows) + `</div>`)
b.WriteString(`</div>`)
}
return b.String()
}
// ---------------------------------------------------------------------------
// Budget state helpers
// ---------------------------------------------------------------------------
type budgetRow struct {
key string
configured string
remaining string
isAllow bool
isBlock bool
exhausted bool
}
func readBudgetRows(sk string, grp GroupConfig) []budgetRow {
keys := make([]string, 0, len(grp.Budget))
for k := range grp.Budget {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
if keys[i] == "total" {
return true
}
if keys[j] == "total" {
return false
}
return keys[i] < keys[j]
})
var liveRemaining map[string]int64
if groupStates != nil {
if gs, ok := groupStates[sk]; ok {
gs.mu.Lock()
liveRemaining = make(map[string]int64, len(gs.remaining))
for k, v := range gs.remaining {
liveRemaining[k] = v
}
gs.mu.Unlock()
}
}
rows := make([]budgetRow, 0, len(keys))
for _, k := range keys {
v := grp.Budget[k]
row := budgetRow{key: k, configured: v}
switch strings.ToUpper(v) {
case "ALLOW":
row.isAllow = true
row.remaining = "—"
case "BLOCK":
row.isBlock = true
row.remaining = "—"
default:
if liveRemaining != nil {
if rem, ok := liveRemaining[k]; ok {
if rem <= 0 {
row.exhausted = true
row.remaining = "exhausted"
} else {
row.remaining = fmtSeconds(rem)
}
} else {
row.remaining = "—"
}
} else {
row.remaining = "—"
}
}
rows = append(rows, row)
}
return rows
}
func renderBudgetTable(rows []budgetRow) string {
if len(rows) == 0 {
return `<div class="muted-line">no budget entries</div>`
}
var b strings.Builder
b.WriteString(`<table class="btable"><thead><tr>` +
`<th>Category</th><th>Limit</th><th>Remaining</th>` +
`</tr></thead><tbody>`)
for _, r := range rows {
remCls, cfgCls := "", ""
switch {
case r.exhausted:
remCls = ` class="rem-exhausted"`
case r.isAllow:
remCls = ` class="rem-allow"`
case r.isBlock:
remCls = ` class="rem-block"`
}
switch {
case r.isAllow:
cfgCls = ` class="cfg-allow"`
case r.isBlock:
cfgCls = ` class="cfg-block"`
}
b.WriteString(`<tr>`)
b.WriteString(`<td class="bkey">` + esc(r.key) + `</td>`)
b.WriteString(`<td` + cfgCls + `>` + esc(r.configured) + `</td>`)
b.WriteString(`<td` + remCls + `>` + r.remaining + `</td>`)
b.WriteString(`</tr>`)
}
b.WriteString(`</tbody></table>`)
return b.String()
}
// ---------------------------------------------------------------------------
// HTML helpers
// ---------------------------------------------------------------------------
func esc(s string) string {
s = strings.ReplaceAll(s, "&", "&")
s = strings.ReplaceAll(s, "<", "<")
s = strings.ReplaceAll(s, ">", ">")
s = strings.ReplaceAll(s, `"`, """)
return s
}
const css = `
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:system-ui,sans-serif;font-size:15px;color:#111;
background:#f5f6f8;min-height:100vh}
/* ── login ── */
.login-wrap{min-height:100vh;display:flex;align-items:center;justify-content:center;
padding:16px}
.login-box{background:#fff;border:1px solid #e2e4e9;border-radius:10px;
padding:32px 28px;width:100%;max-width:320px;
box-shadow:0 2px 10px rgba(0,0,0,.07)}
.login-box h2{margin-bottom:20px;font-size:1.15em;color:#374151}
.login-box label{display:block;font-size:.85em;color:#6b7280;margin-bottom:5px}
.login-box input[type=password]{width:100%;padding:10px 12px;
border:1px solid #d1d5db;border-radius:6px;font-size:15px;outline:none;
-webkit-appearance:none}
.login-box input[type=password]:focus{border-color:#6366f1;
box-shadow:0 0 0 3px rgba(99,102,241,.15)}
.login-box button{width:100%;margin-top:16px;padding:11px;background:#4f46e5;
color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:15px;
font-weight:500;-webkit-appearance:none}
.login-box button:active{background:#4338ca}
.err{color:#b91c1c;font-size:.85em;margin-top:10px}
/* ── main layout ── */
.wrap{max-width:860px;margin:0 auto;padding:20px 12px}
.header{display:flex;align-items:center;justify-content:space-between;
margin-bottom:18px;gap:8px}
.header h2{font-size:1.1em;font-weight:700;white-space:nowrap}
.sub{font-weight:400;color:#6b7280;font-size:.88em;margin-left:5px}
.logout{font-size:.82em;color:#9ca3af;text-decoration:none;white-space:nowrap}
.logout:active{color:#4f46e5}
/* ── actions ── */
.actions{display:flex;align-items:center;gap:14px;margin-top:14px;flex-wrap:wrap}
button[type=submit]{padding:10px 22px;background:#4f46e5;color:#fff;border:none;
border-radius:6px;cursor:pointer;font-size:.92em;font-weight:500;
min-height:44px;-webkit-appearance:none}
button[type=submit]:active{background:#4338ca}
.legend{font-size:.78em;color:#6b7280;line-height:1.6}
.legend b{font-weight:600;color:#374151}
.c-allow{color:#15803d}
.c-free{color:#2563eb}
.c-block{color:#b91c1c}
/* ── status badges ── */
.sbadge{display:inline-block;padding:2px 9px;border-radius:99px;
font-size:.78em;font-weight:600;white-space:nowrap;line-height:1.6}
.st-ok {background:#f0fdf4;color:#15803d}
.st-block {background:#fef2f2;color:#b91c1c}
.st-allow {background:#f0fdf4;color:#15803d}
.st-free {background:#eff6ff;color:#2563eb}
.st-muted {background:#f3f4f6;color:#9ca3af}
/* ── detail panel (shared desktop + mobile) ── */
.detail{margin-top:10px;padding:10px 12px;background:#f9fafb;
border:1px solid #e9eaec;border-radius:7px;font-size:.82em;line-height:1.6}
.meta{display:flex;flex-wrap:wrap;align-items:center;gap:10px 16px;
color:#374151;margin-bottom:8px}
.meta b{color:#111}
.section-label{font-size:.72em;font-weight:700;text-transform:uppercase;
letter-spacing:.05em;color:#9ca3af;margin-top:8px;margin-bottom:4px}
.muted-line{color:#9ca3af;font-style:italic;margin-bottom:2px}
.muted{color:#9ca3af}
.pills{display:flex;flex-wrap:wrap;gap:5px;margin-bottom:2px}
.pill{padding:2px 9px;border-radius:99px;font-size:.8em;font-weight:500}
.pill-sched{background:#eff6ff;color:#2563eb}
.btable-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch;margin-top:2px}
.btable{width:100%;border-collapse:collapse;font-size:.88em;min-width:220px}
.btable thead th{background:#f0f1f3;padding:5px 8px;font-weight:600;
color:#6b7280;text-align:left;font-size:.8em;border-bottom:1px solid #e5e7eb;
white-space:nowrap}
.btable tbody td{padding:5px 8px;border-bottom:1px solid #f3f4f6;color:#374151}
.btable tbody tr:last-child td{border-bottom:none}
.bkey{font-weight:500;color:#111}
.cfg-allow{color:#15803d;font-weight:600}
.cfg-block{color:#b91c1c;font-weight:600}
.rem-exhausted{color:#b91c1c;font-weight:600}
.rem-allow{color:#15803d}
.rem-block{color:#b91c1c}
.dev-section{margin-bottom:10px}
.dev-section:last-child{margin-bottom:0}
.dev-label{display:flex;align-items:center;flex-wrap:wrap;gap:6px;
font-weight:600;color:#374151;padding-bottom:4px;margin-bottom:4px;
border-bottom:1px solid #e9eaec;font-size:.85em}
/* ══════════════════════════════════════════
DESKTOP (≥640px): table layout, hide cards
══════════════════════════════════════════ */
.cards{display:none}
#mob-form{display:none}
.table-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch;
border-radius:8px;border:1px solid #e2e4e9}
table{width:100%;border-collapse:collapse;background:#fff}
thead th{background:#f3f4f6;padding:9px 14px;text-align:left;
font-size:.82em;font-weight:600;color:#374151;
border-bottom:1px solid #e2e4e9;white-space:nowrap}
.th-hint{font-weight:400;color:#9ca3af}
tbody tr.group-row td{border-bottom:1px solid #f0f1f3;vertical-align:top}
tbody tr.group-row:last-child td{border-bottom:none}
td{padding:10px 14px}
td:not(:first-child){white-space:nowrap;padding-top:13px}
.name-cell{min-width:150px}
details summary{cursor:pointer;list-style:none;user-select:none}
details summary::-webkit-details-marker{display:none}
.group-name{font-weight:600;font-size:.95em;display:inline-flex;
align-items:center;gap:5px}
.group-name::after{content:"▸";font-size:.7em;color:#9ca3af;
transition:transform .15s}
details[open] .group-name::after{transform:rotate(90deg)}
label{cursor:pointer}
input[type=radio]{margin-right:3px;cursor:pointer;accent-color:#4f46e5}
.mode-block{color:#b91c1c}
.mode-allow{color:#15803d}
.mode-free{color:#2563eb}
.empty{color:#9ca3af;font-style:italic;padding:16px 14px}
/* ══════════════════════════════════════════
MOBILE (<640px): card layout, hide table
══════════════════════════════════════════ */
@media(max-width:639px){
body{font-size:15px}
.wrap{padding:14px 10px}
/* hide desktop form, show mobile form */
#desk-form{display:none}
#mob-form{display:block}
.cards{display:flex;flex-direction:column;gap:10px}
.card{background:#fff;border:1px solid #e2e4e9;border-radius:10px;
overflow:hidden}
.card-header{display:flex;align-items:center;justify-content:space-between;
flex-wrap:wrap;gap:6px;padding:12px 14px 8px;
border-bottom:1px solid #f0f1f3}
.card-name{font-weight:700;font-size:1em}
/* 2×2 radio grid — big tap targets */
.radio-grid{display:grid;grid-template-columns:1fr 1fr;gap:1px;
background:#e9eaec;border-bottom:1px solid #e9eaec}
.radio-btn{display:flex;align-items:center;justify-content:center;
gap:6px;padding:12px 8px;background:#fff;font-size:.9em;
font-weight:500;cursor:pointer;user-select:none;
-webkit-tap-highlight-color:transparent}
.radio-btn input[type=radio]{accent-color:#4f46e5;width:16px;height:16px}
.radio-btn:active{background:#f5f6f8}
/* details toggle inside card */
.detail-toggle{display:block;padding:10px 14px;font-size:.85em;
color:#6b7280;cursor:pointer;list-style:none;user-select:none;
border-top:1px solid #f0f1f3}
.detail-toggle::-webkit-details-marker{display:none}
.detail-toggle::before{content:"▸ ";font-size:.75em}
details[open] .detail-toggle::before{content:"▾ "}
.detail{margin:0;border-radius:0;border:none;
border-top:1px solid #e9eaec}
}
`
func page(title, body string) string {
return `<!doctype html><html lang="en"><head><meta charset="utf-8">` +
`<meta name="viewport" content="width=device-width,initial-scale=1">` +
`<title>` + esc(title) + `</title>` +
`<style>` + css + `</style></head><body>` +
body + `</body></html>`
}
func mainPage(title, content string) string {
return page(title, `<div class="wrap">`+content+`</div>`)
}
func loginPage(extra string) string {
body := `<div class="login-wrap"><div class="login-box">` +
`<h2>sdproxy</h2>` +
`<form method="post" action="/login">` +
`<label>Password</label>` +
`<input type="password" name="pw" autocomplete="current-password" autofocus>` +
extra +
`<button type="submit">Login</button>` +
`</form>` +
`</div></div>`
return page("sdproxy login", body)
}