main.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. from __future__ import annotations
  2. import json
  3. import sqlite3
  4. from typing import Any
  5. from fastapi import FastAPI, HTTPException, Query
  6. from fastapi.middleware.cors import CORSMiddleware
  7. from . import ai_service, automation_service, settings_service, windows_automation
  8. from .control import (
  9. CONFIRMED_CONTROL_STATUSES,
  10. restart_service,
  11. start_process,
  12. start_service,
  13. stop_process,
  14. stop_service,
  15. )
  16. from .database import get_db, init_db
  17. from .scanner import now_iso, run_full_scan
  18. from .sensors import collect_sensors
  19. from .schemas import (
  20. AiAnalyzeRequest,
  21. AiChatRequest,
  22. AiImportRequest,
  23. AiModelCreate,
  24. AiModelUpdate,
  25. AiProviderCreate,
  26. AiProviderUpdate,
  27. AutomationKeyboardRequest,
  28. AutomationKeyboardActionRequest,
  29. AutomationMouseRequest,
  30. AutomationMouseActionRequest,
  31. AutomationPowerRequest,
  32. AutomationCloseProgramsRequest,
  33. AutomationScreenshotCaptureRequest,
  34. AutomationStartProgramRequest,
  35. AutomationProgramStartRequest,
  36. AutomationProgramStopRequest,
  37. AutomationScreenshotRequest,
  38. AutomationTextInputRequest,
  39. AutomationVisionAnalyzeRequest,
  40. AutomationWorkflowRunRequest,
  41. AutomationWorkflowSaveRequest,
  42. BatchStatusUpdate,
  43. PromptRequest,
  44. StatusUpdate,
  45. SystemSettingsUpdate,
  46. TagAssignRequest,
  47. TagCreate,
  48. TagUpdate,
  49. )
  50. from .smart import collect_all_smart, get_device_smart, scan_devices
  51. AI_PROMPT_TEMPLATE = """请作为资深的 Windows 系统安全专家,帮我分析下面这些 Windows 服务和进程是否可信,并严格按照 JSON 数组格式输出结果。
  52. 输出要求:
  53. 1. 必须且只能输出纯 JSON 数组,不要输出任何额外的解释、问候语,也不要使用 Markdown 代码块(如 ```json)包裹。
  54. 2. 每个对象必须包含以下 8 个字段:type、name、description、judgement、risk_level、reason、suggestion、tags。
  55. 3. type 只能是 "service" 或 "process"。
  56. 4. description 请简要说明该服务或进程的官方用途或常规功能(如果是未知/恶意程序,请描述其伪装意图或表现)。
  57. 5. judgement 只能是 "TRUSTED"、"SUSPICIOUS"、"NEED_MORE_INFO"。
  58. 6. risk_level 只能是 "LOW"、"MEDIUM"、"HIGH"。
  59. 7. 如果提供的信息不足以做出判断,请将 judgement 设为 "NEED_MORE_INFO"。
  60. 8. 待分析数据里的 tags 字段是当前已有标签上下文,不代表最终结论,但如果标签显示为“windows系统”或“本系统相关”,请在 reason 或 suggestion 中体现这一点。
  61. 9. 输出对象里的 tags 字段必须是字符串数组,填写你建议系统最终绑定到该对象上的标签名称。可以使用系统已有标签,也可以在确有必要时给出新的短标签名称;标签名称应简洁稳定,不要把长句放入标签。
  62. JSON 格式示例:
  63. [
  64. {
  65. "type": "service",
  66. "name": "WinDefend",
  67. "description": "Microsoft Defender 防病毒核心服务,负责保护系统免受恶意软件和间谍软件的威胁。",
  68. "judgement": "TRUSTED",
  69. "risk_level": "LOW",
  70. "reason": "这是 Microsoft 官方的安全组件,路径和名称符合系统原生服务的标准特征。",
  71. "suggestion": "可标记为可信,建议保持运行。",
  72. "tags": ["windows系统"]
  73. },
  74. {
  75. "type": "process",
  76. "name": "unknown.exe",
  77. "description": "未知用途的执行文件,无明确的官方功能说明。",
  78. "judgement": "SUSPICIOUS",
  79. "risk_level": "HIGH",
  80. "reason": "进程位于用户 AppData 临时目录,启动命令行异常,且缺少有效的官方数字签名。",
  81. "suggestion": "建议立即隔离,检查文件的 SHA256 散列值及外部网络连接记录,不要直接运行或信任。",
  82. "tags": ["可疑程序"]
  83. }
  84. ]
  85. 下面是待分析数据:
  86. {pending_items_json}
  87. 系统中已有标签信息:
  88. {tags_json}
  89. """
  90. app = FastAPI(title="Windows Monitor API", version="1.0.0")
  91. app.add_middleware(
  92. CORSMiddleware,
  93. allow_origins=["*"],
  94. allow_credentials=True,
  95. allow_methods=["*"],
  96. allow_headers=["*"],
  97. )
  98. @app.on_event("startup")
  99. def startup() -> None:
  100. init_db()
  101. def build_where(
  102. keyword: str | None,
  103. confirm_status: str | None,
  104. present: bool | None,
  105. fields: list[str],
  106. ) -> tuple[str, list[Any]]:
  107. clauses: list[str] = []
  108. params: list[Any] = []
  109. if keyword:
  110. like = f"%{keyword}%"
  111. clauses.append("(" + " OR ".join(f"{field} LIKE ?" for field in fields) + ")")
  112. params.extend([like] * len(fields))
  113. if confirm_status:
  114. clauses.append("confirm_status = ?")
  115. params.append(confirm_status)
  116. if present is not None:
  117. clauses.append("is_present_now = ?")
  118. params.append(1 if present else 0)
  119. return ("WHERE " + " AND ".join(clauses)) if clauses else "", params
  120. def list_items(
  121. table: str,
  122. keyword: str | None,
  123. confirm_status: str | None,
  124. present: bool | None,
  125. page: int,
  126. page_size: int,
  127. fields: list[str],
  128. sort_by: str | None = None,
  129. sort_order: str | None = None,
  130. ) -> dict[str, Any]:
  131. where_sql, params = build_where(keyword, confirm_status, present, fields)
  132. order_sql = build_order_by(table, sort_by, sort_order)
  133. offset = (page - 1) * page_size
  134. with get_db() as conn:
  135. total = conn.execute(f"SELECT COUNT(*) AS total FROM {table} {where_sql}", params).fetchone()["total"]
  136. rows = conn.execute(
  137. f"SELECT * FROM {table} {where_sql} {order_sql} LIMIT ? OFFSET ?",
  138. [*params, page_size, offset],
  139. ).fetchall()
  140. rows = attach_item_metadata(conn, table_to_item_type(table), rows)
  141. return {"items": rows, "total": total, "page": page, "page_size": page_size}
  142. def build_order_by(table: str, sort_by: str | None, sort_order: str | None) -> str:
  143. allowed = {
  144. "windows_services": {
  145. "name",
  146. "display_name",
  147. "status",
  148. "start_type",
  149. "username",
  150. "is_present_now",
  151. "confirm_status",
  152. "first_seen_at",
  153. "last_seen_at",
  154. "updated_at",
  155. },
  156. "windows_processes": {
  157. "name",
  158. "exe_path",
  159. "username",
  160. "status",
  161. "last_pid",
  162. "parent_pid",
  163. "is_present_now",
  164. "confirm_status",
  165. "create_time",
  166. "first_seen_at",
  167. "last_seen_at",
  168. "updated_at",
  169. },
  170. }
  171. default_sql = "ORDER BY is_present_now DESC, last_seen_at DESC"
  172. if not sort_by or sort_by not in allowed.get(table, set()):
  173. return default_sql
  174. direction = "ASC" if sort_order == "asc" else "DESC"
  175. if sort_by == "is_present_now":
  176. return f"ORDER BY {sort_by} {direction}, last_seen_at DESC"
  177. return f"ORDER BY {sort_by} {direction}, is_present_now DESC, last_seen_at DESC"
  178. def get_item(table: str, item_id: int) -> dict[str, Any]:
  179. with get_db() as conn:
  180. item = conn.execute(f"SELECT * FROM {table} WHERE id = ?", (item_id,)).fetchone()
  181. if item:
  182. item = attach_item_metadata(conn, table_to_item_type(table), [item])[0]
  183. if not item:
  184. raise HTTPException(status_code=404, detail="Item not found")
  185. return item
  186. def table_to_item_type(table: str) -> str:
  187. if table == "windows_services":
  188. return "service"
  189. if table == "windows_processes":
  190. return "process"
  191. raise ValueError(f"Unsupported table: {table}")
  192. def bool_tag(row: dict[str, Any]) -> dict[str, Any]:
  193. item = dict(row)
  194. item["is_controllable"] = bool(item["is_controllable"])
  195. item["is_builtin"] = bool(item["is_builtin"])
  196. return item
  197. def all_tags(conn) -> list[dict[str, Any]]:
  198. return [
  199. bool_tag(row)
  200. for row in conn.execute("SELECT * FROM tags ORDER BY is_builtin DESC, name ASC").fetchall()
  201. ]
  202. def tags_for_items(conn, item_type: str, item_ids: list[int]) -> dict[int, list[dict[str, Any]]]:
  203. if not item_ids:
  204. return {}
  205. placeholders = ",".join("?" for _ in item_ids)
  206. rows = conn.execute(
  207. f"""
  208. SELECT it.item_id, t.*
  209. FROM item_tags it
  210. JOIN tags t ON t.id = it.tag_id
  211. WHERE it.item_type = ? AND it.item_id IN ({placeholders})
  212. ORDER BY t.name ASC
  213. """,
  214. [item_type, *item_ids],
  215. ).fetchall()
  216. result = {item_id: [] for item_id in item_ids}
  217. for row in rows:
  218. item_id = row["item_id"]
  219. tag = {key: value for key, value in row.items() if key != "item_id"}
  220. result.setdefault(item_id, []).append(bool_tag(tag))
  221. return result
  222. def can_control_item(item_type: str, row: dict[str, Any], tags: list[dict[str, Any]]) -> bool:
  223. if row.get("confirm_status") not in CONFIRMED_CONTROL_STATUSES:
  224. return False
  225. if item_type == "process":
  226. protected_names = {"system idle process", "system", "registry"}
  227. if row.get("last_pid") in (0, 4) or (row.get("name") or "").lower() in protected_names:
  228. return False
  229. return all(tag.get("is_controllable", True) for tag in tags)
  230. def attach_item_metadata(conn, item_type: str, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
  231. tag_map = tags_for_items(conn, item_type, [row["id"] for row in rows])
  232. enriched = []
  233. for row in rows:
  234. item = dict(row)
  235. item["is_present_now"] = bool(item.get("is_present_now"))
  236. item["tags"] = tag_map.get(row["id"], [])
  237. item["can_control"] = can_control_item(item_type, item, item["tags"])
  238. enriched.append(item)
  239. return enriched
  240. def update_one(table: str, item_id: int, payload: StatusUpdate) -> dict[str, Any]:
  241. get_item(table, item_id)
  242. with get_db() as conn:
  243. conn.execute(
  244. f"UPDATE {table} SET confirm_status = ?, user_note = ?, updated_at = ? WHERE id = ?",
  245. (payload.confirm_status, payload.user_note, now_iso(), item_id),
  246. )
  247. return get_item(table, item_id)
  248. def update_batch(table: str, payload: BatchStatusUpdate) -> dict[str, Any]:
  249. if not payload.ids:
  250. return {"updated": 0}
  251. placeholders = ",".join("?" for _ in payload.ids)
  252. with get_db() as conn:
  253. cursor = conn.execute(
  254. f"""
  255. UPDATE {table}
  256. SET confirm_status = ?, user_note = COALESCE(?, user_note), updated_at = ?
  257. WHERE id IN ({placeholders})
  258. """,
  259. [payload.confirm_status, payload.user_note, now_iso(), *payload.ids],
  260. )
  261. return {"updated": cursor.rowcount}
  262. def rows_for_prompt(table: str, item_type: str, payload: PromptRequest) -> list[dict[str, Any]]:
  263. with get_db() as conn:
  264. if payload.scope == "selected" and payload.ids:
  265. placeholders = ",".join("?" for _ in payload.ids)
  266. rows = conn.execute(f"SELECT * FROM {table} WHERE id IN ({placeholders})", payload.ids).fetchall()
  267. else:
  268. rows = conn.execute(f"SELECT * FROM {table} WHERE confirm_status = 'PENDING'").fetchall()
  269. rows = attach_item_metadata(conn, item_type, rows)
  270. return [normalize_prompt_row(item_type, row) for row in rows]
  271. def normalize_prompt_row(item_type: str, row: dict[str, Any]) -> dict[str, Any]:
  272. if item_type == "service":
  273. return {
  274. "type": "service",
  275. "id": row["id"],
  276. "name": row["name"],
  277. "display_name": row["display_name"],
  278. "status": row["status"],
  279. "start_type": row["start_type"],
  280. "username": row["username"],
  281. "binary_path": row["binary_path"],
  282. "description": row["description"],
  283. "is_present_now": bool(row["is_present_now"]),
  284. "tags": [
  285. {
  286. "name": tag["name"],
  287. "description": tag["description"],
  288. "is_controllable": tag["is_controllable"],
  289. }
  290. for tag in row.get("tags", [])
  291. ],
  292. }
  293. return {
  294. "type": "process",
  295. "id": row["id"],
  296. "name": row["name"],
  297. "exe_path": row["exe_path"],
  298. "cmdline": row["cmdline"],
  299. "username": row["username"],
  300. "status": row["status"],
  301. "last_pid": row["last_pid"],
  302. "parent_pid": row["parent_pid"],
  303. "is_present_now": bool(row["is_present_now"]),
  304. "tags": [
  305. {
  306. "name": tag["name"],
  307. "description": tag["description"],
  308. "is_controllable": tag["is_controllable"],
  309. }
  310. for tag in row.get("tags", [])
  311. ],
  312. }
  313. def markdown_table(rows: list[dict[str, Any]]) -> str:
  314. headers = ["type", "id", "name", "status", "tags", "path_or_command", "user", "present"]
  315. lines = ["| " + " | ".join(headers) + " |", "| " + " | ".join(["---"] * len(headers)) + " |"]
  316. for row in rows:
  317. path_or_command = row.get("binary_path") or row.get("exe_path") or row.get("cmdline") or ""
  318. values = [
  319. str(row.get("type", "")),
  320. str(row.get("id", "")),
  321. str(row.get("name", "")),
  322. str(row.get("status", "")),
  323. ", ".join(tag.get("name", "") for tag in row.get("tags", [])).replace("|", "\\|"),
  324. str(path_or_command).replace("|", "\\|"),
  325. str(row.get("username", "")).replace("|", "\\|"),
  326. "yes" if row.get("is_present_now") else "no",
  327. ]
  328. lines.append("| " + " | ".join(values) + " |")
  329. return "\n".join(lines)
  330. def prompt_response(rows: list[dict[str, Any]]) -> dict[str, Any]:
  331. pending_json = json.dumps(rows, ensure_ascii=False, indent=2)
  332. table = markdown_table(rows)
  333. with get_db() as conn:
  334. tags_json = json.dumps(all_tags(conn), ensure_ascii=False, indent=2)
  335. prompt_text = AI_PROMPT_TEMPLATE.replace("{pending_items_json}", pending_json).replace("{tags_json}", tags_json)
  336. return {"prompt_text": prompt_text, "markdown_table": table, "items": rows}
  337. def set_item_tags(item_type: str, table: str, item_id: int, payload: TagAssignRequest) -> dict[str, Any]:
  338. get_item(table, item_id)
  339. unique_ids = sorted(set(payload.tag_ids))
  340. now = now_iso()
  341. with get_db() as conn:
  342. if unique_ids:
  343. placeholders = ",".join("?" for _ in unique_ids)
  344. found = conn.execute(f"SELECT id FROM tags WHERE id IN ({placeholders})", unique_ids).fetchall()
  345. if len(found) != len(unique_ids):
  346. raise HTTPException(status_code=400, detail="One or more tag ids do not exist")
  347. conn.execute("DELETE FROM item_tags WHERE item_type = ? AND item_id = ?", (item_type, item_id))
  348. for tag_id in unique_ids:
  349. conn.execute(
  350. "INSERT INTO item_tags (item_type, item_id, tag_id, created_at) VALUES (?, ?, ?, ?)",
  351. (item_type, item_id, tag_id, now),
  352. )
  353. return get_item(table, item_id)
  354. def ensure_control_allowed(table: str, item_id: int) -> dict[str, Any]:
  355. item = get_item(table, item_id)
  356. if not item.get("can_control"):
  357. raise HTTPException(status_code=403, detail="This item is not controllable because it is unconfirmed or has a non-controllable tag")
  358. return item
  359. def normalize_import_tag_names(tag_names: list[str] | None) -> list[str]:
  360. if tag_names is None:
  361. return []
  362. normalized = []
  363. seen = set()
  364. for tag_name in tag_names:
  365. name = str(tag_name).strip()[:80]
  366. if not name or name in seen:
  367. continue
  368. seen.add(name)
  369. normalized.append(name)
  370. return normalized
  371. def ensure_tag_ids(conn, tag_names: list[str]) -> list[int]:
  372. tag_ids = []
  373. now = now_iso()
  374. for tag_name in tag_names:
  375. row = conn.execute("SELECT id FROM tags WHERE name = ?", (tag_name,)).fetchone()
  376. if row:
  377. tag_ids.append(row["id"])
  378. continue
  379. cursor = conn.execute(
  380. """
  381. INSERT INTO tags (name, description, is_controllable, is_builtin, created_at, updated_at)
  382. VALUES (?, ?, 1, 0, ?, ?)
  383. """,
  384. (tag_name, "AI 自动新增标签", now, now),
  385. )
  386. tag_ids.append(cursor.lastrowid)
  387. return tag_ids
  388. def replace_item_tags(conn, item_type: str, item_id: int, tag_ids: list[int]) -> None:
  389. now = now_iso()
  390. conn.execute("DELETE FROM item_tags WHERE item_type = ? AND item_id = ?", (item_type, item_id))
  391. for tag_id in tag_ids:
  392. conn.execute(
  393. "INSERT INTO item_tags (item_type, item_id, tag_id, created_at) VALUES (?, ?, ?, ?)",
  394. (item_type, item_id, tag_id, now),
  395. )
  396. def import_ai_results(table: str, item_type: str, payload: AiImportRequest) -> dict[str, Any]:
  397. updated = 0
  398. with get_db() as conn:
  399. for item in payload.items:
  400. if item.type != item_type:
  401. continue
  402. matched_rows = conn.execute(f"SELECT id FROM {table} WHERE name = ?", (item.name,)).fetchall()
  403. tag_ids = ensure_tag_ids(conn, normalize_import_tag_names(item.tags)) if item.tags is not None else None
  404. for row in matched_rows:
  405. cursor = conn.execute(
  406. f"""
  407. UPDATE {table}
  408. SET confirm_status = ?, ai_description = ?, ai_reason = ?,
  409. ai_suggestion = ?, risk_level = ?, updated_at = ?
  410. WHERE id = ?
  411. """,
  412. (
  413. item.judgement,
  414. item.description,
  415. item.reason,
  416. item.suggestion,
  417. item.risk_level,
  418. now_iso(),
  419. row["id"],
  420. ),
  421. )
  422. if tag_ids is not None:
  423. replace_item_tags(conn, item_type, row["id"], tag_ids)
  424. updated += cursor.rowcount
  425. return {"updated": updated}
  426. def ai_update_preview(table: str, item_type: str, proposed_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
  427. names = [item["name"] for item in proposed_items if item.get("type") == item_type and item.get("name")]
  428. if not names:
  429. return []
  430. placeholders = ",".join("?" for _ in names)
  431. with get_db() as conn:
  432. rows = conn.execute(
  433. f"""
  434. SELECT id, name, confirm_status, ai_description, ai_reason, ai_suggestion, risk_level
  435. FROM {table}
  436. WHERE name IN ({placeholders})
  437. """,
  438. names,
  439. ).fetchall()
  440. tag_map = tags_for_items(conn, item_type, [row["id"] for row in rows])
  441. row_map = {}
  442. for row in rows:
  443. current = dict(row)
  444. current["tags"] = [tag["name"] for tag in tag_map.get(row["id"], [])]
  445. row_map[row["name"]] = current
  446. preview = []
  447. for item in proposed_items:
  448. if item.get("type") != item_type:
  449. continue
  450. current = row_map.get(item.get("name"))
  451. preview.append(
  452. {
  453. "matched": current is not None,
  454. "current": current,
  455. "proposed": item,
  456. }
  457. )
  458. return preview
  459. def analyze_items_with_ai(table: str, item_type: str, payload: AiAnalyzeRequest) -> dict[str, Any]:
  460. rows = rows_for_prompt(table, item_type, PromptRequest(scope=payload.scope, ids=payload.ids))
  461. if not rows:
  462. raise HTTPException(status_code=400, detail="No items available for AI analysis")
  463. prompt_data = prompt_response(rows)
  464. result = ai_service.chat(payload.provider_id, payload.model_id, prompt_data["prompt_text"], payload.temperature)
  465. try:
  466. parsed_items = ai_service.parse_ai_items(result["content"])
  467. except (json.JSONDecodeError, ValueError) as exc:
  468. raise HTTPException(
  469. status_code=502,
  470. detail=f"AI output is not valid import JSON: {exc}",
  471. ) from exc
  472. return {
  473. "items": parsed_items,
  474. "preview": ai_update_preview(table, item_type, parsed_items),
  475. "raw_output": result["content"],
  476. "provider": result["provider"],
  477. "model": result["model"],
  478. "prompt_text": prompt_data["prompt_text"],
  479. "markdown_table": prompt_data["markdown_table"],
  480. }
  481. @app.get("/api/dashboard")
  482. def dashboard() -> dict[str, Any]:
  483. with get_db() as conn:
  484. latest_scan = conn.execute("SELECT * FROM scan_records ORDER BY started_at DESC LIMIT 1").fetchone()
  485. service_total = conn.execute("SELECT COUNT(*) AS total FROM windows_services").fetchone()["total"]
  486. process_total = conn.execute("SELECT COUNT(*) AS total FROM windows_processes").fetchone()["total"]
  487. pending_services = conn.execute(
  488. "SELECT COUNT(*) AS total FROM windows_services WHERE confirm_status = 'PENDING'"
  489. ).fetchone()["total"]
  490. pending_processes = conn.execute(
  491. "SELECT COUNT(*) AS total FROM windows_processes WHERE confirm_status = 'PENDING'"
  492. ).fetchone()["total"]
  493. missing_services = conn.execute(
  494. "SELECT COUNT(*) AS total FROM windows_services WHERE is_present_now = 0"
  495. ).fetchone()["total"]
  496. missing_processes = conn.execute(
  497. "SELECT COUNT(*) AS total FROM windows_processes WHERE is_present_now = 0"
  498. ).fetchone()["total"]
  499. return {
  500. "latest_scan": latest_scan,
  501. "service_total": service_total,
  502. "process_total": process_total,
  503. "pending_services": pending_services,
  504. "pending_processes": pending_processes,
  505. "missing_services": missing_services,
  506. "missing_processes": missing_processes,
  507. }
  508. @app.get("/api/tags")
  509. def tags() -> dict[str, Any]:
  510. with get_db() as conn:
  511. rows = all_tags(conn)
  512. return {"items": rows}
  513. @app.post("/api/tags")
  514. def tag_create(payload: TagCreate) -> dict[str, Any]:
  515. now = now_iso()
  516. try:
  517. with get_db() as conn:
  518. cursor = conn.execute(
  519. """
  520. INSERT INTO tags (name, description, is_controllable, is_builtin, created_at, updated_at)
  521. VALUES (?, ?, ?, 0, ?, ?)
  522. """,
  523. (payload.name.strip(), payload.description, 1 if payload.is_controllable else 0, now, now),
  524. )
  525. tag_id = cursor.lastrowid
  526. row = conn.execute("SELECT * FROM tags WHERE id = ?", (tag_id,)).fetchone()
  527. except sqlite3.IntegrityError as exc:
  528. raise HTTPException(status_code=409, detail="Tag name already exists") from exc
  529. return bool_tag(row)
  530. @app.patch("/api/tags/{tag_id}")
  531. def tag_update(tag_id: int, payload: TagUpdate) -> dict[str, Any]:
  532. now = now_iso()
  533. try:
  534. with get_db() as conn:
  535. existing = conn.execute("SELECT * FROM tags WHERE id = ?", (tag_id,)).fetchone()
  536. if not existing:
  537. raise HTTPException(status_code=404, detail="Tag not found")
  538. conn.execute(
  539. """
  540. UPDATE tags
  541. SET name = ?, description = ?, is_controllable = ?, updated_at = ?
  542. WHERE id = ?
  543. """,
  544. (payload.name.strip(), payload.description, 1 if payload.is_controllable else 0, now, tag_id),
  545. )
  546. row = conn.execute("SELECT * FROM tags WHERE id = ?", (tag_id,)).fetchone()
  547. except sqlite3.IntegrityError as exc:
  548. raise HTTPException(status_code=409, detail="Tag name already exists") from exc
  549. return bool_tag(row)
  550. @app.delete("/api/tags/{tag_id}")
  551. def tag_delete(tag_id: int) -> dict[str, Any]:
  552. with get_db() as conn:
  553. row = conn.execute("SELECT * FROM tags WHERE id = ?", (tag_id,)).fetchone()
  554. if not row:
  555. raise HTTPException(status_code=404, detail="Tag not found")
  556. if row["is_builtin"]:
  557. raise HTTPException(status_code=400, detail="Built-in tags cannot be deleted")
  558. cursor = conn.execute("DELETE FROM tags WHERE id = ?", (tag_id,))
  559. return {"deleted": cursor.rowcount}
  560. @app.get("/api/ai/providers")
  561. def ai_providers() -> dict[str, Any]:
  562. return {"items": ai_service.list_providers()}
  563. @app.post("/api/ai/providers")
  564. def ai_provider_create(payload: AiProviderCreate) -> dict[str, Any]:
  565. return ai_service.create_provider(payload)
  566. @app.patch("/api/ai/providers/{provider_id}")
  567. def ai_provider_update(provider_id: int, payload: AiProviderUpdate) -> dict[str, Any]:
  568. return ai_service.update_provider(provider_id, payload)
  569. @app.delete("/api/ai/providers/{provider_id}")
  570. def ai_provider_delete(provider_id: int) -> dict[str, Any]:
  571. return ai_service.delete_provider(provider_id)
  572. @app.get("/api/ai/models")
  573. def ai_models(provider_id: int | None = None) -> dict[str, Any]:
  574. return {"items": ai_service.list_models(provider_id)}
  575. @app.post("/api/ai/models")
  576. def ai_model_create(payload: AiModelCreate) -> dict[str, Any]:
  577. return ai_service.create_model(payload)
  578. @app.patch("/api/ai/models/{model_id}")
  579. def ai_model_update(model_id: int, payload: AiModelUpdate) -> dict[str, Any]:
  580. return ai_service.update_model(model_id, payload)
  581. @app.delete("/api/ai/models/{model_id}")
  582. def ai_model_delete(model_id: int) -> dict[str, Any]:
  583. return ai_service.delete_model(model_id)
  584. @app.post("/api/ai/test")
  585. def ai_test(payload: AiChatRequest) -> dict[str, Any]:
  586. return ai_service.chat(payload.provider_id, payload.model_id, payload.prompt, payload.temperature)
  587. @app.get("/api/settings")
  588. def system_settings() -> dict[str, Any]:
  589. return settings_service.list_settings()
  590. @app.put("/api/settings")
  591. def system_settings_update(payload: SystemSettingsUpdate) -> dict[str, Any]:
  592. return settings_service.update_settings(payload)
  593. @app.post("/api/automation/power/shutdown")
  594. def automation_shutdown(payload: AutomationPowerRequest) -> dict[str, Any]:
  595. return windows_automation.shutdown_windows(payload.delay_seconds, payload.force, payload.reason)
  596. @app.post("/api/automation/power/restart")
  597. def automation_restart(payload: AutomationPowerRequest) -> dict[str, Any]:
  598. return windows_automation.restart_windows(payload.delay_seconds, payload.force, payload.reason)
  599. @app.post("/api/automation/power/cancel")
  600. def automation_power_cancel() -> dict[str, Any]:
  601. return windows_automation.cancel_power_action()
  602. @app.post("/api/automation/programs/start")
  603. def automation_program_start(payload: AutomationProgramStartRequest) -> dict[str, Any]:
  604. return windows_automation.start_program(payload.command, payload.cwd, payload.shell)
  605. @app.post("/api/automation/programs/stop")
  606. def automation_program_stop(payload: AutomationProgramStopRequest) -> dict[str, Any]:
  607. return windows_automation.stop_program(
  608. pid=payload.pid,
  609. name=payload.name,
  610. timeout_seconds=payload.timeout_seconds,
  611. kill_after_timeout=payload.kill_after_timeout,
  612. )
  613. @app.post("/api/automation/screenshot")
  614. def automation_screenshot(payload: AutomationScreenshotRequest) -> dict[str, Any]:
  615. return windows_automation.take_screenshot(payload.save_path, payload.include_base64)
  616. @app.post("/api/automation/mouse")
  617. def automation_mouse(payload: AutomationMouseRequest) -> dict[str, Any]:
  618. return windows_automation.mouse_action(
  619. action=payload.action,
  620. x=payload.x,
  621. y=payload.y,
  622. duration=payload.duration,
  623. button=payload.button,
  624. clicks=payload.clicks,
  625. amount=payload.amount,
  626. )
  627. @app.post("/api/automation/keyboard")
  628. def automation_keyboard(payload: AutomationKeyboardRequest) -> dict[str, Any]:
  629. return windows_automation.keyboard_action(
  630. action=payload.action,
  631. key=payload.key,
  632. keys=payload.keys,
  633. text=payload.text,
  634. interval=payload.interval,
  635. )
  636. @app.post("/api/automation/vision/analyze")
  637. def automation_vision_analyze(payload: AutomationVisionAnalyzeRequest) -> dict[str, Any]:
  638. return automation_service.analyze_screen(payload)
  639. @app.post("/api/automation/vision/screenshot")
  640. def automation_vision_screenshot(payload: AutomationScreenshotCaptureRequest) -> dict[str, Any]:
  641. return automation_service.capture_screenshot(payload)
  642. @app.post("/api/automation/actions/mouse")
  643. def automation_action_mouse(payload: AutomationMouseActionRequest) -> dict[str, Any]:
  644. return automation_service.execute_mouse_action(payload)
  645. @app.post("/api/automation/actions/keyboard")
  646. def automation_action_keyboard(payload: AutomationKeyboardActionRequest) -> dict[str, Any]:
  647. return automation_service.execute_keyboard_action(payload)
  648. @app.post("/api/automation/actions/text-input")
  649. def automation_action_text_input(payload: AutomationTextInputRequest) -> dict[str, Any]:
  650. return automation_service.execute_text_input(payload)
  651. @app.post("/api/automation/actions/start-program")
  652. def automation_action_start_program(payload: AutomationStartProgramRequest) -> dict[str, Any]:
  653. return automation_service.execute_start_program(payload)
  654. @app.post("/api/automation/actions/close-opened-programs")
  655. def automation_action_close_opened_programs(payload: AutomationCloseProgramsRequest) -> dict[str, Any]:
  656. return automation_service.close_opened_programs(payload.pids)
  657. @app.get("/api/automation/workflows")
  658. def automation_workflows(page: int = Query(default=1, ge=1), page_size: int = Query(default=20, ge=1, le=200)) -> dict[str, Any]:
  659. return automation_service.list_workflows(page, page_size)
  660. @app.post("/api/automation/workflows")
  661. def automation_workflow_create(payload: AutomationWorkflowSaveRequest) -> dict[str, Any]:
  662. return automation_service.save_workflow(payload)
  663. @app.get("/api/automation/workflows/{workflow_id}")
  664. def automation_workflow_detail(workflow_id: int) -> dict[str, Any]:
  665. return automation_service.get_workflow(workflow_id)
  666. @app.post("/api/automation/workflows/{workflow_id}/run")
  667. def automation_workflow_run(workflow_id: int, payload: AutomationWorkflowRunRequest) -> dict[str, Any]:
  668. return automation_service.run_workflow(workflow_id, payload)
  669. @app.put("/api/automation/workflows/{workflow_id}")
  670. def automation_workflow_update(workflow_id: int, payload: AutomationWorkflowSaveRequest) -> dict[str, Any]:
  671. return automation_service.update_workflow(workflow_id, payload)
  672. @app.delete("/api/automation/workflows/{workflow_id}")
  673. def automation_workflow_delete(workflow_id: int) -> dict[str, Any]:
  674. return automation_service.delete_workflow(workflow_id)
  675. @app.get("/api/automation/screens")
  676. def automation_screens(page: int = Query(default=1, ge=1), page_size: int = Query(default=20, ge=1, le=200)) -> dict[str, Any]:
  677. return automation_service.list_screens(page, page_size)
  678. @app.get("/api/automation/screens/{screen_id}")
  679. def automation_screen_detail(screen_id: int, include_image: bool = False) -> dict[str, Any]:
  680. return automation_service.get_screen(screen_id, include_image)
  681. @app.delete("/api/automation/screens/{screen_id}")
  682. def automation_screen_delete(screen_id: int) -> dict[str, Any]:
  683. return automation_service.delete_screen(screen_id)
  684. @app.get("/api/automation/errors")
  685. def automation_errors(page: int = Query(default=1, ge=1), page_size: int = Query(default=20, ge=1, le=200)) -> dict[str, Any]:
  686. return automation_service.list_errors(page, page_size)
  687. @app.get("/api/automation/errors/{error_id}")
  688. def automation_error_detail(error_id: int, include_images: bool = False) -> dict[str, Any]:
  689. return automation_service.get_error(error_id, include_images)
  690. @app.get("/api/sensors")
  691. def sensors() -> dict[str, Any]:
  692. return collect_sensors()
  693. @app.get("/api/smart/scan")
  694. def smart_scan() -> dict[str, Any]:
  695. return scan_devices()
  696. @app.get("/api/smart/devices")
  697. def smart_devices(include_jmb39x: bool = True, jmb39x_slots: int = Query(default=8, ge=0, le=16)) -> dict[str, Any]:
  698. return collect_all_smart(include_jmb39x=include_jmb39x, jmb39x_slots=jmb39x_slots)
  699. @app.get("/api/smart/device")
  700. def smart_device(device: str, device_type: str | None = None) -> dict[str, Any]:
  701. return get_device_smart(device, device_type)
  702. @app.post("/api/scans/run")
  703. def run_scan() -> dict[str, Any]:
  704. return run_full_scan()
  705. @app.get("/api/scans")
  706. def scan_history(page: int = 1, page_size: int = 20) -> dict[str, Any]:
  707. offset = (page - 1) * page_size
  708. with get_db() as conn:
  709. total = conn.execute("SELECT COUNT(*) AS total FROM scan_records").fetchone()["total"]
  710. rows = conn.execute(
  711. "SELECT * FROM scan_records ORDER BY started_at DESC LIMIT ? OFFSET ?",
  712. (page_size, offset),
  713. ).fetchall()
  714. return {"items": rows, "total": total, "page": page, "page_size": page_size}
  715. @app.get("/api/scans/{scan_id}")
  716. def scan_detail(scan_id: int) -> dict[str, Any]:
  717. with get_db() as conn:
  718. scan = conn.execute("SELECT * FROM scan_records WHERE id = ?", (scan_id,)).fetchone()
  719. if not scan:
  720. raise HTTPException(status_code=404, detail="Scan not found")
  721. return scan
  722. @app.get("/api/services")
  723. def services(
  724. keyword: str | None = None,
  725. confirm_status: str | None = None,
  726. present: bool | None = None,
  727. sort_by: str | None = None,
  728. sort_order: str | None = Query(default=None, pattern="^(asc|desc)$"),
  729. page: int = Query(default=1, ge=1),
  730. page_size: int = Query(default=20, ge=1, le=200),
  731. ) -> dict[str, Any]:
  732. return list_items(
  733. "windows_services",
  734. keyword,
  735. confirm_status,
  736. present,
  737. page,
  738. page_size,
  739. ["name", "display_name", "binary_path", "description"],
  740. sort_by,
  741. sort_order,
  742. )
  743. @app.patch("/api/services/batch")
  744. def service_batch_update(payload: BatchStatusUpdate) -> dict[str, Any]:
  745. return update_batch("windows_services", payload)
  746. @app.post("/api/services/import-ai")
  747. def service_import_ai(payload: AiImportRequest) -> dict[str, Any]:
  748. return import_ai_results("windows_services", "service", payload)
  749. @app.post("/api/services/analyze-ai")
  750. def service_analyze_ai(payload: AiAnalyzeRequest) -> dict[str, Any]:
  751. return analyze_items_with_ai("windows_services", "service", payload)
  752. @app.post("/api/services/ai-prompt")
  753. def service_ai_prompt(payload: PromptRequest) -> dict[str, Any]:
  754. return prompt_response(rows_for_prompt("windows_services", "service", payload))
  755. @app.put("/api/services/{service_id}/tags")
  756. def service_tags_update(service_id: int, payload: TagAssignRequest) -> dict[str, Any]:
  757. return set_item_tags("service", "windows_services", service_id, payload)
  758. @app.post("/api/services/{service_id}/start")
  759. def service_start(service_id: int) -> dict[str, Any]:
  760. item = ensure_control_allowed("windows_services", service_id)
  761. if not item.get("is_present_now"):
  762. raise HTTPException(status_code=400, detail="This service was not present in the latest scan")
  763. result = start_service(item["name"])
  764. with get_db() as conn:
  765. conn.execute(
  766. "UPDATE windows_services SET status = ?, updated_at = ? WHERE id = ?",
  767. (result.get("status") or "running", now_iso(), service_id),
  768. )
  769. return result
  770. @app.post("/api/services/{service_id}/stop")
  771. def service_stop(service_id: int) -> dict[str, Any]:
  772. item = ensure_control_allowed("windows_services", service_id)
  773. if not item.get("is_present_now"):
  774. raise HTTPException(status_code=400, detail="This service was not present in the latest scan")
  775. result = stop_service(item["name"])
  776. with get_db() as conn:
  777. conn.execute(
  778. "UPDATE windows_services SET status = ?, updated_at = ? WHERE id = ?",
  779. (result.get("status") or "stopped", now_iso(), service_id),
  780. )
  781. return result
  782. @app.post("/api/services/{service_id}/restart")
  783. def service_restart(service_id: int) -> dict[str, Any]:
  784. item = ensure_control_allowed("windows_services", service_id)
  785. if not item.get("is_present_now"):
  786. raise HTTPException(status_code=400, detail="This service was not present in the latest scan")
  787. result = restart_service(item["name"])
  788. with get_db() as conn:
  789. conn.execute(
  790. "UPDATE windows_services SET status = ?, updated_at = ? WHERE id = ?",
  791. (result.get("status") or "running", now_iso(), service_id),
  792. )
  793. return result
  794. @app.get("/api/services/{service_id}")
  795. def service_detail(service_id: int) -> dict[str, Any]:
  796. return get_item("windows_services", service_id)
  797. @app.patch("/api/services/{service_id}")
  798. def service_update(service_id: int, payload: StatusUpdate) -> dict[str, Any]:
  799. return update_one("windows_services", service_id, payload)
  800. @app.get("/api/processes")
  801. def processes(
  802. keyword: str | None = None,
  803. confirm_status: str | None = None,
  804. present: bool | None = None,
  805. sort_by: str | None = None,
  806. sort_order: str | None = Query(default=None, pattern="^(asc|desc)$"),
  807. page: int = Query(default=1, ge=1),
  808. page_size: int = Query(default=20, ge=1, le=200),
  809. ) -> dict[str, Any]:
  810. return list_items(
  811. "windows_processes",
  812. keyword,
  813. confirm_status,
  814. present,
  815. page,
  816. page_size,
  817. ["name", "exe_path", "cmdline", "username"],
  818. sort_by,
  819. sort_order,
  820. )
  821. @app.patch("/api/processes/batch")
  822. def process_batch_update(payload: BatchStatusUpdate) -> dict[str, Any]:
  823. return update_batch("windows_processes", payload)
  824. @app.post("/api/processes/import-ai")
  825. def process_import_ai(payload: AiImportRequest) -> dict[str, Any]:
  826. return import_ai_results("windows_processes", "process", payload)
  827. @app.post("/api/processes/analyze-ai")
  828. def process_analyze_ai(payload: AiAnalyzeRequest) -> dict[str, Any]:
  829. return analyze_items_with_ai("windows_processes", "process", payload)
  830. @app.post("/api/processes/ai-prompt")
  831. def process_ai_prompt(payload: PromptRequest) -> dict[str, Any]:
  832. return prompt_response(rows_for_prompt("windows_processes", "process", payload))
  833. @app.put("/api/processes/{process_id}/tags")
  834. def process_tags_update(process_id: int, payload: TagAssignRequest) -> dict[str, Any]:
  835. return set_item_tags("process", "windows_processes", process_id, payload)
  836. @app.post("/api/processes/{process_id}/start")
  837. def process_start(process_id: int) -> dict[str, Any]:
  838. item = ensure_control_allowed("windows_processes", process_id)
  839. result = start_process(item)
  840. with get_db() as conn:
  841. conn.execute(
  842. "UPDATE windows_processes SET last_pid = ?, is_present_now = 1, status = ?, updated_at = ? WHERE id = ?",
  843. (result.get("pid"), "running", now_iso(), process_id),
  844. )
  845. return result
  846. @app.post("/api/processes/{process_id}/stop")
  847. def process_stop(process_id: int) -> dict[str, Any]:
  848. item = ensure_control_allowed("windows_processes", process_id)
  849. if not item.get("is_present_now"):
  850. raise HTTPException(status_code=400, detail="This process was not present in the latest scan")
  851. result = stop_process(item)
  852. with get_db() as conn:
  853. conn.execute(
  854. "UPDATE windows_processes SET is_present_now = 0, status = ?, updated_at = ? WHERE id = ?",
  855. ("stopped", now_iso(), process_id),
  856. )
  857. return result
  858. @app.get("/api/processes/{process_id}")
  859. def process_detail(process_id: int) -> dict[str, Any]:
  860. return get_item("windows_processes", process_id)
  861. @app.patch("/api/processes/{process_id}")
  862. def process_update(process_id: int, payload: StatusUpdate) -> dict[str, Any]:
  863. return update_one("windows_processes", process_id, payload)