diff --git a/.gitignore b/.gitignore index 8080ba0..6535c8d 100644 --- a/.gitignore +++ b/.gitignore @@ -95,6 +95,7 @@ server/go/web/assets/index.html server/go/users.json server/go/devices.json server/go/device_notes.json +server/go/device_groups.json server/go/build/ server/go/cmd/*.syso server/go/.claude/settings.json diff --git a/docs/Mcp_Go_Minimal_Design.md b/docs/Mcp_Go_Minimal_Design.md index baf5422..6f56501 100644 --- a/docs/Mcp_Go_Minimal_Design.md +++ b/docs/Mcp_Go_Minimal_Design.md @@ -144,12 +144,14 @@ `client_type/group/ip/os` 为大小写不敏感子串过滤;`name` 匹配计算机名与备注,`query` 匹配 计算机名、备注与 IP;`online=true`(默认)只列在线,`false` 只列历史中存在但当前离线的; `include_offline=true` 时再合并 `devicehistory.Store.Offline(online)`。`total` 是过滤后命中数, -`totalAll` 是过滤前总数,`hasMore` 表示同一条件下还有下一页。 +`totalAll` 是过滤前总数,`hasMore` 表示同一条件下还有下一页。`group` 过滤作用于 Web 控制台 +覆盖后的分组(`device_groups.json`,见下文 `hosts[]`)。 `hosts[]` 的字段按 `outputSchema`:`id/name/group/version/clientType/os/ip/rtt/activeWindow/ screen/online/last_seen`,以及 hub 或历史记录里确有的 `location/install_time`,和 Go 版 -Web 控制台设置过的 `remark`(`device_notes.json`,未设置时省略);两个服务端都没有 -`authStatus/tls`,不输出。离线历史条目不存 `clientType`,也没有 `rtt/activeWindow`。 +Web 控制台设置过的 `remark`(`device_notes.json`,未设置时省略)。`group` 以 Web 控制台的 +覆盖值优先(`device_groups.json`),没有覆盖时才用主机上报/历史记录里的分组;两个服务端都 +没有 `authStatus/tls`,不输出。离线历史条目不存 `clientType`,也没有 `rtt/activeWindow`。 #### `get_host_detail` diff --git a/server/go/cmd/main.go b/server/go/cmd/main.go index e6fea4a..f324a37 100644 --- a/server/go/cmd/main.go +++ b/server/go/cmd/main.go @@ -1204,6 +1204,21 @@ func main() { log.Info("Device remarks loaded from %s (%d remark(s))", notesFile, len(deviceNotes.Snapshot())) } + // Per-device group overrides (the web console's "edit group") live next to + // the remark table with the same fail-safe policy: a malformed file is + // never overwritten and edits are refused until it is fixed. + groupsFile := os.Getenv("YAMA_DEVICE_GROUPS_FILE") + if groupsFile == "" { + groupsFile = filepath.Join(filepath.Dir(usersFile), "device_groups.json") + rememberDefault("YAMA_DEVICE_GROUPS_FILE", groupsFile) + } + deviceGroups := web.NewDeviceGroups(groupsFile) + if err := deviceGroups.Load(); err != nil { + log.Warn("Failed to load device groups from %s: %v (group edits are refused until the file is fixed)", groupsFile, err) + } else { + log.Info("Device groups loaded from %s (%d override(s))", groupsFile, len(deviceGroups.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 @@ -1294,6 +1309,8 @@ func main() { DeviceACL: deviceACL, // Web-console remarks are returned by list_hosts/get_host_detail. DeviceRemarks: deviceNotes, + // Web-console group overrides are applied to the group field/filter. + DeviceGroups: deviceGroups, }) if mcpSrv.Enabled() { // Terminal tools need the hub's shell events (ready/data/closed). @@ -1435,6 +1452,7 @@ func main() { SSO: ssoDetector, DeviceACL: deviceACL, DeviceNotes: deviceNotes, + DeviceGroups: deviceGroups, TransferTarget: transferTarget, TransferDays: transferDays, TransferTransport: transferTransport, diff --git a/server/go/devicehistory/devicehistory.go b/server/go/devicehistory/devicehistory.go index 01286bb..c397ab6 100644 --- a/server/go/devicehistory/devicehistory.go +++ b/server/go/devicehistory/devicehistory.go @@ -332,6 +332,19 @@ func (s *Store) Remove(id string) bool { return existed } +// Has reports whether id has a history record (online or offline). Callers +// that write per-device side data use it to refuse an ID this server has never +// seen, so a stale UI cannot create an orphan entry. +func (s *Store) Has(id string) bool { + if id == "" { + return false + } + s.mu.Lock() + _, ok := s.devices[id] + s.mu.Unlock() + return ok +} + // Flush writes the current state synchronously. Normally the debounced timer // does this; Flush exists for tests and graceful shutdown. func (s *Store) Flush() error { diff --git a/server/go/mcp/server.go b/server/go/mcp/server.go index f30dbb9..e11df06 100644 --- a/server/go/mcp/server.go +++ b/server/go/mcp/server.go @@ -58,6 +58,17 @@ type deviceRemarkSnapshotter interface { Notes() map[string]string } +// DeviceGroups reports the web console's group override for a device ("" when +// the host keeps the group it reported). Implemented by web.DeviceGroups. +type DeviceGroups interface { + Group(deviceID string) string +} + +// deviceGroupSnapshotter mirrors deviceRemarkSnapshotter for the group table. +type deviceGroupSnapshotter interface { + Groups() map[string]string +} + // deviceOwnerSnapshotter is an optional DeviceOwner capability: returning the // whole binding table lets a long operation (the audit scan) apply the policy // without a read-lock acquisition per record. Implemented by web.DeviceACL. @@ -79,19 +90,35 @@ func (s *Server) ownerChecker() func(deviceID string) bool { return func(id string) bool { return s.cfg.DeviceACL.Owner(id) == "" } } -// remarkLookup returns a per-call remark lookup, or nil when no remark table -// is configured. A table that can snapshot its whole map is read once, so a -// large listing neither takes a read lock per device nor observes a save -// halfway through; other tables fall back to one Note() per device. -func (s *Server) remarkLookup() func(deviceID string) string { - if s.cfg.DeviceRemarks == nil { - return nil +// hostView carries the per-call label snapshots used by one host listing. A +// table that can snapshot its whole map is read once, so a large listing +// neither takes a read lock per device nor observes a save halfway through; +// other tables fall back to one lookup per device. nil means the table is not +// configured. +type hostView struct { + remarkOf func(deviceID string) string + groupOf func(deviceID string) string +} + +func (s *Server) hostView() hostView { + var v hostView + if s.cfg.DeviceRemarks != nil { + if snap, ok := s.cfg.DeviceRemarks.(deviceRemarkSnapshotter); ok { + notes := snap.Notes() + v.remarkOf = func(id string) string { return notes[id] } + } else { + v.remarkOf = func(id string) string { return s.cfg.DeviceRemarks.Note(id) } + } } - if snap, ok := s.cfg.DeviceRemarks.(deviceRemarkSnapshotter); ok { - notes := snap.Notes() - return func(id string) string { return notes[id] } + if s.cfg.DeviceGroups != nil { + if snap, ok := s.cfg.DeviceGroups.(deviceGroupSnapshotter); ok { + groups := snap.Groups() + v.groupOf = func(id string) string { return groups[id] } + } else { + v.groupOf = func(id string) string { return s.cfg.DeviceGroups.Group(id) } + } } - return func(id string) string { return s.cfg.DeviceRemarks.Note(id) } + return v } // Config is filled by cmd/main.go from the YAMA_MCP_* environment variables; @@ -124,6 +151,10 @@ type Config struct { // DeviceRemarks, when non-nil, adds the web console's remark to // list_hosts/get_host_detail and lets the name/query filters match it. DeviceRemarks DeviceRemarks + + // DeviceGroups, when non-nil, applies the web console's group override to + // the group field and the group filter in the host tools. + DeviceGroups DeviceGroups } // toolFunc implements one tools/call. It returns either a result value or a @@ -517,5 +548,5 @@ const serverInstructions = `这是 YAMA 服务端的 MCP 端点(Go 实现) 4) get_screenshot 只支持 mode=screen(按链路状况自适应缩放,max_width 省略时最大 1024);本实现没有 CLIENT_CAP_SCREEN_REGION 扩展,mode=region/window/monitor 与区域类参数一律返回 -32005。 5) list_files / read_file 走文件传输通道;list_files 支持 ids 批量(最多 50 台、整批 50 秒)。read_file 只接受单个普通文件且整文件不超过 2 MiB,目录用 list_files;本实现没有 download_file / search_file,超限文件只能改用 terminal_exec 分段查看,或连 Windows 主控端的完整服务端。 6) terminal_exec 需要客户端支持终端(CLIENT_CAP_TERMINAL),会在目标主机上创建持久会话;用完调用 terminal_close 释放,闲置会话由服务端回收。调用被取消时返回的 message 里带 session_id,可用它轮询或关闭。 -7) 本实现不维护授权状态与 TLS 标记:list_hosts / get_host_detail 不返回 authStatus/tls;备注(remark)由 Web 控制台维护,设置后会随主机返回,query 也匹配备注。get_server_status 只报版本、在线台数与监听地址,没有 switches/sessions。 +7) 本实现不维护授权状态与 TLS 标记:list_hosts / get_host_detail 不返回 authStatus/tls;备注(remark)与分组(group)可由 Web 控制台维护:备注设置后随主机返回且 query/name 会匹配,分组覆盖值同时用于返回字段和 group 过滤。get_server_status 只报版本、在线台数与监听地址,没有 switches/sessions。 8) 列表与详情都是调用时刻的快照,主机可能在操作期间掉线;写操作前先读一次现状,动作后再复核。` diff --git a/server/go/mcp/tools_local.go b/server/go/mcp/tools_local.go index 944e610..8d718b0 100644 --- a/server/go/mcp/tools_local.go +++ b/server/go/mcp/tools_local.go @@ -142,9 +142,15 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp ctF := strings.ToLower(args.ClientType) matched := make([]hub.DeviceInfo, 0, len(pool)) - remarkOf := s.remarkLookup() + view := s.hostView() for _, d := range pool { group := d.Group + if view.groupOf != nil { + // A web-console override wins over the group the host reported. + if g := view.groupOf(d.ID); g != "" { + group = g + } + } if group == "" { group = "default" } @@ -157,8 +163,8 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp clientType = s.clientType(d.ID) } remark := "" - if remarkOf != nil { - remark = remarkOf(d.ID) + if view.remarkOf != nil { + remark = view.remarkOf(d.ID) } // query matches computer name, remark and IP; name matches computer // name and remark, like the Win32 server. The remark is the web @@ -194,7 +200,7 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp end := min(begin+limit, total) hosts := make([]map[string]any, 0, end-begin) for _, d := range matched[begin:end] { - hosts = append(hosts, s.hostJSON(d, remarkOf)) + hosts = append(hosts, s.hostJSON(d, view)) } structured := map[string]any{ @@ -215,11 +221,16 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp // hostJSON projects a hub device onto the list_hosts/get_host_detail schema. // Fields the Go server does not know (authStatus, tls, clientType of an -// offline entry) are omitted rather than fabricated. remark is included when -// the web console has one for the device; remarkOf is the per-call snapshot -// (nil when no remark table is configured). -func (s *Server) hostJSON(d hub.DeviceInfo, remarkOf func(string) string) map[string]any { +// offline entry) are omitted rather than fabricated. remark and group come +// from the web console when it has them (view carries the per-call snapshots). +func (s *Server) hostJSON(d hub.DeviceInfo, view hostView) map[string]any { group := d.Group + if view.groupOf != nil { + // A web-console override wins over the group the host reported. + if g := view.groupOf(d.ID); g != "" { + group = g + } + } if group == "" { group = "default" } @@ -229,8 +240,8 @@ func (s *Server) hostJSON(d hub.DeviceInfo, remarkOf func(string) string) map[st "group": group, "online": d.Online, } - if remarkOf != nil { - if remark := remarkOf(d.ID); remark != "" { + if view.remarkOf != nil { + if remark := view.remarkOf(d.ID); remark != "" { h["remark"] = remark } } @@ -316,7 +327,7 @@ func (s *Server) callGetHostDetail(_ context.Context, raw json.RawMessage) (any, return nil, errf(CodeInvalidParams, "Missing required parameter: id or ids") } online, offline := s.hostMaps() - host, rerr := s.lookupHost(args.ID, online, offline, s.remarkLookup()) + host, rerr := s.lookupHost(args.ID, online, offline, s.hostView()) if rerr != nil { return nil, rerr } @@ -329,11 +340,11 @@ func (s *Server) hostDetailBatch(ids []string) (any, *rpcError) { "Too many ids: %d (max %d per batch)", len(ids), batchMaxIDs) } online, offline := s.hostMaps() - remarkOf := s.remarkLookup() // one snapshot for the whole batch + view := s.hostView() // one snapshot for the whole batch results := make([]map[string]any, 0, len(ids)) succeeded, failed := 0, 0 for _, id := range ids { - host, rerr := s.lookupHost(id, online, offline, remarkOf) + host, rerr := s.lookupHost(id, online, offline, view) if rerr != nil { results = append(results, map[string]any{ "id": id, @@ -392,17 +403,17 @@ func (s *Server) hostMaps() (online, offline map[string]hub.DeviceInfo) { // lookupHost resolves one host: online first, then the last-known history // record. It mirrors the Win32 server, which answers offline hosts with their // final snapshot instead of an error. -func (s *Server) lookupHost(id string, online, offline map[string]hub.DeviceInfo, remarkOf func(string) string) (map[string]any, *rpcError) { +func (s *Server) lookupHost(id string, online, offline map[string]hub.DeviceInfo, view hostView) (map[string]any, *rpcError) { if !isDecimalID(id) { return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string") } if d, ok := online[id]; ok { - h := s.hostJSON(d, remarkOf) + h := s.hostJSON(d, view) h["capabilities"] = s.capabilities(d) return h, nil } if d, ok := offline[id]; ok { - return s.hostJSON(d, remarkOf), nil + return s.hostJSON(d, view), nil } return nil, errf(CodeOffline, "Host not found or offline: %s", id) } diff --git a/server/go/mcp/tools_local_test.go b/server/go/mcp/tools_local_test.go index ead05f1..56ee273 100644 --- a/server/go/mcp/tools_local_test.go +++ b/server/go/mcp/tools_local_test.go @@ -226,9 +226,22 @@ type fakeRemarkSnapshot map[string]string func (f fakeRemarkSnapshot) Note(deviceID string) string { return f[deviceID] } func (f fakeRemarkSnapshot) Notes() map[string]string { return f } +// fakeGroups stands in for web.DeviceGroups (per-device fallback path). +type fakeGroups map[string]string + +func (f fakeGroups) Group(deviceID string) string { return f[deviceID] } + +// fakeGroupSnapshot also implements Groups(), the snapshot capability the +// shipped web.DeviceGroups provides. +type fakeGroupSnapshot map[string]string + +func (f fakeGroupSnapshot) Group(deviceID string) string { return f[deviceID] } +func (f fakeGroupSnapshot) Groups() map[string]string { return f } + func TestListHostsPoolsAndProjection(t *testing.T) { f := newLocalFixture(t) f.srv.cfg.DeviceRemarks = fakeRemarkSnapshot{"1001": "Reception PC"} + f.srv.cfg.DeviceGroups = fakeGroupSnapshot{"1002": "Remote"} text, sc := mustCallLocal(t, f.srv, "list_hosts", `{}`) hosts := hostList(t, sc) @@ -285,6 +298,9 @@ func TestListHostsPoolsAndProjection(t *testing.T) { if got := strField(t, alpha, "remark"); got != "Reception PC" { t.Fatalf("remark = %q, want the web console's label", got) } + if !strings.Contains(text, "1002\tBETA\t-\t192.168.1.2\tRemote\tWindows 11\ttrue\tEXE\t-") { + t.Fatalf("text = %q, want BETA row with the group override", text) + } if _, ok := hosts[1]["remark"]; ok { t.Fatalf("unset remark present on %v", hosts[1]["id"]) } @@ -378,6 +394,33 @@ func TestListHostsFilters(t *testing.T) { } } +// TestListHostsGroupOverride: the web console's group override drives both the +// projected group and the group filter, including for offline records. +func TestListHostsGroupOverride(t *testing.T) { + f := newLocalFixture(t) + f.srv.cfg.DeviceGroups = fakeGroupSnapshot{"1002": "Remote", "1003": "Remote", "2001": "Archive"} + + _, sc := mustCallLocal(t, f.srv, "list_hosts", `{"group":"remote"}`) + wantIDs(t, hostList(t, sc), "1002", "1003") + + _, sc = mustCallLocal(t, f.srv, "list_hosts", `{"online":false,"group":"archive"}`) + wantIDs(t, hostList(t, sc), "2001") + if got := strField(t, hostList(t, sc)[0], "group"); got != "Archive" { + t.Fatalf("offline group = %q, want the override", got) + } +} + +// TestListHostsGroupOverrideFallback covers a DeviceGroups implementation that +// participates through Group() only (no whole-table snapshot). +func TestListHostsGroupOverrideFallback(t *testing.T) { + f := newLocalFixture(t) + f.srv.cfg.DeviceGroups = fakeGroups{"1002": "Remote"} + _, sc := mustCallLocal(t, f.srv, "list_hosts", `{}`) + if got := strField(t, hostList(t, sc)[1], "group"); got != "Remote" { + t.Fatalf("group = %q, want the override", got) + } +} + func TestListHostsPaging(t *testing.T) { f := newLocalFixture(t) diff --git a/server/go/web/audit.go b/server/go/web/audit.go index 1d1c3e2..471a4f9 100644 --- a/server/go/web/audit.go +++ b/server/go/web/audit.go @@ -39,6 +39,7 @@ const ( auditDeviceBind = "admin.device.bind" auditDeviceUnbind = "admin.device.unbind" auditDeviceRemark = "admin.device.remark" + auditDeviceGroup = "admin.device.group" auditQuery = "admin.audit.query" ) diff --git a/server/go/web/device_groups.go b/server/go/web/device_groups.go new file mode 100644 index 0000000..763be24 --- /dev/null +++ b/server/go/web/device_groups.go @@ -0,0 +1,251 @@ +package web + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "time" + "unicode/utf8" +) + +// MaxGroupRunes bounds the per-device group label. The Win32 server's +// "regroup host" dialog rejects names of 24 characters or more (the command +// payload is a fixed 50-byte buffer); the Go console keeps the same limit so +// a group name written here can also be handed to the client later. +const MaxGroupRunes = 23 + +// DeviceGroupEntry is one web-console group override. +type DeviceGroupEntry struct { + Group string `json:"group"` + UpdatedAt time.Time `json:"updated_at"` + UpdatedBy string `json:"updated_by,omitempty"` +} + +// deviceGroupsFile is the on-disk shape of device_groups.json. Version is +// reserved for future migrations; v1 is a flat deviceID -> group map. +type deviceGroupsFile struct { + Version int `json:"version"` + Devices map[string]DeviceGroupEntry `json:"devices"` +} + +// DeviceGroups is the per-device group table used by the Go web console. A +// device with no entry keeps the group it reported at login; an entry +// overrides that group for every Go-side view (device list, group filter, +// MCP), works for offline records too, and survives restarts. +// +// It deliberately does NOT write CMD_SET_GROUP to the client: the host keeps +// reporting its own group to other masters. An empty Path disables +// persistence (tests). +type DeviceGroups struct { + mu sync.RWMutex + path string + entries map[string]DeviceGroupEntry + // 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 override it still holds. + loadErr error +} + +// NewDeviceGroups returns an empty table backed by path. +func NewDeviceGroups(path string) *DeviceGroups { + return &DeviceGroups{path: path, entries: make(map[string]DeviceGroupEntry)} +} + +// 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 so the unreadable file survives for recovery. +func (g *DeviceGroups) Load() error { + if g.path == "" { + return nil + } + data, err := os.ReadFile(g.path) + if err != nil { + if os.IsNotExist(err) { + return nil + } + return g.failLoad(fmt.Errorf("read %s: %w", g.path, err)) + } + var f deviceGroupsFile + if err := json.Unmarshal(data, &f); err != nil { + return g.failLoad(fmt.Errorf("parse %s: %w", g.path, err)) + } + if f.Version > deviceGroupsFileVersion { + return g.failLoad(fmt.Errorf("unsupported %s version %d (this server writes %d)", + g.path, f.Version, deviceGroupsFileVersion)) + } + entries := make(map[string]DeviceGroupEntry, len(f.Devices)) + for id, e := range f.Devices { + id = strings.TrimSpace(id) + e.Group = capRunes(sanitizeLabel(e.Group), MaxGroupRunes) + if id == "" || e.Group == "" { + continue + } + entries[id] = e + } + g.mu.Lock() + g.entries = entries + g.loadErr = nil + g.mu.Unlock() + return nil +} + +// deviceGroupsFileVersion is the on-disk format we write. A file from a newer +// version is refused instead of being read as v1 and overwritten. +const deviceGroupsFileVersion = 1 + +// failLoad records the reason writes are disabled and returns it. +func (g *DeviceGroups) failLoad(err error) error { + g.mu.Lock() + g.loadErr = err + g.mu.Unlock() + return err +} + +// Group returns the override for deviceID, or "" when the device keeps the +// group it reported. +func (g *DeviceGroups) Group(deviceID string) string { + if g == nil { + return "" + } + g.mu.RLock() + defer g.mu.RUnlock() + return g.entries[deviceID].Group +} + +// Groups returns a copy of the deviceID -> group map. Callers that look up +// many devices in one pass take this snapshot instead of a read lock per +// device. +func (g *DeviceGroups) Groups() map[string]string { + if g == nil { + return map[string]string{} + } + g.mu.RLock() + defer g.mu.RUnlock() + out := make(map[string]string, len(g.entries)) + for id, e := range g.entries { + out[id] = e.Group + } + return out +} + +// Snapshot returns a copy of the table (for logs and tests). +func (g *DeviceGroups) Snapshot() map[string]DeviceGroupEntry { + if g == nil { + return map[string]DeviceGroupEntry{} + } + g.mu.RLock() + defer g.mu.RUnlock() + out := make(map[string]DeviceGroupEntry, len(g.entries)) + for id, e := range g.entries { + out[id] = e + } + return out +} + +// Set stores group for deviceID. An empty group clears the override (the +// device falls back to the group it reports). Control characters are folded to +// spaces, the result is trimmed, and more than MaxGroupRunes runes is +// rejected. On persistence failure the in-memory table is rolled back. +func (g *DeviceGroups) Set(deviceID, group, actor string) error { + deviceID = strings.TrimSpace(deviceID) + if deviceID == "" { + return fmt.Errorf("empty device id") + } + group = sanitizeLabel(group) + if utf8.RuneCountInString(group) > MaxGroupRunes { + return fmt.Errorf("group is too long (max %d characters)", MaxGroupRunes) + } + + g.mu.Lock() + defer g.mu.Unlock() + if g.loadErr != nil { + return fmt.Errorf("device groups unavailable: %w", g.loadErr) + } + prev, had := g.entries[deviceID] + if group == "" { + if !had { + return nil + } + delete(g.entries, deviceID) + } else { + g.entries[deviceID] = DeviceGroupEntry{Group: group, UpdatedAt: time.Now().UTC(), UpdatedBy: actor} + } + if err := g.saveLocked(); err != nil { + if had { + g.entries[deviceID] = prev + } else { + delete(g.entries, deviceID) + } + return err + } + return nil +} + +// Remove drops the override of one device (idempotent). Called when the device +// record is deleted so a future client reusing the same ID cannot inherit the +// group. +func (g *DeviceGroups) Remove(deviceID string) error { + if g == nil { + return nil + } + deviceID = strings.TrimSpace(deviceID) + if deviceID == "" { + return nil + } + g.mu.Lock() + defer g.mu.Unlock() + if g.loadErr != nil { + return fmt.Errorf("device groups unavailable: %w", g.loadErr) + } + prev, ok := g.entries[deviceID] + if !ok { + return nil + } + delete(g.entries, deviceID) + if err := g.saveLocked(); err != nil { + g.entries[deviceID] = prev + return err + } + return nil +} + +// saveLocked writes the table via a temp file + rename. Caller holds g.mu. +func (g *DeviceGroups) saveLocked() error { + if g.path == "" { + return nil + } + f := deviceGroupsFile{Version: deviceGroupsFileVersion, Devices: g.entries} + data, err := json.MarshalIndent(f, "", " ") + if err != nil { + return fmt.Errorf("encode device groups: %w", err) + } + dir := filepath.Dir(g.path) + if dir == "" { + dir = "." + } + tmp, err := os.CreateTemp(dir, ".device_groups-*.tmp") + if err != nil { + return fmt.Errorf("create temp groups: %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 groups: %w", err) + } + if err := tmp.Sync(); err != nil { + _ = tmp.Close() + return fmt.Errorf("sync temp groups: %w", err) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("close temp groups: %w", err) + } + if err := os.Rename(tmpName, g.path); err != nil { + return fmt.Errorf("rename groups: %w", err) + } + return nil +} diff --git a/server/go/web/device_groups_test.go b/server/go/web/device_groups_test.go new file mode 100644 index 0000000..e45c1c9 --- /dev/null +++ b/server/go/web/device_groups_test.go @@ -0,0 +1,230 @@ +package web + +import ( + "encoding/json" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "unicode/utf8" +) + +// TestDeviceGroupsSetPersistClear covers the store: sanitize, save, reload, +// clear, the rune cap and the corrupt-file write protection. +func TestDeviceGroupsSetPersistClear(t *testing.T) { + path := filepath.Join(t.TempDir(), "device_groups.json") + groups := NewDeviceGroups(path) + + if err := groups.Set("dev-1", " Office\nWest\t", "admin"); err != nil { + t.Fatalf("Set: %v", err) + } + if got := groups.Group("dev-1"); got != "Office West" { + t.Fatalf("Group = %q, want %q", got, "Office West") + } + + reloaded := NewDeviceGroups(path) + if err := reloaded.Load(); err != nil { + t.Fatalf("Load: %v", err) + } + if got := reloaded.Group("dev-1"); got != "Office West" { + t.Fatalf("reloaded Group = %q, want %q", got, "Office West") + } + + // The cap matches the Win32 regroup dialog (< 24 characters). + if err := groups.Set("dev-1", strings.Repeat("x", MaxGroupRunes+1), "admin"); err == nil { + t.Fatal("Set accepted an over-long group") + } + if err := groups.Set("dev-1", strings.Repeat("y", MaxGroupRunes), "admin"); err != nil { + t.Fatalf("Set at the limit: %v", err) + } + + // An empty group clears the override. + if err := groups.Set("dev-1", " ", "admin"); err != nil { + t.Fatalf("clear: %v", err) + } + if got := groups.Group("dev-1"); got != "" { + t.Fatalf("Group after clear = %q, want empty", got) + } + + // Groups() is the bulk snapshot callers take per listing; it must be a copy. + if err := groups.Set("dev-2", "Bulk", "admin"); err != nil { + t.Fatalf("Set dev-2: %v", err) + } + snap := groups.Groups() + if snap["dev-2"] != "Bulk" { + t.Fatalf("Groups()[dev-2] = %q, want %q", snap["dev-2"], "Bulk") + } + snap["dev-2"] = "mutated" + if got := groups.Group("dev-2"); got != "Bulk" { + t.Fatalf("mutating the snapshot changed the store: %q", got) + } + if err := groups.Remove("dev-2"); err != nil { + t.Fatalf("Remove: %v", err) + } + if err := groups.Remove("dev-2"); err != nil { + t.Fatalf("Remove twice: %v", err) + } + if got := groups.Group("dev-2"); got != "" { + t.Fatalf("Group after Remove = %q", got) + } +} + +// TestDeviceGroupsBadFileRefusesWrites: an unparsable file must never be +// replaced by the first save. +func TestDeviceGroupsBadFileRefusesWrites(t *testing.T) { + path := filepath.Join(t.TempDir(), "device_groups.json") + bad := []byte("{not json") + if err := os.WriteFile(path, bad, 0644); err != nil { + t.Fatalf("seed: %v", err) + } + groups := NewDeviceGroups(path) + if err := groups.Load(); err == nil { + t.Fatal("Load accepted a malformed file") + } + if err := groups.Set("dev-1", "x", "admin"); err == nil { + t.Fatal("Set 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) + } +} + +// TestDeviceGroupsLoadAppliesInvariants: values read back from disk are +// sanitized and capped, so a restored file cannot break the card layout. +func TestDeviceGroupsLoadAppliesInvariants(t *testing.T) { + path := filepath.Join(t.TempDir(), "device_groups.json") + long := "Team\nA " + strings.Repeat("x", MaxGroupRunes) + data, err := json.Marshal(deviceGroupsFile{Version: deviceGroupsFileVersion, + Devices: map[string]DeviceGroupEntry{"dev-1": {Group: long}}}) + if err != nil { + t.Fatalf("marshal: %v", err) + } + if err := os.WriteFile(path, data, 0644); err != nil { + t.Fatalf("seed: %v", err) + } + groups := NewDeviceGroups(path) + if err := groups.Load(); err != nil { + t.Fatalf("Load: %v", err) + } + got := groups.Group("dev-1") + if strings.ContainsAny(got, "\r\n\t") { + t.Fatalf("loaded group kept control characters: %q", got) + } + if n := utf8.RuneCountInString(got); n != MaxGroupRunes { + t.Fatalf("loaded group has %d runes, want %d", n, MaxGroupRunes) + } +} + +// TestSetDeviceGroupHandler exercises the WebSocket path: the superadmin moves +// a host, device_list reports the override plus groupEdit, get_groups offers +// the new name, and clearing restores the reported group. +func TestSetDeviceGroupHandler(t *testing.T) { + wh, _, _ := aclTestHub(t) + groups := NewDeviceGroups(filepath.Join(t.TempDir(), "device_groups.json")) + wh.withDeviceGroups(groups) + + c, tok := aclTestClient(t, wh, "admin", "admin") + + send := func(id, group string) map[string]any { + raw, err := json.Marshal(map[string]any{"token": tok, "id": id, "group": group}) + if err != nil { + t.Fatalf("marshal: %v", err) + } + wh.dispatch(c, "set_device_group", raw) + return readUntilCmd(t, c, "set_device_group_result") + } + + res := send("pub", " Office\nWest ") + if res["ok"] != true { + t.Fatalf("set group failed: %v", res) + } + if res["group"] != "Office West" { + t.Fatalf("reply group = %v, want %q", res["group"], "Office West") + } + + // device_list reports the override 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["groupEdit"] != true { + t.Fatalf("device_list groupEdit = %v, want true", list["groupEdit"]) + } + found := false + for _, it := range list["devices"].([]any) { + m := it.(map[string]any) + if m["id"] == "pub" { + found = true + if m["group"] != "Office West" { + t.Fatalf("device_list group = %v, want override", m["group"]) + } + } + } + if !found { + t.Fatal("device_list did not include the public device") + } + + // get_groups offers the override name. + rawGroups, _ := json.Marshal(map[string]any{"token": tok}) + wh.dispatch(c, "get_groups", rawGroups) + gr := readUntilCmd(t, c, "groups") + var names []string + for _, g := range gr["groups"].([]any) { + names = append(names, g.(string)) + } + if !slices.Contains(names, "Office West") { + t.Fatalf("groups = %v, want the override included", names) + } + // The overridden device's stale reported group must not linger in the list. + if slices.Contains(names, "shared") { + t.Fatalf("groups = %v, want the overridden reported group omitted", names) + } + + // A stale card (device deleted between render and save) must not create an + // orphan override. + if res := send("ghost-id", "Nowhere"); res["ok"] == true { + t.Fatalf("group override accepted for an unknown device: %v", res) + } + + // Clearing restores the group the host reported. + res = send("pub", "") + if res["ok"] != true { + t.Fatalf("clear group failed: %v", res) + } + wh.dispatch(c, "get_devices", rawList) + list = readUntilCmd(t, c, "device_list") + for _, it := range list["devices"].([]any) { + m := it.(map[string]any) + if m["id"] == "pub" && m["group"] != "shared" { + t.Fatalf("group after clear = %v, want reported %q", m["group"], "shared") + } + } +} + +// TestSetDeviceGroupPermissions: viewers cannot edit, and an admin that cannot +// see a private device cannot move it. +func TestSetDeviceGroupPermissions(t *testing.T) { + wh, _, _ := aclTestHub(t) + wh.withDeviceGroups(NewDeviceGroups("")) + + attempt := func(c *wsClient, tok, id string) map[string]any { + raw, _ := json.Marshal(map[string]any{"token": tok, "id": id, "group": "x"}) + wh.dispatch(c, "set_device_group", raw) + return readUntilCmd(t, c, "set_device_group_result") + } + + cv, tokv := aclTestClient(t, wh, "viewer1", "viewer") + if res := attempt(cv, tokv, "pub"); res["ok"] == true { + t.Fatal("viewer was allowed to move a host") + } + + 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 move a host") + } + + cs, toks := aclTestClient(t, wh, "admin", "admin") + if res := attempt(cs, toks, "a-dev"); res["ok"] != true { + t.Fatalf("superadmin was refused: %v", res) + } +} diff --git a/server/go/web/device_notes.go b/server/go/web/device_notes.go index fefd13e..4ad23e8 100644 --- a/server/go/web/device_notes.go +++ b/server/go/web/device_notes.go @@ -83,7 +83,7 @@ func (n *DeviceNotes) Load() error { 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)) + e.Note = capRunes(sanitizeLabel(e.Note), MaxRemarkRunes) if id == "" || e.Note == "" { continue } @@ -154,7 +154,7 @@ func (n *DeviceNotes) Set(deviceID, note, actor string) error { if deviceID == "" { return fmt.Errorf("empty device id") } - note = sanitizeRemark(note) + note = sanitizeLabel(note) if utf8.RuneCountInString(note) > MaxRemarkRunes { return fmt.Errorf("remark is too long (max %d characters)", MaxRemarkRunes) } @@ -212,10 +212,11 @@ func (n *DeviceNotes) Remove(deviceID string) error { return nil } -// sanitizeRemark folds line breaks and other control characters (including +// 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. -func sanitizeRemark(s string) string { +// 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 ' ' @@ -225,13 +226,14 @@ func sanitizeRemark(s string) string { 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 { +// 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 string([]rune(s)[:MaxRemarkRunes]) + return strings.TrimSpace(string([]rune(s)[:max])) } // saveLocked writes the table via a temp file + rename. Caller holds n.mu. diff --git a/server/go/web/device_notes_test.go b/server/go/web/device_notes_test.go index 46a95bb..76c0214 100644 --- a/server/go/web/device_notes_test.go +++ b/server/go/web/device_notes_test.go @@ -165,6 +165,14 @@ func TestSetDeviceRemarkHandler(t *testing.T) { if got := notes.Note("pub"); got != "Keep" { t.Fatalf("invalid payload changed the remark to %q", got) } + + // A stale card (device deleted between render and save) must not create an + // orphan remark. + rawGhost, _ := json.Marshal(map[string]any{"token": tok, "id": "ghost-id", "remark": "x"}) + wh.dispatch(c, "set_device_remark", rawGhost) + if ghost := readUntilCmd(t, c, "set_device_remark_result"); ghost["ok"] == true { + t.Fatalf("remark accepted for an unknown device: %v", ghost) + } } // TestDeviceNotesBadFileRefusesWrites: a file that cannot be parsed must not diff --git a/server/go/web/server.go b/server/go/web/server.go index 744ee9d..581d7f5 100644 --- a/server/go/web/server.go +++ b/server/go/web/server.go @@ -34,6 +34,7 @@ type Server struct { 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 + deviceGroups *DeviceGroups // nil → no "edit group" entry in the UI ws *wsHub allowedOrigins []string // for WS Origin allowlist; empty = same-origin only loginIPLimit *wsauth.RateLimiter @@ -103,6 +104,9 @@ type Config struct { // shared page hides the action on a backend that does not implement it // (the MFC server). DeviceNotes *DeviceNotes + // DeviceGroups is the per-device group override table. nil disables the + // "edit group" menu entry the same way (device_list reports groupEdit). + DeviceGroups *DeviceGroups // 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 @@ -146,6 +150,7 @@ func (s *Server) WithConfig(cfg Config) *Server { s.sso = cfg.SSO s.deviceACL = cfg.DeviceACL s.deviceNotes = cfg.DeviceNotes + s.deviceGroups = cfg.DeviceGroups s.transferTarget = cfg.TransferTarget s.transferDays = cfg.TransferDays s.transferTransport = cfg.TransferTransport @@ -175,6 +180,7 @@ func (s *Server) Start() error { withTrustForwardedFor(s.trustForwardedFor). withDeviceACL(s.deviceACL). withDeviceNotes(s.deviceNotes). + withDeviceGroups(s.deviceGroups). withTransferDefaults(s.transferTarget, s.transferDays, s.transferTransport) mux := http.NewServeMux() diff --git a/server/go/web/ws.go b/server/go/web/ws.go index d1451a9..8d5ab0f 100644 --- a/server/go/web/ws.go +++ b/server/go/web/ws.go @@ -162,6 +162,7 @@ type wsHub struct { 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) + groups *DeviceGroups // nil → no "edit group" entry (MFC backend) log *logger.Logger mu sync.RWMutex @@ -247,6 +248,15 @@ func (h *wsHub) withDeviceNotes(notes *DeviceNotes) *wsHub { return h } +// withDeviceGroups installs the per-device group override table. A nil table +// disables "edit group": its presence is what the device_list reply reports as +// groupEdit, so the shared page only offers the menu entry on a backend that +// implements it (the MFC server does not). +func (h *wsHub) withDeviceGroups(groups *DeviceGroups) *wsHub { + h.groups = groups + 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 diff --git a/server/go/web/ws_handlers.go b/server/go/web/ws_handlers.go index 23742a4..b24afa7 100644 --- a/server/go/web/ws_handlers.go +++ b/server/go/web/ws_handlers.go @@ -106,6 +106,8 @@ func (h *wsHub) dispatch(c *wsClient, cmd string, raw []byte) { h.handleUnbindDevice(c, raw) case "set_device_remark": h.handleSetDeviceRemark(c, raw) + case "set_device_group": + h.handleSetDeviceGroup(c, raw) case "get_groups": h.handleGetGroups(c, raw) case "query_audit": @@ -124,6 +126,16 @@ func (h *wsHub) dispatch(c *wsClient, cmd string, raw []byte) { } } +// deviceExists reports whether id is online or has a history record. Handlers +// that write per-device side tables use it so a stale card (the device was +// deleted between render and save) cannot create an orphan entry. +func (h *wsHub) deviceExists(id string) bool { + if h.devices.IsOnline(id) { + return true + } + return h.history != nil && h.history.Has(id) +} + // requireAdmin combines token validation with a role=="admin" check. The // reply on failure has the standard `{cmd, ok:false, msg}` shape so the // front-end's generic toast handler can surface the reason. @@ -807,6 +819,8 @@ func (h *wsHub) handleGetDevices(c *wsClient, raw []byte) { // remark table reports it, so the shared page hides the menu entry // on the MFC server. "remarkEdit": h.notes != nil, + // ... and for "edit group", which only the Go server implements. + "groupEdit": h.groups != nil, })) } @@ -819,6 +833,10 @@ type deviceListItem struct { // 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"` + // GroupOverride marks Group as a web-console override rather than the + // group the host reported, so the edit dialog can prefill without turning + // the reported value into a permanent override. + GroupOverride bool `json:"groupOverride,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. @@ -838,6 +856,10 @@ func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem { if h.notes != nil { remarks = h.notes.Snapshot() } + var groups map[string]string + if h.groups != nil { + groups = h.groups.Groups() + } out := make([]deviceListItem, 0, len(all)) for _, d := range all { if !h.canAccessDevice(c, d.ID) { @@ -851,6 +873,12 @@ func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem { if remarks != nil { item.Remark = remarks[d.ID].Note } + // A web-console group override wins over the group the host reported + // at login (and over the group stored in the offline history record). + if g := groups[d.ID]; g != "" { + item.DeviceInfo.Group = g + item.GroupOverride = true + } if h.history != nil { if target, until, ok := h.history.Transfer(d.ID); ok { item.TransferTo, item.TransferUntil = target, until @@ -1302,6 +1330,7 @@ func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) { // client that happens to reuse the same ID. h.dropDeviceBinding(in.ID) h.dropDeviceNote(in.ID) + h.dropDeviceGroup(in.ID) h.audit(c, false, auditDeviceAdmin, map[string]any{ "device_id": in.ID, "mode": "uninstall", @@ -1344,6 +1373,7 @@ func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) { } h.dropDeviceBinding(in.ID) h.dropDeviceNote(in.ID) + h.dropDeviceGroup(in.ID) h.audit(c, false, auditDeviceAdmin, map[string]any{ "device_id": in.ID, "mode": "removed", @@ -1595,16 +1625,21 @@ func (h *wsHub) handleListUsers(c *wsClient, raw []byte) { })) } -// handleGetGroups returns the deduplicated set of group labels currently -// observed on online devices, plus a synthetic "default" entry that the -// admin UI uses for ungrouped devices. Admin-only — non-admins don't get -// to enumerate the device fleet's groups. Matches the contract of -// CWebService::HandleGetGroups (WebService.cpp:1130). +// handleGetGroups returns the deduplicated set of group labels the admin UI +// can offer: Web-console overrides (including groups that exist only on +// offline records) plus the groups online devices report, and a synthetic +// "default" entry for ungrouped devices. A device whose group is overridden +// contributes only the override, never its stale reported group. Admin-only — +// non-admins don't get to enumerate the device fleet's groups. func (h *wsHub) handleGetGroups(c *wsClient, raw []byte) { const replyCmd = "groups" if !h.requireAdmin(c, raw, replyCmd) { return } + var overrides map[string]string + if h.groups != nil { + overrides = h.groups.Groups() + } seen := map[string]struct{}{"default": {}} for _, d := range h.devices.ListDevices() { // Group names are device metadata: do not reveal groups that only @@ -1612,12 +1647,23 @@ func (h *wsHub) handleGetGroups(c *wsClient, raw []byte) { if !h.canAccessDevice(c, d.ID) { continue } + if overrides[d.ID] != "" { + continue // the override loop below adds the effective group + } g := d.Group if g == "" { g = "default" } seen[g] = struct{}{} } + // Web-console overrides define groups too, including groups that only + // exist on offline records; the per-device access check still applies. + for id, g := range overrides { + if g == "" || !h.canAccessDevice(c, id) { + continue + } + seen[g] = struct{}{} + } groups := make([]string, 0, len(seen)) for g := range seen { groups = append(groups, g) @@ -1780,9 +1826,13 @@ func (h *wsHub) handleSetDeviceRemark(c *wsClient, raw []byte) { if h.denyIfNoDeviceAccess(c, id, replyCmd) { return } + if !h.deviceExists(id) { + fail("Device not found", "not_found") + 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) + remark := sanitizeLabel(in.Remark) if utf8.RuneCountInString(remark) > MaxRemarkRunes { fail("Remark is too long (max "+strconv.Itoa(MaxRemarkRunes)+" characters)", "too_long") return @@ -1803,6 +1853,73 @@ func (h *wsHub) handleSetDeviceRemark(c *wsClient, raw []byte) { })) } +// handleSetDeviceGroup sets the web-console group override for one device. +// Admin role only, and only for a device the caller can access. An empty group +// clears the override, so the device falls back to the group it reports. +// +// The override changes every Go-side view (device list, group filter, MCP) and +// works for offline records, but it does not send CMD_SET_GROUP: the host keeps +// reporting its own group to other masters. +func (h *wsHub) handleSetDeviceGroup(c *wsClient, raw []byte) { + const replyCmd = "set_device_group_result" + if !h.requireAdmin(c, raw, replyCmd) { + return + } + var in struct { + ID string `json:"id"` + Group string `json:"group"` + } + id := "" + fail := func(msg, reason string) { + h.audit(c, true, auditDeviceGroup, map[string]any{ + "device_id": id, + "ok": false, + "reason": reason, + "error": msg, + }) + c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "msg": msg})) + } + 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.groups == nil { + fail("Device groups are not enabled on this server", "disabled") + return + } + if h.denyIfNoDeviceAccess(c, id, replyCmd) { + return + } + if !h.deviceExists(id) { + fail("Device not found", "not_found") + return + } + group := sanitizeLabel(in.Group) + if utf8.RuneCountInString(group) > MaxGroupRunes { + fail("Group is too long (max "+strconv.Itoa(MaxGroupRunes)+" characters)", "too_long") + return + } + if err := h.groups.Set(id, group, c.user); err != nil { + fail("Failed to save group: "+err.Error(), "save_failed") + return + } + h.audit(c, false, auditDeviceGroup, map[string]any{ + "device_id": id, + "ok": true, + "cleared": group == "", + }) + // Every open console re-reads the list so the card and group filter move. + h.broadcastAuthenticated(`{"cmd":"devices_changed"}`) + c.queue(mustJSON(map[string]any{ + "cmd": replyCmd, "ok": true, "id": id, "group": group, + })) +} + // normalizeDeviceIDs merges the batch and single-device forms, trims blanks // and dedupes while preserving order. func normalizeDeviceIDs(ids []string, single string) []string { @@ -1912,6 +2029,16 @@ func (h *wsHub) dropDeviceNote(deviceID string) { } } +// dropDeviceGroup removes the group override together with the device record. +func (h *wsHub) dropDeviceGroup(deviceID string) { + if h.groups == nil { + return + } + if err := h.groups.Remove(deviceID); err != nil { + h.log.Warn("device group 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 diff --git a/server/web/index.html b/server/web/index.html index b785a54..e033650 100644 --- a/server/web/index.html +++ b/server/web/index.html @@ -658,7 +658,7 @@ flex-shrink: 1; } /* 卡片操作:右上角只留一个「…」按钮,点开才弹出菜单(终端 / 备注 / - 绑定 / 转移 / 删除),菜单项带简短功能说明。独立于卡片本体点击事件 + 分组 / 绑定 / 转移 / 删除),菜单项带简短功能说明。独立于卡片本体点击事件 (onclick stopPropagation)。List 视图卡片是一行,按钮垂直居中。 */ .device-card .card-actions { position: absolute; @@ -2314,6 +2314,33 @@ + +
+ @@ -3045,8 +3072,9 @@ // 只有实现了「转移主机」的后端(Go)才会带这个字段; // MFC 复用同一份页面但不下发它,按钮因此不会出现。 transferCfg = msg.transfer || null; - // 备注编辑同理由后端能力位决定(Go 才有;MFC 页面不显示)。 + // 备注/分组编辑同理由后端能力位决定(Go 才有;MFC 页面不显示)。 remarkEditAvailable = msg.remarkEdit === true; + groupEditAvailable = msg.groupEdit === true; // Keep current page (renderDeviceList adjusts if out of range) renderDeviceList(); renderWallSidebar(); @@ -3374,6 +3402,14 @@ appAlert(msg.msg || 'Failed to save remark', 'Edit Remark'); } break; + case 'set_device_group_result': + if (msg.ok) { + closeGroupModal(); + getDevices(); + } else { + appAlert(msg.msg || 'Failed to save group', 'Edit Group'); + } + break; case 'device_revoked': { // The superadmin bound this device to someone else while we // were watching it. Stop streaming immediately. @@ -5145,7 +5181,7 @@ // ---- 卡片「…」操作菜单 ---- // 无论有几个操作,卡片上只显示一个「…」;点开弹出的菜单里才是终端/备注/ - // 绑定/转移/删除,每项带一句功能说明。菜单项在点击时按设备实时生成,权限和 + // 分组/绑定/转移/删除,每项带一句功能说明。菜单项在点击时按设备实时生成,权限和 // 在线状态不会因为列表渲染后变化而过期。 let cardMenuEl = null; let cardMenuBtn = null; @@ -5154,6 +5190,8 @@ '