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
@@ -94,6 +94,7 @@ nul
|
|||||||
server/go/web/assets/index.html
|
server/go/web/assets/index.html
|
||||||
server/go/users.json
|
server/go/users.json
|
||||||
server/go/devices.json
|
server/go/devices.json
|
||||||
|
server/go/device_notes.json
|
||||||
server/go/build/
|
server/go/build/
|
||||||
server/go/cmd/*.syso
|
server/go/cmd/*.syso
|
||||||
server/go/.claude/settings.json
|
server/go/.claude/settings.json
|
||||||
|
|||||||
@@ -1188,6 +1188,22 @@ func main() {
|
|||||||
}
|
}
|
||||||
log.Info("Device ACL loaded from %s (%d binding(s))", aclFile, len(deviceACL.Snapshot()))
|
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
|
// 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).
|
// (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
|
// Generous enough that a NAT office whose devices all re-auth at once is
|
||||||
@@ -1416,6 +1432,7 @@ func main() {
|
|||||||
BrandName: brandName,
|
BrandName: brandName,
|
||||||
SSO: ssoDetector,
|
SSO: ssoDetector,
|
||||||
DeviceACL: deviceACL,
|
DeviceACL: deviceACL,
|
||||||
|
DeviceNotes: deviceNotes,
|
||||||
TransferTarget: transferTarget,
|
TransferTarget: transferTarget,
|
||||||
TransferDays: transferDays,
|
TransferDays: transferDays,
|
||||||
TransferTransport: transferTransport,
|
TransferTransport: transferTransport,
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ const (
|
|||||||
auditDeviceTransfer = "admin.device.transfer"
|
auditDeviceTransfer = "admin.device.transfer"
|
||||||
auditDeviceBind = "admin.device.bind"
|
auditDeviceBind = "admin.device.bind"
|
||||||
auditDeviceUnbind = "admin.device.unbind"
|
auditDeviceUnbind = "admin.device.unbind"
|
||||||
|
auditDeviceRemark = "admin.device.remark"
|
||||||
auditQuery = "admin.audit.query"
|
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
|
auth *wsauth.Authenticator
|
||||||
history *devicehistory.Store // nil → no offline devices
|
history *devicehistory.Store // nil → no offline devices
|
||||||
deviceACL *DeviceACL // nil → no per-device owner filtering
|
deviceACL *DeviceACL // nil → no per-device owner filtering
|
||||||
|
deviceNotes *DeviceNotes // nil → no "edit remark" entry in the UI
|
||||||
ws *wsHub
|
ws *wsHub
|
||||||
allowedOrigins []string // for WS Origin allowlist; empty = same-origin only
|
allowedOrigins []string // for WS Origin allowlist; empty = same-origin only
|
||||||
loginIPLimit *wsauth.RateLimiter
|
loginIPLimit *wsauth.RateLimiter
|
||||||
@@ -96,6 +97,12 @@ type Config struct {
|
|||||||
// behaviour: every authenticated session sees every device). The shipped
|
// behaviour: every authenticated session sees every device). The shipped
|
||||||
// server always wires one; tests may omit it.
|
// server always wires one; tests may omit it.
|
||||||
DeviceACL *DeviceACL
|
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
|
// TransferTarget ("host:port") and TransferDays pre-fill the web UI's
|
||||||
// "transfer host" dialog. Reporting them is also what tells the shared
|
// "transfer host" dialog. Reporting them is also what tells the shared
|
||||||
// page that this backend implements COMMAND_ASSIGN_MASTER — the MFC server
|
// 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.brandName = resolveBrandName(cfg.BrandName, s.basePath)
|
||||||
s.sso = cfg.SSO
|
s.sso = cfg.SSO
|
||||||
s.deviceACL = cfg.DeviceACL
|
s.deviceACL = cfg.DeviceACL
|
||||||
|
s.deviceNotes = cfg.DeviceNotes
|
||||||
s.transferTarget = cfg.TransferTarget
|
s.transferTarget = cfg.TransferTarget
|
||||||
s.transferDays = cfg.TransferDays
|
s.transferDays = cfg.TransferDays
|
||||||
s.transferTransport = cfg.TransferTransport
|
s.transferTransport = cfg.TransferTransport
|
||||||
@@ -166,6 +174,7 @@ func (s *Server) Start() error {
|
|||||||
withLoginRateLimiters(s.loginIPLimit, s.loginUserLimit).
|
withLoginRateLimiters(s.loginIPLimit, s.loginUserLimit).
|
||||||
withTrustForwardedFor(s.trustForwardedFor).
|
withTrustForwardedFor(s.trustForwardedFor).
|
||||||
withDeviceACL(s.deviceACL).
|
withDeviceACL(s.deviceACL).
|
||||||
|
withDeviceNotes(s.deviceNotes).
|
||||||
withTransferDefaults(s.transferTarget, s.transferDays, s.transferTransport)
|
withTransferDefaults(s.transferTarget, s.transferDays, s.transferTransport)
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
|
|||||||
@@ -161,6 +161,7 @@ type wsHub struct {
|
|||||||
devices *hub.Hub
|
devices *hub.Hub
|
||||||
history *devicehistory.Store // nil → device_list stays online-only
|
history *devicehistory.Store // nil → device_list stays online-only
|
||||||
acl *DeviceACL // nil → every device is public (tests/embedders)
|
acl *DeviceACL // nil → every device is public (tests/embedders)
|
||||||
|
notes *DeviceNotes // nil → no "edit remark" entry (MFC backend)
|
||||||
log *logger.Logger
|
log *logger.Logger
|
||||||
|
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
@@ -237,6 +238,15 @@ func (h *wsHub) withDeviceACL(acl *DeviceACL) *wsHub {
|
|||||||
return h
|
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
|
// withTransferDefaults installs the pre-filled target/days and the link type
|
||||||
// (protocol.TransferTransport*) for the web UI's "transfer host" dialog. An
|
// (protocol.TransferTransport*) for the web UI's "transfer host" dialog. An
|
||||||
// empty target still enables the feature: the operator types the address in
|
// empty target still enables the feature: the operator types the address in
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
"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)
|
h.handleBindDevice(c, raw)
|
||||||
case "unbind_device":
|
case "unbind_device":
|
||||||
h.handleUnbindDevice(c, raw)
|
h.handleUnbindDevice(c, raw)
|
||||||
|
case "set_device_remark":
|
||||||
|
h.handleSetDeviceRemark(c, raw)
|
||||||
case "get_groups":
|
case "get_groups":
|
||||||
h.handleGetGroups(c, raw)
|
h.handleGetGroups(c, raw)
|
||||||
case "query_audit":
|
case "query_audit":
|
||||||
@@ -800,6 +803,10 @@ func (h *wsHub) handleGetDevices(c *wsClient, raw []byte) {
|
|||||||
"target": h.transferTarget,
|
"target": h.transferTarget,
|
||||||
"days": h.transferDays,
|
"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 {
|
type deviceListItem struct {
|
||||||
hub.DeviceInfo
|
hub.DeviceInfo
|
||||||
Owner string `json:"owner,omitempty"`
|
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"
|
// TransferTo / TransferUntil carry the "handed over to another master"
|
||||||
// marker so the card can say where the host went and how long it stays
|
// marker so the card can say where the host went and how long it stays
|
||||||
// there. Absent for a host that was never transferred.
|
// 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.
|
// is either public or owned by the caller, so the field adds nothing.
|
||||||
func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem {
|
func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem {
|
||||||
all := h.listDevicesWithOffline()
|
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))
|
out := make([]deviceListItem, 0, len(all))
|
||||||
for _, d := range all {
|
for _, d := range all {
|
||||||
if !h.canAccessDevice(c, d.ID) {
|
if !h.canAccessDevice(c, d.ID) {
|
||||||
@@ -831,6 +848,9 @@ func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem {
|
|||||||
owner = h.acl.Owner(d.ID)
|
owner = h.acl.Owner(d.ID)
|
||||||
}
|
}
|
||||||
item := deviceListItem{DeviceInfo: d, Owner: owner}
|
item := deviceListItem{DeviceInfo: d, Owner: owner}
|
||||||
|
if remarks != nil {
|
||||||
|
item.Remark = remarks[d.ID].Note
|
||||||
|
}
|
||||||
if h.history != nil {
|
if h.history != nil {
|
||||||
if target, until, ok := h.history.Transfer(d.ID); ok {
|
if target, until, ok := h.history.Transfer(d.ID); ok {
|
||||||
item.TransferTo, item.TransferUntil = target, until
|
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
|
// The device is gone; its binding must not survive a later
|
||||||
// client that happens to reuse the same ID.
|
// client that happens to reuse the same ID.
|
||||||
h.dropDeviceBinding(in.ID)
|
h.dropDeviceBinding(in.ID)
|
||||||
|
h.dropDeviceNote(in.ID)
|
||||||
h.audit(c, false, auditDeviceAdmin, map[string]any{
|
h.audit(c, false, auditDeviceAdmin, map[string]any{
|
||||||
"device_id": in.ID,
|
"device_id": in.ID,
|
||||||
"mode": "uninstall",
|
"mode": "uninstall",
|
||||||
@@ -1322,6 +1343,7 @@ func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
h.dropDeviceBinding(in.ID)
|
h.dropDeviceBinding(in.ID)
|
||||||
|
h.dropDeviceNote(in.ID)
|
||||||
h.audit(c, false, auditDeviceAdmin, map[string]any{
|
h.audit(c, false, auditDeviceAdmin, map[string]any{
|
||||||
"device_id": in.ID,
|
"device_id": in.ID,
|
||||||
"mode": "removed",
|
"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)}))
|
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
|
// normalizeDeviceIDs merges the batch and single-device forms, trims blanks
|
||||||
// and dedupes while preserving order.
|
// and dedupes while preserving order.
|
||||||
func normalizeDeviceIDs(ids []string, single string) []string {
|
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
|
// handleTermOpen kicks off a web terminal session. On success the wsClient
|
||||||
// records `termWatching = deviceID` so subsequent term_input / term_resize
|
// records `termWatching = deviceID` so subsequent term_input / term_resize
|
||||||
// have a target, and the hub sends COMMAND_SHELL to the device. The
|
// have a target, and the hub sends COMMAND_SHELL to the device. The
|
||||||
|
|||||||
+89
-7
@@ -657,8 +657,8 @@
|
|||||||
max-width: 240px;
|
max-width: 240px;
|
||||||
flex-shrink: 1;
|
flex-shrink: 1;
|
||||||
}
|
}
|
||||||
/* 卡片操作:右上角只留一个「…」按钮,点开才弹出菜单(终端 / 绑定 /
|
/* 卡片操作:右上角只留一个「…」按钮,点开才弹出菜单(终端 / 备注 /
|
||||||
转移 / 删除),菜单项带简短功能说明。独立于卡片本体点击事件
|
绑定 / 转移 / 删除),菜单项带简短功能说明。独立于卡片本体点击事件
|
||||||
(onclick stopPropagation)。List 视图卡片是一行,按钮垂直居中。 */
|
(onclick stopPropagation)。List 视图卡片是一行,按钮垂直居中。 */
|
||||||
.device-card .card-actions {
|
.device-card .card-actions {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
@@ -2289,6 +2289,31 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 修改备注(Go 后端):备注是卡片标题旁的显示标签 "hostname (备注)"。 -->
|
||||||
|
<div class="modal-overlay" id="remark-device-modal" onclick="if(event.target===this)closeRemarkModal()">
|
||||||
|
<div class="modal-content" style="max-width:440px;">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3>Edit Remark</h3>
|
||||||
|
<button class="modal-close" onclick="closeRemarkModal()">×</button>
|
||||||
|
</div>
|
||||||
|
<div class="user-form">
|
||||||
|
<div id="remark-device-name" style="font-size:13px;color:#aaa;margin-bottom:10px;"></div>
|
||||||
|
<label style="font-size:13px;color:#aaa;display:block;margin:8px 0 4px;">
|
||||||
|
Remark
|
||||||
|
</label>
|
||||||
|
<input type="text" id="remark-input" maxlength="64"
|
||||||
|
placeholder="e.g. Reception PC" autocomplete="off">
|
||||||
|
<div style="font-size:12px;color:#888;margin-top:8px;">
|
||||||
|
Shown on the card as "hostname (remark)". Leave it empty to clear the remark.
|
||||||
|
</div>
|
||||||
|
<div style="display:flex;gap:8px;margin-top:14px;">
|
||||||
|
<button onclick="confirmSetRemark()">Save</button>
|
||||||
|
<button class="cancel-btn" onclick="closeRemarkModal()">Cancel</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- Generic alert / confirmation dialog. Replaces native alert()/confirm():
|
<!-- Generic alert / confirmation dialog. Replaces native alert()/confirm():
|
||||||
their button labels come from the browser locale (e.g. German on a
|
their button labels come from the browser locale (e.g. German on a
|
||||||
German system) and do not match the app. -->
|
German system) and do not match the app. -->
|
||||||
@@ -3020,6 +3045,8 @@
|
|||||||
// 只有实现了「转移主机」的后端(Go)才会带这个字段;
|
// 只有实现了「转移主机」的后端(Go)才会带这个字段;
|
||||||
// MFC 复用同一份页面但不下发它,按钮因此不会出现。
|
// MFC 复用同一份页面但不下发它,按钮因此不会出现。
|
||||||
transferCfg = msg.transfer || null;
|
transferCfg = msg.transfer || null;
|
||||||
|
// 备注编辑同理由后端能力位决定(Go 才有;MFC 页面不显示)。
|
||||||
|
remarkEditAvailable = msg.remarkEdit === true;
|
||||||
// Keep current page (renderDeviceList adjusts if out of range)
|
// Keep current page (renderDeviceList adjusts if out of range)
|
||||||
renderDeviceList();
|
renderDeviceList();
|
||||||
renderWallSidebar();
|
renderWallSidebar();
|
||||||
@@ -3339,6 +3366,14 @@
|
|||||||
appAlert(msg.msg || 'Failed to unbind device', 'Device Binding');
|
appAlert(msg.msg || 'Failed to unbind device', 'Device Binding');
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
case 'set_device_remark_result':
|
||||||
|
if (msg.ok) {
|
||||||
|
closeRemarkModal();
|
||||||
|
getDevices();
|
||||||
|
} else {
|
||||||
|
appAlert(msg.msg || 'Failed to save remark', 'Edit Remark');
|
||||||
|
}
|
||||||
|
break;
|
||||||
case 'device_revoked': {
|
case 'device_revoked': {
|
||||||
// The superadmin bound this device to someone else while we
|
// The superadmin bound this device to someone else while we
|
||||||
// were watching it. Stop streaming immediately.
|
// were watching it. Stop streaming immediately.
|
||||||
@@ -5109,14 +5144,16 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ---- 卡片「…」操作菜单 ----
|
// ---- 卡片「…」操作菜单 ----
|
||||||
// 无论有几个操作,卡片上只显示一个「…」;点开弹出的菜单里才是终端/绑定/
|
// 无论有几个操作,卡片上只显示一个「…」;点开弹出的菜单里才是终端/备注/
|
||||||
// 转移/删除,每项带一句功能说明。菜单项在点击时按设备实时生成,权限和
|
// 绑定/转移/删除,每项带一句功能说明。菜单项在点击时按设备实时生成,权限和
|
||||||
// 在线状态不会因为列表渲染后变化而过期。
|
// 在线状态不会因为列表渲染后变化而过期。
|
||||||
let cardMenuEl = null;
|
let cardMenuEl = null;
|
||||||
let cardMenuBtn = null;
|
let cardMenuBtn = null;
|
||||||
const cardMenuSvg = {
|
const cardMenuSvg = {
|
||||||
term: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
term: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
||||||
'<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/></svg>',
|
'<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/></svg>',
|
||||||
|
edit: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
||||||
|
'<path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>',
|
||||||
bind: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
bind: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
||||||
'<rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>',
|
'<rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>',
|
||||||
transfer: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
transfer: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
||||||
@@ -5126,9 +5163,17 @@
|
|||||||
'<path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>'
|
'<path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>'
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 备注编辑:只有实现了该功能的后端(Go)在 device_list 里报 remarkEdit
|
||||||
|
// 才出现;MFC 复用同一份页面但不下发这个字段,菜单项因此不会出现。
|
||||||
|
let remarkEditAvailable = false;
|
||||||
|
|
||||||
|
function canEditRemark() {
|
||||||
|
return remarkEditAvailable && currentUserRole === 'admin';
|
||||||
|
}
|
||||||
|
|
||||||
function hasCardActions(d) {
|
function hasCardActions(d) {
|
||||||
if (d.online !== false) return true; // 在线设备至少有终端
|
if (d.online !== false) return true; // 在线设备至少有终端
|
||||||
return canBindDevices() || canDeleteDevices();
|
return canEditRemark() || canBindDevices() || canDeleteDevices();
|
||||||
}
|
}
|
||||||
|
|
||||||
function cardMenuEntries(d) {
|
function cardMenuEntries(d) {
|
||||||
@@ -5138,6 +5183,10 @@
|
|||||||
out.push({ kind: 'term', label: 'Terminal', desc: 'Open a remote shell',
|
out.push({ kind: 'term', label: 'Terminal', desc: 'Open a remote shell',
|
||||||
run: () => openTerminal(d.id) });
|
run: () => openTerminal(d.id) });
|
||||||
}
|
}
|
||||||
|
if (canEditRemark()) {
|
||||||
|
out.push({ kind: 'edit', label: 'Edit remark', desc: 'Set the label shown on the card',
|
||||||
|
run: () => openRemarkModal(d.id) });
|
||||||
|
}
|
||||||
if (canBindDevices()) {
|
if (canBindDevices()) {
|
||||||
out.push({ kind: 'bind', label: 'Bind owner', desc: 'Assign this host to a user',
|
out.push({ kind: 'bind', label: 'Bind owner', desc: 'Assign this host to a user',
|
||||||
run: () => openBindModal(d.id) });
|
run: () => openBindModal(d.id) });
|
||||||
@@ -5260,7 +5309,7 @@
|
|||||||
const rtt = d.rtt || '-';
|
const rtt = d.rtt || '-';
|
||||||
const ver = d.version || '-';
|
const ver = d.version || '-';
|
||||||
const activeWin = d.activeWindow || '';
|
const activeWin = d.activeWindow || '';
|
||||||
// 操作全部收进右上角的「…」菜单(终端 / 绑定 / 转移 / 删除),
|
// 操作全部收进右上角的「…」菜单(终端 / 备注 / 绑定 / 转移 / 删除),
|
||||||
// 具体条目见 cardMenuEntries。这里只决定按钮是否出现。
|
// 具体条目见 cardMenuEntries。这里只决定按钮是否出现。
|
||||||
const actionsHtml = hasCardActions(d)
|
const actionsHtml = hasCardActions(d)
|
||||||
? '<div class="card-actions">' +
|
? '<div class="card-actions">' +
|
||||||
@@ -5587,6 +5636,38 @@
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== 修改备注(Go 后端) =====
|
||||||
|
// 备注显示为卡片标题 "hostname (备注)";留空 = 清除。服务端持久化到
|
||||||
|
// device_notes.json,与设备历史/绑定独立,离线记录也能改。
|
||||||
|
let pendingRemarkDeviceId = null;
|
||||||
|
|
||||||
|
function openRemarkModal(id) {
|
||||||
|
if (!canEditRemark()) return;
|
||||||
|
const d = devices.find(x => String(x.id) === String(id));
|
||||||
|
if (!d) { appAlert('Device not found.', 'Edit Remark'); return; }
|
||||||
|
pendingRemarkDeviceId = String(id);
|
||||||
|
document.getElementById('remark-device-name').textContent =
|
||||||
|
(d.name || 'Unknown') + ' (' + String(id) + ')';
|
||||||
|
document.getElementById('remark-input').value = d.remark || '';
|
||||||
|
document.getElementById('remark-device-modal').classList.add('active');
|
||||||
|
const input = document.getElementById('remark-input');
|
||||||
|
input.focus();
|
||||||
|
input.select();
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeRemarkModal() {
|
||||||
|
pendingRemarkDeviceId = null;
|
||||||
|
document.getElementById('remark-device-modal').classList.remove('active');
|
||||||
|
}
|
||||||
|
|
||||||
|
function confirmSetRemark() {
|
||||||
|
if (!pendingRemarkDeviceId || !ws || ws.readyState !== WebSocket.OPEN) return;
|
||||||
|
const remark = document.getElementById('remark-input').value.trim();
|
||||||
|
ws.send(JSON.stringify({
|
||||||
|
cmd: 'set_device_remark', token, id: pendingRemarkDeviceId, remark,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
// ===== 删除设备 =====
|
// ===== 删除设备 =====
|
||||||
// 两种情况都删除服务端 devices.json 中的历史记录;在线设备额外按 MFC
|
// 两种情况都删除服务端 devices.json 中的历史记录;在线设备额外按 MFC
|
||||||
// 的做法发送单字节 TOKEN_UNINSTALL(卸载主机)。都先弹二次确认。
|
// 的做法发送单字节 TOKEN_UNINSTALL(卸载主机)。都先弹二次确认。
|
||||||
@@ -5794,7 +5875,8 @@
|
|||||||
'remote.screen.start', 'remote.screen.stop', 'remote.screen.denied',
|
'remote.screen.start', 'remote.screen.stop', 'remote.screen.denied',
|
||||||
'remote.terminal.start', 'remote.terminal.stop', 'remote.terminal.denied',
|
'remote.terminal.start', 'remote.terminal.stop', 'remote.terminal.denied',
|
||||||
'remote.clipboard.set', 'remote.clipboard.get', 'remote.rdp_reset',
|
'remote.clipboard.set', 'remote.clipboard.get', 'remote.rdp_reset',
|
||||||
'admin.user.create', 'admin.user.delete', 'admin.device.delete', 'admin.audit.query',
|
'admin.user.create', 'admin.user.delete', 'admin.device.delete', 'admin.device.bind',
|
||||||
|
'admin.device.unbind', 'admin.device.transfer', 'admin.device.remark', 'admin.audit.query',
|
||||||
'device.online', 'device.offline',
|
'device.online', 'device.offline',
|
||||||
'device.auth.success', 'device.auth.failure', 'device.auth.throttled',
|
'device.auth.success', 'device.auth.failure', 'device.auth.throttled',
|
||||||
'device.auth.heartbeat.success',
|
'device.auth.heartbeat.success',
|
||||||
|
|||||||
Reference in new issue
Block a user