Feature: edit device remarks from the web console
The Go web console now stores a per-device remark and renders it as "hostname (remark)" on the card, the label displayName already supported. The card's "..." menu gets an Edit remark entry directly below Terminal; it opens a small dialog, and an empty value clears the label. Remarks live in device_notes.json next to users.json, independent of the device history and ACL, so offline records carry them too. The WebSocket command set_device_remark is admin-only and honors the device ACL (a private device of another owner is refused). Updates are audited as admin.device.remark and broadcast as devices_changed so every open console refreshes. Deleting a device drops its remark. The device_list reply reports remarkEdit only when a notes table is wired, so the shared page hides the entry on the MFC server, which does not implement it. A malformed or newer-version device_notes.json disables writes instead of letting the first save overwrite labels it could not parse; loaded values are re-sanitized and capped. Verified with go test ./..., vet, gofmt, and a node --check pass on the inline script. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
1bd7fa5b2d
commit
95d2bbc1b6
9 files changed
+741
-7
No files matched your search
@@ -1188,6 +1188,22 @@ func main() {
|
||||
}
|
||||
log.Info("Device ACL loaded from %s (%d binding(s))", aclFile, len(deviceACL.Snapshot()))
|
||||
|
||||
// Per-device remarks (the web card's "hostname (remark)" label) live next
|
||||
// to the ACL. A malformed file only loses labels — it carries no access
|
||||
// rights — so the server still starts; the store then refuses every edit
|
||||
// so the unreadable file is never overwritten.
|
||||
notesFile := os.Getenv("YAMA_DEVICE_NOTES_FILE")
|
||||
if notesFile == "" {
|
||||
notesFile = filepath.Join(filepath.Dir(usersFile), "device_notes.json")
|
||||
rememberDefault("YAMA_DEVICE_NOTES_FILE", notesFile)
|
||||
}
|
||||
deviceNotes := web.NewDeviceNotes(notesFile)
|
||||
if err := deviceNotes.Load(); err != nil {
|
||||
log.Warn("Failed to load device remarks from %s: %v (remark edits are refused until the file is fixed)", notesFile, err)
|
||||
} else {
|
||||
log.Info("Device remarks loaded from %s (%d remark(s))", notesFile, len(deviceNotes.Snapshot()))
|
||||
}
|
||||
|
||||
// TCP authorization (TOKEN_AUTH) brute-force throttle. Keyed by source IP
|
||||
// (the real TCP peer — there is no X-Forwarded-For on the device port).
|
||||
// Generous enough that a NAT office whose devices all re-auth at once is
|
||||
@@ -1416,6 +1432,7 @@ func main() {
|
||||
BrandName: brandName,
|
||||
SSO: ssoDetector,
|
||||
DeviceACL: deviceACL,
|
||||
DeviceNotes: deviceNotes,
|
||||
TransferTarget: transferTarget,
|
||||
TransferDays: transferDays,
|
||||
TransferTransport: transferTransport,
|
||||
|
||||
@@ -38,6 +38,7 @@ const (
|
||||
auditDeviceTransfer = "admin.device.transfer"
|
||||
auditDeviceBind = "admin.device.bind"
|
||||
auditDeviceUnbind = "admin.device.unbind"
|
||||
auditDeviceRemark = "admin.device.remark"
|
||||
auditQuery = "admin.audit.query"
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// TestDeviceNotesSetPersistClear covers the store on its own: sanitize, save,
|
||||
// reload, clear, and the rune cap.
|
||||
func TestDeviceNotesSetPersistClear(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "device_notes.json")
|
||||
notes := NewDeviceNotes(path)
|
||||
|
||||
// Control characters are folded to spaces and the ends trimmed, so the
|
||||
// label always renders on one line.
|
||||
if err := notes.Set("dev-1", " Reception\nPC\t", "admin"); err != nil {
|
||||
t.Fatalf("Set: %v", err)
|
||||
}
|
||||
if got := notes.Note("dev-1"); got != "Reception PC" {
|
||||
t.Fatalf("Note = %q, want %q", got, "Reception PC")
|
||||
}
|
||||
|
||||
// The table survives a restart.
|
||||
reloaded := NewDeviceNotes(path)
|
||||
if err := reloaded.Load(); err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if got := reloaded.Note("dev-1"); got != "Reception PC" {
|
||||
t.Fatalf("reloaded Note = %q, want %q", got, "Reception PC")
|
||||
}
|
||||
|
||||
// More than MaxRemarkRunes runes is rejected without touching the table.
|
||||
tooLong := strings.Repeat("x", MaxRemarkRunes+1)
|
||||
if err := notes.Set("dev-1", tooLong, "admin"); err == nil {
|
||||
t.Fatal("Set accepted an over-long remark")
|
||||
}
|
||||
if got := notes.Note("dev-1"); got != "Reception PC" {
|
||||
t.Fatalf("rejected Set changed the note to %q", got)
|
||||
}
|
||||
if err := notes.Set("dev-1", strings.Repeat("y", MaxRemarkRunes), "admin"); err != nil {
|
||||
t.Fatalf("Set at the limit: %v", err)
|
||||
}
|
||||
|
||||
// An empty remark clears the entry, and the clearing is persisted.
|
||||
if err := notes.Set("dev-1", " ", "admin"); err != nil {
|
||||
t.Fatalf("clear: %v", err)
|
||||
}
|
||||
if got := notes.Note("dev-1"); got != "" {
|
||||
t.Fatalf("Note after clear = %q, want empty", got)
|
||||
}
|
||||
reloaded = NewDeviceNotes(path)
|
||||
if err := reloaded.Load(); err != nil {
|
||||
t.Fatalf("Load after clear: %v", err)
|
||||
}
|
||||
if got := reloaded.Note("dev-1"); got != "" {
|
||||
t.Fatalf("reloaded Note after clear = %q, want empty", got)
|
||||
}
|
||||
|
||||
// Remove is idempotent and drops the entry.
|
||||
if err := notes.Set("dev-2", "Keep", "admin"); err != nil {
|
||||
t.Fatalf("Set dev-2: %v", err)
|
||||
}
|
||||
if err := notes.Remove("dev-2"); err != nil {
|
||||
t.Fatalf("Remove: %v", err)
|
||||
}
|
||||
if err := notes.Remove("dev-2"); err != nil {
|
||||
t.Fatalf("Remove twice: %v", err)
|
||||
}
|
||||
if got := notes.Note("dev-2"); got != "" {
|
||||
t.Fatalf("Note after Remove = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetDeviceRemarkHandler exercises the WebSocket path: the superadmin
|
||||
// sets a remark, device_list reports it (plus the remarkEdit capability), and
|
||||
// clearing removes it.
|
||||
func TestSetDeviceRemarkHandler(t *testing.T) {
|
||||
wh, _, _ := aclTestHub(t)
|
||||
path := filepath.Join(t.TempDir(), "device_notes.json")
|
||||
notes := NewDeviceNotes(path)
|
||||
wh.withDeviceNotes(notes)
|
||||
|
||||
c, tok := aclTestClient(t, wh, "admin", "admin")
|
||||
|
||||
send := func(id, remark string) map[string]any {
|
||||
raw, err := json.Marshal(map[string]any{"token": tok, "id": id, "remark": remark})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
wh.dispatch(c, "set_device_remark", raw)
|
||||
return readUntilCmd(t, c, "set_device_remark_result")
|
||||
}
|
||||
|
||||
res := send("pub", " Reception\nPC ")
|
||||
if res["ok"] != true {
|
||||
t.Fatalf("set remark failed: %v", res)
|
||||
}
|
||||
if res["remark"] != "Reception PC" {
|
||||
t.Fatalf("reply remark = %v, want %q", res["remark"], "Reception PC")
|
||||
}
|
||||
if got := notes.Note("pub"); got != "Reception PC" {
|
||||
t.Fatalf("stored remark = %q", got)
|
||||
}
|
||||
|
||||
// device_list carries the label and the capability the menu keys off.
|
||||
rawList, _ := json.Marshal(map[string]any{"token": tok})
|
||||
wh.dispatch(c, "get_devices", rawList)
|
||||
list := readUntilCmd(t, c, "device_list")
|
||||
if list["remarkEdit"] != true {
|
||||
t.Fatalf("device_list remarkEdit = %v, want true", list["remarkEdit"])
|
||||
}
|
||||
items, _ := list["devices"].([]any)
|
||||
found := false
|
||||
for _, it := range items {
|
||||
m, _ := it.(map[string]any)
|
||||
if m["id"] == "pub" {
|
||||
found = true
|
||||
if m["remark"] != "Reception PC" {
|
||||
t.Fatalf("device_list remark = %v, want %q", m["remark"], "Reception PC")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("device_list did not include the public device")
|
||||
}
|
||||
|
||||
// Empty remark clears it.
|
||||
res = send("pub", "")
|
||||
if res["ok"] != true {
|
||||
t.Fatalf("clear remark failed: %v", res)
|
||||
}
|
||||
if got := notes.Note("pub"); got != "" {
|
||||
t.Fatalf("remark after clear = %q", got)
|
||||
}
|
||||
|
||||
// A payload with a non-string remark must be rejected, not treated as an
|
||||
// empty remark (which would clear the label).
|
||||
if err := notes.Set("pub", "Keep", "admin"); err != nil {
|
||||
t.Fatalf("Set before invalid payload: %v", err)
|
||||
}
|
||||
rawBad, _ := json.Marshal(map[string]any{"token": tok, "id": "pub", "remark": 123})
|
||||
wh.dispatch(c, "set_device_remark", rawBad)
|
||||
bad := readUntilCmd(t, c, "set_device_remark_result")
|
||||
if bad["ok"] == true {
|
||||
t.Fatalf("invalid payload accepted: %v", bad)
|
||||
}
|
||||
if got := notes.Note("pub"); got != "Keep" {
|
||||
t.Fatalf("invalid payload changed the remark to %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeviceNotesBadFileRefusesWrites: a file that cannot be parsed must not
|
||||
// be replaced by the first save (that would destroy every remark in it).
|
||||
func TestDeviceNotesBadFileRefusesWrites(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "device_notes.json")
|
||||
bad := []byte("{not json")
|
||||
if err := os.WriteFile(path, bad, 0644); err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
notes := NewDeviceNotes(path)
|
||||
if err := notes.Load(); err == nil {
|
||||
t.Fatal("Load accepted a malformed file")
|
||||
}
|
||||
if err := notes.Set("dev-1", "x", "admin"); err == nil {
|
||||
t.Fatal("Set wrote over a file that failed to load")
|
||||
}
|
||||
if err := notes.Remove("dev-1"); err == nil {
|
||||
t.Fatal("Remove wrote over a file that failed to load")
|
||||
}
|
||||
if got, _ := os.ReadFile(path); string(got) != string(bad) {
|
||||
t.Fatalf("original file was modified: %q", got)
|
||||
}
|
||||
|
||||
// A newer on-disk version is refused the same way.
|
||||
future, err := json.Marshal(deviceNotesFile{Version: deviceNotesFileVersion + 1,
|
||||
Devices: map[string]DeviceNoteEntry{"dev-1": {Note: "x"}}})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal future file: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(path, future, 0644); err != nil {
|
||||
t.Fatalf("seed future: %v", err)
|
||||
}
|
||||
futureNotes := NewDeviceNotes(path)
|
||||
if err := futureNotes.Load(); err == nil {
|
||||
t.Fatal("Load accepted a newer file version")
|
||||
}
|
||||
if err := futureNotes.Set("dev-1", "y", "admin"); err == nil {
|
||||
t.Fatal("Set wrote over a newer file version")
|
||||
}
|
||||
if got, _ := os.ReadFile(path); string(got) != string(future) {
|
||||
t.Fatal("newer file was modified")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeviceNotesLoadAppliesInvariants: values read back from disk go through
|
||||
// the same sanitize + rune cap as Set, so a restored file cannot put a
|
||||
// multi-line or over-long label on a card.
|
||||
func TestDeviceNotesLoadAppliesInvariants(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "device_notes.json")
|
||||
long := "Reception\nPC " + strings.Repeat("x", MaxRemarkRunes)
|
||||
data, err := json.Marshal(deviceNotesFile{Version: deviceNotesFileVersion,
|
||||
Devices: map[string]DeviceNoteEntry{"dev-1": {Note: long}}})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(path, data, 0644); err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
notes := NewDeviceNotes(path)
|
||||
if err := notes.Load(); err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
got := notes.Note("dev-1")
|
||||
if strings.ContainsAny(got, "\r\n\t") {
|
||||
t.Fatalf("loaded remark kept control characters: %q", got)
|
||||
}
|
||||
if n := utf8.RuneCountInString(got); n != MaxRemarkRunes {
|
||||
t.Fatalf("loaded remark has %d runes, want %d", n, MaxRemarkRunes)
|
||||
}
|
||||
if !strings.HasPrefix(got, "Reception PC ") {
|
||||
t.Fatalf("loaded remark lost its prefix: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetDeviceRemarkPermissions: viewers cannot edit, and an admin that the
|
||||
// ACL does not let see a private device cannot edit it either.
|
||||
func TestSetDeviceRemarkPermissions(t *testing.T) {
|
||||
wh, _, _ := aclTestHub(t)
|
||||
wh.withDeviceNotes(NewDeviceNotes(""))
|
||||
|
||||
attempt := func(c *wsClient, tok, id string) map[string]any {
|
||||
raw, _ := json.Marshal(map[string]any{"token": tok, "id": id, "remark": "x"})
|
||||
wh.dispatch(c, "set_device_remark", raw)
|
||||
return readUntilCmd(t, c, "set_device_remark_result")
|
||||
}
|
||||
|
||||
cv, tokv := aclTestClient(t, wh, "viewer1", "viewer")
|
||||
if res := attempt(cv, tokv, "pub"); res["ok"] == true {
|
||||
t.Fatal("viewer was allowed to edit a remark")
|
||||
}
|
||||
|
||||
// a-dev is bound to a@corp.com; another admin cannot see it, so the server
|
||||
// must refuse to label it as well.
|
||||
ca, toka := aclTestClient(t, wh, "other-admin", "admin")
|
||||
if res := attempt(ca, toka, "a-dev"); res["ok"] == true {
|
||||
t.Fatal("admin without device access was allowed to edit a remark")
|
||||
}
|
||||
|
||||
// The superadmin can label any device.
|
||||
cs, toks := aclTestClient(t, wh, "admin", "admin")
|
||||
if res := attempt(cs, toks, "a-dev"); res["ok"] != true {
|
||||
t.Fatalf("superadmin was refused: %v", res)
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,7 @@ type Server struct {
|
||||
auth *wsauth.Authenticator
|
||||
history *devicehistory.Store // nil → no offline devices
|
||||
deviceACL *DeviceACL // nil → no per-device owner filtering
|
||||
deviceNotes *DeviceNotes // nil → no "edit remark" entry in the UI
|
||||
ws *wsHub
|
||||
allowedOrigins []string // for WS Origin allowlist; empty = same-origin only
|
||||
loginIPLimit *wsauth.RateLimiter
|
||||
@@ -96,6 +97,12 @@ type Config struct {
|
||||
// behaviour: every authenticated session sees every device). The shipped
|
||||
// server always wires one; tests may omit it.
|
||||
DeviceACL *DeviceACL
|
||||
// DeviceNotes is the per-device remark table rendered on the card as
|
||||
// "hostname (remark)". nil disables the "edit remark" menu entry: the
|
||||
// device_list reply reports remarkEdit only when this is wired, so the
|
||||
// shared page hides the action on a backend that does not implement it
|
||||
// (the MFC server).
|
||||
DeviceNotes *DeviceNotes
|
||||
// TransferTarget ("host:port") and TransferDays pre-fill the web UI's
|
||||
// "transfer host" dialog. Reporting them is also what tells the shared
|
||||
// page that this backend implements COMMAND_ASSIGN_MASTER — the MFC server
|
||||
@@ -138,6 +145,7 @@ func (s *Server) WithConfig(cfg Config) *Server {
|
||||
s.brandName = resolveBrandName(cfg.BrandName, s.basePath)
|
||||
s.sso = cfg.SSO
|
||||
s.deviceACL = cfg.DeviceACL
|
||||
s.deviceNotes = cfg.DeviceNotes
|
||||
s.transferTarget = cfg.TransferTarget
|
||||
s.transferDays = cfg.TransferDays
|
||||
s.transferTransport = cfg.TransferTransport
|
||||
@@ -166,6 +174,7 @@ func (s *Server) Start() error {
|
||||
withLoginRateLimiters(s.loginIPLimit, s.loginUserLimit).
|
||||
withTrustForwardedFor(s.trustForwardedFor).
|
||||
withDeviceACL(s.deviceACL).
|
||||
withDeviceNotes(s.deviceNotes).
|
||||
withTransferDefaults(s.transferTarget, s.transferDays, s.transferTransport)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
@@ -161,6 +161,7 @@ type wsHub struct {
|
||||
devices *hub.Hub
|
||||
history *devicehistory.Store // nil → device_list stays online-only
|
||||
acl *DeviceACL // nil → every device is public (tests/embedders)
|
||||
notes *DeviceNotes // nil → no "edit remark" entry (MFC backend)
|
||||
log *logger.Logger
|
||||
|
||||
mu sync.RWMutex
|
||||
@@ -237,6 +238,15 @@ func (h *wsHub) withDeviceACL(acl *DeviceACL) *wsHub {
|
||||
return h
|
||||
}
|
||||
|
||||
// withDeviceNotes installs the per-device remark table. A nil table disables
|
||||
// "edit remark": its presence is what the device_list reply reports as
|
||||
// remarkEdit, so the shared page only offers the menu entry on a backend that
|
||||
// implements it (the MFC server does not).
|
||||
func (h *wsHub) withDeviceNotes(notes *DeviceNotes) *wsHub {
|
||||
h.notes = notes
|
||||
return h
|
||||
}
|
||||
|
||||
// withTransferDefaults installs the pre-filled target/days and the link type
|
||||
// (protocol.TransferTransport*) for the web UI's "transfer host" dialog. An
|
||||
// empty target still enables the feature: the operator types the address in
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
||||
@@ -103,6 +104,8 @@ func (h *wsHub) dispatch(c *wsClient, cmd string, raw []byte) {
|
||||
h.handleBindDevice(c, raw)
|
||||
case "unbind_device":
|
||||
h.handleUnbindDevice(c, raw)
|
||||
case "set_device_remark":
|
||||
h.handleSetDeviceRemark(c, raw)
|
||||
case "get_groups":
|
||||
h.handleGetGroups(c, raw)
|
||||
case "query_audit":
|
||||
@@ -800,6 +803,10 @@ func (h *wsHub) handleGetDevices(c *wsClient, raw []byte) {
|
||||
"target": h.transferTarget,
|
||||
"days": h.transferDays,
|
||||
},
|
||||
// Same convention for "edit remark": only a backend that wires a
|
||||
// remark table reports it, so the shared page hides the menu entry
|
||||
// on the MFC server.
|
||||
"remarkEdit": h.notes != nil,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -809,6 +816,9 @@ func (h *wsHub) handleGetDevices(c *wsClient, raw []byte) {
|
||||
type deviceListItem struct {
|
||||
hub.DeviceInfo
|
||||
Owner string `json:"owner,omitempty"`
|
||||
// Remark is the operator's label for this host, rendered as
|
||||
// "hostname (remark)" on the card. Set by the Go web console only.
|
||||
Remark string `json:"remark,omitempty"`
|
||||
// TransferTo / TransferUntil carry the "handed over to another master"
|
||||
// marker so the card can say where the host went and how long it stays
|
||||
// there. Absent for a host that was never transferred.
|
||||
@@ -821,6 +831,13 @@ type deviceListItem struct {
|
||||
// is either public or owned by the caller, so the field adds nothing.
|
||||
func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem {
|
||||
all := h.listDevicesWithOffline()
|
||||
// One snapshot instead of a read lock per device: Set holds the write
|
||||
// lock across the temp-file fsync + rename, and a slow disk must not
|
||||
// block every console's device list.
|
||||
var remarks map[string]DeviceNoteEntry
|
||||
if h.notes != nil {
|
||||
remarks = h.notes.Snapshot()
|
||||
}
|
||||
out := make([]deviceListItem, 0, len(all))
|
||||
for _, d := range all {
|
||||
if !h.canAccessDevice(c, d.ID) {
|
||||
@@ -831,6 +848,9 @@ func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem {
|
||||
owner = h.acl.Owner(d.ID)
|
||||
}
|
||||
item := deviceListItem{DeviceInfo: d, Owner: owner}
|
||||
if remarks != nil {
|
||||
item.Remark = remarks[d.ID].Note
|
||||
}
|
||||
if h.history != nil {
|
||||
if target, until, ok := h.history.Transfer(d.ID); ok {
|
||||
item.TransferTo, item.TransferUntil = target, until
|
||||
@@ -1281,6 +1301,7 @@ func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) {
|
||||
// The device is gone; its binding must not survive a later
|
||||
// client that happens to reuse the same ID.
|
||||
h.dropDeviceBinding(in.ID)
|
||||
h.dropDeviceNote(in.ID)
|
||||
h.audit(c, false, auditDeviceAdmin, map[string]any{
|
||||
"device_id": in.ID,
|
||||
"mode": "uninstall",
|
||||
@@ -1322,6 +1343,7 @@ func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) {
|
||||
return
|
||||
}
|
||||
h.dropDeviceBinding(in.ID)
|
||||
h.dropDeviceNote(in.ID)
|
||||
h.audit(c, false, auditDeviceAdmin, map[string]any{
|
||||
"device_id": in.ID,
|
||||
"mode": "removed",
|
||||
@@ -1716,6 +1738,71 @@ func (h *wsHub) handleUnbindDevice(c *wsClient, raw []byte) {
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": true, "count": len(ids)}))
|
||||
}
|
||||
|
||||
// handleSetDeviceRemark stores the free-text label shown on the device card
|
||||
// ("hostname (remark)"). Admin role only, and only for a device the caller can
|
||||
// access: the ACL keeps a private device out of other admins' cards, and the
|
||||
// server enforces the same rule so a hand-crafted request cannot label it
|
||||
// either. An empty remark clears the label.
|
||||
func (h *wsHub) handleSetDeviceRemark(c *wsClient, raw []byte) {
|
||||
const replyCmd = "set_device_remark_result"
|
||||
if !h.requireAdmin(c, raw, replyCmd) {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
ID string `json:"id"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
id := ""
|
||||
fail := func(msg, reason string) {
|
||||
h.audit(c, true, auditDeviceRemark, map[string]any{
|
||||
"device_id": id,
|
||||
"ok": false,
|
||||
"reason": reason,
|
||||
"error": msg,
|
||||
})
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "msg": msg}))
|
||||
}
|
||||
// An unparsable payload (e.g. a non-string remark) must be rejected, not
|
||||
// treated as an empty remark: empty clears the label.
|
||||
if err := json.Unmarshal(raw, &in); err != nil {
|
||||
fail("Invalid request", "invalid_request")
|
||||
return
|
||||
}
|
||||
id = strings.TrimSpace(in.ID)
|
||||
if id == "" {
|
||||
fail("Invalid device id", "invalid_id")
|
||||
return
|
||||
}
|
||||
if h.notes == nil {
|
||||
fail("Device remarks are not enabled on this server", "disabled")
|
||||
return
|
||||
}
|
||||
if h.denyIfNoDeviceAccess(c, id, replyCmd) {
|
||||
return
|
||||
}
|
||||
// Sanitize before the length check and the reply so the echoed value is
|
||||
// exactly what the store keeps (control characters folded to spaces).
|
||||
remark := sanitizeRemark(in.Remark)
|
||||
if utf8.RuneCountInString(remark) > MaxRemarkRunes {
|
||||
fail("Remark is too long (max "+strconv.Itoa(MaxRemarkRunes)+" characters)", "too_long")
|
||||
return
|
||||
}
|
||||
if err := h.notes.Set(id, remark, c.user); err != nil {
|
||||
fail("Failed to save remark: "+err.Error(), "save_failed")
|
||||
return
|
||||
}
|
||||
h.audit(c, false, auditDeviceRemark, map[string]any{
|
||||
"device_id": id,
|
||||
"ok": true,
|
||||
"cleared": remark == "",
|
||||
})
|
||||
// Every open console re-reads the list so the card shows the new label.
|
||||
h.broadcastAuthenticated(`{"cmd":"devices_changed"}`)
|
||||
c.queue(mustJSON(map[string]any{
|
||||
"cmd": replyCmd, "ok": true, "id": id, "remark": remark,
|
||||
}))
|
||||
}
|
||||
|
||||
// normalizeDeviceIDs merges the batch and single-device forms, trims blanks
|
||||
// and dedupes while preserving order.
|
||||
func normalizeDeviceIDs(ids []string, single string) []string {
|
||||
@@ -1814,6 +1901,17 @@ func (h *wsHub) dropDeviceBinding(deviceID string) {
|
||||
}
|
||||
}
|
||||
|
||||
// dropDeviceNote removes the remark together with the device record, so a
|
||||
// future client that reuses the same ID starts with a clean card.
|
||||
func (h *wsHub) dropDeviceNote(deviceID string) {
|
||||
if h.notes == nil {
|
||||
return
|
||||
}
|
||||
if err := h.notes.Remove(deviceID); err != nil {
|
||||
h.log.Warn("device remark remove failed for %s: %v", deviceID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// handleTermOpen kicks off a web terminal session. On success the wsClient
|
||||
// records `termWatching = deviceID` so subsequent term_input / term_resize
|
||||
// have a target, and the hub sends COMMAND_SHELL to the device. The
|
||||
|
||||
Reference in new issue
Block a user