main.py 38 KB

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