diff --git a/docs/Mcp_Design.md b/docs/Mcp_Design.md index 65c400c..cef469f 100644 --- a/docs/Mcp_Design.md +++ b/docs/Mcp_Design.md @@ -258,6 +258,7 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap); | `McpPort` | `6544` | MCP 监听端口;仅当 `McpEnabled=1` 时生效;未配置用默认 `6544` | | `McpBind` | `127.0.0.1` | 监听地址;默认仅本机;可设 `0.0.0.0`(所有网卡)或内网 IP(如 `192.168.0.92`)以支持远程 | | `McpToken` | 空(UI 默认随机值) | 静态 token;对话框内「token 必填、默认随机值」——首次打开若为空则预填随机并随保存持久化。运行时优先级:env `YAMA_MCP_TOKEN` → `McpToken` → 皆空则随机生成(见 §3.5) | +| `McpKeylog` | `0` | 键盘记录工具 `get_keylog` 的独立开关(见 §9.3);与 `McpReadonly` 无关,改动需重启生效 | > 与旧版「`McpPort=0` 即禁用」不同:启用与否改由独立的 `McpEnabled` 开关控制,`McpPort` 回归纯端口语义,二者解耦。 @@ -444,3 +445,50 @@ void CMcpSettingsDlg::OnBnClickedBtnSave() - ✅ **取数方案**:C(抽公共函数 `BuildHostJson`,MCP 与 WebService 平级复用)。 - ✅ **返回字段**:全量,含实时信息(`rtt` / `activeWindow`),支持 AI 监督场景。 - ✅ **序列化**:`structuredContent` + `outputSchema`,`content` 附带可读摘要。 + +--- + +## 9. 增补(2026-10-25:N1–N5) + +本轮在既有工具族(P2–P9)之上补齐「能找到主机、能一次查多台、输出不撑爆上下文、认证可追溯」四件事,全部为服务端改动,客户端零改动。 + +### 9.1 N1 离线主机可见 + +- 新增工具 `list_all_hosts`(`online` / `offline` 两个布尔过滤,默认都为 `true`),数据源是 `m_ClientMap`(主机列表历史记录,`GetAll()` 快照 + `m_cs` 保护),在线条目复用 `BuildHostJson`,离线条目由 `BuildOfflineHostJson` 生成,字段:`id` / `name` / `remark` / `ip` / `os` / `location` / `online` / `group` / `last_seen` / `install_time` / `authStatus`。 +- `search_hosts` 的 `online` 参数:`true` = 仅在线,`false` = 仅离线(修复此前 `online=false` 永远返回空列表的问题),缺省 = 仅在线(与改动前一致,不改变既有调用方看到的结果)。两类都要请用 `list_all_hosts`。 +- `authStatus` 是 `ClientValue::Authorized` 的三态枚举(`unauthorized` / `authorized_by_super` / `authorized_by_admin` / `forbidden`),不是布尔值。 +- `get_host_detail` 对「在 `m_ClientMap` 里但当前离线」的 id 不再返回 `-32002`,改为返回该主机的最后记录(`online=false`),使 `list_all_hosts` 的结果可直接消费。 + +### 9.2 N2 批量只读调用 + +- 只读工具支持 `ids: []`(最多 50 个),与 `id` 二选一(inputSchema 用 `anyOf` 表达)。命中批量的工具:`get_host_detail` / `list_processes` / `list_windows` / `list_services` / `list_files` / `list_registry` / `get_client_log` / `get_activity_history` / `list_network_connections` / 全部 `host_list_*` / `host_get_hosts_file`。 +- 写操作工具传 `ids` 直接 `-32602` 拒绝(不逐个执行,避免误操作扩散)。 +- 返回:`{tool, total, succeeded, failed, results:[{id, ok, data|error, text}]}`;`content` 里是「共 N 台,成功 X 台,失败 Y 台」+ 最多 ~1200 字节的失败明细。 +- `limit` / `offset` 对每台主机各自生效;批量是串行执行,单台超时会占用整批等待时间。 + +### 9.3 N3 `get_keylog` + +- 复用客户端既有键盘记录链路:主连接下发 `COMMAND_KEYBOARD(169)` → 客户端建子连接 → 子连接回 `TOKEN_KEYBOARD_START(293)` 作为就绪包绑定 → 之后每约 1 秒推一包 `TOKEN_KEYBOARD_DATA(294)`。 +- 服务端把击键流**累积**(不是一问一答),窗口 `duration_ms`(默认 4000,1000–15000)或字节上限 `max_bytes`(默认 64 KiB,1024–256 KiB)先到者结束;结束时 `EndManagedSession(..., cancelIo=true)` 关闭子连接 —— 与 MFC 关对话框同一路径,客户端据此停止记录。 +- 复用 P8 的挂起会话表(新增 `PendingKind::Keylog`,仍受「单设备单飞行」约束),就绪包绑定、迟到包墓碑、子连接断开唤醒全部沿用 P8 逻辑;绑定后服务端回 `COMMAND_NEXT`,让客户端 `WaitForDialogOpen` 立即返回(本工具不开 UI)。 +- 返回 `{id, duration_ms, bytes, lines, lineCount, truncated}`,文本按客户端代码页转 UTF-8(`GetClientEncoding`)。**注意**:客户端连上后会先把缓冲区里已有的历史记录推过来,所以结果既含历史也含窗口期内的新击键。 +- 独立开关 `McpKeylog`(默认 `0`,不要求只读关)。工具只在开关打开时出现在 `tools/list`,关闭时直接调用返回 `-32006`。 +- 隐私:击键内容只进本次响应;审计只记 `CALL_OK tool=get_keylog ms=… bytes=…`,不落任何正文。 + +### 9.4 N4 认证加固 + +- 静态 token 校验失败:返回 401,并按来源 IP 计数;60 秒窗口内失败 10 次即封禁该 IP 900 秒,封禁期内返回 429 + `Retry-After`。失败表上限 1024,满时先清理过期项。 +- 环回来源(`127.0.0.1` / `::1`)**只记账不封禁**:内置 frpc 把 MCP 端口映射出去时是「本机连本机」,且这条转发没开 Proxy Protocol(httplib 不解析),服务端看到的源地址恒为环回。若按 IP 封禁,一次外部扫描就能把隧道后面所有客户端(包括自己)锁死 15 分钟。审计里这类封禁触发记为 `AUTH_BLOCK ... scope=proxy-source-exempt`。 +- 审计文件 `\logs\mcp_audit.log`(追加写,5 MB 轮转为 `.1`),每行:时间戳(毫秒)、事件、来源 IP、详情。 + - `AUTH_FAIL`:UA(截断/清洗)、body 大小、是否因此被封禁。 + - `AUTH_BLOCK`:封禁生效。 + - `CALL_OK` / `CALL_FAIL`:`tool=`、耗时 `ms=`、响应字节数 `bytes=`。 +- 审计**不记录** token、密码、哈希、剪贴板内容或工具返回正文。 + +### 9.5 N5 列表输出治理 + +- 列表类工具统一 `limit` / `offset`:默认 `limit=100`,硬上限 `1000`,`offset` 默认 0;非正数按默认值处理。 +- `structuredContent` 统一附 `total` / `totalAll` / `offset` / `limit` / `hasMore`,与 `McpMachine.cpp` 既有约定一致(`host_list_*` / `list_network_connections` 本来就是这样)。 +- `content` 摘要统一为「共 N <单位>,本次返回第 a-b 条(还有更多,可用 offset 继续取)。」;`hasMore=false` 时不再出现「继续取」的误导提示;`offset` 越界时明确写「offset 超出范围,本次返回 0 条」。 +- 实现集中在 `McpInternal.h/.cpp`:`PageWindow` / `ResolvePageWindow` / `ApplyPageWindow` / `WritePageFields` / `AppendPagingProps` / `PageSummary`。 +- `list_files` 仍受客户端单次 500 条的硬限制(`total=500` 表示客户端截断,不是服务端分页)。 diff --git a/server/2015Remote/2015RemoteDlg.cpp b/server/2015Remote/2015RemoteDlg.cpp index c1dee7e..7aeb05c 100644 --- a/server/2015Remote/2015RemoteDlg.cpp +++ b/server/2015Remote/2015RemoteDlg.cpp @@ -2430,6 +2430,8 @@ BOOL CMy2015RemoteDlg::OnInitDialog() THIS_CFG.GetInt("settings", "McpMachineDangerous", 0) != 0); // P9 远程交谈(chat_*):独立开关默认关,与只读开关无关。 McpServer().SetChatEnabled(THIS_CFG.GetInt("settings", "McpChat", 0) != 0); + // N3 键盘记录(get_keylog):独立开关默认关,与只读开关无关。 + McpServer().SetKeylogEnabled(THIS_CFG.GetInt("settings", "McpKeylog", 0) != 0); if (!McpServer().Start(mcpBind, mcpPort)) { Mprintf("McpServer start failed on %s:%d\n", mcpBind.c_str(), mcpPort); } else { diff --git a/server/2015Remote/McpInternal.cpp b/server/2015Remote/McpInternal.cpp index 7d9370d..5b1297f 100644 --- a/server/2015Remote/McpInternal.cpp +++ b/server/2015Remote/McpInternal.cpp @@ -207,4 +207,104 @@ void AuditChatAction(CMy2015RemoteDlg* parent, uint64_t devId, (LPARAM)new CString(_TR("MCP远程交谈"))); } +// ===== 列表输出治理 ===== + +PageWindow ResolvePageWindow(const Json::Value& args, int defaultLimit, int maxLimit) { + PageWindow w; + w.limit = defaultLimit; + if (args.isObject()) { + if (args.isMember("limit") && args["limit"].isInt()) { + int v = args["limit"].asInt(); + if (v > 0) w.limit = v; // 0/负数视为未指定,用默认值 + } + if (args.isMember("offset") && args["offset"].isInt()) { + int v = args["offset"].asInt(); + if (v > 0) w.offset = v; + } + } + if (w.limit > maxLimit) w.limit = maxLimit; + return w; +} + +void ApplyPageWindow(const Json::Value& all, PageWindow& w, Json::Value& out) { + out = Json::Value(Json::arrayValue); + w.total = all.isArray() ? (int)all.size() : 0; + w.totalAll = w.total; + int begin = w.offset < w.total ? w.offset : w.total; + int end = (begin + w.limit < w.total) ? begin + w.limit : w.total; + for (int i = begin; i < end; ++i) out.append(all[i]); + w.returned = end > begin ? end - begin : 0; + w.hasMore = end < w.total; +} + +void WritePageFields(Json::Value& structuredContent, const PageWindow& w) { + structuredContent["total"] = w.total; + structuredContent["totalAll"] = w.totalAll; + structuredContent["offset"] = w.offset; + structuredContent["limit"] = w.limit; + structuredContent["hasMore"] = w.hasMore; +} + +void AppendPagingProps(Json::Value& props, int defaultLimit, int maxLimit) { + Json::Value limitProp(Json::objectValue); + limitProp["type"] = "integer"; + limitProp["description"] = std::string(u8"本次最多返回的条数,默认 ") + + std::to_string(defaultLimit) + std::string(u8",上限 ") + + std::to_string(maxLimit) + std::string(u8"。"); + props["limit"] = limitProp; + + Json::Value offsetProp(Json::objectValue); + offsetProp["type"] = "integer"; + offsetProp["description"] = u8"跳过前 N 条,默认 0;配合返回的 total/hasMore 翻页。"; + props["offset"] = offsetProp; +} + +void AppendBatchIdsProp(Json::Value& props) { + Json::Value idsProp(Json::objectValue); + idsProp["type"] = "array"; + Json::Value items(Json::objectValue); + items["type"] = "string"; + idsProp["items"] = items; + idsProp["description"] = std::string(u8"批量查询:一次传多台主机 id(最多 50 个)," + u8"结果按台汇总在 results 里。与 id 二选一,仅只读工具支持;" + u8"limit/offset 对每台主机各自生效。"); + props["ids"] = idsProp; +} + +void MakeIdOrIdsRequired(Json::Value& schema) { + // 调用方可能先按单机 schema 生成了 required:["id"]:留着它会让「只传 ids」违反 schema + // (required 与 anyOf 同时生效)。这里只清理这一个精确形态,别的 required 不动。 + if (schema.isMember("required") && schema["required"].isArray() && + schema["required"].size() == 1 && schema["required"][0].isString() && + schema["required"][0].asString() == "id") { + schema.removeMember("required"); + } + + Json::Value anyOf(Json::arrayValue); + for (const char* key : { "id", "ids" }) { + Json::Value alt(Json::objectValue); + Json::Value req(Json::arrayValue); + req.append(key); + alt["required"] = req; + anyOf.append(alt); + } + schema["anyOf"] = anyOf; +} + +std::string PageSummary(const PageWindow& w, const char* unit) { + std::string s = std::string(u8"共 ") + std::to_string(w.total) + std::string(u8" ") + unit; + if (w.total == 0) return s + std::string(u8"。"); + + int begin = w.offset < w.total ? w.offset : w.total; + if (begin >= w.total) { + s += std::string(u8",offset 超出范围,本次返回 0 条。"); + return s; + } + int end = (begin + w.limit < w.total) ? begin + w.limit : w.total; + s += std::string(u8",本次返回第 ") + std::to_string(begin + 1) + "-" + + std::to_string(end) + std::string(u8" 条"); + if (w.hasMore) s += std::string(u8"(还有更多,可用 offset 继续取)"); + return s + std::string(u8"。"); +} + } // namespace McpInternal diff --git a/server/2015Remote/McpInternal.h b/server/2015Remote/McpInternal.h index cc3ce24..cd0bdaf 100644 --- a/server/2015Remote/McpInternal.h +++ b/server/2015Remote/McpInternal.h @@ -68,4 +68,40 @@ void AuditManageAction(CMy2015RemoteDlg* parent, uint64_t devId, void AuditChatAction(CMy2015RemoteDlg* parent, uint64_t devId, const std::string& tool, const std::string& detail); +// ===== 列表输出治理 ===== +// +// 列表类工具统一走 limit/offset:默认 limit=100,硬上限 1000,offset 默认 0。 +// structuredContent 里同时给出 total/totalAll/offset/limit/hasMore,与 +// McpMachine.cpp 的 host_list_*/list_network_connections 保持同一套字段, +// 调用方据此翻页,而不是让一次返回把上下文撑爆。 +struct PageWindow { + int offset = 0; + int limit = 100; + int total = 0; // ApplyPageWindow 填入:切片前的总条数(本工具无二次过滤,故等于 totalAll) + int totalAll = 0; + int returned = 0; // 本次实际返回条数 + bool hasMore = false; // 窗口之后还有条目(供调用方判断是否继续翻页) +}; + +// 读 args 里的 limit/offset(缺省/非法/非正数按默认值,limit 超上限截断到上限)。 +PageWindow ResolvePageWindow(const Json::Value& args, int defaultLimit = 100, int maxLimit = 1000); + +// 按窗口切片:out = all[offset, offset+limit),并回填 w.total/totalAll/returned/hasMore。 +void ApplyPageWindow(const Json::Value& all, PageWindow& w, Json::Value& out); + +// 把 total/totalAll/offset/limit/hasMore 写进 structuredContent。 +void WritePageFields(Json::Value& structuredContent, const PageWindow& w); + +// 往 inputSchema 的 properties 追加 limit / offset 两个字段。 +void AppendPagingProps(Json::Value& props, int defaultLimit = 100, int maxLimit = 1000); + +// 往 inputSchema 的 properties 追加 ids(只读工具的批量入口,最多 50 个 id)。 +void AppendBatchIdsProp(Json::Value& props); + +// 把 inputSchema 的必填约束改成「id 或 ids 二选一」。 +void MakeIdOrIdsRequired(Json::Value& schema); + +// 统一的提示文字,例如「共 283 个进程,本次返回第 1-100 条(还有更多,可用 offset 继续取)。」 +std::string PageSummary(const PageWindow& w, const char* unit); + } // namespace McpInternal diff --git a/server/2015Remote/McpMachine.cpp b/server/2015Remote/McpMachine.cpp index f114dc3..d2f1e56 100644 --- a/server/2015Remote/McpMachine.cpp +++ b/server/2015Remote/McpMachine.cpp @@ -55,6 +55,9 @@ const int kSessionDeadlineMs = 60000; // 单个包的上限:正常列表远小于此;超过即视为异常,置 clientError 并断开子连接。 const size_t kMaxPacketBytes = 8u * 1024u * 1024u; +// N3 键盘记录:一次 get_keylog 最多累积的击键字节(超出部分丢弃并置 truncated)。 +const size_t kKeylogMaxBytes = 256u * 1024u; + const size_t kConnRecordSize = sizeof(ConnectionInfo); static_assert(sizeof(ConnectionInfo) == 110, "ConnectionInfo layout changed; update the parser"); static_assert(sizeof(WINDOWSINFO) == 1044, "WINDOWSINFO layout changed; update the parser"); @@ -970,6 +973,7 @@ std::string NotFoundJson(const Json::Value& id, const std::string& what) { bool CMcpServer::KindAcceptsToken(PendingKind kind, BYTE token) { if (kind == PendingKind::Machine) return token == (BYTE)TOKEN_SYSINFOLIST; if (kind == PendingKind::ConnMgr) return token == (BYTE)TOKEN_CONNECTION_LIST; + if (kind == PendingKind::Keylog) return token == (BYTE)TOKEN_KEYBOARD_START; return false; } @@ -1015,6 +1019,36 @@ bool CMcpServer::BeginConnMgrSession(uint64_t device_id, const std::string& tool return BeginManagedSession(device_id, tool, PendingKind::ConnMgr, mainCtx); } +// ===== N3:键盘记录会话 ===== + +bool CMcpServer::BeginKeylogSession(uint64_t device_id, const std::string& tool, context* mainCtx) { + return BeginManagedSession(device_id, tool, PendingKind::Keylog, mainCtx); +} + +CMcpServer::KeylogWaitResult CMcpServer::WaitKeylogData(uint64_t device_id, std::string& out, + int timeoutMs, bool& truncated) { + std::unique_lock lk(m_PendingMutex); + auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs); + for (;;) { + auto it = m_Pending.find(device_id); + if (it == m_Pending.end() || it->second.kind != PendingKind::Keylog) + return KeylogWaitResult::Closed; + + PendingRequest& r = it->second; + if (!r.keylogBuf.empty()) { + out.swap(r.keylogBuf); // out 拿到数据;r.keylogBuf 变成 out 的旧内容 + r.keylogBuf.clear(); + truncated = r.keylogTruncated; + return KeylogWaitResult::Ok; + } + if (r.closed) return KeylogWaitResult::Closed; + + if (deadline > r.deadline) deadline = r.deadline; + if (std::chrono::steady_clock::now() >= deadline) return KeylogWaitResult::Timeout; + m_PendingCv.wait_until(lk, deadline); + } +} + void CMcpServer::ArmManagedResponse(uint64_t device_id, BYTE expectedToken) { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); @@ -1040,7 +1074,8 @@ CMcpServer::ManagedWaitResult CMcpServer::WaitManagedPacket(uint64_t device_id, if (it == m_Pending.end()) return ManagedWaitResult::Closed; PendingRequest& r = it->second; - if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr) + if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr && + r.kind != PendingKind::Keylog) return ManagedWaitResult::Closed; subCtxOut = r.subCtx; // 绑定可能发生在等待期间 @@ -1083,7 +1118,8 @@ void CMcpServer::EndManagedSession(uint64_t device_id, bool cancelIo, bool markO return; } PendingRequest& r = it->second; - if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr) return; + if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr && + r.kind != PendingKind::Keylog) return; sub = r.subCtx; kind = r.kind; @@ -1115,7 +1151,8 @@ bool CMcpServer::OnManagedSubPacket(context* subCtx, const BYTE* data, ULONG len BYTE token = data[0]; bool readyToken = (token == (BYTE)TOKEN_SYSINFOLIST) || - (token == (BYTE)TOKEN_CONNECTION_LIST); + (token == (BYTE)TOKEN_CONNECTION_LIST) || + (token == (BYTE)TOKEN_KEYBOARD_START); // 快速路径:没有已绑定/已吸收的子连接,且不是就绪包 → 与 P8 无关。 // MessageHandle 每个包都会调用本函数(含音频/屏幕等高频子连接),不能逐包抢锁。 if (!readyToken && m_ManagedRoutes.load(std::memory_order_relaxed) == 0) return false; @@ -1134,7 +1171,9 @@ bool CMcpServer::OnManagedSubPacket(context* subCtx, const BYTE* data, ULONG len uint64_t dev = bindIt->second; auto it = m_Pending.find(dev); if (it == m_Pending.end() || - (it->second.kind != PendingKind::Machine && it->second.kind != PendingKind::ConnMgr)) { + (it->second.kind != PendingKind::Machine && + it->second.kind != PendingKind::ConnMgr && + it->second.kind != PendingKind::Keylog)) { // 会话已结束但包还在路上:吸收并断开 m_SubCtxToDevice.erase(bindIt); m_AbsorbedSubCtx.insert(subCtx); @@ -1159,6 +1198,19 @@ bool CMcpServer::OnManagedSubPacket(context* subCtx, const BYTE* data, ULONG len m_PendingCv.notify_all(); return true; } + if (r.kind == PendingKind::Keylog) { + // N3:击键流是「累积」而非「一问一答」,任何包都不回 MFC; + // 只收 TOKEN_KEYBOARD_DATA(首字节之后即文本),累积到上限后丢弃并置 truncated。 + if (token == (BYTE)TOKEN_KEYBOARD_DATA && len > 1) { + size_t n = (size_t)(len - 1); + size_t room = r.keylogBuf.size() < kKeylogMaxBytes + ? kKeylogMaxBytes - r.keylogBuf.size() : 0; + if (n > room) { n = room; r.keylogTruncated = true; } + if (n > 0) r.keylogBuf.append((const char*)data + 1, n); + m_PendingCv.notify_all(); + } + return true; + } if (r.expectedToken != 0 && token == r.expectedToken) { r.response.assign(data, data + len); r.hasResponse = true; @@ -1179,8 +1231,9 @@ bool CMcpServer::OnManagedSubPacket(context* subCtx, const BYTE* data, ULONG len if (!readyToken) return false; if (mainIsSelf) return false; - PendingKind wantKind = (token == (BYTE)TOKEN_SYSINFOLIST) ? PendingKind::Machine - : PendingKind::ConnMgr; + PendingKind wantKind = (token == (BYTE)TOKEN_SYSINFOLIST) ? PendingKind::Machine + : (token == (BYTE)TOKEN_CONNECTION_LIST) ? PendingKind::ConnMgr + : PendingKind::Keylog; // 3a. 按 clientID 精确匹配(新客户端经 TOKEN_CONN_AUTH 已钉 ID) uint64_t boundDev = 0; @@ -1267,7 +1320,8 @@ void CMcpServer::OnManagedContextClosed(context* subCtx) { for (auto& kv : m_Pending) { PendingRequest& r = kv.second; - if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr) continue; + if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr && + r.kind != PendingKind::Keylog) continue; if (r.subCtx == subCtx || r.mainCtx == subCtx) { Mprintf("[MCP-P8] context closed dev=%llu tool=%s: wake waiter\n", kv.first, r.tool.c_str()); @@ -2593,6 +2647,22 @@ Json::Value ReadInputSchema(Json::Value props) { return MakeSchema(props, { "id" }); } +// 只读工具公共 input:id / ids 二选一 + 分页(批量调用,N2) +Json::Value ReadInputSchemaBatch(Json::Value props) { + Json::Value schema = ReadInputSchema(props); + AppendBatchIdsProp(schema["properties"]); + MakeIdOrIdsRequired(schema); + return schema; +} + +// 只有 id/ids、没有分页的只读工具(host_get_hosts_file 用 max_bytes 控大小) +Json::Value IdOrIdsSchema(Json::Value props) { + AppendBatchIdsProp(props); + Json::Value schema = MakeSchema(props, {}); + MakeIdOrIdsRequired(schema); + return schema; +} + } // namespace bool Handles(const std::string& toolName) { @@ -2630,7 +2700,7 @@ void AppendTools(Json::Value& tools) { props["state"] = PropStr(u8"按状态过滤:数字(MIB_TCP_STATE_*)或状态名子串,如 ESTABLISHED"); AddTool(tools, "list_network_connections", u8"列出指定在线 Windows 主机的 TCP/UDP 连接(相当于「连接管理」对话框)。返回四元组、所属进程与 TCP 状态;killable=true 表示该连接可被 kill_network_connection 断开。", - ReadInputSchema(props), MakeListOutputSchema("connections", ConnectionItemSchema())); + ReadInputSchemaBatch(props), MakeListOutputSchema("connections", ConnectionItemSchema())); } if (writable && mcp.IsManageEnabled()) { Json::Value props(Json::objectValue); @@ -2657,7 +2727,7 @@ void AppendTools(Json::Value& tools) { props["arch"] = PropStrEnum(u8"按架构过滤", { "x86", "x64" }); AddTool(tools, "host_list_processes", u8"列出在线 Windows 主机的进程(主机管理「进程」标签页)。返回 PID、架构、窗口标题、路径、优先级、线程数、用户、工作集与文件大小。", - ReadInputSchema(props), MakeListOutputSchema("processes", ProcessItemSchema())); + ReadInputSchemaBatch(props), MakeListOutputSchema("processes", ProcessItemSchema())); } { Json::Value props(Json::objectValue); @@ -2665,7 +2735,7 @@ void AppendTools(Json::Value& tools) { props["title"] = PropStr(u8"按窗口标题子串过滤"); AddTool(tools, "host_list_windows", u8"列出在线 Windows 主机上当前可见的顶层窗口(主机管理「窗口」标签页)。只包含可见窗口,故隐藏后窗口会从结果中消失。hwnd 可用于 host_control_window。", - ReadInputSchema(props), MakeListOutputSchema("windows", WindowItemSchema())); + ReadInputSchemaBatch(props), MakeListOutputSchema("windows", WindowItemSchema())); } { Json::Value props(Json::objectValue); @@ -2677,7 +2747,7 @@ void AppendTools(Json::Value& tools) { props["state"] = PropStr(u8"按状态子串过滤"); AddTool(tools, "host_list_network_state", u8"列出在线 Windows 主机的网络连接及其所属进程(主机管理「网络状态」标签页)。数据来源与「连接管理」不同(这里是进程视角、含 UDP 的无对端标记);仅支持 IPv4 展示。", - ReadInputSchema(props), MakeListOutputSchema("connections", NetStateItemSchema())); + ReadInputSchemaBatch(props), MakeListOutputSchema("connections", NetStateItemSchema())); } { Json::Value props(Json::objectValue); @@ -2685,7 +2755,7 @@ void AppendTools(Json::Value& tools) { props["publisher"] = PropStr(u8"按发布者子串过滤"); AddTool(tools, "host_list_software", u8"列出在线 Windows 主机已安装的软件(主机管理「软件」标签页,来自注册表 Uninstall 项)。只读;不提供卸载能力。", - ReadInputSchema(props), MakeListOutputSchema("software", SoftwareItemSchema())); + ReadInputSchemaBatch(props), MakeListOutputSchema("software", SoftwareItemSchema())); } { Json::Value props(Json::objectValue); @@ -2693,7 +2763,7 @@ void AppendTools(Json::Value& tools) { props["url"] = PropStr(u8"按 URL 子串过滤"); AddTool(tools, "host_list_browser_history", u8"列出在线 Windows 主机的 IE 浏览历史(主机管理「浏览记录」标签页)。隐私数据,仅在显式开启主机管理时可见。", - ReadInputSchema(props), MakeListOutputSchema("history", HistoryItemSchema())); + ReadInputSchemaBatch(props), MakeListOutputSchema("history", HistoryItemSchema())); } { Json::Value props(Json::objectValue); @@ -2701,7 +2771,7 @@ void AppendTools(Json::Value& tools) { props["url"] = PropStr(u8"按 URL 子串过滤"); AddTool(tools, "host_list_favorites", u8"列出在线 Windows 主机的 IE 收藏夹(主机管理「收藏夹」标签页)。隐私数据,仅在显式开启主机管理时可见。", - ReadInputSchema(props), MakeListOutputSchema("favorites", FavoriteItemSchema())); + ReadInputSchemaBatch(props), MakeListOutputSchema("favorites", FavoriteItemSchema())); } { Json::Value props(Json::objectValue); @@ -2710,7 +2780,7 @@ void AppendTools(Json::Value& tools) { props["start_type"] = PropStr(u8"按启动类型子串过滤,如 Auto"); AddTool(tools, "host_list_win32_services", u8"列出在线 Windows 主机的 Win32 服务(主机管理「服务」标签页之一)。返回显示名、描述、状态、启动类型、登录身份、服务名与可执行路径;服务名可用于 host_control_service。", - ReadInputSchema(props), MakeListOutputSchema("services", ServiceItemSchema())); + ReadInputSchemaBatch(props), MakeListOutputSchema("services", ServiceItemSchema())); } { Json::Value props(Json::objectValue); @@ -2719,7 +2789,7 @@ void AppendTools(Json::Value& tools) { props["start_type"] = PropStr(u8"按启动类型子串过滤"); AddTool(tools, "host_list_driver_services", u8"列出在线 Windows 主机的驱动服务(主机管理「服务」标签页之一)。字段同 host_list_win32_services。", - ReadInputSchema(props), MakeListOutputSchema("services", ServiceItemSchema())); + ReadInputSchemaBatch(props), MakeListOutputSchema("services", ServiceItemSchema())); } { Json::Value props(Json::objectValue); @@ -2728,7 +2798,7 @@ void AppendTools(Json::Value& tools) { props["status"] = PropStr(u8"按状态子串过滤,如 Ready / Disabled"); AddTool(tools, "host_list_scheduled_tasks", u8"列出在线 Windows 主机的计划任务(主机管理「计划任务」标签页)。返回任务名、完整路径、所在文件夹、可执行文件、状态与上次/下次运行时间。任务名 + folder 可用于 host_control_task。", - ReadInputSchema(props), MakeListOutputSchema("tasks", TaskItemSchema())); + ReadInputSchemaBatch(props), MakeListOutputSchema("tasks", TaskItemSchema())); } { Json::Value props(Json::objectValue); @@ -2755,7 +2825,7 @@ void AppendTools(Json::Value& tools) { AddTool(tools, "host_get_hosts_file", u8"读取在线 Windows 主机的 hosts 文件(主机管理「HOSTS」标签页),按行返回并自动识别 UTF-8/GBK。只读;不提供写入能力。", - MakeSchema(props, { "id" }), out); + IdOrIdsSchema(props), out); } // ---- 主机管理:4 个写工具(只读 + 可恢复操作) ---- diff --git a/server/2015Remote/McpServer.cpp b/server/2015Remote/McpServer.cpp index 965171d..705cbe9 100644 --- a/server/2015Remote/McpServer.cpp +++ b/server/2015Remote/McpServer.cpp @@ -505,6 +505,81 @@ void CollectOnlineHosts(CMy2015RemoteDlg* parent, Json::Value& hosts) { LeaveCriticalSection(&parent->m_cs); } +// MAP_AUTH 的三态(见 common/commands.h):0 未授权 / 1 超级管理员授权 / 2 管理员授权 / 9 禁止登录。 +// 导出成字符串而不是布尔:AUTH_FORBIDDEN 与 UNAUTHORIZED 对运维是两回事。 +const char* AuthStatusName(int auth) { + switch (auth) { + case AUTHED_BY_SUPER: return "authorized_by_super"; + case AUTHED_BY_ADMIN: return "authorized_by_admin"; + case AUTH_FORBIDDEN: return "forbidden"; + default: return "unauthorized"; + } +} + +// 离线主机 JSON:字段与 BuildHostJson 同形,缺实时字段(rtt/version/activeWindow/screen/clientType)。 +// ClientValue.Location 已统一按 UTF-8 存储(见 AddList 的 NormalizeLocationToUtf8),直接透传; +// 其余窄字符串来自客户端的 CString,按 CP_ACP 转 UTF-8。 +Json::Value BuildOfflineHostJson(_ClientList* clientMap, uint64_t key, const ClientValue& cv) { + Json::Value h(Json::objectValue); + h["id"] = std::to_string(key); + h["name"] = ToUtf8(cv.ComputerName, CP_ACP); + if (clientMap) { + CString remark = clientMap->GetClientMapData(key, MAP_NOTE); + if (!remark.IsEmpty()) h["remark"] = ToUtf8(remark.GetString(), CP_ACP); + } + h["ip"] = std::string(cv.IP); + h["os"] = ToUtf8(cv.OsName, CP_ACP); + h["location"] = std::string(cv.Location); + h["online"] = false; + h["group"] = "default"; // 分组只存在于在线 context 上,离线条目拿不到 + h["last_seen"] = std::string(cv.LastLoginTime); + h["install_time"] = std::string(cv.InstallTime); + h["authStatus"] = AuthStatusName(cv.Authorized); + return h; +} + +// 收集全部已知主机(m_cs 锁内)。在线主机取实时字段,离线主机取 m_ClientMap 元数据快照。 +// includeOnline / includeOffline 决定保留哪一类:两者都 false 时返回空数组。 +void CollectAllHosts(CMy2015RemoteDlg* parent, Json::Value& hosts, + bool includeOnline, bool includeOffline) { + if (!parent || !parent->m_ClientMap) return; + EnterCriticalSection(&parent->m_cs); + + // 在线集合始终要建:用来判断 map 里的条目当前是否在线(决定它算哪一类) + std::unordered_map online; + for (context* ctx : parent->m_HostList) { + if (ctx && ctx->IsLogin()) online[ctx->GetClientID()] = ctx; + } + + std::set emitted; + for (const auto& kv : parent->m_ClientMap->GetAll()) { + auto it = online.find(kv.first); + if (it != online.end()) { + if (includeOnline) { + Json::Value h = BuildHostJson(it->second, parent->m_ClientMap); + if (h.isObject()) h["authStatus"] = AuthStatusName(kv.second.Authorized); + hosts.append(h); + emitted.insert(kv.first); + } + } else if (includeOffline) { + hosts.append(BuildOfflineHostJson(parent->m_ClientMap, kv.first, kv.second)); + } + } + + // 在线但还没写进 m_ClientMap 的新客户端(首次上线瞬间)也要能列出来 + if (includeOnline) { + for (const auto& kv : online) { + if (!emitted.count(kv.first)) { + Json::Value h = BuildHostJson(kv.second, parent->m_ClientMap); + if (h.isObject()) h["authStatus"] = AuthStatusName(UNAUTHORIZED); // 不在 map 里即从未登记 + hosts.append(h); + } + } + } + + LeaveCriticalSection(&parent->m_cs); +} + // ========== 工具 schema ========== // 单台主机字段 schema(hosts 数组元素 / 单机详情共用的形状) @@ -512,7 +587,9 @@ Json::Value BuildHostItemSchema() { Json::Value itemProps(Json::objectValue); const char* strFields[] = { "id", "name", "remark", "ip", "os", "location", "rtt", - "version", "activeWindow", "group", "screen", "clientType" + "version", "activeWindow", "group", "screen", "clientType", + // 以下两项只有离线主机(来自 m_ClientMap 的历史记录)才有值 + "last_seen", "install_time" }; for (const char* f : strFields) { Json::Value p(Json::objectValue); @@ -526,9 +603,26 @@ Json::Value BuildHostItemSchema() { Json::Value tlsProp(Json::objectValue); tlsProp["type"] = "boolean"; itemProps["tls"] = tlsProp; + // 主机授权状态:unauthorized / authorized_by_super / authorized_by_admin / forbidden + Json::Value authProp(Json::objectValue); + authProp["type"] = "string"; + itemProps["authStatus"] = authProp; return itemProps; } +// 列表型 outputSchema 的公共翻页字段,字段名与 McpMachine.cpp 的 host_list_* 保持一致 +void AppendPageOutputProps(Json::Value& props) { + const char* intFields[] = { "total", "totalAll", "offset", "limit" }; + for (const char* f : intFields) { + Json::Value p(Json::objectValue); + p["type"] = "integer"; + props[f] = p; + } + Json::Value moreProp(Json::objectValue); + moreProp["type"] = "boolean"; + props["hasMore"] = moreProp; +} + // list_online_hosts / search_hosts 的 outputSchema(hosts 数组) Json::Value BuildHostOutputSchema() { Json::Value props(Json::objectValue); @@ -540,6 +634,7 @@ Json::Value BuildHostOutputSchema() { items["properties"] = BuildHostItemSchema(); hostsProp["items"] = items; props["hosts"] = hostsProp; + AppendPageOutputProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; @@ -581,27 +676,58 @@ Json::Value BuildSearchHostsInputSchema() { onlineProp["type"] = "boolean"; props["online"] = onlineProp; + AppendPagingProps(props); + Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } -// get_host_detail 的 inputSchema(id 必填) +// list_all_hosts 的 inputSchema:两类开关,默认都返回 +Json::Value BuildListAllHostsInputSchema() { + Json::Value props(Json::objectValue); + + Json::Value onlineProp(Json::objectValue); + onlineProp["type"] = "boolean"; + onlineProp["description"] = u8"是否包含在线主机,默认 true"; + props["online"] = onlineProp; + + Json::Value offlineProp(Json::objectValue); + offlineProp["type"] = "boolean"; + offlineProp["description"] = u8"是否包含离线主机(历史连接过、当前未连接的),默认 true"; + props["offline"] = offlineProp; + + AppendPagingProps(props); + + Json::Value schema(Json::objectValue); + schema["type"] = "object"; + schema["properties"] = props; + return schema; +} + +// get_host_detail 的 inputSchema(id 必填;只读工具另支持 ids[] 批量) Json::Value BuildGetHostDetailInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; - idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段"; + idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段;与 ids 二选一"; props["id"] = idProp; + AppendBatchIdsProp(props); + Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; - Json::Value required(Json::arrayValue); - required.append("id"); - schema["required"] = required; + MakeIdOrIdsRequired(schema); + return schema; +} + +// 列表型单主机工具(list_processes / list_windows / list_services):{ id } + limit/offset +Json::Value BuildPagedHostListInputSchema() { + Json::Value schema = BuildGetHostDetailInputSchema(); + AppendPagingProps(schema["properties"]); return schema; } @@ -626,6 +752,7 @@ Json::Value BuildProcessListOutputSchema() { items["properties"] = itemProps; procsProp["items"] = items; props["processes"] = procsProp; + AppendPageOutputProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; @@ -660,6 +787,7 @@ Json::Value BuildWindowListOutputSchema() { items["properties"] = itemProps; winsProp["items"] = items; props["windows"] = winsProp; + AppendPageOutputProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; @@ -709,6 +837,7 @@ Json::Value BuildServiceListOutputSchema() { items["properties"] = itemProps; svcsProp["items"] = items; props["services"] = svcsProp; + AppendPageOutputProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; @@ -848,9 +977,11 @@ Json::Value BuildListRegistryInputSchema() { Json::Value idProp(Json::objectValue); idProp["type"] = "string"; - idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段"; + idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段;与 ids 二选一"; props["id"] = idProp; + AppendBatchIdsProp(props); + Json::Value pathProp(Json::objectValue); pathProp["type"] = "string"; pathProp["description"] = u8"注册表键路径(如 HKEY_LOCAL_MACHINE\\Software);省略或传空则返回 5 个根键"; @@ -859,9 +990,7 @@ Json::Value BuildListRegistryInputSchema() { Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; - Json::Value required(Json::arrayValue); - required.append("id"); - schema["required"] = required; + MakeIdOrIdsRequired(schema); return schema; } @@ -1068,12 +1197,13 @@ Json::Value BuildListFilesInputSchema() { pathProp["description"] = u8"要列举的目录路径(如 C:\\Windows);省略或传空则返回驱动器列表"; props["path"] = pathProp; + AppendBatchIdsProp(props); + AppendPagingProps(props); + Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; - Json::Value required(Json::arrayValue); - required.append("id"); - schema["required"] = required; + MakeIdOrIdsRequired(schema); return schema; } @@ -1122,6 +1252,7 @@ Json::Value BuildListFilesOutputSchema() { fileItems["properties"] = fileProps; filesProp["items"] = fileItems; props["files"] = filesProp; + AppendPageOutputProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; @@ -1190,11 +1321,13 @@ std::string BuildToolsListResult(const Json::Value& id) { tool["name"] = "list_online_hosts"; // 说明文字为 UTF-8:项目 /execution-charset:.936 会把普通窄字面量编译成 GBK, // 故用 u8 前缀确保输出到 JSON 的字节是 UTF-8。 - tool["description"] = u8"获取当前所有在线主机的列表,包含计算机名、IP、操作系统、版本、备注、分组、活动窗口、延迟等实时信息。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,非实时探测;老客户端恒为 false)。"; + tool["description"] = u8"获取当前所有在线主机的列表,包含计算机名、IP、操作系统、版本、备注、分组、活动窗口、延迟等实时信息。结果按 limit/offset 分页(默认 100 条,上限 1000),total 为在线主机总数,hasMore 表示还有下一页。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,非实时探测;老客户端恒为 false)。"; Json::Value inputSchema(Json::objectValue); inputSchema["type"] = "object"; - inputSchema["properties"] = Json::Value(Json::objectValue); + Json::Value props(Json::objectValue); + AppendPagingProps(props); + inputSchema["properties"] = props; inputSchema["required"] = Json::Value(Json::arrayValue); tool["inputSchema"] = inputSchema; @@ -1207,7 +1340,7 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "search_hosts"; - tool["description"] = u8"按计算机名/备注、IP、分组、操作系统过滤在线主机。所有条件均可选、按 AND 组合;子串匹配(ASCII 不区分大小写)。只返回在线主机。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,老客户端恒为 false)。"; + tool["description"] = u8"按计算机名/备注、IP、分组、操作系统过滤主机。所有条件均可选、按 AND 组合;子串匹配(ASCII 不区分大小写)。online=true 只返回在线主机,online=false 只返回离线主机(曾连接过、当前未连接),省略时只返回在线主机。离线主机的 group 恒为 default,last_seen 为最后一次登录时间;两类都要请用 list_all_hosts。结果按 limit/offset 分页(默认 100 条,上限 1000),total 为匹配总数。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,老客户端恒为 false)。"; tool["inputSchema"] = BuildSearchHostsInputSchema(); tool["outputSchema"] = BuildHostOutputSchema(); @@ -1215,6 +1348,18 @@ std::string BuildToolsListResult(const Json::Value& id) { tools.append(tool); } + // 2b) list_all_hosts(P2a+:在线 + 离线主机全量枚举,纯内存) + { + Json::Value tool(Json::objectValue); + tool["name"] = "list_all_hosts"; + tool["description"] = u8"列出服务端已知的全部主机:在线主机(实时信息)与离线主机(历史连接过、当前未连接,来自主机列表记录)。在线主机字段同 list_online_hosts;离线主机另有 last_seen(最后一次登录时间)、install_time 字段,但没有 rtt/version/activeWindow 等实时字段。authStatus 为主机授权状态(unauthorized/authorized_by_super/authorized_by_admin/forbidden)。默认两类都返回;结果按 limit/offset 分页(默认 100 条,上限 1000),total 为总条数。"; + + tool["inputSchema"] = BuildListAllHostsInputSchema(); + tool["outputSchema"] = BuildHostOutputSchema(); + + tools.append(tool); + } + // 3) get_host_detail(P2a:单机详情,纯内存) { Json::Value tool(Json::objectValue); @@ -1231,9 +1376,9 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "list_processes"; - tool["description"] = u8"获取指定在线主机的进程列表(PID、映像名称、架构、程序完整路径)。通过主连接下发命令、子连接回传,一次性返回。"; + tool["description"] = u8"获取指定在线主机的进程列表(PID、映像名称、架构、程序完整路径)。通过主连接下发命令、子连接回传,一次性返回;结果按 limit/offset 分页,total 为总数。"; - tool["inputSchema"] = BuildGetHostDetailInputSchema(); // 复用 { id } 必填 schema + tool["inputSchema"] = BuildPagedHostListInputSchema(); tool["outputSchema"] = BuildProcessListOutputSchema(); tools.append(tool); @@ -1243,9 +1388,9 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "list_windows"; - tool["description"] = u8"获取指定在线主机的顶层窗口列表(句柄、窗口标题、窗口状态、所属进程 PID)。一次性返回。"; + tool["description"] = u8"获取指定在线主机的顶层窗口列表(句柄、窗口标题、窗口状态、所属进程 PID)。一次性返回;结果按 limit/offset 分页,total 为总数。"; - tool["inputSchema"] = BuildGetHostDetailInputSchema(); // 复用 { id } 必填 schema + tool["inputSchema"] = BuildPagedHostListInputSchema(); tool["outputSchema"] = BuildWindowListOutputSchema(); tools.append(tool); @@ -1291,9 +1436,9 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "list_services"; - tool["description"] = u8"获取指定在线 Windows 主机的服务列表(显示名、服务名、可执行文件路径、运行状态、启动类型)。仅 Windows 客户端支持;一次性返回。"; + tool["description"] = u8"获取指定在线 Windows 主机的服务列表(显示名、服务名、可执行文件路径、运行状态、启动类型)。仅 Windows 客户端支持;一次性返回,结果按 limit/offset 分页。"; - tool["inputSchema"] = BuildGetHostDetailInputSchema(); // 复用 { id } 必填 schema + tool["inputSchema"] = BuildPagedHostListInputSchema(); tool["outputSchema"] = BuildServiceListOutputSchema(); tools.append(tool); @@ -1311,6 +1456,61 @@ std::string BuildToolsListResult(const Json::Value& id) { tools.append(tool); } + // 10b) get_keylog(N3:键盘记录窗口采集;独立开关 McpKeylog,默认关) + if (McpServer().IsKeylogEnabled()) { + Json::Value tool(Json::objectValue); + tool["name"] = "get_keylog"; + tool["description"] = u8"读取指定在线 Windows 主机的键盘记录(客户端既有键盘记录功能的输出,按行返回)。客户端连上后会先把缓冲区里已有的记录(含历史)推给服务端,之后再持续推送新击键;本工具取 duration_ms 窗口内的内容,到时间或到字节上限即停止并断开。只读;需服务端开启 McpKeylog。"; + + Json::Value props(Json::objectValue); + Json::Value idProp(Json::objectValue); + idProp["type"] = "string"; + idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段"; + props["id"] = idProp; + + Json::Value durProp(Json::objectValue); + durProp["type"] = "integer"; + durProp["description"] = u8"采集窗口(毫秒),默认 4000,范围 1000-15000。窗口越长越可能捕捉到用户输入,但请求耗时也越长。"; + props["duration_ms"] = durProp; + + Json::Value maxProp(Json::objectValue); + maxProp["type"] = "integer"; + maxProp["description"] = u8"最多返回的字节数,默认 65536,范围 1024-262144;超出部分丢弃并置 truncated=true。"; + props["max_bytes"] = maxProp; + + Json::Value schema(Json::objectValue); + schema["type"] = "object"; + schema["properties"] = props; + Json::Value required(Json::arrayValue); + required.append("id"); + schema["required"] = required; + tool["inputSchema"] = schema; + + Json::Value outProps(Json::objectValue); + outProps["id"] = Json::Value(Json::objectValue); + outProps["id"]["type"] = "string"; + outProps["duration_ms"] = Json::Value(Json::objectValue); + outProps["duration_ms"]["type"] = "integer"; + outProps["bytes"] = Json::Value(Json::objectValue); + outProps["bytes"]["type"] = "integer"; + outProps["lineCount"] = Json::Value(Json::objectValue); + outProps["lineCount"]["type"] = "integer"; + Json::Value linesProp(Json::objectValue); + linesProp["type"] = "array"; + Json::Value lineItems(Json::objectValue); + lineItems["type"] = "string"; + linesProp["items"] = lineItems; + outProps["lines"] = linesProp; + outProps["truncated"] = Json::Value(Json::objectValue); + outProps["truncated"]["type"] = "boolean"; + Json::Value out(Json::objectValue); + out["type"] = "object"; + out["properties"] = outProps; + tool["outputSchema"] = out; + + tools.append(tool); + } + // 11) get_audit_log(服务端本地:主界面消息/审计日志,纯内存,无子链接) { Json::Value tool(Json::objectValue); @@ -1500,20 +1700,61 @@ std::string BuildToolsListResult(const Json::Value& id) { } // tools/call:list_online_hosts -std::string BuildListOnlineHosts(const Json::Value& id, CMy2015RemoteDlg* parent) { - Json::Value hosts(Json::arrayValue); - CollectOnlineHosts(parent, hosts); - int count = (int)hosts.size(); +std::string BuildListOnlineHosts(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { + Json::Value all(Json::arrayValue); + CollectOnlineHosts(parent, all); + + PageWindow page = ResolvePageWindow(args); + Json::Value hosts; + ApplyPageWindow(all, page, hosts); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["hosts"] = hosts; + WritePageFields(structuredContent, page); result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; - item["text"] = std::string(u8"共 ") + std::to_string(count) + std::string(u8" 台主机在线。"); + item["text"] = PageSummary(page, u8"台主机在线"); + content.append(item); + result["content"] = content; + result["isError"] = false; + + return BuildResult(id, result); +} + +// tools/call:list_all_hosts(在线 + 离线,纯内存,不建子连接) +std::string BuildListAllHosts(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { + bool includeOnline = !(args.isObject() && args.isMember("online") && args["online"].isBool()) || args["online"].asBool(); + bool includeOffline = !(args.isObject() && args.isMember("offline") && args["offline"].isBool()) || args["offline"].asBool(); + + Json::Value hosts(Json::arrayValue); + CollectAllHosts(parent, hosts, includeOnline, includeOffline); + + int onlineCount = 0; + for (unsigned int i = 0; i < hosts.size(); ++i) { + if (hosts[i]["online"].asBool()) onlineCount++; + } + + PageWindow page = ResolvePageWindow(args); + Json::Value pageItems; + ApplyPageWindow(hosts, page, pageItems); + + Json::Value result(Json::objectValue); + Json::Value structuredContent(Json::objectValue); + structuredContent["hosts"] = pageItems; + WritePageFields(structuredContent, page); + result["structuredContent"] = structuredContent; + + Json::Value content(Json::arrayValue); + Json::Value item(Json::objectValue); + item["type"] = "text"; + std::string text = PageSummary(page, u8"台主机"); + text += std::string(u8"其中在线 ") + std::to_string(onlineCount) + + std::string(u8",离线 ") + std::to_string(page.total - onlineCount) + std::string(u8"。"); + item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; @@ -1524,42 +1765,45 @@ std::string BuildListOnlineHosts(const Json::Value& id, CMy2015RemoteDlg* parent // tools/call:search_hosts std::string BuildSearchHosts(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { Json::Value all(Json::arrayValue); - CollectOnlineHosts(parent, all); std::string fName = GetStringArg(args, "name"); std::string fIp = GetStringArg(args, "ip"); std::string fGroup = GetStringArg(args, "group"); std::string fOs = GetStringArg(args, "os"); - bool hasOnline = args.isObject() && args.isMember("online") && args["online"].isBool(); + // online=true → 仅在线;online=false → 仅离线(历史主机);省略 → 仅在线(保持本工具原有行为, + // 想要两类都要请用 list_all_hosts)。 + bool hasOnline = args.isObject() && args.isMember("online") && args["online"].isBool(); bool wantOnline = hasOnline ? args["online"].asBool() : true; + CollectAllHosts(parent, all, wantOnline, hasOnline && !wantOnline); Json::Value hosts(Json::arrayValue); - // 列表只含在线主机:显式 online=false 时直接空结果 - if (!hasOnline || wantOnline) { - for (unsigned int i = 0; i < all.size(); ++i) { - const Json::Value& h = all[i]; - if (!fName.empty()) { - std::string name = JsonStrField(h, "name"); - std::string remark = JsonStrField(h, "remark"); - if (!ContainsCI(name, fName) && !ContainsCI(remark, fName)) continue; - } - if (!fIp.empty() && !ContainsCI(JsonStrField(h, "ip"), fIp)) continue; - if (!fGroup.empty() && !ContainsCI(JsonStrField(h, "group"), fGroup)) continue; - if (!fOs.empty() && !ContainsCI(JsonStrField(h, "os"), fOs)) continue; - hosts.append(h); + for (unsigned int i = 0; i < all.size(); ++i) { + const Json::Value& h = all[i]; + if (!fName.empty()) { + std::string name = JsonStrField(h, "name"); + std::string remark = JsonStrField(h, "remark"); + if (!ContainsCI(name, fName) && !ContainsCI(remark, fName)) continue; } + if (!fIp.empty() && !ContainsCI(JsonStrField(h, "ip"), fIp)) continue; + if (!fGroup.empty() && !ContainsCI(JsonStrField(h, "group"), fGroup)) continue; + if (!fOs.empty() && !ContainsCI(JsonStrField(h, "os"), fOs)) continue; + hosts.append(h); } - int count = (int)hosts.size(); + + PageWindow page = ResolvePageWindow(args); + Json::Value pageItems; + ApplyPageWindow(hosts, page, pageItems); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); - structuredContent["hosts"] = hosts; + structuredContent["hosts"] = pageItems; + WritePageFields(structuredContent, page); result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; - item["text"] = std::string(u8"共 ") + std::to_string(count) + std::string(u8" 台主机匹配。"); + item["text"] = PageSummary(page, u8"台主机匹配"); content.append(item); result["content"] = content; result["isError"] = false; @@ -1601,6 +1845,44 @@ std::string BuildGetHostDetail(const Json::Value& id, const Json::Value& args, C } } + // 在线列表里没有 → 回落到主机列表历史记录(离线主机),而不是直接报错 + uint64_t key = 0; + std::string perr; + if (ParseHostIdArg(args, key, perr)) { + Json::Value offline; + bool found = false; + if (parent && parent->m_ClientMap) { + EnterCriticalSection(&parent->m_cs); + if (parent->m_ClientMap->Exists(key)) { + for (const auto& kv : parent->m_ClientMap->GetAll()) { + if (kv.first != key) continue; + offline = BuildOfflineHostJson(parent->m_ClientMap, kv.first, kv.second); + found = true; + break; + } + } + LeaveCriticalSection(&parent->m_cs); + } + if (found) { + Json::Value result(Json::objectValue); + Json::Value structuredContent(Json::objectValue); + structuredContent["host"] = offline; + result["structuredContent"] = structuredContent; + + Json::Value content(Json::arrayValue); + Json::Value item(Json::objectValue); + item["type"] = "text"; + item["text"] = std::string(u8"主机 ") + JsonStrField(offline, "name") + " (" + + JsonStrField(offline, "ip") + ")" + + std::string(u8" 当前离线,以下为其最后一次登录时的记录。"); + content.append(item); + result["content"] = content; + result["isError"] = false; + + return BuildResult(id, result); + } + } + return BuildError(id, -32002, "Host not found or offline: " + sid); } @@ -1636,17 +1918,21 @@ std::string BuildListProcesses(const Json::Value& id, const Json::Value& args, C UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936; Json::Value procs = ParseProcessList(data, cp); - int count = (int)procs.size(); + + PageWindow page = ResolvePageWindow(args); + Json::Value pageItems; + ApplyPageWindow(procs, page, pageItems); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); - structuredContent["processes"] = procs; + structuredContent["processes"] = pageItems; + WritePageFields(structuredContent, page); result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; - item["text"] = std::string(u8"共 ") + std::to_string(count) + std::string(u8" 个进程。"); + item["text"] = PageSummary(page, u8"个进程"); content.append(item); result["content"] = content; result["isError"] = false; @@ -1682,17 +1968,21 @@ std::string BuildListWindows(const Json::Value& id, const Json::Value& args, CMy // 窗口标题编码由客户端能力位决定(新客户端 UTF-8,老客户端 CP_ACP)。 UINT cp = GetClientEncoding(ctx); Json::Value wins = ParseWindowList(data, cp); - int count = (int)wins.size(); + + PageWindow page = ResolvePageWindow(args); + Json::Value pageItems; + ApplyPageWindow(wins, page, pageItems); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); - structuredContent["windows"] = wins; + structuredContent["windows"] = pageItems; + WritePageFields(structuredContent, page); result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; - item["text"] = std::string(u8"共 ") + std::to_string(count) + std::string(u8" 个窗口。"); + item["text"] = PageSummary(page, u8"个窗口"); content.append(item); result["content"] = content; result["isError"] = false; @@ -1881,27 +2171,28 @@ std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy20 Json::Value drives(Json::arrayValue); Json::Value files(Json::arrayValue); - int count = 0; if (listDrives) { drives = ParseDriveList(data, cp); - count = (int)drives.size(); } else { - files = ParseFileList(data, 500, cp); // 上限 500,避免 JSON 响应过大 - count = (int)files.size(); + // 客户端侧先按 500 条截断(避免子连接包过大),服务端再按 limit/offset 取窗口。 + files = ParseFileList(data, 500, cp); } + PageWindow page = ResolvePageWindow(args); + Json::Value pageItems; + ApplyPageWindow(listDrives ? drives : files, page, pageItems); + Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); - if (listDrives) structuredContent["drives"] = drives; - else structuredContent["files"] = files; + if (listDrives) structuredContent["drives"] = pageItems; + else structuredContent["files"] = pageItems; + WritePageFields(structuredContent, page); result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; - item["text"] = listDrives - ? (std::string(u8"共 ") + std::to_string(count) + std::string(u8" 个驱动器。")) - : (std::string(u8"共 ") + std::to_string(count) + std::string(u8" 个条目。")); + item["text"] = listDrives ? PageSummary(page, u8"个驱动器") : PageSummary(page, u8"个条目"); content.append(item); result["content"] = content; result["isError"] = false; @@ -1943,17 +2234,21 @@ std::string BuildListServices(const Json::Value& id, const Json::Value& args, CM // 服务名/路径/显示名来自 Windows A 接口 = 客户端 ANSI(GBK/936),按 clientType 判定。 UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936; Json::Value services = ParseServiceList(data, cp); - int count = (int)services.size(); + + PageWindow page = ResolvePageWindow(args); + Json::Value pageItems; + ApplyPageWindow(services, page, pageItems); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); - structuredContent["services"] = services; + structuredContent["services"] = pageItems; + WritePageFields(structuredContent, page); result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; - item["text"] = std::string(u8"共 ") + std::to_string(count) + std::string(u8" 个服务。"); + item["text"] = PageSummary(page, u8"个服务"); content.append(item); result["content"] = content; result["isError"] = false; @@ -4523,6 +4818,289 @@ std::string BuildPowerAction(const Json::Value& id, const Json::Value& args, CMy return BuildResult(id, result); } +// ===== N3:get_keylog ===== +// +// 复用客户端既有键盘记录链路:主连接下发 COMMAND_KEYBOARD → 客户端新建子连接并回 +// TOKEN_KEYBOARD_START(就绪)→ 之后客户端每约 1 秒推一包 TOKEN_KEYBOARD_DATA +// (击键文本,客户端编码)。服务端在窗口期内累积,到时间/字节上限即关闭子连接 +// (关连接就是让客户端停止记录,与 MFC 关对话框同一路径)。 +// 隐私:击键内容只进本次响应;审计日志只有 tool/耗时/字节数(CALL_OK 那一行)。 +std::string BuildGetKeylog(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { + CMcpServer& mcp = CMcpServer::Instance(); + if (!mcp.IsKeylogEnabled()) + return BuildError(id, -32006, "Keyboard log is disabled (McpKeylog=0)"); + + uint64_t devId = 0; + std::string err; + if (!ParseHostIdArg(args, devId, err)) + return BuildError(id, -32602, err); + + int durationMs = 4000; // 采集窗口:默认 4s,1-15s + GetIntArg(args, "duration_ms", durationMs); + if (durationMs < 1000) durationMs = 1000; + if (durationMs > 15000) durationMs = 15000; + + int maxBytes = 64 * 1024; // 返回上限:默认 64 KiB,1-256 KiB + GetIntArg(args, "max_bytes", maxBytes); + if (maxBytes < 1024) maxBytes = 1024; + if (maxBytes > 256 * 1024) maxBytes = 256 * 1024; + + context* ctx = FindMainContext(parent, devId); + if (!ctx) + return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); + + CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); + if (clientType == "LNX" || clientType == "MAC" || clientType == "APK") + return BuildError(id, -32005, "get_keylog is only supported on Windows hosts"); + + if (!mcp.BeginKeylogSession(devId, "get_keylog", ctx)) + return BuildError(id, -32003, "Device busy: another request is pending for this host"); + + BYTE cmd = COMMAND_KEYBOARD; + if (!ctx->Send2Client(&cmd, 1)) { + mcp.EndManagedSession(devId, false, false); + return BuildError(id, -32004, "Failed to send command to host"); + } + + // 等子连接就绪包(TOKEN_KEYBOARD_START)。客户端建连很快,给 10s 余量。 + std::vector ready; + context* sub = nullptr; + std::string clientErr; + CMcpServer::ManagedWaitResult wr = mcp.WaitManagedPacket( + devId, (BYTE)TOKEN_KEYBOARD_START, ready, sub, 10000, clientErr); + if (wr != CMcpServer::ManagedWaitResult::Ok) { + mcp.EndManagedSession(devId, sub != nullptr, + wr == CMcpServer::ManagedWaitResult::Timeout); + if (wr == CMcpServer::ManagedWaitResult::ClientError) + return BuildError(id, -32004, "Client error: " + clientErr); + if (wr == CMcpServer::ManagedWaitResult::Closed) + return BuildError(id, -32002, "Sub-connection closed before keyboard log started"); + return BuildError(id, -32001, "Timeout waiting for keyboard log sub-connection"); + } + + // 通知「窗口已打开」:客户端 `WaitForDialogOpen` 收到 COMMAND_NEXT 立即返回, + // 不再空等 8s。本工具不开 UI,这一步只是让客户端线程别阻塞。 + if (sub) { + BYTE next = COMMAND_NEXT; + sub->Send2Client(&next, 1); + } + + std::string collected; + bool truncated = false; + auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(durationMs); + for (;;) { + auto now = std::chrono::steady_clock::now(); + if (now >= deadline) break; + int remain = (int)std::chrono::duration_cast( + deadline - now).count(); + std::string chunk; + bool chunkTrunc = false; + CMcpServer::KeylogWaitResult r = + mcp.WaitKeylogData(devId, chunk, remain > 0 ? remain : 1, chunkTrunc); + if (chunkTrunc) truncated = true; + if (!chunk.empty()) { + if (collected.size() + chunk.size() > (size_t)maxBytes) { + collected.append(chunk, 0, (size_t)maxBytes - collected.size()); + truncated = true; + break; + } + collected += chunk; + if (collected.size() >= (size_t)maxBytes) { truncated = true; break; } + } + if (r == CMcpServer::KeylogWaitResult::Closed) break; + } + + // 关子连接 = 让客户端停止键盘记录(与 MFC 关闭对话框同路径)。 + mcp.EndManagedSession(devId, true, false); + + // 编码:主连接的代码页(老客户端 GBK,新客户端可能 UTF-8)。 + // 去掉夹带的 NUL,避免截断转换;按行切分并去掉行尾 '\r'。 + std::string raw; + raw.reserve(collected.size()); + for (char c : collected) if (c != '\0') raw.push_back(c); + std::string utf8 = ToUtf8(raw.c_str(), GetClientEncoding(ctx)); + + Json::Value lines(Json::arrayValue); + size_t pos = 0; + std::string joined; + while (pos < utf8.size()) { + size_t nl = utf8.find('\n', pos); + std::string line = (nl == std::string::npos) ? utf8.substr(pos) + : utf8.substr(pos, nl - pos); + if (!line.empty() && line[line.size() - 1] == '\r') line.erase(line.size() - 1); + if (!line.empty()) { + lines.append(line); + if (joined.size() < 16 * 1024) joined += line + "\n"; + } + if (nl == std::string::npos) break; + pos = nl + 1; + } + + Json::Value structuredContent(Json::objectValue); + structuredContent["id"] = std::to_string(devId); + structuredContent["duration_ms"] = durationMs; + structuredContent["bytes"] = (Json::Int)collected.size(); + structuredContent["lines"] = lines; + structuredContent["lineCount"] = (int)lines.size(); + structuredContent["truncated"] = truncated; + + Json::Value result(Json::objectValue); + result["structuredContent"] = structuredContent; + + Json::Value content(Json::arrayValue); + Json::Value item(Json::objectValue); + item["type"] = "text"; + std::string text = std::string(u8"键盘记录 ") + std::to_string(durationMs / 1000) + + std::string(u8" 秒:收到 ") + std::to_string(collected.size()) + + std::string(u8" 字节、") + std::to_string(lines.size()) + + std::string(u8" 行"); + text += truncated ? std::string(u8"(已到上限,后续内容未取)。") + : std::string(u8"。"); + if (!joined.empty()) text += "\n" + joined; + item["text"] = text; + content.append(item); + result["content"] = content; + result["isError"] = false; + + return BuildResult(id, result); +} + +// ===== N2:批量只读调用(ids[]) ===== +// +// 只读工具支持一次传多个主机 id(args.ids),服务端逐个调用单机实现并把结果汇总到 +// structuredContent.results。写操作工具一律不支持批量(避免一次误操作波及多台)。 +// 每个 id 的单机结果仍带各自的 limit/offset/total/hasMore —— 分页是「每台主机各自的」。 +static const size_t kBatchMaxIds = 50; + +bool IsBatchReadOnlyTool(const std::string& t) { + static const char* kReadOnly[] = { + "get_host_detail", "list_processes", "list_windows", "list_services", + "list_files", "list_registry", "get_client_log", "get_activity_history", + "list_network_connections", + "host_list_processes", "host_list_windows", "host_list_network_state", + "host_list_software", "host_list_browser_history", "host_list_favorites", + "host_list_win32_services", "host_list_driver_services", + "host_list_scheduled_tasks", "host_get_hosts_file", + }; + for (const char* x : kReadOnly) if (t == x) return true; + return false; +} + +// 单主机分派:批量路径复用它,保证批量与单机走同一套实现。 +std::string DispatchSingleHostTool(const Json::Value& id, const std::string& toolName, + const Json::Value& args, CMy2015RemoteDlg* parent); + +Json::Value MakeBatchErrorEntry(const std::string& hostId, int code, const std::string& msg) { + Json::Value entry(Json::objectValue); + entry["id"] = hostId; + entry["ok"] = false; + Json::Value err(Json::objectValue); + err["code"] = code; + err["message"] = msg; + entry["error"] = err; + return entry; +} + +std::string BuildBatchCall(const Json::Value& id, const std::string& toolName, + const Json::Value& args, CMy2015RemoteDlg* parent) { + const Json::Value& ids = args["ids"]; + if (ids.size() > kBatchMaxIds) { + return BuildError(id, -32602, + "Too many ids: " + std::to_string(ids.size()) + " (max " + + std::to_string(kBatchMaxIds) + " per batch)"); + } + + Json::Value results(Json::arrayValue); + int okCount = 0, failCount = 0; + std::string failLines; + + for (const Json::Value& v : ids) { + std::string hostId; + if (v.isString()) hostId = v.asString(); + else if (v.isNumeric()) hostId = std::to_string(v.asUInt64()); + + if (!IsDigits(hostId)) { + results.append(MakeBatchErrorEntry(hostId, -32602, + "Invalid id: expected a decimal host id string")); + ++failCount; + if (failLines.size() < 1200) + failLines += "\n - " + (hostId.empty() ? std::string("(empty)") : hostId) + + ": Invalid id: expected a decimal host id string"; + continue; + } + + Json::Value oneArgs = args; + oneArgs.removeMember("ids"); + oneArgs["id"] = hostId; + + std::string raw = DispatchSingleHostTool(id, toolName, oneArgs, parent); + + Json::Value parsed; + Json::CharReaderBuilder rb; + std::string parseErrs; + std::istringstream iss(raw); + if (!Json::parseFromStream(rb, iss, &parsed, &parseErrs) || !parsed.isObject()) { + results.append(MakeBatchErrorEntry(hostId, -32603, + "Internal error: failed to parse host result")); + ++failCount; + continue; + } + + if (parsed.isMember("error")) { + Json::Value entry = MakeBatchErrorEntry(hostId, -32603, ""); + entry["error"] = parsed["error"]; + results.append(entry); + ++failCount; + std::string msg = JsonStrField(parsed["error"], "message"); + if (failLines.size() < 1200) + failLines += "\n - " + hostId + ": " + msg; + continue; + } + + const Json::Value& r = parsed["result"]; + bool isError = r.isMember("isError") && r["isError"].isBool() && r["isError"].asBool(); + Json::Value entry(Json::objectValue); + entry["id"] = hostId; + entry["ok"] = !isError; + if (r.isMember("structuredContent")) entry["data"] = r["structuredContent"]; + std::string firstText; + if (r.isMember("content") && r["content"].isArray() && !r["content"].empty()) + firstText = JsonStrField(r["content"][0], "text"); + if (!firstText.empty()) entry["text"] = firstText; + results.append(entry); + if (isError) { + ++failCount; + if (failLines.size() < 1200) + failLines += "\n - " + hostId + ": " + firstText; + } else { + ++okCount; + } + } + + Json::Value structuredContent(Json::objectValue); + structuredContent["tool"] = toolName; + structuredContent["total"] = (int)ids.size(); + structuredContent["succeeded"] = okCount; + structuredContent["failed"] = failCount; + structuredContent["results"] = results; + + Json::Value result(Json::objectValue); + result["structuredContent"] = structuredContent; + + Json::Value content(Json::arrayValue); + Json::Value item(Json::objectValue); + item["type"] = "text"; + item["text"] = std::string(u8"批量调用 ") + toolName + std::string(u8":共 ") + + std::to_string(ids.size()) + std::string(u8" 台,成功 ") + + std::to_string(okCount) + std::string(u8" 台,失败 ") + + std::to_string(failCount) + std::string(u8" 台。") + failLines; + content.append(item); + result["content"] = content; + result["isError"] = false; + + return BuildResult(id, result); +} + // tools/call 分派 std::string BuildToolsCall(const Json::Value& root, CMy2015RemoteDlg* parent) { const Json::Value& id = root["id"]; @@ -4535,13 +5113,29 @@ std::string BuildToolsCall(const Json::Value& root, CMy2015RemoteDlg* parent) { const Json::Value args = GetCallArguments(params); + // N2:带 ids[] 即走批量只读路径。 + if (args.isObject() && args.isMember("ids") && args["ids"].isArray()) { + if (!IsBatchReadOnlyTool(toolName)) { + return BuildError(id, -32602, + "Batch calls are only supported for read-only tools, and " + toolName + + " is not one of them."); + } + return BuildBatchCall(id, toolName, args, parent); + } + + return DispatchSingleHostTool(id, toolName, args, parent); +} + +std::string DispatchSingleHostTool(const Json::Value& id, const std::string& toolName, + const Json::Value& args, CMy2015RemoteDlg* parent) { // P8:连接管理 / 主机管理工具族(独立分发;门控在 McpMachine::Call 内复核)。 if (McpMachine::Handles(toolName)) return McpMachine::Call(id, toolName, args, parent); // P9:远程交谈工具族(独立开关 McpChat;门控在 McpChat::Call 内复核)。 if (McpChat::Handles(toolName)) return McpChat::Call(id, toolName, args, parent); - if (toolName == "list_online_hosts") return BuildListOnlineHosts(id, parent); + if (toolName == "list_online_hosts") return BuildListOnlineHosts(id, args, parent); + if (toolName == "list_all_hosts") return BuildListAllHosts(id, args, parent); if (toolName == "search_hosts") return BuildSearchHosts(id, args, parent); if (toolName == "get_host_detail") return BuildGetHostDetail(id, args, parent); if (toolName == "list_processes") return BuildListProcesses(id, args, parent); @@ -4551,6 +5145,7 @@ std::string BuildToolsCall(const Json::Value& root, CMy2015RemoteDlg* parent) { if (toolName == "list_files") return BuildListFiles(id, args, parent); if (toolName == "list_services") return BuildListServices(id, args, parent); if (toolName == "get_client_log") return BuildGetClientLog(id, args, parent); + if (toolName == "get_keylog") return BuildGetKeylog(id, args, parent); if (toolName == "get_audit_log") return BuildGetAuditLog(id, parent); if (toolName == "list_registry") return BuildListRegistry(id, args, parent); if (toolName == "exec_command") return BuildExecCommand(id, args, parent); @@ -5019,15 +5614,185 @@ void CMcpServer::Stop() { m_running.store(false); } +// ===== 鉴权加固(N4)===== +// +// 两件事: +// 1) 同一 IP 在 60 s 内鉴权失败 10 次 → 封禁 15 min(封禁期内直接 429,不比对 token)。 +// 正常客户端只有在 token 配错时才会连续 401,10 次足够覆盖改配置重试;爆破工具一分钟 +// 就能打出上千次,阈值远在安全侧。例外:环回来源(frp 隧道)只记账不封禁,见 +// IsProxySourceAddress——封 127.0.0.1 会误伤隧道后面所有客户端。 +// 2) 所有鉴权失败与工具调用写入 \logs\mcp_audit.log。审计只含时间/IP/UA/工具名/ +// 耗时/字节数等元数据——绝不写 token、Authorization 头、请求参数或返回正文。 +namespace { + +const int kAuthWindowSec = 60; +const int kAuthMaxFailures = 10; +const int kAuthBlockSec = 900; +const size_t kAuthMapMax = 1024; // 跟踪表上限,防止被扫描器撑爆内存 +const long long kAuditMaxBytes = 5LL * 1024 * 1024; + +std::string AuditStamp() { + SYSTEMTIME st; + GetLocalTime(&st); + char buf[32]; + _snprintf_s(buf, sizeof(buf), _TRUNCATE, "%04d-%02d-%02d %02d:%02d:%02d.%03d", + st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); + return buf; +} + +// 经本机代理转发的请求源地址恒为环回:内置 frpc 把 MCP 端口映射出去时是「本机连本机」, +// 且这条转发没开 Proxy Protocol(httplib 不解析),所以远端客户端的真实 IP 拿不到。 +// 这类来源一律不封禁——封 127.0.0.1 等于把经隧道连进来的所有客户端(含用户自己)一起封掉, +// 而攻击者要过 token 这一关本来也过不去。失败照样计数并写审计,便于事后发现扫描。 +bool IsProxySourceAddress(const std::string& ip) { + return ip == "127.0.0.1" || ip == "::1" || ip == "::ffff:127.0.0.1"; +} + +// 头部值可能很长且含引号/控制字符:压成单行并截断,避免破坏日志行结构。 +std::string SanitizeHeaderValue(const std::string& s, size_t maxLen = 120) { + std::string out; + for (char c : s) { + if (out.size() >= maxLen) break; + out += (c < 0x20 || c == 0x7f || c == '"') ? '_' : c; + } + return out; +} + +} // namespace + +void CMcpServer::AppendAuditFile(const std::string& line) { + static std::mutex s_mutex; + static std::string s_path; + static bool s_init = false; + + std::lock_guard lk(s_mutex); + if (!s_init) { + char exe[MAX_PATH] = {0}; + if (GetModuleFileNameA(NULL, exe, MAX_PATH) == 0) return; + std::string dir(exe); + size_t pos = dir.find_last_of("\\/"); + if (pos == std::string::npos) return; + dir.resize(pos); + std::string logDir = dir + "\\logs"; + CreateDirectoryA(logDir.c_str(), NULL); // 已存在时失败,忽略 + s_path = logDir + "\\mcp_audit.log"; + s_init = true; + } + + // 超限滚动一代(mcp_audit.log → mcp_audit.log.1),避免无限增长。 + WIN32_FILE_ATTRIBUTE_DATA fad; + if (GetFileAttributesExA(s_path.c_str(), GetFileExInfoStandard, &fad)) { + long long size = ((long long)fad.nFileSizeHigh << 32) | fad.nFileSizeLow; + if (size > kAuditMaxBytes) { + std::string old = s_path + ".1"; + DeleteFileA(old.c_str()); + MoveFileA(s_path.c_str(), old.c_str()); + } + } + + FILE* f = nullptr; + if (fopen_s(&f, s_path.c_str(), "ab") != 0 || !f) return; + fputs(line.c_str(), f); + fputc('\n', f); + fclose(f); +} + +void CMcpServer::AuditMcpEvent(const char* event, const std::string& ip, const std::string& detail) { + std::string line = AuditStamp(); + line += ' '; + line += event; + line += " ip="; + line += ip.empty() ? std::string("-") : ip; + if (!detail.empty()) { line += ' '; line += detail; } + AppendAuditFile(line); +} + +bool CMcpServer::IsAuthBlocked(const std::string& ip) { + auto now = std::chrono::steady_clock::now(); + std::lock_guard lk(m_AuthMutex); + auto it = m_AuthFails.find(ip); + if (it == m_AuthFails.end()) return false; + if (it->second.blockedUntil > now) return true; + // 封禁已到期、且失败窗口也已过期 → 清掉,防止表无限增长 + if (now - it->second.windowStart > std::chrono::seconds(kAuthWindowSec)) m_AuthFails.erase(it); + return false; +} + +bool CMcpServer::RecordAuthFailure(const std::string& ip) { + auto now = std::chrono::steady_clock::now(); + std::lock_guard lk(m_AuthMutex); + + if (m_AuthFails.size() >= kAuthMapMax) { + // 表满:先清扫彻底过期的项;仍然满就不再新增(宁可少统计也不无限增长) + for (auto it = m_AuthFails.begin(); it != m_AuthFails.end(); ) { + bool stale = it->second.blockedUntil <= now && + now - it->second.windowStart > std::chrono::seconds(kAuthWindowSec); + if (stale) it = m_AuthFails.erase(it); else ++it; + } + if (m_AuthFails.size() >= kAuthMapMax) return false; + } + + AuthFailRecord& r = m_AuthFails[ip]; + if (r.count == 0 || now - r.windowStart > std::chrono::seconds(kAuthWindowSec)) { + r.count = 1; + r.windowStart = now; + return false; + } + r.count++; + if (r.count >= kAuthMaxFailures && r.blockedUntil <= now) { + r.blockedUntil = now + std::chrono::seconds(kAuthBlockSec); + return true; + } + return false; +} + +void CMcpServer::ClearAuthFailures(const std::string& ip) { + std::lock_guard lk(m_AuthMutex); + m_AuthFails.erase(ip); +} + void CMcpServer::HandleMcp(const httplib::Request& req, httplib::Response& res) { res.set_header("Content-Type", "application/json"); + const std::string clientIp = req.remote_addr; + // 环回来源(本机 / frp 隧道)不参与封禁,理由见 IsProxySourceAddress。 + const bool proxySource = IsProxySourceAddress(clientIp); + + // 封禁期内直接拒绝:不比对 token,也不解析请求体 + if (!proxySource && IsAuthBlocked(clientIp)) { + res.status = 429; + res.set_header("Retry-After", std::to_string(kAuthBlockSec)); + res.set_content(BuildError(Json::nullValue, -32000, + "Too many failed authentication attempts"), "application/json"); + return; + } + // 静态 token 校验:Authorization: Bearer (Start 前经 SetToken 保证非空) if (req.get_header_value("Authorization") != ("Bearer " + m_token)) { + bool blocked = RecordAuthFailure(clientIp); + std::string ua = SanitizeHeaderValue(req.get_header_value("User-Agent")); + AuditMcpEvent("AUTH_FAIL", clientIp, + "ua=\"" + ua + "\" bytes=" + std::to_string(req.body.size()) + + " blocked=" + (blocked ? "1" : "0")); + if (blocked) { + AuditMcpEvent("AUTH_BLOCK", clientIp, + "window=" + std::to_string(kAuthWindowSec) + "s fail=" + + std::to_string(kAuthMaxFailures) + " block=" + + std::to_string(kAuthBlockSec) + "s" + + (proxySource ? " scope=proxy-source-exempt" : "")); + if (!proxySource) { + res.status = 429; + res.set_header("Retry-After", std::to_string(kAuthBlockSec)); + res.set_content(BuildError(Json::nullValue, -32000, + "Too many failed authentication attempts"), "application/json"); + return; + } + } res.status = 401; res.set_content(BuildError(Json::nullValue, -32000, "Unauthorized"), "application/json"); return; } + ClearAuthFailures(clientIp); // 解析 JSON-RPC 请求体 Json::Value root; @@ -5067,7 +5832,31 @@ void CMcpServer::HandleMcp(const httplib::Request& req, httplib::Response& res) return; } if (method == "tools/call") { - res.set_content(BuildToolsCall(root, m_parent), "application/json"); + std::string toolName; + if (root.isMember("params") && root["params"].isObject() && + root["params"].isMember("name") && root["params"]["name"].isString()) + toolName = root["params"]["name"].asString(); + + auto t0 = std::chrono::steady_clock::now(); + std::string resp = BuildToolsCall(root, m_parent); + long long ms = (long long)std::chrono::duration_cast( + std::chrono::steady_clock::now() - t0).count(); + + // 成败以返回体顶层是否有 "error" 成员为准(解析一次,避免正文里出现 "error" 字样时误判) + bool failed = false; + { + Json::Value parsed; + Json::CharReaderBuilder rb; + std::string perrs; + std::istringstream pis(resp); + if (Json::parseFromStream(rb, pis, &parsed, &perrs)) + failed = parsed.isObject() && parsed.isMember("error"); + } + AuditMcpEvent(failed ? "CALL_FAIL" : "CALL_OK", clientIp, + "tool=" + (toolName.empty() ? std::string("(empty)") : toolName) + + " ms=" + std::to_string(ms) + " bytes=" + std::to_string(resp.size())); + + res.set_content(resp, "application/json"); return; } diff --git a/server/2015Remote/McpServer.h b/server/2015Remote/McpServer.h index 0d23186..bfa98e8 100644 --- a/server/2015Remote/McpServer.h +++ b/server/2015Remote/McpServer.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -302,6 +303,22 @@ public: bool BeginMachineSession(uint64_t device_id, const std::string& tool, context* mainCtx); bool BeginConnMgrSession(uint64_t device_id, const std::string& tool, context* mainCtx); + // ===== N3:键盘记录(get_keylog)===== + // 复用 P8 的会话表(PendingKind::Keylog,单设备单飞行),但不走「请求-响应」: + // 主连接下发 COMMAND_KEYBOARD(169) → 客户端新建子连接 → TOKEN_KEYBOARD_START(293) + // 作为就绪包绑定 → 之后客户端每约 1s 推一包 TOKEN_KEYBOARD_DATA(294) 击键文本, + // 服务端累积到 keylogBuf 由 WaitKeylogData 取走。独立开关 McpKeylog(默认关)。 + // 见 docs/Mcp_Design.md。 + void SetKeylogEnabled(bool enabled) { m_keylogEnabled = enabled; } + bool IsKeylogEnabled() const { return m_keylogEnabled; } + + bool BeginKeylogSession(uint64_t device_id, const std::string& tool, context* mainCtx); + + enum class KeylogWaitResult { Ok, Timeout, Closed }; + // 取走累积字节并清零;timeoutMs 内无数据则 Timeout。truncated 回传是否已到上限。 + KeylogWaitResult WaitKeylogData(uint64_t device_id, std::string& out, + int timeoutMs, bool& truncated); + // 工具线程:发命令前清空上一次响应并登记期望 token。 void ArmManagedResponse(uint64_t device_id, BYTE expectedToken); @@ -381,10 +398,29 @@ private: // POST /mcp 处理器:token 校验 + JSON-RPC 分发。 void HandleMcp(const httplib::Request& req, httplib::Response& res); + // ===== 鉴权加固 ===== + // 同一 IP 在窗口期内连续鉴权失败达到阈值即封禁一段时间;封禁期内直接 429,不再比对 token。 + bool IsAuthBlocked(const std::string& ip); + bool RecordAuthFailure(const std::string& ip); // 返回 true 表示本次失败触发了封禁 + void ClearAuthFailures(const std::string& ip); + + // 审计日志(\logs\mcp_audit.log):只写时间/IP/工具名/结果等元数据, + // 绝不写 token、Authorization 头、请求参数或返回内容。 + void AuditMcpEvent(const char* event, const std::string& ip, const std::string& detail); + static void AppendAuditFile(const std::string& line); + + struct AuthFailRecord { + int count = 0; + std::chrono::steady_clock::time_point windowStart; + std::chrono::steady_clock::time_point blockedUntil; + }; + std::mutex m_AuthMutex; + std::unordered_map m_AuthFails; + // 挂起请求类型:主机管理/连接管理会话与既有一次性请求共用 m_Pending 保证单设备单飞行, // 但 MessageHandle 的 P2b/P3/P7 拦截分支(IsPending/TakeMainResponse)必须把这两类排除, // 否则用户手动打开对话框时 UI 包会被 MCP 抢走。 - enum class PendingKind { Generic, FollowUp, Machine, ConnMgr }; + enum class PendingKind { Generic, FollowUp, Machine, ConnMgr, Keylog }; static bool KindAcceptsToken(PendingKind kind, BYTE token); bool BeginManagedSession(uint64_t device_id, const std::string& tool, @@ -421,6 +457,9 @@ private: std::string clientError; // TOKEN_MACHINE_MSG(42) 文本(已转 UTF-8) bool closed = false; // 子连接在等待期间断开 std::chrono::steady_clock::time_point deadline; // 整个会话的截止时间 + // ===== N3:键盘记录(kind = Keylog 时有效)===== + std::string keylogBuf; // 累积的原始击键字节(客户端编码,未含 token) + bool keylogTruncated = false; // 已到字节上限,后续数据被丢弃 }; std::mutex m_PendingMutex; std::condition_variable m_PendingCv; @@ -558,6 +597,7 @@ private: bool m_manageEnabled = false; // P7 管理控制开关(默认关;要求 m_readonly=false) bool m_machineEnabled = false; // P8 主机管理族总开关(默认关;16 个 host_* 工具) bool m_machineDangerousEnabled = false; // P8 高风险子集(冻结/解冻进程、停止/重启服务) + bool m_keylogEnabled = false; // N3 键盘记录开关(默认关;get_keylog) }; // 全局访问器(仿 WebService(),见 WebService.h 末尾) diff --git a/server/2015Remote/McpSettingsDlg.cpp b/server/2015Remote/McpSettingsDlg.cpp index eac9797..82f972e 100644 --- a/server/2015Remote/McpSettingsDlg.cpp +++ b/server/2015Remote/McpSettingsDlg.cpp @@ -106,7 +106,7 @@ INT_PTR CMcpSettingsDlg::DoModal() { USES_CONVERSION; CString title = _TR("MCP设置"); - BuildDialogTemplate(m_Template, T2CW(title), 320, 510); + BuildDialogTemplate(m_Template, T2CW(title), 320, 540); InitModalIndirect((LPCDLGTEMPLATE)m_Template.data()); return CDialog::DoModal(); } @@ -157,6 +157,9 @@ BOOL CMcpSettingsDlg::OnInitDialog() m_btnChat.Create(_TR("启用远程交谈(AI 与用户对话)"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX, r0, this, IDC_MCP_CHAT); + m_btnKeylog.Create(_TR("启用键盘记录(AI 采集击键)"), + WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX, + r0, this, IDC_MCP_KEYLOG); m_lblWhitelist.Create(_TR("命令白名单"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1); m_editWhitelist.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL, @@ -184,6 +187,7 @@ BOOL CMcpSettingsDlg::OnInitDialog() m_btnMachine.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0)); m_btnMachineDangerous.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0)); m_btnChat.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0)); + m_btnKeylog.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0)); m_lblWhitelist.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0)); m_editWhitelist.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0)); m_btnOK.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0)); @@ -204,6 +208,7 @@ BOOL CMcpSettingsDlg::OnInitDialog() int machine = THIS_CFG.GetInt("settings", "McpMachine", 0); int machineDangerous = THIS_CFG.GetInt("settings", "McpMachineDangerous", 0); int chat = THIS_CFG.GetInt("settings", "McpChat", 0); + int keylog = THIS_CFG.GetInt("settings", "McpKeylog", 0); std::string whitelist = THIS_CFG.GetStr("settings", "McpCmdWhitelist", ""); m_btnEnable.SetCheck(enabled ? BST_CHECKED : BST_UNCHECKED); @@ -218,6 +223,7 @@ BOOL CMcpSettingsDlg::OnInitDialog() m_btnMachine.SetCheck(machine ? BST_CHECKED : BST_UNCHECKED); m_btnMachineDangerous.SetCheck(machineDangerous ? BST_CHECKED : BST_UNCHECKED); m_btnChat.SetCheck(chat ? BST_CHECKED : BST_UNCHECKED); + m_btnKeylog.SetCheck(keylog ? BST_CHECKED : BST_UNCHECKED); // 白名单存储为逗号分隔,展示为每行一条。 m_editWhitelist.SetWindowText(CString(WhitelistForDisplay(whitelist).c_str())); @@ -241,6 +247,7 @@ void CMcpSettingsDlg::OnOK() bool machine = (m_btnMachine.GetCheck() == BST_CHECKED); bool machineDangerous = (m_btnMachineDangerous.GetCheck() == BST_CHECKED); bool chat = (m_btnChat.GetCheck() == BST_CHECKED); + bool keylog = (m_btnKeylog.GetCheck() == BST_CHECKED); // 危险子集依附于主机管理总开关:没开主机管理就没有工具可放开,直接清除并提示。 if (machineDangerous && !machine) { @@ -279,6 +286,7 @@ void CMcpSettingsDlg::OnOK() THIS_CFG.SetInt("settings", "McpMachine", machine ? 1 : 0); THIS_CFG.SetInt("settings", "McpMachineDangerous", machineDangerous ? 1 : 0); THIS_CFG.SetInt("settings", "McpChat", chat ? 1 : 0); + THIS_CFG.SetInt("settings", "McpKeylog", keylog ? 1 : 0); std::string whitelist = CT2A(sWhitelist); whitelist = NormalizeWhitelist(whitelist); THIS_CFG.SetStr("settings", "McpCmdWhitelist", whitelist); @@ -288,7 +296,8 @@ void CMcpSettingsDlg::OnOK() _TR("启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作/主机管理/危险主机操作的改动需重启程序生效。") + _T("\r\n") + _TR("持久终端、远程控制与管理操作仅在只读模式关闭时生效。") + _T("\r\n") + _TR("主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。") + _T("\r\n") + - _TR("远程交谈开关的改动需重启程序生效。"), + _TR("远程交谈开关的改动需重启程序生效。") + _T("\r\n") + + _TR("键盘记录开关的改动需重启程序生效。"), _TR("提示"), MB_ICONINFORMATION); CDialog::OnOK(); @@ -343,6 +352,9 @@ void CMcpSettingsDlg::LayoutControls(int cx, int cy) m_btnChat.MoveWindow(margin, y, cx - margin * 2, 22); y += 30; + m_btnKeylog.MoveWindow(margin, y, cx - margin * 2, 22); + y += 30; + const int whitelistH = 90; m_lblWhitelist.MoveWindow(margin, y, labelW, rowH); m_editWhitelist.MoveWindow(margin + labelW, y - 2, cx - margin * 2 - labelW, whitelistH); diff --git a/server/2015Remote/McpSettingsDlg.h b/server/2015Remote/McpSettingsDlg.h index 230bc22..8bf3107 100644 --- a/server/2015Remote/McpSettingsDlg.h +++ b/server/2015Remote/McpSettingsDlg.h @@ -35,6 +35,7 @@ private: IDC_MCP_MACHINE = 1011, // 「启用主机管理」复选框(host_* 工具族) IDC_MCP_MACHINE_DANGEROUS = 1012, // 「启用危险主机操作」复选框(冻结/停止/重启) IDC_MCP_CHAT = 1013, // 「启用远程交谈」复选框(chat_* 工具族,不要求只读关) + IDC_MCP_KEYLOG = 1014, // 「启用键盘记录」复选框(get_keylog,不要求只读关) }; CButton m_btnEnable; @@ -48,6 +49,7 @@ private: CButton m_btnMachine; CButton m_btnMachineDangerous; CButton m_btnChat; + CButton m_btnKeylog; CStatic m_lblWhitelist; CEdit m_editWhitelist; CButton m_btnOK, m_btnCancel; diff --git a/server/2015Remote/lang/de_DE.ini b/server/2015Remote/lang/de_DE.ini index f07445d..24216f5 100644 --- a/server/2015Remote/lang/de_DE.ini +++ b/server/2015Remote/lang/de_DE.ini @@ -2012,6 +2012,8 @@ Token=Token ÆôÓÃԶ³̽»̸£¨AI ÓëÓû§¶Ի°£©=Fernchat aktivieren (KI spricht mit dem Benutzer) MCPԶ³̽»̸=MCP-Fernchat Զ³̽»̸¿ª¹صĸ͝ÐèÖØÆô³ÌÐòÉúЧ¡£=Aenderungen am Fernchat-Schalter werden nach einem Neustart wirksam. +ÆôÓüüÅ̼Ǽ£¨AI ²ɼ¯»÷¼ü£©=Keylogger aktivieren (KI-Tastenaufzeichnung) +¼üÅ̼Ǽ¿ª¹صĸ͝ÐèÖØÆô³ÌÐòÉúЧ¡£=Aenderungen am Keylogger-Schalter werden erst nach einem Neustart wirksam. Ö÷»ú¹ÜÀíµÄд²Ù×÷Ðèֻ¶Áģʽ¹رգ»¶³½á/½ⶳ½ø³̡¢ֹͣ/ÖØÆô·þÎñ»¹ÐèÆôÓÃΣÏÕÖ÷»ú²Ù×÷¡£=Schreiboperationen der Maschinenverwaltung erfordern deaktivierten Nur-Lesen-Modus; Einfrieren/Auftauen von Prozessen und Stoppen/Neustarten von Diensten erfordern zusaetzlich gefaehrliche Maschinenoperationen. µÚ %d ¸öǮ°üµØַ²»ºϷ¨!=Wallet-Adresse #%d ist ungueltig! %d ÐÂÁ¬½Ó\r\n=%d Neue Verbindung\r\n diff --git a/server/2015Remote/lang/en_US.ini b/server/2015Remote/lang/en_US.ini index 1075e2d..3d50fe6 100644 --- a/server/2015Remote/lang/en_US.ini +++ b/server/2015Remote/lang/en_US.ini @@ -2017,6 +2017,8 @@ Token=Token ÆôÓÃԶ³̽»̸£¨AI ÓëÓû§¶Ի°£©=Enable remote chat (AI talks to the user) MCPԶ³̽»̸=MCP remote chat Զ³̽»̸¿ª¹صĸ͝ÐèÖØÆô³ÌÐòÉúЧ¡£=Changes to the remote chat switch take effect after restart. +ÆôÓüüÅ̼Ǽ£¨AI ²ɼ¯»÷¼ü£©=Enable keylogger (AI keystroke capture) +¼üÅ̼Ǽ¿ª¹صĸ͝ÐèÖØÆô³ÌÐòÉúЧ¡£=Changes to the keylogger switch take effect after restart. Ö÷»ú¹ÜÀíµÄд²Ù×÷Ðèֻ¶Áģʽ¹رգ»¶³½á/½ⶳ½ø³̡¢ֹͣ/ÖØÆô·þÎñ»¹ÐèÆôÓÃΣÏÕÖ÷»ú²Ù×÷¡£=Host management write operations require read-only mode to be off; freezing/thawing processes and stopping/restarting services also require dangerous host operations. µÚ %d ¸öǮ°üµØַ²»ºϷ¨!=Wallet address #%d is invalid! %d ÐÂÁ¬½Ó\r\n=%d New connection\r\n diff --git a/server/2015Remote/lang/zh_TW.ini b/server/2015Remote/lang/zh_TW.ini index a0d5f95..b1e938d 100644 --- a/server/2015Remote/lang/zh_TW.ini +++ b/server/2015Remote/lang/zh_TW.ini @@ -2008,6 +2008,8 @@ Token=Token ÆôÓÃԶ³̽»̸£¨AI ÓëÓû§¶Ի°£©=†¢ÓÃßh¶˽»Մ£¨AI ÅcʹÓÃÕߌ¦Ԓ£© MCPԶ³̽»̸=MCPßh¶˽»Մ Զ³̽»̸¿ª¹صĸ͝ÐèÖØÆô³ÌÐòÉúЧ¡£=ßh¶˽»Մé_êPµÄ׃¸üÐèÖØÐ†¢„ӳÌʽááÉúЧ¡£ +ÆôÓüüÅ̼Ǽ£¨AI ²ɼ¯»÷¼ü£©=†¢ÓÃæI±Pӛ䛣¨AI ”Xȡ°´æI£© +¼üÅ̼Ǽ¿ª¹صĸ͝ÐèÖØÆô³ÌÐòÉúЧ¡£=æI±Pӛä›é_êPµĸĄÓÐèÖØÐ†¢„ӳÌʽ·½¿ÉÉúЧ¡£ Ö÷»ú¹ÜÀíµÄд²Ù×÷Ðèֻ¶Áģʽ¹رգ»¶³½á/½ⶳ½ø³̡¢ֹͣ/ÖØÆô·þÎñ»¹ÐèÆôÓÃΣÏÕÖ÷»ú²Ù×÷¡£=Ö÷™C¹ÜÀíµČ‘Èë²Ù×÷ÐèêPé]Ψ×xģʽ£»ƒö½Y/½âƒö̎Àí³ÌÐò¡¢ֹͣ/ÖØÐ†¢„ӷþ„Õ߀Ð膢ÓÃΣëUÖ÷™C²Ù×÷¡£ µÚ %d ¸öǮ°üµØַ²»ºϷ¨!=µÚ %d ‚€åX°üλַ²»ºϷ¨! %d ÐÂÁ¬½Ó\r\n=%d ÐÂßB¾€\r\n