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 = capRemark(sanitizeRemark(e.Note)) 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 = sanitizeRemark(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 } // sanitizeRemark 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. func sanitizeRemark(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) } // capRemark truncates s to MaxRemarkRunes runes. Used on values read back // from disk, where an older/hand-edited file may exceed the current limit. func capRemark(s string) string { if utf8.RuneCountInString(s) <= MaxRemarkRunes { return s } return string([]rune(s)[:MaxRemarkRunes]) } // 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 }