Feature: add per-device owner bindings to the web console

Web 控制台此前所有 admin 角色用户共享全部设备。新增设备级归属:内置 admin
把设备绑定给一个用户名后,该设备对其他 admin/viewer 不可见不可控,只有
owner 与内置 admin 可见可控。

- 新增 device_acl.json(与 users.json 同目录,YAMA_DEVICE_ACL_FILE 可覆盖),
  原子写、启动加载;文件损坏拒绝启动,避免私人设备变成公共。
- 可见性:内置 admin 全部;未绑定设备仅 admin 角色;绑定设备仅 owner。
  覆盖 get_devices、/api/devices、屏幕墙,以及 connect/term_open/mouse/key/
  clipboard/keyframe/rdp_reset 全部控制通道;device_update 也只推给可见者。
- 只有内置 admin(用户名 admin + role admin)能 bind/unbind;admin 角色保留
  建用户、删设备、审计等既有功能。删设备清绑定。
- 审计日志也按归属过滤:非内置 admin 只能看到公共设备和自己绑定设备的记录
  (device_id / device / devices 三种写法都识别);auditquery 增 DeviceAllowed
  钩子,ACL 提供 Owner 快照,避免扫描时逐条加锁。
- 删用户会解绑其设备;但账号名下有绑定设备时只有内置 admin 能删,其他 admin
  删除会把设备释放到公共池,属于越权。解绑在删除前完成,解绑失败中止删除;
  删除失败时回滚绑定。
- 绑定/解绑后立即重新校验在线会话:失去权限的屏幕/终端会话被断开。
- 本地用户名禁止 '@'(保留给 SSO 邮箱);本地密码登录拒绝 '@' 用户名,
  SSO 拒绝名为 admin 的身份,避免绕过超级管理员判定。
- 前端:superadmin 卡片显示 owner、绑定按钮和弹窗(本地用户 datalist +
  SSO 邮箱自由输入);deviceAcl 能力位由服务端挑战下发,C++ 端无此位不显示;
  设备 ID 经 jsAttr 转义后再进 onclick,修掉存储型 XSS。

验证:go build/test/vet 全绿;新增 ACL 持久化、可见性矩阵、控制通道拒绝、
绑定/解绑会话重校验、device_update 不泄露、分组过滤、删用户解绑与越权拒绝、
审计按归属过滤等测试;本地起 Go 服务 + WebSocket 探针验证 challenge、绑定、
非 superadmin 拒绝、解绑。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
yuanyuanxiangandClaude Code committed 2026-11-19 11:17:51 +01:00
1 parent db148c4a69
commit 46434b46d0
16 files changed
+1716 -30

No files matched your search

+187 -7
View File
@@ -669,7 +669,8 @@
.device-card .card-icon-btn:active { transform: scale(0.92); }
.device-card .card-term-btn:hover { background: rgba(76, 175, 80, 0.25); color: #4caf50; }
.device-card .card-del-btn:hover { background: rgba(231, 76, 60, 0.25); color: #e74c3c; }
.device-card h3 { padding-right: 86px; } /* 给右上角两个操作图标让位 */
.device-card .card-bind-btn:hover { background: rgba(230, 126, 34, 0.25); color: #e67e22; }
.device-card h3 { padding-right: 124px; } /* 给右上角操作图标让位 */
.device-grid.list-view .device-card .card-actions {
top: 50%;
transform: translateY(-50%);
@@ -2173,6 +2174,34 @@
</div>
</div>
<!-- Device Binding Modal(仅内置 admin 超级管理员可见) -->
<div class="modal-overlay" id="bind-device-modal" onclick="if(event.target===this)closeBindModal()">
<div class="modal-content" style="max-width:440px;">
<div class="modal-header">
<h3>Device Binding</h3>
<button class="modal-close" onclick="closeBindModal()">&times;</button>
</div>
<div class="user-form">
<div id="bind-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;">
Owner (local username or SSO email)
</label>
<input type="text" id="bind-owner" list="bind-owner-options"
placeholder="alice or user@corp.com" autocomplete="off">
<datalist id="bind-owner-options"></datalist>
<div style="font-size:12px;color:#888;margin-top:8px;">
Bound devices are hidden from every other user except the built-in admin.
Unbind returns the device to the public pool. SSO usernames are email
addresses and must match the portal username exactly.
</div>
<div style="display:flex;gap:8px;margin-top:14px;">
<button onclick="confirmBindDevice()">Bind</button>
<button class="cancel-btn" onclick="confirmUnbindDevice()">Unbind</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. -->
@@ -2387,7 +2416,7 @@
};
// 服务端能力协商:旧 C++ / Go 服务端没有 caps,前端隐藏 Wall。
let serverCaps = { multiWatch: false, keyframeRequest: false, offlineDevices: false, auditLog: false };
let serverCaps = { multiWatch: false, keyframeRequest: false, offlineDevices: false, auditLog: false, deviceAcl: false };
// 离线设备开关:localStorage 只保存用户偏好,是否可用由服务端能力位决定。
// 关闭时只影响 Grid/List;Wall 侧边栏始终列出离线设备(灰显、不可操作)。
@@ -2734,8 +2763,10 @@
if (!data || !data.token) return false;
token = data.token;
currentUserRole = data.role || 'viewer';
currentUsername = data.username || '';
localStorage.setItem('token', token);
localStorage.setItem('role', currentUserRole);
localStorage.setItem('username', currentUsername);
return true;
} catch (e) {
return false;
@@ -2840,7 +2871,8 @@
multiWatch: !!(msg.caps && msg.caps.multiWatch),
keyframeRequest: !!(msg.caps && msg.caps.keyframeRequest),
offlineDevices: !!(msg.caps && msg.caps.offlineDevices),
auditLog: !!(msg.caps && msg.caps.auditLog)
auditLog: !!(msg.caps && msg.caps.auditLog),
deviceAcl: !!(msg.caps && msg.caps.deviceAcl)
};
updateWallAvailability();
applyOfflineCapability();
@@ -2859,8 +2891,10 @@
if (msg.ok) {
token = msg.token;
currentUserRole = msg.role || 'viewer';
currentUsername = msg.username || currentUsername;
localStorage.setItem('token', token);
localStorage.setItem('role', currentUserRole);
localStorage.setItem('username', currentUsername);
document.getElementById('login-error').textContent = '';
// Show Users / Audit Log buttons for admin only
updateAdminButtons();
@@ -2879,11 +2913,22 @@
token = null;
localStorage.removeItem('token');
localStorage.removeItem('role');
localStorage.removeItem('username');
currentUserRole = 'viewer';
currentUsername = '';
updateAdminButtons();
showPage('login-page');
break;
}
if (msg.username && msg.username !== currentUsername) {
currentUsername = msg.username;
localStorage.setItem('username', currentUsername);
}
if (msg.role && msg.role !== currentUserRole) {
currentUserRole = msg.role;
localStorage.setItem('role', currentUserRole);
}
updateAdminButtons();
devices = msg.devices || [];
// Keep current page (renderDeviceList adjusts if out of range)
renderDeviceList();
@@ -3149,7 +3194,10 @@
break;
case 'delete_user_result':
if (msg.ok) {
showUserMsg('User deleted', false);
const unbound = msg.unbound_devices || 0;
showUserMsg(unbound > 0
? 'User deleted; ' + unbound + ' device binding(s) released'
: 'User deleted', false);
listUsers();
} else {
showUserMsg(msg.msg || 'Failed to delete user', true);
@@ -3166,9 +3214,44 @@
break;
case 'list_users_result':
if (msg.ok) {
// The built-in admin is the superadmin, never a bind target.
knownLocalUsers = (msg.users || [])
.map(u => u.username)
.filter(u => u && u !== 'admin');
renderUsersList(msg.users);
const bindModal = document.getElementById('bind-device-modal');
if (bindModal && bindModal.classList.contains('active')) {
populateBindOwnerOptions();
}
}
break;
case 'bind_device_result':
if (msg.ok) {
closeBindModal();
getDevices();
} else {
appAlert(msg.msg || 'Failed to bind device', 'Device Binding');
}
break;
case 'unbind_device_result':
if (msg.ok) {
closeBindModal();
getDevices();
} else {
appAlert(msg.msg || 'Failed to unbind device', 'Device Binding');
}
break;
case 'device_revoked': {
// The superadmin bound this device to someone else while we
// were watching it. Stop streaming immediately.
const rid = String(msg.id);
if (currentDevice && String(currentDevice.id) === rid) {
appAlert(msg.msg || 'Access to this device was revoked', 'Access Revoked');
disconnect();
}
getDevices();
break;
}
case 'groups':
if (msg.ok) {
renderGroupsCheckboxes(msg.groups);
@@ -4962,17 +5045,27 @@
if (!offline) {
actions.push(
'<button class="card-icon-btn card-term-btn" title="Open Terminal" aria-label="Terminal" ' +
'onclick="event.stopPropagation();openTerminal(\'' + d.id + '\')">' +
'onclick="event.stopPropagation();openTerminal(\'' + jsAttr(d.id) + '\')">' +
'<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>' +
'</button>');
}
if (canBindDevices()) {
actions.push(
'<button class="card-icon-btn card-bind-btn" title="Bind owner" aria-label="Bind owner" ' +
'onclick="event.stopPropagation();openBindModal(\'' + jsAttr(d.id) + '\')">' +
'<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>' +
'</button>');
}
if (canDeleteDevices()) {
actions.push(
'<button class="card-icon-btn card-del-btn" title="' +
(offline ? 'Delete record' : 'Uninstall host') + '" aria-label="Delete" ' +
'onclick="event.stopPropagation();askDeleteDevice(\'' + d.id + '\')">' +
'onclick="event.stopPropagation();askDeleteDevice(\'' + jsAttr(d.id) + '\')">' +
'<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="3 6 5 6 21 6"/>' +
'<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>' +
@@ -4984,7 +5077,7 @@
const actionsHtml = actions.length
? '<div class="card-actions">' + actions.join('') + '</div>' : '';
return '<div class="device-card' + (offline ? ' offline' : '') + '"' +
(offline ? '' : ' onclick="connectDevice(\'' + d.id + '\')"') + '>' +
(offline ? '' : ' onclick="connectDevice(\'' + jsAttr(d.id) + '\')"') + '>' +
actionsHtml +
'<h3>' + escapeHtml(displayName(d)) + '</h3>' +
'<div class="info-row">' +
@@ -4992,6 +5085,9 @@
'<div class="info"><span class="info-label">Loc:</span> ' + escapeHtml(loc) + '</div>' +
'</div>' +
'<div class="info"><span class="info-label">OS:</span> ' + escapeHtml(d.os || '-') + '</div>' +
(isSuperAdmin() && d.owner
? '<div class="info"><span class="info-label">Owner:</span> ' + escapeHtml(d.owner) + '</div>'
: '') +
'<div class="meta-row">' +
(offline
? '<span class="meta-item offline-badge">Offline</span>'
@@ -5141,8 +5237,10 @@
connectWebSocket(); // Reconnect immediately
token = null;
currentUserRole = 'viewer';
currentUsername = '';
localStorage.removeItem('token');
localStorage.removeItem('role');
localStorage.removeItem('username');
// 分组过滤器是按账号的临时偏好:换账号不应继承上一个账号的选择。
selectedGroups = [];
groupDropdownOpen = false;
@@ -5224,6 +5322,69 @@
});
}
// ===== 设备绑定(仅内置 admin 超级管理员) =====
// 绑定后该设备从其他 admin/viewer 的列表中消失,只有 owner 和内置 admin
// 可见可控。服务端强制;前端只负责入口和展示。
let pendingBindDeviceId = null;
let knownLocalUsers = [];
function isSuperAdmin() {
return currentUserRole === 'admin' && currentUsername === 'admin';
}
function canBindDevices() {
return !!(serverCaps.deviceAcl && isSuperAdmin());
}
function populateBindOwnerOptions() {
const dl = document.getElementById('bind-owner-options');
if (!dl) return;
dl.innerHTML = knownLocalUsers.map(u =>
'<option value="' + escapeHtml(u) + '"></option>').join('');
}
function openBindModal(id) {
if (!canBindDevices()) return;
const d = devices.find(x => String(x.id) === String(id));
if (!d) { appAlert('Device not found.', 'Device Binding'); return; }
pendingBindDeviceId = String(id);
document.getElementById('bind-device-name').textContent =
displayName(d) + ' (' + String(id) + ')';
const ownerInput = document.getElementById('bind-owner');
ownerInput.value = d.owner || '';
populateBindOwnerOptions();
document.getElementById('bind-device-modal').classList.add('active');
// Refresh the local-user suggestions (list_users is admin-only, and
// the superadmin is an admin). SSO emails are free-text.
if (ws && ws.readyState === WebSocket.OPEN && token) {
ws.send(JSON.stringify({ cmd: 'list_users', token }));
}
}
function closeBindModal() {
pendingBindDeviceId = null;
document.getElementById('bind-device-modal').classList.remove('active');
}
function confirmBindDevice() {
if (!pendingBindDeviceId || !ws || ws.readyState !== WebSocket.OPEN) return;
const username = document.getElementById('bind-owner').value.trim();
if (!username) {
appAlert('Enter a local username or an SSO email address.', 'Device Binding');
return;
}
ws.send(JSON.stringify({
cmd: 'bind_device', token, ids: [pendingBindDeviceId], username,
}));
}
function confirmUnbindDevice() {
if (!pendingBindDeviceId || !ws || ws.readyState !== WebSocket.OPEN) return;
ws.send(JSON.stringify({
cmd: 'unbind_device', token, ids: [pendingBindDeviceId],
}));
}
// ===== 删除设备 =====
// 两种情况都删除服务端 devices.json 中的历史记录;在线设备额外按 MFC
// 的做法发送单字节 TOKEN_UNINSTALL(卸载主机)。都先弹二次确认。
@@ -5268,6 +5429,10 @@
// User Management Functions
let currentUserRole = 'viewer';
// Username of the current session. Only the built-in "admin" account is
// the superadmin allowed to bind devices; other admin-role users keep
// their existing UI but are subject to the device ACL server-side.
let currentUsername = '';
function openUsersModal() {
document.getElementById('users-modal').classList.add('active');
@@ -7650,6 +7815,20 @@
return div.innerHTML;
}
// Safely embed a value inside a single-quoted JS string that itself
// sits in a double-quoted HTML attribute. Device IDs are client-
// supplied, so never interpolate them raw into onclick handlers.
function jsAttr(value) {
const s = String(value == null ? '' : value)
.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/</g, '\\x3c')
.replace(/>/g, '\\x3e');
return escapeHtml(s);
}
// 设备显示名:有备注则 "hostname (备注)",否则就是 hostname。
// 服务端备注从 m_ClientMap MAP_NOTE 取(参看 BuildDeviceListJson)。
function displayName(d) {
@@ -7925,6 +8104,7 @@
// Restore token and role from localStorage (local-login fallback).
token = localStorage.getItem('token');
currentUserRole = localStorage.getItem('role') || 'viewer';
currentUsername = localStorage.getItem('username') || '';
// Attempt portal SSO first: if the user is already logged into the
// parent domain, the server bridges the portal session cookie into
// a YAMA session token so the login form is skipped. On failure