Files
yuanyuanxianganddeepseek-flash 034b11fa6a Feature: let the web console move a host to another group
The Go server now keeps a per-device group override (device_groups.json)
edited from the card's "..." menu below Edit remark. The override wins
over the group the host reported (or the offline history record) in the
device list, the group filter, get_groups and the MCP host tools, so
offline records can be regrouped and the change survives restarts. An
empty value clears the override; names are capped at 23 characters,
matching the Win32 regroup dialog.

The command is admin-only and honours the device ACL; it refuses IDs the
server has never seen (online or in history) so a stale card cannot
create an orphan entry, and the remark handler gets the same guard. Each
change is audited as admin.device.group, deleting a device drops its
override, and values loaded from disk are trimmed and capped like
remarks. The menu entry is gated on the groupEdit capability, so the
shared page hides it on the MFC server.

Like remarks, the override is a Go-side label: no CMD_SET_GROUP is sent,
so the host keeps reporting its own group to other masters. Verified
with go test ./..., go vet, gofmt and a node --check pass on the page.

Co-Authored-By: deepseek-flash
2026-11-27 15:15:27 +01:00

276 lines
7.9 KiB
Go

package web
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
)
// MaxRemarkRunes bounds the per-device remark. The card renders it next to
// the computer name ("host (remark)"), so this is a label, not a note field:
// long enough for "Reception PC - 3rd floor", short enough to keep the card
// intact.
const MaxRemarkRunes = 64
// deviceNotesFileVersion is the on-disk format we write. A file from a newer
// version is refused instead of being read as v1 and overwritten.
const deviceNotesFileVersion = 1
// DeviceNoteEntry is one device remark.
type DeviceNoteEntry struct {
Note string `json:"note"`
UpdatedAt time.Time `json:"updated_at"`
UpdatedBy string `json:"updated_by,omitempty"`
}
// deviceNotesFile is the on-disk shape of device_notes.json. Version is
// reserved for future migrations; v1 is a flat deviceID -> remark map.
type deviceNotesFile struct {
Version int `json:"version"`
Devices map[string]DeviceNoteEntry `json:"devices"`
}
// DeviceNotes is the per-device remark table used by the web console. Remarks
// are labels, not access control, so the table is independent of DeviceACL: a
// device can carry a remark whether or not it is bound to an owner. An empty
// Path disables persistence (tests).
type DeviceNotes struct {
mu sync.RWMutex
path string
entries map[string]DeviceNoteEntry
// loadErr records why Load failed. While set, Set/Remove refuse to write:
// persisting the in-memory (empty) table would replace the unreadable file
// and destroy every remark it still holds.
loadErr error
}
// NewDeviceNotes returns an empty table backed by path.
func NewDeviceNotes(path string) *DeviceNotes {
return &DeviceNotes{path: path, entries: make(map[string]DeviceNoteEntry)}
}
// Load reads Path into memory. A missing file is an empty table. A malformed
// file (or one written by a newer version) is returned as an error and leaves
// the table write-disabled: the caller may log and continue serving, but the
// unreadable file must survive so its remarks can be recovered.
func (n *DeviceNotes) Load() error {
if n.path == "" {
return nil
}
data, err := os.ReadFile(n.path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return n.failLoad(fmt.Errorf("read %s: %w", n.path, err))
}
var f deviceNotesFile
if err := json.Unmarshal(data, &f); err != nil {
return n.failLoad(fmt.Errorf("parse %s: %w", n.path, err))
}
if f.Version > deviceNotesFileVersion {
return n.failLoad(fmt.Errorf("unsupported %s version %d (this server writes %d)",
n.path, f.Version, deviceNotesFileVersion))
}
entries := make(map[string]DeviceNoteEntry, len(f.Devices))
for id, e := range f.Devices {
id = strings.TrimSpace(id)
// Apply the same invariants Set enforces: a hand-edited or restored
// file must not put a multi-line / over-long label on a card.
e.Note = capRunes(sanitizeLabel(e.Note), MaxRemarkRunes)
if id == "" || e.Note == "" {
continue
}
entries[id] = e
}
n.mu.Lock()
n.entries = entries
n.loadErr = nil
n.mu.Unlock()
return nil
}
// failLoad records the reason writes are disabled and returns it.
func (n *DeviceNotes) failLoad(err error) error {
n.mu.Lock()
n.loadErr = err
n.mu.Unlock()
return err
}
// Note returns the remark of deviceID, or "" when it has none.
func (n *DeviceNotes) Note(deviceID string) string {
if n == nil {
return ""
}
n.mu.RLock()
defer n.mu.RUnlock()
return n.entries[deviceID].Note
}
// Notes returns a copy of the deviceID -> remark map. Callers that look up
// many devices in one pass (MCP host listings) take this snapshot instead of a
// read lock per device, so a save's fsync cannot stall the whole listing.
func (n *DeviceNotes) Notes() map[string]string {
if n == nil {
return map[string]string{}
}
n.mu.RLock()
defer n.mu.RUnlock()
out := make(map[string]string, len(n.entries))
for id, e := range n.entries {
out[id] = e.Note
}
return out
}
// Snapshot returns a copy of the table (for logs and tests).
func (n *DeviceNotes) Snapshot() map[string]DeviceNoteEntry {
if n == nil {
return map[string]DeviceNoteEntry{}
}
n.mu.RLock()
defer n.mu.RUnlock()
out := make(map[string]DeviceNoteEntry, len(n.entries))
for id, e := range n.entries {
out[id] = e
}
return out
}
// Set stores note for deviceID. An empty note clears the remark. Control
// characters (line breaks etc.) are folded to spaces and the result is
// trimmed; more than MaxRemarkRunes runes is rejected. On persistence failure
// the in-memory table is rolled back so it never claims a remark that would
// not survive a restart.
func (n *DeviceNotes) Set(deviceID, note, actor string) error {
deviceID = strings.TrimSpace(deviceID)
if deviceID == "" {
return fmt.Errorf("empty device id")
}
note = sanitizeLabel(note)
if utf8.RuneCountInString(note) > MaxRemarkRunes {
return fmt.Errorf("remark is too long (max %d characters)", MaxRemarkRunes)
}
n.mu.Lock()
defer n.mu.Unlock()
if n.loadErr != nil {
return fmt.Errorf("device remarks unavailable: %w", n.loadErr)
}
prev, had := n.entries[deviceID]
if note == "" {
if !had {
return nil
}
delete(n.entries, deviceID)
} else {
n.entries[deviceID] = DeviceNoteEntry{Note: note, UpdatedAt: time.Now().UTC(), UpdatedBy: actor}
}
if err := n.saveLocked(); err != nil {
if had {
n.entries[deviceID] = prev
} else {
delete(n.entries, deviceID)
}
return err
}
return nil
}
// Remove drops the remark of one device (idempotent). Called when the device
// record is deleted so a future client reusing the same ID cannot inherit the
// label.
func (n *DeviceNotes) Remove(deviceID string) error {
if n == nil {
return nil
}
deviceID = strings.TrimSpace(deviceID)
if deviceID == "" {
return nil
}
n.mu.Lock()
defer n.mu.Unlock()
if n.loadErr != nil {
return fmt.Errorf("device remarks unavailable: %w", n.loadErr)
}
prev, ok := n.entries[deviceID]
if !ok {
return nil
}
delete(n.entries, deviceID)
if err := n.saveLocked(); err != nil {
n.entries[deviceID] = prev
return err
}
return nil
}
// sanitizeLabel folds line breaks and other control characters (including
// bidi/zero-width formatting runes, which could reorder the card title) to
// spaces so the label always renders on one line, then trims both ends.
// Shared by the per-device remark and group tables.
func sanitizeLabel(s string) string {
s = strings.Map(func(r rune) rune {
if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) {
return ' '
}
return r
}, s)
return strings.TrimSpace(s)
}
// capRunes truncates s to max runes. Used on values read back from disk, where
// an older/hand-edited file may exceed the current limit. Trims again after the
// cut so the stored label cannot end in an invisible space.
func capRunes(s string, max int) string {
if utf8.RuneCountInString(s) <= max {
return s
}
return strings.TrimSpace(string([]rune(s)[:max]))
}
// saveLocked writes the table via a temp file + rename. Caller holds n.mu.
func (n *DeviceNotes) saveLocked() error {
if n.path == "" {
return nil
}
f := deviceNotesFile{Version: 1, Devices: n.entries}
data, err := json.MarshalIndent(f, "", " ")
if err != nil {
return fmt.Errorf("encode device notes: %w", err)
}
dir := filepath.Dir(n.path)
if dir == "" {
dir = "."
}
tmp, err := os.CreateTemp(dir, ".device_notes-*.tmp")
if err != nil {
return fmt.Errorf("create temp notes: %w", err)
}
tmpName := tmp.Name()
defer func() { _ = os.Remove(tmpName) }() // no-op after a successful rename
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return fmt.Errorf("write temp notes: %w", err)
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
return fmt.Errorf("sync temp notes: %w", err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("close temp notes: %w", err)
}
if err := os.Rename(tmpName, n.path); err != nil {
return fmt.Errorf("rename notes: %w", err)
}
return nil
}