Compare commits
6
Commits
830dcf1672
...
4b96885016
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b96885016 | ||
|
|
034b11fa6a | ||
|
|
5f764b2425 | ||
|
|
95d2bbc1b6 | ||
|
|
1bd7fa5b2d | ||
|
|
c9a18856e5 |
No files matched your search
@@ -94,6 +94,8 @@ nul
|
||||
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
|
||||
|
||||
@@ -69,6 +69,13 @@ static bool ClientCompressUsesZlib()
|
||||
#endif
|
||||
}
|
||||
|
||||
// 对外暴露同一判定:分享前要确认新建的分享实例会用什么算法(它构造时读的就是
|
||||
// 这个配置),不能用某条现有连接的 m_useZlib 代替。
|
||||
bool IOCPClient::ConfiguredWireZlib()
|
||||
{
|
||||
return ClientCompressUsesZlib();
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Construction/Destruction
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -214,6 +214,11 @@ public:
|
||||
// COMMAND_SET_COMPRESS 用它原地切换,避免 S_CLIENT_UPDATE 把进程内测试客户端停死。
|
||||
void SetWireCompression(bool useZlib) { m_useZlib = useZlib; }
|
||||
|
||||
// 整机配置里选定的线缆压缩模式(新连接构造时读的同一个键)。分享实例会继承它,
|
||||
// 所以分享前按它判断,而不是按当前连接的 m_useZlib:并行上线时不同连接的模式
|
||||
// 可以和配置不一致。
|
||||
static bool ConfiguredWireZlib();
|
||||
|
||||
void SetServerAddress(const char* szServerIP, unsigned short uPort)
|
||||
{
|
||||
m_Domain = szServerIP ? szServerIP : "127.0.0.1";
|
||||
|
||||
@@ -1154,6 +1154,23 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
Mprintf("[compress-switch] unsupported mode '%s', ignored\n", mode.c_str());
|
||||
break;
|
||||
}
|
||||
// 分享实例不能改写整机的线缆压缩配置:它跑的是同一个 OnReceive,放行的话
|
||||
// 分享目标主控就能改掉主机连归属方的模式,主机下次重启会按别家的选择连回来。
|
||||
if (!m_ClientApp || !m_ClientApp->IsMainInstance()) {
|
||||
Mprintf("[compress-switch] refused: not the main instance\n");
|
||||
ClientMsg msg("线缆压缩", "Compression switch refused: only the owning master may switch");
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
// 存在分享链路时只允许切回 zstd。压缩模式是整机配置(settings\compress),
|
||||
// 分享实例及后续子连接都会继承;对端若只支持 zstd(如 Go 服务端),切到
|
||||
// zlib 会让分享链路在下次建连后失联。zstd 对所有对端都兼容。
|
||||
if (mode == "zlib" && m_cfg && !m_cfg->GetStr("settings", "share_list").empty()) {
|
||||
Mprintf("[compress-switch] refused zlib: share links present\n");
|
||||
ClientMsg msg("线缆压缩", "Compression switch refused: this host has share links; cancel sharing before switching to zlib");
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
if (m_cfg)
|
||||
m_cfg->SetStr("settings", "compress", mode);
|
||||
Mprintf("[compress-switch] set to %s, reconnecting\n", mode.c_str());
|
||||
@@ -1470,6 +1487,17 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
// 主机当前走 zlib 时不接受分享:分享实例构造时会读整机 compress
|
||||
// 配置,带着 zlib 去连分享目标;对端若只支持 zstd(如 Go 服务端),
|
||||
// 这条分享链路一建就连不上。先切回 zstd 再分享。
|
||||
// 按配置判断而非当前连接:并行上线时当前连接的模式可能已不是新实例
|
||||
// 将要使用的模式(配置由收到切换命令的那条连接写入,是整机共享的)。
|
||||
if (IOCPClient::ConfiguredWireZlib()) {
|
||||
Mprintf("Share ignored: client uses zlib wire compression\n");
|
||||
ClientMsg msg("分享主机", "Client uses zlib wire compression, switch it back to zstd before sharing");
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
if (targetKey.empty())
|
||||
break;
|
||||
auto share = targetKey;
|
||||
|
||||
@@ -141,14 +141,17 @@
|
||||
{ "hosts": [ /* ... */ ], "total": 7, "totalAll": 9, "limit": 100, "offset": 0, "hasMore": false }
|
||||
```
|
||||
|
||||
`client_type/group/ip/os` 为大小写不敏感子串过滤;`name` 只匹配计算机名,`query` 同时匹配
|
||||
`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`;两个服务端都
|
||||
没有 `authStatus/tls/remark`,不输出。离线历史条目不存 `clientType`,也没有 `rtt/activeWindow`。
|
||||
screen/online/last_seen`,以及 hub 或历史记录里确有的 `location/install_time`,和 Go 版
|
||||
Web 控制台设置过的 `remark`(`device_notes.json`,未设置时省略)。`group` 以 Web 控制台的
|
||||
覆盖值优先(`device_groups.json`),没有覆盖时才用主机上报/历史记录里的分组;两个服务端都
|
||||
没有 `authStatus/tls`,不输出。离线历史条目不存 `clientType`,也没有 `rtt/activeWindow`。
|
||||
|
||||
#### `get_host_detail`
|
||||
|
||||
@@ -255,7 +258,7 @@ M5 之前传任一参数都返回 `-32005` 并在 message 里点名。细节见
|
||||
|
||||
| 工具 | 汇总行之后 |
|
||||
|---|---|
|
||||
| `list_hosts` | 表头 `id name ip group os online clientType last_seen`,随后每台一行 |
|
||||
| `list_hosts` | 表头 `id name remark ip group os online clientType last_seen`,随后每台一行 |
|
||||
| `get_host_detail` | 单台:主机 JSON(compact);批量:`id ok detail`,成功行是主机 JSON,失败行是错误信息 |
|
||||
| `list_files` | 盘符 `drive typeName fileSystem totalMB freeMB`;目录 `name isDir size mtime` |
|
||||
| `get_audit_log` | `time type msg`,`msg` 是去掉信封字段后的 compact JSON |
|
||||
|
||||
@@ -97,7 +97,7 @@
|
||||
| `list_files` 的 `id/ids/path/limit/offset` | 全部实现;`offset` 是服务端在完整列表上做窗口裁剪;批量走 results 汇总 |
|
||||
| `read_file` 的语义 | **行语义**:`offset` 起始行(负数=末尾 N 行)、`limit` 行数、`max_bytes` 字节上限;`encoding` 支持 `auto/utf-8/gbk/gb18030/latin1` |
|
||||
| 输出字段 | `list_hosts` → `hosts/total/totalAll/limit/offset/hasMore`;`list_files` → `files`(不是 `entries`)/`drives`;`get_host_detail.capabilities` → `screenPreview/screenRegion/windowInfo/fileTransferV2/c2cPaths/registry/remoteControl/platform`;`read_file` → `encoding/eol/lines_total/lines_returned/sha256/size/text/truncated` |
|
||||
| hub 没有的字段 | `authStatus/tls/location/install_time/remark` 不伪造、直接不给(`outputSchema` 只强制 `hosts`) |
|
||||
| hub 没有的字段 | `authStatus/tls/location/install_time` 不伪造、直接不给(`outputSchema` 只强制 `hosts`);`remark` 来自 Web 控制台备注表(`DeviceNotes`),有则填、无则省略 |
|
||||
|
||||
`read_file` 的整文件下载仍受 `YAMA_MCP_READ_MAX`(2 MiB)硬门约束,超过 → `-32602`(schema 描述同款口径)。
|
||||
|
||||
@@ -197,7 +197,8 @@ curl -s -X POST localhost:18090/mcp -H "Authorization: Bearer $YAMA_MCP_TOKEN" \
|
||||
决定是否并入历史;`online/ip/os/group/name/client_type/query` 全为过滤(`name`/`query`
|
||||
大小写不敏感子串);按 `outputSchema` 返回 `{hosts,total,totalAll,limit,offset,hasMore}`,
|
||||
host 字段按 schema 命名组装,hub/历史里确有的 `location/install_time/screen/version` 照填,
|
||||
两边都没有的 `authStatus/tls/remark` 不伪造。
|
||||
两边都没有的 `authStatus/tls` 不伪造;`remark` 来自 Web 控制台备注表(`DeviceNotes`,
|
||||
有则填、无则省略),沿用 `name`/`query` 的过滤口径。
|
||||
- `get_host_detail`:`id` 或 `ids`(≤50,批量走 `{tool,total,succeeded,failed,skipped,results[]}`);
|
||||
`capabilities{screenPreview,screenRegion,windowInfo,fileTransferV2,c2cPaths,registry,remoteControl,platform}`
|
||||
(`protocol.SupportsCap` 逐位)——**不含 `v2`**(恒真,列出来误导)。
|
||||
|
||||
@@ -906,6 +906,16 @@ void CLicenseDlg::OnLicenseViewIPs()
|
||||
start = end + 1;
|
||||
}
|
||||
|
||||
// 按最后活跃时间倒序展示(新的在前);无时间戳/无法解析的记录排在最后。
|
||||
// 存储侧已保证最近上报的条目在前,这里再做一次稳定排序,兼容旧版本写下的
|
||||
// "首次出现倒序" 数据,打开对话框即可看到正确的顺序。
|
||||
std::stable_sort(records.begin(), records.end(),
|
||||
[](const IPRecord& a, const IPRecord& b) {
|
||||
int da = (a.daysAgo < 0) ? 0x7FFFFFFF : a.daysAgo;
|
||||
int db = (b.daysAgo < 0) ? 0x7FFFFFFF : b.daysAgo;
|
||||
return da < db;
|
||||
});
|
||||
|
||||
// 如果有记录被删除,保存更新后的 IP 列表
|
||||
if (removedCount > 0) {
|
||||
// 锁内只做 I/O —— UI 控件更新(SetItemText)放锁外,避免锁内触发
|
||||
|
||||
@@ -251,6 +251,11 @@ bool UpdateLicenseAuthorization(const std::string& deviceID, const std::string&
|
||||
|
||||
// IP 列表管理常量
|
||||
#define MAX_IP_HISTORY 1000 // 最多保留 几 个不同的 IP
|
||||
// 单个 IP 值总字节数上限。Win32 profile API 对单个值有约 64KB 的硬限制:
|
||||
// 值超过后 GetPrivateProfileStringA 只返回被截断的尾部,而
|
||||
// WritePrivateProfileStringA 会把整行再追加一遍(实测 66KB 的值读回 464 字节、
|
||||
// 文件膨胀到两倍),之后的读改写会永久写坏历史。留出余量按 60KB 控制。
|
||||
#define MAX_IP_LIST_BYTES 60000
|
||||
|
||||
// 解析 IP 列表字符串为 vector<pair<IP, 时间戳>>
|
||||
// 格式: "192.168.1.1|260218, 10.0.0.1|260215" (yyMMdd)
|
||||
@@ -306,7 +311,8 @@ static std::string SerializeIPList(const std::vector<std::pair<std::string, std:
|
||||
return result;
|
||||
}
|
||||
|
||||
// 更新 IP 列表:添加新 IP 或更新已有 IP 的时间戳
|
||||
// 更新 IP 列表:添加新 IP 或刷新已有 IP 的时间戳,并按最后活跃时间倒序排列
|
||||
// (最近上报的条目始终在最前,查看 IP 历史时即为倒序)。
|
||||
// 格式: IP(机器名)|时间戳,例如 "1.2.3.4(PC01)|260219" (yyMMdd 格式)
|
||||
// 返回更新后的 IP 列表字符串
|
||||
static std::string UpdateIPList(const std::string& existingIPList, const std::string& newIP, const std::string& machineName = "")
|
||||
@@ -341,11 +347,12 @@ static std::string UpdateIPList(const std::string& existingIPList, const std::st
|
||||
};
|
||||
|
||||
// 查找是否已存在该 IP(只比较 IP 部分,兼容旧格式)
|
||||
// 命中的条目连同新时间戳移到列表开头:列表顺序 = 最后活跃时间倒序
|
||||
bool found = false;
|
||||
for (auto& entry : ipList) {
|
||||
if (extractIP(entry.first) == newIP) {
|
||||
entry.first = ipKey; // 更新为新格式(带机器名)
|
||||
entry.second = timestamp; // 更新时间戳
|
||||
for (auto it = ipList.begin(); it != ipList.end(); ++it) {
|
||||
if (extractIP(it->first) == newIP) {
|
||||
ipList.erase(it);
|
||||
ipList.insert(ipList.begin(), { ipKey, timestamp });
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
@@ -354,11 +361,27 @@ static std::string UpdateIPList(const std::string& existingIPList, const std::st
|
||||
if (!found) {
|
||||
// 新 IP,添加到开头(最近的在前)
|
||||
ipList.insert(ipList.begin(), { ipKey, timestamp });
|
||||
}
|
||||
|
||||
// 限制数量
|
||||
if (ipList.size() > MAX_IP_HISTORY) {
|
||||
ipList.resize(MAX_IP_HISTORY);
|
||||
}
|
||||
// 限制数量:达到上限时淘汰尾部(最久未活跃)的记录,保证新记录始终写得进去
|
||||
if (ipList.size() > MAX_IP_HISTORY) {
|
||||
ipList.resize(MAX_IP_HISTORY);
|
||||
}
|
||||
|
||||
// 限制字节数:尾部(最久未活跃)继续淘汰,避免单个值越过 INI 的 64KB 上限后
|
||||
// 读写整体失效(见 MAX_IP_LIST_BYTES 注释)。机器名很长时条数没到上限也会触发。
|
||||
size_t totalBytes = 0;
|
||||
for (size_t i = 0; i < ipList.size(); ++i) {
|
||||
totalBytes += ipList[i].first.size();
|
||||
if (!ipList[i].second.empty()) totalBytes += 1 + ipList[i].second.size();
|
||||
if (i > 0) totalBytes += 2; // ", " 分隔符
|
||||
}
|
||||
while (ipList.size() > 1 && totalBytes > MAX_IP_LIST_BYTES) {
|
||||
const auto& last = ipList.back();
|
||||
totalBytes -= last.first.size();
|
||||
if (!last.second.empty()) totalBytes -= 1 + last.second.size();
|
||||
totalBytes -= 2; // 去掉它前面的 ", "
|
||||
ipList.pop_back();
|
||||
}
|
||||
|
||||
return SerializeIPList(ipList);
|
||||
|
||||
@@ -1188,6 +1188,37 @@ func main() {
|
||||
}
|
||||
log.Info("Device ACL loaded from %s (%d binding(s))", aclFile, len(deviceACL.Snapshot()))
|
||||
|
||||
// Per-device remarks (the web card's "hostname (remark)" label) live next
|
||||
// to the ACL. A malformed file only loses labels — it carries no access
|
||||
// rights — so the server still starts; the store then refuses every edit
|
||||
// so the unreadable file is never overwritten.
|
||||
notesFile := os.Getenv("YAMA_DEVICE_NOTES_FILE")
|
||||
if notesFile == "" {
|
||||
notesFile = filepath.Join(filepath.Dir(usersFile), "device_notes.json")
|
||||
rememberDefault("YAMA_DEVICE_NOTES_FILE", notesFile)
|
||||
}
|
||||
deviceNotes := web.NewDeviceNotes(notesFile)
|
||||
if err := deviceNotes.Load(); err != nil {
|
||||
log.Warn("Failed to load device remarks from %s: %v (remark edits are refused until the file is fixed)", notesFile, err)
|
||||
} else {
|
||||
log.Info("Device remarks loaded from %s (%d remark(s))", notesFile, len(deviceNotes.Snapshot()))
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -1276,6 +1307,10 @@ func main() {
|
||||
Bind: bindAddr,
|
||||
// Devices bound to a web user are invisible/unreachable through MCP.
|
||||
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).
|
||||
@@ -1416,6 +1451,8 @@ func main() {
|
||||
BrandName: brandName,
|
||||
SSO: ssoDetector,
|
||||
DeviceACL: deviceACL,
|
||||
DeviceNotes: deviceNotes,
|
||||
DeviceGroups: deviceGroups,
|
||||
TransferTarget: transferTarget,
|
||||
TransferDays: transferDays,
|
||||
TransferTransport: transferTransport,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+66
-1
@@ -43,6 +43,32 @@ type DeviceOwner interface {
|
||||
Owner(deviceID string) string
|
||||
}
|
||||
|
||||
// DeviceRemarks reports the web console's remark for a device ("" when none).
|
||||
// Implemented by web.DeviceNotes; declared as an interface for the same reason
|
||||
// as DeviceOwner. A nil table simply leaves the field out of the host JSON.
|
||||
type DeviceRemarks interface {
|
||||
Note(deviceID string) string
|
||||
}
|
||||
|
||||
// deviceRemarkSnapshotter is an optional DeviceRemarks capability: returning
|
||||
// the whole table lets a host listing take one snapshot instead of a read lock
|
||||
// per device, so a remark save's fsync cannot stall the call and one listing
|
||||
// cannot mix pre-edit and post-edit labels. Implemented by web.DeviceNotes.
|
||||
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.
|
||||
@@ -64,6 +90,37 @@ func (s *Server) ownerChecker() func(deviceID string) bool {
|
||||
return func(id string) bool { return s.cfg.DeviceACL.Owner(id) == "" }
|
||||
}
|
||||
|
||||
// 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 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 v
|
||||
}
|
||||
|
||||
// Config is filled by cmd/main.go from the YAMA_MCP_* environment variables;
|
||||
// the package itself never reads the environment, so tests are deterministic.
|
||||
type Config struct {
|
||||
@@ -90,6 +147,14 @@ type Config struct {
|
||||
// in list_hosts/get_host_detail and unreachable by ID in every device-
|
||||
// targeted tool, even if its ID is known.
|
||||
DeviceACL DeviceOwner
|
||||
|
||||
// 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
|
||||
@@ -483,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) 本实现不维护备注与授权状态:list_hosts / get_host_detail 不返回 remark/authStatus/tls;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) 列表与详情都是调用时刻的快照,主机可能在操作期间掉线;写操作前先读一次现状,动作后再复核。`
|
||||
@@ -142,8 +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))
|
||||
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"
|
||||
}
|
||||
@@ -155,12 +162,20 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp
|
||||
if d.Online {
|
||||
clientType = s.clientType(d.ID)
|
||||
}
|
||||
// query matches computer name, remark and IP. The two servers keep no
|
||||
// remark column, so name+IP is the full set here.
|
||||
if q != "" && !strings.Contains(strings.ToLower(d.Name), q) && !strings.Contains(strings.ToLower(ip), q) {
|
||||
remark := ""
|
||||
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
|
||||
// console's label (empty unless an admin set it).
|
||||
if q != "" && !strings.Contains(strings.ToLower(d.Name), q) &&
|
||||
!strings.Contains(strings.ToLower(ip), q) &&
|
||||
!strings.Contains(strings.ToLower(remark), q) {
|
||||
continue
|
||||
}
|
||||
if nameF != "" && !strings.Contains(strings.ToLower(d.Name), nameF) {
|
||||
if nameF != "" && !strings.Contains(strings.ToLower(d.Name), nameF) &&
|
||||
!strings.Contains(strings.ToLower(remark), nameF) {
|
||||
continue
|
||||
}
|
||||
if ipF != "" && !strings.Contains(strings.ToLower(ip), ipF) {
|
||||
@@ -185,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))
|
||||
hosts = append(hosts, s.hostJSON(d, view))
|
||||
}
|
||||
|
||||
structured := map[string]any{
|
||||
@@ -205,10 +220,17 @@ 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, remark, clientType of
|
||||
// an offline entry) are omitted rather than fabricated.
|
||||
func (s *Server) hostJSON(d hub.DeviceInfo) map[string]any {
|
||||
// Fields the Go server does not know (authStatus, tls, clientType of an
|
||||
// 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"
|
||||
}
|
||||
@@ -218,6 +240,11 @@ func (s *Server) hostJSON(d hub.DeviceInfo) map[string]any {
|
||||
"group": group,
|
||||
"online": d.Online,
|
||||
}
|
||||
if view.remarkOf != nil {
|
||||
if remark := view.remarkOf(d.ID); remark != "" {
|
||||
h["remark"] = remark
|
||||
}
|
||||
}
|
||||
if d.Version != "" {
|
||||
h["version"] = d.Version
|
||||
}
|
||||
@@ -300,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)
|
||||
host, rerr := s.lookupHost(args.ID, online, offline, s.hostView())
|
||||
if rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
@@ -313,10 +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()
|
||||
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)
|
||||
host, rerr := s.lookupHost(id, online, offline, view)
|
||||
if rerr != nil {
|
||||
results = append(results, map[string]any{
|
||||
"id": id,
|
||||
@@ -375,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) (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)
|
||||
h := s.hostJSON(d, view)
|
||||
h["capabilities"] = s.capabilities(d)
|
||||
return h, nil
|
||||
}
|
||||
if d, ok := offline[id]; ok {
|
||||
return s.hostJSON(d), nil
|
||||
return s.hostJSON(d, view), nil
|
||||
}
|
||||
return nil, errf(CodeOffline, "Host not found or offline: %s", id)
|
||||
}
|
||||
@@ -449,13 +477,13 @@ func appendHostRows(text string, hosts []map[string]any) string {
|
||||
for _, h := range hosts {
|
||||
online, _ := h["online"].(bool)
|
||||
rows = append(rows, []string{
|
||||
tableText(h["id"]), tableText(h["name"]), tableText(h["ip"]),
|
||||
tableText(h["group"]), tableText(h["os"]), strconv.FormatBool(online),
|
||||
tableText(h["clientType"]), tableText(h["last_seen"]),
|
||||
tableText(h["id"]), tableText(h["name"]), tableText(h["remark"]),
|
||||
tableText(h["ip"]), tableText(h["group"]), tableText(h["os"]),
|
||||
strconv.FormatBool(online), tableText(h["clientType"]), tableText(h["last_seen"]),
|
||||
})
|
||||
}
|
||||
return appendRows(text,
|
||||
[]string{"id", "name", "ip", "group", "os", "online", "clientType", "last_seen"},
|
||||
[]string{"id", "name", "remark", "ip", "group", "os", "online", "clientType", "last_seen"},
|
||||
rows)
|
||||
}
|
||||
|
||||
|
||||
@@ -213,8 +213,35 @@ func TestAppendRowsSanitizesCells(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// fakeRemarks stands in for web.DeviceNotes: the map value is the remark. It
|
||||
// only implements Note, so it exercises the per-device fallback path.
|
||||
type fakeRemarks map[string]string
|
||||
|
||||
func (f fakeRemarks) Note(deviceID string) string { return f[deviceID] }
|
||||
|
||||
// fakeRemarkSnapshot also implements Notes(), the snapshot capability the
|
||||
// shipped web.DeviceNotes provides.
|
||||
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)
|
||||
@@ -236,11 +263,11 @@ func TestListHostsPoolsAndProjection(t *testing.T) {
|
||||
}
|
||||
// Text-only MCP clients never see structuredContent, so the table in the
|
||||
// text block must carry the id every follow-up call is addressed by.
|
||||
if !strings.Contains(text, "id\tname\tip\tgroup\tos\tonline\tclientType\tlast_seen") {
|
||||
if !strings.Contains(text, "id\tname\tremark\tip\tgroup\tos\tonline\tclientType\tlast_seen") {
|
||||
t.Fatalf("text = %q, want host table header", text)
|
||||
}
|
||||
if !strings.Contains(text, "1001\tALPHA\t10.0.0.1\tdefault\tWindows 10\ttrue\tEXE\t-") {
|
||||
t.Fatalf("text = %q, want ALPHA row with id first", text)
|
||||
if !strings.Contains(text, "1001\tALPHA\tReception PC\t10.0.0.1\tdefault\tWindows 10\ttrue\tEXE\t-") {
|
||||
t.Fatalf("text = %q, want ALPHA row with id first and remark", text)
|
||||
}
|
||||
|
||||
alpha := hosts[0]
|
||||
@@ -268,7 +295,16 @@ func TestListHostsPoolsAndProjection(t *testing.T) {
|
||||
if _, ok := alpha["last_seen"]; ok {
|
||||
t.Fatal("online host carries last_seen")
|
||||
}
|
||||
for _, absent := range []string{"remark", "authStatus", "tls"} {
|
||||
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"])
|
||||
}
|
||||
for _, absent := range []string{"authStatus", "tls"} {
|
||||
if _, ok := alpha[absent]; ok {
|
||||
t.Fatalf("%s present but the Go server has no such data", absent)
|
||||
}
|
||||
@@ -306,6 +342,7 @@ func TestListHostsPoolsAndProjection(t *testing.T) {
|
||||
|
||||
func TestListHostsFilters(t *testing.T) {
|
||||
f := newLocalFixture(t)
|
||||
f.srv.cfg.DeviceRemarks = fakeRemarks{"1001": "Reception PC"}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
@@ -313,6 +350,7 @@ func TestListHostsFilters(t *testing.T) {
|
||||
want []string
|
||||
}{
|
||||
{"name substring", `{"name":"beta"}`, []string{"1002"}},
|
||||
{"name matches remark", `{"name":"reception"}`, []string{"1001"}},
|
||||
{"group substring", `{"group":"office"}`, []string{"1002", "1003"}},
|
||||
{"os substring case-insensitive", `{"os":"windows"}`, []string{"1001", "1002"}},
|
||||
{"client type", `{"client_type":"lnx"}`, []string{"1003"}},
|
||||
@@ -320,6 +358,7 @@ func TestListHostsFilters(t *testing.T) {
|
||||
{"peer ip fallback", `{"ip":"192.168.1.2"}`, []string{"1002"}},
|
||||
{"query matches name", `{"query":"gamma"}`, []string{"1003"}},
|
||||
{"query matches ip", `{"query":"10.0.0.1"}`, []string{"1001"}},
|
||||
{"query matches remark", `{"query":"reception"}`, []string{"1001"}},
|
||||
{"filters are ANDed", `{"group":"office","os":"ubuntu"}`, []string{"1003"}},
|
||||
{"no match", `{"name":"zzz"}`, nil},
|
||||
}
|
||||
@@ -355,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)
|
||||
|
||||
|
||||
@@ -38,6 +38,8 @@ const (
|
||||
auditDeviceTransfer = "admin.device.transfer"
|
||||
auditDeviceBind = "admin.device.bind"
|
||||
auditDeviceUnbind = "admin.device.unbind"
|
||||
auditDeviceRemark = "admin.device.remark"
|
||||
auditDeviceGroup = "admin.device.group"
|
||||
auditQuery = "admin.audit.query"
|
||||
)
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// MaxRemarkRunes bounds the per-device remark. The card renders it next to
|
||||
// the computer name ("host (remark)"), so this is a label, not a note field:
|
||||
// long enough for "Reception PC - 3rd floor", short enough to keep the card
|
||||
// intact.
|
||||
const MaxRemarkRunes = 64
|
||||
|
||||
// deviceNotesFileVersion is the on-disk format we write. A file from a newer
|
||||
// version is refused instead of being read as v1 and overwritten.
|
||||
const deviceNotesFileVersion = 1
|
||||
|
||||
// DeviceNoteEntry is one device remark.
|
||||
type DeviceNoteEntry struct {
|
||||
Note string `json:"note"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
UpdatedBy string `json:"updated_by,omitempty"`
|
||||
}
|
||||
|
||||
// deviceNotesFile is the on-disk shape of device_notes.json. Version is
|
||||
// reserved for future migrations; v1 is a flat deviceID -> remark map.
|
||||
type deviceNotesFile struct {
|
||||
Version int `json:"version"`
|
||||
Devices map[string]DeviceNoteEntry `json:"devices"`
|
||||
}
|
||||
|
||||
// DeviceNotes is the per-device remark table used by the web console. Remarks
|
||||
// are labels, not access control, so the table is independent of DeviceACL: a
|
||||
// device can carry a remark whether or not it is bound to an owner. An empty
|
||||
// Path disables persistence (tests).
|
||||
type DeviceNotes struct {
|
||||
mu sync.RWMutex
|
||||
path string
|
||||
entries map[string]DeviceNoteEntry
|
||||
// loadErr records why Load failed. While set, Set/Remove refuse to write:
|
||||
// persisting the in-memory (empty) table would replace the unreadable file
|
||||
// and destroy every remark it still holds.
|
||||
loadErr error
|
||||
}
|
||||
|
||||
// NewDeviceNotes returns an empty table backed by path.
|
||||
func NewDeviceNotes(path string) *DeviceNotes {
|
||||
return &DeviceNotes{path: path, entries: make(map[string]DeviceNoteEntry)}
|
||||
}
|
||||
|
||||
// Load reads Path into memory. A missing file is an empty table. A malformed
|
||||
// file (or one written by a newer version) is returned as an error and leaves
|
||||
// the table write-disabled: the caller may log and continue serving, but the
|
||||
// unreadable file must survive so its remarks can be recovered.
|
||||
func (n *DeviceNotes) Load() error {
|
||||
if n.path == "" {
|
||||
return nil
|
||||
}
|
||||
data, err := os.ReadFile(n.path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return n.failLoad(fmt.Errorf("read %s: %w", n.path, err))
|
||||
}
|
||||
var f deviceNotesFile
|
||||
if err := json.Unmarshal(data, &f); err != nil {
|
||||
return n.failLoad(fmt.Errorf("parse %s: %w", n.path, err))
|
||||
}
|
||||
if f.Version > deviceNotesFileVersion {
|
||||
return n.failLoad(fmt.Errorf("unsupported %s version %d (this server writes %d)",
|
||||
n.path, f.Version, deviceNotesFileVersion))
|
||||
}
|
||||
entries := make(map[string]DeviceNoteEntry, len(f.Devices))
|
||||
for id, e := range f.Devices {
|
||||
id = strings.TrimSpace(id)
|
||||
// Apply the same invariants Set enforces: a hand-edited or restored
|
||||
// file must not put a multi-line / over-long label on a card.
|
||||
e.Note = capRunes(sanitizeLabel(e.Note), MaxRemarkRunes)
|
||||
if id == "" || e.Note == "" {
|
||||
continue
|
||||
}
|
||||
entries[id] = e
|
||||
}
|
||||
n.mu.Lock()
|
||||
n.entries = entries
|
||||
n.loadErr = nil
|
||||
n.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// failLoad records the reason writes are disabled and returns it.
|
||||
func (n *DeviceNotes) failLoad(err error) error {
|
||||
n.mu.Lock()
|
||||
n.loadErr = err
|
||||
n.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
// Note returns the remark of deviceID, or "" when it has none.
|
||||
func (n *DeviceNotes) Note(deviceID string) string {
|
||||
if n == nil {
|
||||
return ""
|
||||
}
|
||||
n.mu.RLock()
|
||||
defer n.mu.RUnlock()
|
||||
return n.entries[deviceID].Note
|
||||
}
|
||||
|
||||
// Notes returns a copy of the deviceID -> remark map. Callers that look up
|
||||
// many devices in one pass (MCP host listings) take this snapshot instead of a
|
||||
// read lock per device, so a save's fsync cannot stall the whole listing.
|
||||
func (n *DeviceNotes) Notes() map[string]string {
|
||||
if n == nil {
|
||||
return map[string]string{}
|
||||
}
|
||||
n.mu.RLock()
|
||||
defer n.mu.RUnlock()
|
||||
out := make(map[string]string, len(n.entries))
|
||||
for id, e := range n.entries {
|
||||
out[id] = e.Note
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Snapshot returns a copy of the table (for logs and tests).
|
||||
func (n *DeviceNotes) Snapshot() map[string]DeviceNoteEntry {
|
||||
if n == nil {
|
||||
return map[string]DeviceNoteEntry{}
|
||||
}
|
||||
n.mu.RLock()
|
||||
defer n.mu.RUnlock()
|
||||
out := make(map[string]DeviceNoteEntry, len(n.entries))
|
||||
for id, e := range n.entries {
|
||||
out[id] = e
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Set stores note for deviceID. An empty note clears the remark. Control
|
||||
// characters (line breaks etc.) are folded to spaces and the result is
|
||||
// trimmed; more than MaxRemarkRunes runes is rejected. On persistence failure
|
||||
// the in-memory table is rolled back so it never claims a remark that would
|
||||
// not survive a restart.
|
||||
func (n *DeviceNotes) Set(deviceID, note, actor string) error {
|
||||
deviceID = strings.TrimSpace(deviceID)
|
||||
if deviceID == "" {
|
||||
return fmt.Errorf("empty device id")
|
||||
}
|
||||
note = sanitizeLabel(note)
|
||||
if utf8.RuneCountInString(note) > MaxRemarkRunes {
|
||||
return fmt.Errorf("remark is too long (max %d characters)", MaxRemarkRunes)
|
||||
}
|
||||
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
if n.loadErr != nil {
|
||||
return fmt.Errorf("device remarks unavailable: %w", n.loadErr)
|
||||
}
|
||||
prev, had := n.entries[deviceID]
|
||||
if note == "" {
|
||||
if !had {
|
||||
return nil
|
||||
}
|
||||
delete(n.entries, deviceID)
|
||||
} else {
|
||||
n.entries[deviceID] = DeviceNoteEntry{Note: note, UpdatedAt: time.Now().UTC(), UpdatedBy: actor}
|
||||
}
|
||||
if err := n.saveLocked(); err != nil {
|
||||
if had {
|
||||
n.entries[deviceID] = prev
|
||||
} else {
|
||||
delete(n.entries, deviceID)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove drops the remark of one device (idempotent). Called when the device
|
||||
// record is deleted so a future client reusing the same ID cannot inherit the
|
||||
// label.
|
||||
func (n *DeviceNotes) Remove(deviceID string) error {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
deviceID = strings.TrimSpace(deviceID)
|
||||
if deviceID == "" {
|
||||
return nil
|
||||
}
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
if n.loadErr != nil {
|
||||
return fmt.Errorf("device remarks unavailable: %w", n.loadErr)
|
||||
}
|
||||
prev, ok := n.entries[deviceID]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
delete(n.entries, deviceID)
|
||||
if err := n.saveLocked(); err != nil {
|
||||
n.entries[deviceID] = prev
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sanitizeLabel folds line breaks and other control characters (including
|
||||
// bidi/zero-width formatting runes, which could reorder the card title) to
|
||||
// spaces so the label always renders on one line, then trims both ends.
|
||||
// Shared by the per-device remark and group tables.
|
||||
func sanitizeLabel(s string) string {
|
||||
s = strings.Map(func(r rune) rune {
|
||||
if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) {
|
||||
return ' '
|
||||
}
|
||||
return r
|
||||
}, s)
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
// capRunes truncates s to max runes. Used on values read back from disk, where
|
||||
// an older/hand-edited file may exceed the current limit. Trims again after the
|
||||
// cut so the stored label cannot end in an invisible space.
|
||||
func capRunes(s string, max int) string {
|
||||
if utf8.RuneCountInString(s) <= max {
|
||||
return s
|
||||
}
|
||||
return strings.TrimSpace(string([]rune(s)[:max]))
|
||||
}
|
||||
|
||||
// saveLocked writes the table via a temp file + rename. Caller holds n.mu.
|
||||
func (n *DeviceNotes) saveLocked() error {
|
||||
if n.path == "" {
|
||||
return nil
|
||||
}
|
||||
f := deviceNotesFile{Version: 1, Devices: n.entries}
|
||||
data, err := json.MarshalIndent(f, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode device notes: %w", err)
|
||||
}
|
||||
dir := filepath.Dir(n.path)
|
||||
if dir == "" {
|
||||
dir = "."
|
||||
}
|
||||
tmp, err := os.CreateTemp(dir, ".device_notes-*.tmp")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create temp notes: %w", err)
|
||||
}
|
||||
tmpName := tmp.Name()
|
||||
defer func() { _ = os.Remove(tmpName) }() // no-op after a successful rename
|
||||
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
_ = tmp.Close()
|
||||
return fmt.Errorf("write temp notes: %w", err)
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
_ = tmp.Close()
|
||||
return fmt.Errorf("sync temp notes: %w", err)
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return fmt.Errorf("close temp notes: %w", err)
|
||||
}
|
||||
if err := os.Rename(tmpName, n.path); err != nil {
|
||||
return fmt.Errorf("rename notes: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
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)
|
||||
}
|
||||
|
||||
// Notes() is the bulk snapshot callers take per listing; it must be a
|
||||
// copy, not a live view of the table.
|
||||
if err := notes.Set("dev-3", "Bulk", "admin"); err != nil {
|
||||
t.Fatalf("Set dev-3: %v", err)
|
||||
}
|
||||
snap := notes.Notes()
|
||||
if snap["dev-3"] != "Bulk" {
|
||||
t.Fatalf("Notes()[dev-3] = %q, want %q", snap["dev-3"], "Bulk")
|
||||
}
|
||||
snap["dev-3"] = "mutated"
|
||||
if got := notes.Note("dev-3"); got != "Bulk" {
|
||||
t.Fatalf("mutating the snapshot changed the store: %q", 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)
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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,8 @@ type Server struct {
|
||||
auth *wsauth.Authenticator
|
||||
history *devicehistory.Store // nil → no offline devices
|
||||
deviceACL *DeviceACL // nil → no per-device owner filtering
|
||||
deviceNotes *DeviceNotes // nil → no "edit remark" entry in the UI
|
||||
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
|
||||
@@ -96,6 +98,15 @@ type Config struct {
|
||||
// behaviour: every authenticated session sees every device). The shipped
|
||||
// server always wires one; tests may omit it.
|
||||
DeviceACL *DeviceACL
|
||||
// DeviceNotes is the per-device remark table rendered on the card as
|
||||
// "hostname (remark)". nil disables the "edit remark" menu entry: the
|
||||
// device_list reply reports remarkEdit only when this is wired, so the
|
||||
// shared page hides the action on a backend that does not implement it
|
||||
// (the MFC server).
|
||||
DeviceNotes *DeviceNotes
|
||||
// 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
|
||||
@@ -138,6 +149,8 @@ func (s *Server) WithConfig(cfg Config) *Server {
|
||||
s.brandName = resolveBrandName(cfg.BrandName, s.basePath)
|
||||
s.sso = cfg.SSO
|
||||
s.deviceACL = cfg.DeviceACL
|
||||
s.deviceNotes = cfg.DeviceNotes
|
||||
s.deviceGroups = cfg.DeviceGroups
|
||||
s.transferTarget = cfg.TransferTarget
|
||||
s.transferDays = cfg.TransferDays
|
||||
s.transferTransport = cfg.TransferTransport
|
||||
@@ -166,6 +179,8 @@ func (s *Server) Start() error {
|
||||
withLoginRateLimiters(s.loginIPLimit, s.loginUserLimit).
|
||||
withTrustForwardedFor(s.trustForwardedFor).
|
||||
withDeviceACL(s.deviceACL).
|
||||
withDeviceNotes(s.deviceNotes).
|
||||
withDeviceGroups(s.deviceGroups).
|
||||
withTransferDefaults(s.transferTarget, s.transferDays, s.transferTransport)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
@@ -161,6 +161,8 @@ type wsHub struct {
|
||||
devices *hub.Hub
|
||||
history *devicehistory.Store // nil → device_list stays online-only
|
||||
acl *DeviceACL // nil → every device is public (tests/embedders)
|
||||
notes *DeviceNotes // nil → no "edit remark" entry (MFC backend)
|
||||
groups *DeviceGroups // nil → no "edit group" entry (MFC backend)
|
||||
log *logger.Logger
|
||||
|
||||
mu sync.RWMutex
|
||||
@@ -237,6 +239,24 @@ func (h *wsHub) withDeviceACL(acl *DeviceACL) *wsHub {
|
||||
return h
|
||||
}
|
||||
|
||||
// withDeviceNotes installs the per-device remark table. A nil table disables
|
||||
// "edit remark": its presence is what the device_list reply reports as
|
||||
// remarkEdit, so the shared page only offers the menu entry on a backend that
|
||||
// implements it (the MFC server does not).
|
||||
func (h *wsHub) withDeviceNotes(notes *DeviceNotes) *wsHub {
|
||||
h.notes = notes
|
||||
return h
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
||||
@@ -103,6 +104,10 @@ func (h *wsHub) dispatch(c *wsClient, cmd string, raw []byte) {
|
||||
h.handleBindDevice(c, raw)
|
||||
case "unbind_device":
|
||||
h.handleUnbindDevice(c, raw)
|
||||
case "set_device_remark":
|
||||
h.handleSetDeviceRemark(c, raw)
|
||||
case "set_device_group":
|
||||
h.handleSetDeviceGroup(c, raw)
|
||||
case "get_groups":
|
||||
h.handleGetGroups(c, raw)
|
||||
case "query_audit":
|
||||
@@ -121,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.
|
||||
@@ -800,6 +815,12 @@ func (h *wsHub) handleGetDevices(c *wsClient, raw []byte) {
|
||||
"target": h.transferTarget,
|
||||
"days": h.transferDays,
|
||||
},
|
||||
// Same convention for "edit remark": only a backend that wires a
|
||||
// remark table reports it, so the shared page hides the menu entry
|
||||
// on the MFC server.
|
||||
"remarkEdit": h.notes != nil,
|
||||
// ... and for "edit group", which only the Go server implements.
|
||||
"groupEdit": h.groups != nil,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -809,6 +830,13 @@ func (h *wsHub) handleGetDevices(c *wsClient, raw []byte) {
|
||||
type deviceListItem struct {
|
||||
hub.DeviceInfo
|
||||
Owner string `json:"owner,omitempty"`
|
||||
// Remark is the operator's label for this host, rendered as
|
||||
// "hostname (remark)" on the card. Set by the Go web console only.
|
||||
Remark string `json:"remark,omitempty"`
|
||||
// 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.
|
||||
@@ -821,6 +849,17 @@ type deviceListItem struct {
|
||||
// is either public or owned by the caller, so the field adds nothing.
|
||||
func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem {
|
||||
all := h.listDevicesWithOffline()
|
||||
// One snapshot instead of a read lock per device: Set holds the write
|
||||
// lock across the temp-file fsync + rename, and a slow disk must not
|
||||
// block every console's device list.
|
||||
var remarks map[string]DeviceNoteEntry
|
||||
if h.notes != nil {
|
||||
remarks = h.notes.Snapshot()
|
||||
}
|
||||
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) {
|
||||
@@ -831,6 +870,15 @@ func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem {
|
||||
owner = h.acl.Owner(d.ID)
|
||||
}
|
||||
item := deviceListItem{DeviceInfo: d, Owner: owner}
|
||||
if remarks != nil {
|
||||
item.Remark = remarks[d.ID].Note
|
||||
}
|
||||
// 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
|
||||
@@ -1281,6 +1329,8 @@ func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) {
|
||||
// The device is gone; its binding must not survive a later
|
||||
// client that happens to reuse the same ID.
|
||||
h.dropDeviceBinding(in.ID)
|
||||
h.dropDeviceNote(in.ID)
|
||||
h.dropDeviceGroup(in.ID)
|
||||
h.audit(c, false, auditDeviceAdmin, map[string]any{
|
||||
"device_id": in.ID,
|
||||
"mode": "uninstall",
|
||||
@@ -1322,6 +1372,8 @@ func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) {
|
||||
return
|
||||
}
|
||||
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",
|
||||
@@ -1573,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
|
||||
@@ -1590,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)
|
||||
@@ -1716,6 +1784,146 @@ func (h *wsHub) handleUnbindDevice(c *wsClient, raw []byte) {
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": true, "count": len(ids)}))
|
||||
}
|
||||
|
||||
// handleSetDeviceRemark stores the free-text label shown on the device card
|
||||
// ("hostname (remark)"). Admin role only, and only for a device the caller can
|
||||
// access: the ACL keeps a private device out of other admins' cards, and the
|
||||
// server enforces the same rule so a hand-crafted request cannot label it
|
||||
// either. An empty remark clears the label.
|
||||
func (h *wsHub) handleSetDeviceRemark(c *wsClient, raw []byte) {
|
||||
const replyCmd = "set_device_remark_result"
|
||||
if !h.requireAdmin(c, raw, replyCmd) {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
ID string `json:"id"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
id := ""
|
||||
fail := func(msg, reason string) {
|
||||
h.audit(c, true, auditDeviceRemark, map[string]any{
|
||||
"device_id": id,
|
||||
"ok": false,
|
||||
"reason": reason,
|
||||
"error": msg,
|
||||
})
|
||||
// id lets the page drop a late reply meant for a dialog it has since
|
||||
// closed and replaced with another device's.
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "id": id, "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
|
||||
}
|
||||
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 := sanitizeLabel(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,
|
||||
}))
|
||||
}
|
||||
|
||||
// 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,
|
||||
})
|
||||
// id lets the page drop a late reply meant for a dialog it has since
|
||||
// closed and replaced with another device's.
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "id": id, "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 {
|
||||
@@ -1814,6 +2022,27 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
+198
-16
@@ -657,8 +657,8 @@
|
||||
max-width: 240px;
|
||||
flex-shrink: 1;
|
||||
}
|
||||
/* 卡片操作:右上角只留一个「…」按钮,点开才弹出菜单(终端 / 绑定 /
|
||||
转移 / 删除),菜单项带简短功能说明。独立于卡片本体点击事件
|
||||
/* 卡片操作:右上角只留一个「…」按钮,点开才弹出菜单(终端 / 备注 /
|
||||
分组 / 绑定 / 转移 / 删除),菜单项带简短功能说明。独立于卡片本体点击事件
|
||||
(onclick stopPropagation)。List 视图卡片是一行,按钮垂直居中。 */
|
||||
.device-card .card-actions {
|
||||
position: absolute;
|
||||
@@ -725,6 +725,8 @@
|
||||
margin-top: 1px;
|
||||
}
|
||||
.card-menu-item.term .card-menu-icon { color: #4caf50; }
|
||||
.card-menu-item.edit .card-menu-icon { color: #4dabf7; }
|
||||
.card-menu-item.group .card-menu-icon { color: #b197fc; }
|
||||
.card-menu-item.bind .card-menu-icon { color: #e67e22; }
|
||||
.card-menu-item.transfer .card-menu-icon { color: #d68910; }
|
||||
.card-menu-item.del .card-menu-icon { color: #e74c3c; }
|
||||
@@ -2193,7 +2195,7 @@
|
||||
</div>
|
||||
|
||||
<!-- Logout Confirmation Modal -->
|
||||
<div class="modal-overlay" id="logout-confirm-modal" onclick="if(event.target===this)cancelLogout()">
|
||||
<div class="modal-overlay" id="logout-confirm-modal">
|
||||
<div class="confirm-modal-content">
|
||||
<div class="confirm-modal-icon">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
@@ -2212,7 +2214,7 @@
|
||||
</div>
|
||||
|
||||
<!-- Delete Device Confirmation Modal(离线=删除历史记录;在线=下发卸载主机) -->
|
||||
<div class="modal-overlay" id="delete-device-modal" onclick="if(event.target===this)cancelDeleteDevice()">
|
||||
<div class="modal-overlay" id="delete-device-modal">
|
||||
<div class="confirm-modal-content">
|
||||
<div class="confirm-modal-icon">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
@@ -2232,7 +2234,7 @@
|
||||
</div>
|
||||
|
||||
<!-- Transfer Host Modal(仅 Go 后端:device_list 带 transfer 字段时才有入口) -->
|
||||
<div class="modal-overlay" id="transfer-device-modal" onclick="if(event.target===this)cancelTransferDevice()">
|
||||
<div class="modal-overlay" id="transfer-device-modal">
|
||||
<div class="modal-content" style="max-width:460px;">
|
||||
<div class="modal-header">
|
||||
<h3>Transfer Host</h3>
|
||||
@@ -2262,7 +2264,7 @@
|
||||
</div>
|
||||
|
||||
<!-- Device Binding Modal(仅内置 admin 超级管理员可见) -->
|
||||
<div class="modal-overlay" id="bind-device-modal" onclick="if(event.target===this)closeBindModal()">
|
||||
<div class="modal-overlay" id="bind-device-modal">
|
||||
<div class="modal-content" style="max-width:440px;">
|
||||
<div class="modal-header">
|
||||
<h3>Device Binding</h3>
|
||||
@@ -2289,10 +2291,62 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 修改备注(Go 后端):备注是卡片标题旁的显示标签 "hostname (备注)"。 -->
|
||||
<div class="modal-overlay" id="remark-device-modal">
|
||||
<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>
|
||||
|
||||
<!-- 修改分组(Go 后端):覆盖主机上报的分组,仅影响本服务端的显示/过滤/MCP。 -->
|
||||
<div class="modal-overlay" id="group-device-modal">
|
||||
<div class="modal-content" style="max-width:440px;">
|
||||
<div class="modal-header">
|
||||
<h3>Edit Group</h3>
|
||||
<button class="modal-close" onclick="closeGroupModal()">×</button>
|
||||
</div>
|
||||
<div class="user-form">
|
||||
<div id="group-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;">
|
||||
Group
|
||||
</label>
|
||||
<input type="text" id="group-input" list="group-options" maxlength="23"
|
||||
placeholder="e.g. Office" autocomplete="off">
|
||||
<datalist id="group-options"></datalist>
|
||||
<div style="font-size:12px;color:#888;margin-top:8px;">
|
||||
Changes how this server groups and filters the host. Leave it empty to use the
|
||||
group the host reports. Max 23 characters.
|
||||
</div>
|
||||
<div style="display:flex;gap:8px;margin-top:14px;">
|
||||
<button onclick="confirmSetGroup()">Save</button>
|
||||
<button class="cancel-btn" onclick="closeGroupModal()">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Generic alert / confirmation dialog. Replaces native alert()/confirm():
|
||||
their button labels come from the browser locale (e.g. German on a
|
||||
German system) and do not match the app. -->
|
||||
<div class="modal-overlay" id="app-dialog" onclick="if(event.target===this)closeAppDialog(false)"
|
||||
<div class="modal-overlay" id="app-dialog"
|
||||
onkeydown="if(event.key==='Escape')closeAppDialog(false)">
|
||||
<div class="confirm-modal-content" id="app-dialog-content" role="dialog" aria-modal="true"
|
||||
aria-labelledby="app-dialog-title" aria-describedby="app-dialog-message">
|
||||
@@ -3020,6 +3074,9 @@
|
||||
// 只有实现了「转移主机」的后端(Go)才会带这个字段;
|
||||
// MFC 复用同一份页面但不下发它,按钮因此不会出现。
|
||||
transferCfg = msg.transfer || null;
|
||||
// 备注/分组编辑同理由后端能力位决定(Go 才有;MFC 页面不显示)。
|
||||
remarkEditAvailable = msg.remarkEdit === true;
|
||||
groupEditAvailable = msg.groupEdit === true;
|
||||
// Keep current page (renderDeviceList adjusts if out of range)
|
||||
renderDeviceList();
|
||||
renderWallSidebar();
|
||||
@@ -3339,6 +3396,25 @@
|
||||
appAlert(msg.msg || 'Failed to unbind device', 'Device Binding');
|
||||
}
|
||||
break;
|
||||
case 'set_device_remark_result':
|
||||
// 只收尾"当前开着的那台设备"的对话框:请求在飞时管理员可能
|
||||
// 已经取消并打开了另一台设备,迟到的回复不能把它关掉。列表
|
||||
// 刷新由服务端的 devices_changed 广播负责,这里不重复拉取。
|
||||
if (msg.id !== undefined && String(msg.id) !== pendingRemarkDeviceId) break;
|
||||
if (msg.ok) {
|
||||
closeRemarkModal();
|
||||
} else {
|
||||
appAlert(msg.msg || 'Failed to save remark', 'Edit Remark');
|
||||
}
|
||||
break;
|
||||
case 'set_device_group_result':
|
||||
if (msg.id !== undefined && String(msg.id) !== pendingGroupDeviceId) break;
|
||||
if (msg.ok) {
|
||||
closeGroupModal();
|
||||
} 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.
|
||||
@@ -5109,14 +5185,18 @@
|
||||
}
|
||||
|
||||
// ---- 卡片「…」操作菜单 ----
|
||||
// 无论有几个操作,卡片上只显示一个「…」;点开弹出的菜单里才是终端/绑定/
|
||||
// 转移/删除,每项带一句功能说明。菜单项在点击时按设备实时生成,权限和
|
||||
// 无论有几个操作,卡片上只显示一个「…」;点开弹出的菜单里才是终端/备注/
|
||||
// 分组/绑定/转移/删除,每项带一句功能说明。菜单项在点击时按设备实时生成,权限和
|
||||
// 在线状态不会因为列表渲染后变化而过期。
|
||||
let cardMenuEl = null;
|
||||
let cardMenuBtn = null;
|
||||
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">' +
|
||||
'<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>',
|
||||
group: '<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="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/></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">' +
|
||||
'<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">' +
|
||||
@@ -5126,9 +5206,22 @@
|
||||
'<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 / groupEdit 才出现;MFC 复用同一份页面但不下发这些字段。
|
||||
let remarkEditAvailable = false;
|
||||
let groupEditAvailable = false;
|
||||
|
||||
function canEditRemark() {
|
||||
return remarkEditAvailable && currentUserRole === 'admin';
|
||||
}
|
||||
|
||||
function canEditGroup() {
|
||||
return groupEditAvailable && currentUserRole === 'admin';
|
||||
}
|
||||
|
||||
function hasCardActions(d) {
|
||||
if (d.online !== false) return true; // 在线设备至少有终端
|
||||
return canBindDevices() || canDeleteDevices();
|
||||
return canEditRemark() || canEditGroup() || canBindDevices() || canDeleteDevices();
|
||||
}
|
||||
|
||||
function cardMenuEntries(d) {
|
||||
@@ -5138,6 +5231,14 @@
|
||||
out.push({ kind: 'term', label: 'Terminal', desc: 'Open a remote shell',
|
||||
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 (canEditGroup()) {
|
||||
out.push({ kind: 'group', label: 'Edit group', desc: 'Move this host to another group',
|
||||
run: () => openGroupModal(d.id) });
|
||||
}
|
||||
if (canBindDevices()) {
|
||||
out.push({ kind: 'bind', label: 'Bind owner', desc: 'Assign this host to a user',
|
||||
run: () => openBindModal(d.id) });
|
||||
@@ -5260,7 +5361,7 @@
|
||||
const rtt = d.rtt || '-';
|
||||
const ver = d.version || '-';
|
||||
const activeWin = d.activeWindow || '';
|
||||
// 操作全部收进右上角的「…」菜单(终端 / 绑定 / 转移 / 删除),
|
||||
// 操作全部收进右上角的「…」菜单(终端 / 备注 / 分组 / 绑定 / 转移 / 删除),
|
||||
// 具体条目见 cardMenuEntries。这里只决定按钮是否出现。
|
||||
const actionsHtml = hasCardActions(d)
|
||||
? '<div class="card-actions">' +
|
||||
@@ -5290,15 +5391,15 @@
|
||||
? '<span class="meta-item offline-badge">Offline</span>'
|
||||
: '<span class="meta-item rtt ' + getRttClass(rtt) + '">RTT: ' + escapeHtml(rtt) + '</span>') +
|
||||
'<span class="meta-item">Ver: ' + escapeHtml(ver) + '</span>' +
|
||||
'<span class="meta-item">' + screenInfo + '</span>' +
|
||||
'<span class="meta-item">' + escapeHtml(screenInfo) + '</span>' +
|
||||
'</div>' +
|
||||
(offline ? '<div class="last-seen">Last seen: ' + escapeHtml(formatLastSeen(d.last_seen)) + '</div>' : '') +
|
||||
(d.transferTo
|
||||
? '<div class="transfer-badge" title="Transferred to ' + escapeHtml(d.transferTo) + '">' +
|
||||
? '<div class="transfer-badge" title="Transferred to ' + escapeAttr(d.transferTo) + '">' +
|
||||
'Transferred → ' + escapeHtml(d.transferTo) + ' · ' +
|
||||
escapeHtml(formatTransferLeft(d.transferUntil)) + '</div>'
|
||||
: '') +
|
||||
(!offline && activeWin ? '<div class="active-window' + (isWindowBusy(activeWin) ? ' busy' : '') + '" title="' + escapeHtml(activeWin) + '">' + escapeHtml(activeWin) + '</div>' : '') +
|
||||
(!offline && activeWin ? '<div class="active-window' + (isWindowBusy(activeWin) ? ' busy' : '') + '" title="' + escapeAttr(activeWin) + '">' + escapeHtml(activeWin) + '</div>' : '') +
|
||||
'</div>';
|
||||
}).join('');
|
||||
}
|
||||
@@ -5587,6 +5688,85 @@
|
||||
}));
|
||||
}
|
||||
|
||||
// ===== 修改备注(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) return;
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
||||
appAlert('Not connected to the server. Try again in a moment.', 'Edit Remark');
|
||||
return;
|
||||
}
|
||||
const remark = document.getElementById('remark-input').value.trim();
|
||||
ws.send(JSON.stringify({
|
||||
cmd: 'set_device_remark', token, id: pendingRemarkDeviceId, remark,
|
||||
}));
|
||||
}
|
||||
|
||||
// ===== 修改分组(Go 后端) =====
|
||||
// 覆盖主机上报的分组,影响本服务端的卡片分组、分组过滤与 MCP;不下发
|
||||
// CMD_SET_GROUP,主机对其它主控仍按自己上报的分组显示。留空 = 撤销覆盖。
|
||||
let pendingGroupDeviceId = null;
|
||||
|
||||
function openGroupModal(id) {
|
||||
if (!canEditGroup()) return;
|
||||
const d = devices.find(x => String(x.id) === String(id));
|
||||
if (!d) { appAlert('Device not found.', 'Edit Group'); return; }
|
||||
pendingGroupDeviceId = String(id);
|
||||
document.getElementById('group-device-name').textContent =
|
||||
displayName(d) + ' (' + String(id) + ')';
|
||||
// 建议值取当前列表里已有的分组(含覆盖后的)。
|
||||
const groups = Array.from(new Set(devices.map(x => x.group).filter(Boolean))).sort();
|
||||
document.getElementById('group-options').innerHTML =
|
||||
groups.map(g => '<option value="' + escapeAttr(g) + '"></option>').join('');
|
||||
// 只有覆盖值才预填。主机上报的分组只放进 placeholder:否则"打开即保存"
|
||||
// 会把上报值固化成覆盖,之后主机改了分组,控制台还停在旧值。
|
||||
const input = document.getElementById('group-input');
|
||||
input.value = d.groupOverride === true ? (d.group || '') : '';
|
||||
input.placeholder = d.group ? ('Current: ' + d.group) : 'e.g. Office';
|
||||
document.getElementById('group-device-modal').classList.add('active');
|
||||
input.focus();
|
||||
input.select();
|
||||
}
|
||||
|
||||
function closeGroupModal() {
|
||||
pendingGroupDeviceId = null;
|
||||
document.getElementById('group-device-modal').classList.remove('active');
|
||||
}
|
||||
|
||||
function confirmSetGroup() {
|
||||
if (!pendingGroupDeviceId) return;
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
||||
appAlert('Not connected to the server. Try again in a moment.', 'Edit Group');
|
||||
return;
|
||||
}
|
||||
const group = document.getElementById('group-input').value.trim();
|
||||
ws.send(JSON.stringify({
|
||||
cmd: 'set_device_group', token, id: pendingGroupDeviceId, group,
|
||||
}));
|
||||
}
|
||||
|
||||
// ===== 删除设备 =====
|
||||
// 两种情况都删除服务端 devices.json 中的历史记录;在线设备额外按 MFC
|
||||
// 的做法发送单字节 TOKEN_UNINSTALL(卸载主机)。都先弹二次确认。
|
||||
@@ -5794,7 +5974,9 @@
|
||||
'remote.screen.start', 'remote.screen.stop', 'remote.screen.denied',
|
||||
'remote.terminal.start', 'remote.terminal.stop', 'remote.terminal.denied',
|
||||
'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.device.group', 'admin.audit.query',
|
||||
'device.online', 'device.offline',
|
||||
'device.auth.success', 'device.auth.failure', 'device.auth.throttled',
|
||||
'device.auth.heartbeat.success',
|
||||
@@ -5944,7 +6126,7 @@
|
||||
tbody.innerHTML = events.map(rec => {
|
||||
const level = rec.level === 'warn' ? 'warn' : 'info';
|
||||
return '<tr>' +
|
||||
'<td title="' + escapeHtml(rec.time || '') + '">' + formatAuditTime(rec.time) + '</td>' +
|
||||
'<td title="' + escapeAttr(rec.time || '') + '">' + formatAuditTime(rec.time) + '</td>' +
|
||||
'<td><span class="audit-level ' + level + '">' + level + '</span></td>' +
|
||||
'<td>' + escapeHtml(rec.event || '') + '</td>' +
|
||||
'<td>' + escapeHtml(rec.actor || '') + '</td>' +
|
||||
|
||||
Reference in new issue
Block a user