main.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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 .control import (
  8. CONFIRMED_CONTROL_STATUSES,
  9. restart_service,
  10. start_process,
  11. start_service,
  12. stop_process,
  13. stop_service,
  14. )
  15. from .database import get_db, init_db
  16. from .scanner import now_iso, run_full_scan
  17. from .sensors import collect_sensors
  18. from .schemas import AiImportRequest, BatchStatusUpdate, PromptRequest, StatusUpdate, TagAssignRequest, TagCreate, TagUpdate
  19. from .smart import collect_all_smart, get_device_smart, scan_devices
  20. AI_PROMPT_TEMPLATE = """请作为资深的 Windows 系统安全专家,帮我分析下面这些 Windows 服务和进程是否可信,并严格按照 JSON 数组格式输出结果。
  21. 输出要求:
  22. 1. 必须且只能输出纯 JSON 数组,不要输出任何额外的解释、问候语,也不要使用 Markdown 代码块(如 ```json)包裹。
  23. 2. 每个对象必须包含以下 7 个字段:type、name、description、judgement、risk_level、reason、suggestion。
  24. 3. type 只能是 "service" 或 "process"。
  25. 4. description 请简要说明该服务或进程的官方用途或常规功能(如果是未知/恶意程序,请描述其伪装意图或表现)。
  26. 5. judgement 只能是 "TRUSTED"、"SUSPICIOUS"、"NEED_MORE_INFO"。
  27. 6. risk_level 只能是 "LOW"、"MEDIUM"、"HIGH"。
  28. 7. 如果提供的信息不足以做出判断,请将 judgement 设为 "NEED_MORE_INFO"。
  29. 8. 请结合每个对象的 tags 字段进行判断。已有标签是人工上下文,不代表最终结论,但如果标签显示为“windows系统”或“本系统相关”,请在 reason 或 suggestion 中体现这一点。
  30. 9. 如果你认为某个对象适合系统已有标签,可以在 suggestion 中建议使用对应标签名称;不要创造不存在的新标签。
  31. JSON 格式示例:
  32. [
  33. {
  34. "type": "service",
  35. "name": "WinDefend",
  36. "description": "Microsoft Defender 防病毒核心服务,负责保护系统免受恶意软件和间谍软件的威胁。",
  37. "judgement": "TRUSTED",
  38. "risk_level": "LOW",
  39. "reason": "这是 Microsoft 官方的安全组件,路径和名称符合系统原生服务的标准特征。",
  40. "suggestion": "可标记为可信,建议保持运行。"
  41. },
  42. {
  43. "type": "process",
  44. "name": "unknown.exe",
  45. "description": "未知用途的执行文件,无明确的官方功能说明。",
  46. "judgement": "SUSPICIOUS",
  47. "risk_level": "HIGH",
  48. "reason": "进程位于用户 AppData 临时目录,启动命令行异常,且缺少有效的官方数字签名。",
  49. "suggestion": "建议立即隔离,检查文件的 SHA256 散列值及外部网络连接记录,不要直接运行或信任。"
  50. }
  51. ]
  52. 下面是待分析数据:
  53. {pending_items_json}
  54. 系统中已有标签信息:
  55. {tags_json}
  56. """
  57. app = FastAPI(title="Windows Monitor API", version="1.0.0")
  58. app.add_middleware(
  59. CORSMiddleware,
  60. allow_origins=["*"],
  61. allow_credentials=True,
  62. allow_methods=["*"],
  63. allow_headers=["*"],
  64. )
  65. @app.on_event("startup")
  66. def startup() -> None:
  67. init_db()
  68. def build_where(
  69. keyword: str | None,
  70. confirm_status: str | None,
  71. present: bool | None,
  72. fields: list[str],
  73. ) -> tuple[str, list[Any]]:
  74. clauses: list[str] = []
  75. params: list[Any] = []
  76. if keyword:
  77. like = f"%{keyword}%"
  78. clauses.append("(" + " OR ".join(f"{field} LIKE ?" for field in fields) + ")")
  79. params.extend([like] * len(fields))
  80. if confirm_status:
  81. clauses.append("confirm_status = ?")
  82. params.append(confirm_status)
  83. if present is not None:
  84. clauses.append("is_present_now = ?")
  85. params.append(1 if present else 0)
  86. return ("WHERE " + " AND ".join(clauses)) if clauses else "", params
  87. def list_items(
  88. table: str,
  89. keyword: str | None,
  90. confirm_status: str | None,
  91. present: bool | None,
  92. page: int,
  93. page_size: int,
  94. fields: list[str],
  95. ) -> dict[str, Any]:
  96. where_sql, params = build_where(keyword, confirm_status, present, fields)
  97. offset = (page - 1) * page_size
  98. with get_db() as conn:
  99. total = conn.execute(f"SELECT COUNT(*) AS total FROM {table} {where_sql}", params).fetchone()["total"]
  100. rows = conn.execute(
  101. f"SELECT * FROM {table} {where_sql} ORDER BY is_present_now DESC, last_seen_at DESC LIMIT ? OFFSET ?",
  102. [*params, page_size, offset],
  103. ).fetchall()
  104. rows = attach_item_metadata(conn, table_to_item_type(table), rows)
  105. return {"items": rows, "total": total, "page": page, "page_size": page_size}
  106. def get_item(table: str, item_id: int) -> dict[str, Any]:
  107. with get_db() as conn:
  108. item = conn.execute(f"SELECT * FROM {table} WHERE id = ?", (item_id,)).fetchone()
  109. if item:
  110. item = attach_item_metadata(conn, table_to_item_type(table), [item])[0]
  111. if not item:
  112. raise HTTPException(status_code=404, detail="Item not found")
  113. return item
  114. def table_to_item_type(table: str) -> str:
  115. if table == "windows_services":
  116. return "service"
  117. if table == "windows_processes":
  118. return "process"
  119. raise ValueError(f"Unsupported table: {table}")
  120. def bool_tag(row: dict[str, Any]) -> dict[str, Any]:
  121. item = dict(row)
  122. item["is_controllable"] = bool(item["is_controllable"])
  123. item["is_builtin"] = bool(item["is_builtin"])
  124. return item
  125. def all_tags(conn) -> list[dict[str, Any]]:
  126. return [
  127. bool_tag(row)
  128. for row in conn.execute("SELECT * FROM tags ORDER BY is_builtin DESC, name ASC").fetchall()
  129. ]
  130. def tags_for_items(conn, item_type: str, item_ids: list[int]) -> dict[int, list[dict[str, Any]]]:
  131. if not item_ids:
  132. return {}
  133. placeholders = ",".join("?" for _ in item_ids)
  134. rows = conn.execute(
  135. f"""
  136. SELECT it.item_id, t.*
  137. FROM item_tags it
  138. JOIN tags t ON t.id = it.tag_id
  139. WHERE it.item_type = ? AND it.item_id IN ({placeholders})
  140. ORDER BY t.name ASC
  141. """,
  142. [item_type, *item_ids],
  143. ).fetchall()
  144. result = {item_id: [] for item_id in item_ids}
  145. for row in rows:
  146. item_id = row["item_id"]
  147. tag = {key: value for key, value in row.items() if key != "item_id"}
  148. result.setdefault(item_id, []).append(bool_tag(tag))
  149. return result
  150. def can_control_item(item_type: str, row: dict[str, Any], tags: list[dict[str, Any]]) -> bool:
  151. if row.get("confirm_status") not in CONFIRMED_CONTROL_STATUSES:
  152. return False
  153. if item_type == "process":
  154. protected_names = {"system idle process", "system", "registry"}
  155. if row.get("last_pid") in (0, 4) or (row.get("name") or "").lower() in protected_names:
  156. return False
  157. return all(tag.get("is_controllable", True) for tag in tags)
  158. def attach_item_metadata(conn, item_type: str, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
  159. tag_map = tags_for_items(conn, item_type, [row["id"] for row in rows])
  160. enriched = []
  161. for row in rows:
  162. item = dict(row)
  163. item["is_present_now"] = bool(item.get("is_present_now"))
  164. item["tags"] = tag_map.get(row["id"], [])
  165. item["can_control"] = can_control_item(item_type, item, item["tags"])
  166. enriched.append(item)
  167. return enriched
  168. def update_one(table: str, item_id: int, payload: StatusUpdate) -> dict[str, Any]:
  169. get_item(table, item_id)
  170. with get_db() as conn:
  171. conn.execute(
  172. f"UPDATE {table} SET confirm_status = ?, user_note = ?, updated_at = ? WHERE id = ?",
  173. (payload.confirm_status, payload.user_note, now_iso(), item_id),
  174. )
  175. return get_item(table, item_id)
  176. def update_batch(table: str, payload: BatchStatusUpdate) -> dict[str, Any]:
  177. if not payload.ids:
  178. return {"updated": 0}
  179. placeholders = ",".join("?" for _ in payload.ids)
  180. with get_db() as conn:
  181. cursor = conn.execute(
  182. f"""
  183. UPDATE {table}
  184. SET confirm_status = ?, user_note = COALESCE(?, user_note), updated_at = ?
  185. WHERE id IN ({placeholders})
  186. """,
  187. [payload.confirm_status, payload.user_note, now_iso(), *payload.ids],
  188. )
  189. return {"updated": cursor.rowcount}
  190. def rows_for_prompt(table: str, item_type: str, payload: PromptRequest) -> list[dict[str, Any]]:
  191. with get_db() as conn:
  192. if payload.scope == "selected" and payload.ids:
  193. placeholders = ",".join("?" for _ in payload.ids)
  194. rows = conn.execute(f"SELECT * FROM {table} WHERE id IN ({placeholders})", payload.ids).fetchall()
  195. else:
  196. rows = conn.execute(f"SELECT * FROM {table} WHERE confirm_status = 'PENDING'").fetchall()
  197. rows = attach_item_metadata(conn, item_type, rows)
  198. return [normalize_prompt_row(item_type, row) for row in rows]
  199. def normalize_prompt_row(item_type: str, row: dict[str, Any]) -> dict[str, Any]:
  200. if item_type == "service":
  201. return {
  202. "type": "service",
  203. "id": row["id"],
  204. "name": row["name"],
  205. "display_name": row["display_name"],
  206. "status": row["status"],
  207. "start_type": row["start_type"],
  208. "username": row["username"],
  209. "binary_path": row["binary_path"],
  210. "description": row["description"],
  211. "is_present_now": bool(row["is_present_now"]),
  212. "tags": [
  213. {
  214. "name": tag["name"],
  215. "description": tag["description"],
  216. "is_controllable": tag["is_controllable"],
  217. }
  218. for tag in row.get("tags", [])
  219. ],
  220. }
  221. return {
  222. "type": "process",
  223. "id": row["id"],
  224. "name": row["name"],
  225. "exe_path": row["exe_path"],
  226. "cmdline": row["cmdline"],
  227. "username": row["username"],
  228. "status": row["status"],
  229. "last_pid": row["last_pid"],
  230. "parent_pid": row["parent_pid"],
  231. "is_present_now": bool(row["is_present_now"]),
  232. "tags": [
  233. {
  234. "name": tag["name"],
  235. "description": tag["description"],
  236. "is_controllable": tag["is_controllable"],
  237. }
  238. for tag in row.get("tags", [])
  239. ],
  240. }
  241. def markdown_table(rows: list[dict[str, Any]]) -> str:
  242. headers = ["type", "id", "name", "status", "tags", "path_or_command", "user", "present"]
  243. lines = ["| " + " | ".join(headers) + " |", "| " + " | ".join(["---"] * len(headers)) + " |"]
  244. for row in rows:
  245. path_or_command = row.get("binary_path") or row.get("exe_path") or row.get("cmdline") or ""
  246. values = [
  247. str(row.get("type", "")),
  248. str(row.get("id", "")),
  249. str(row.get("name", "")),
  250. str(row.get("status", "")),
  251. ", ".join(tag.get("name", "") for tag in row.get("tags", [])).replace("|", "\\|"),
  252. str(path_or_command).replace("|", "\\|"),
  253. str(row.get("username", "")).replace("|", "\\|"),
  254. "yes" if row.get("is_present_now") else "no",
  255. ]
  256. lines.append("| " + " | ".join(values) + " |")
  257. return "\n".join(lines)
  258. def prompt_response(rows: list[dict[str, Any]]) -> dict[str, Any]:
  259. pending_json = json.dumps(rows, ensure_ascii=False, indent=2)
  260. table = markdown_table(rows)
  261. with get_db() as conn:
  262. tags_json = json.dumps(all_tags(conn), ensure_ascii=False, indent=2)
  263. prompt_text = AI_PROMPT_TEMPLATE.replace("{pending_items_json}", pending_json).replace("{tags_json}", tags_json)
  264. return {"prompt_text": prompt_text, "markdown_table": table, "items": rows}
  265. def set_item_tags(item_type: str, table: str, item_id: int, payload: TagAssignRequest) -> dict[str, Any]:
  266. get_item(table, item_id)
  267. unique_ids = sorted(set(payload.tag_ids))
  268. now = now_iso()
  269. with get_db() as conn:
  270. if unique_ids:
  271. placeholders = ",".join("?" for _ in unique_ids)
  272. found = conn.execute(f"SELECT id FROM tags WHERE id IN ({placeholders})", unique_ids).fetchall()
  273. if len(found) != len(unique_ids):
  274. raise HTTPException(status_code=400, detail="One or more tag ids do not exist")
  275. conn.execute("DELETE FROM item_tags WHERE item_type = ? AND item_id = ?", (item_type, item_id))
  276. for tag_id in unique_ids:
  277. conn.execute(
  278. "INSERT INTO item_tags (item_type, item_id, tag_id, created_at) VALUES (?, ?, ?, ?)",
  279. (item_type, item_id, tag_id, now),
  280. )
  281. return get_item(table, item_id)
  282. def ensure_control_allowed(table: str, item_id: int) -> dict[str, Any]:
  283. item = get_item(table, item_id)
  284. if not item.get("can_control"):
  285. raise HTTPException(status_code=403, detail="This item is not controllable because it is unconfirmed or has a non-controllable tag")
  286. return item
  287. def import_ai_results(table: str, item_type: str, payload: AiImportRequest) -> dict[str, Any]:
  288. updated = 0
  289. with get_db() as conn:
  290. for item in payload.items:
  291. if item.type != item_type:
  292. continue
  293. cursor = conn.execute(
  294. f"""
  295. UPDATE {table}
  296. SET confirm_status = ?, ai_description = ?, ai_reason = ?,
  297. ai_suggestion = ?, risk_level = ?, updated_at = ?
  298. WHERE name = ?
  299. """,
  300. (
  301. item.judgement,
  302. item.description,
  303. item.reason,
  304. item.suggestion,
  305. item.risk_level,
  306. now_iso(),
  307. item.name,
  308. ),
  309. )
  310. updated += cursor.rowcount
  311. return {"updated": updated}
  312. @app.get("/api/dashboard")
  313. def dashboard() -> dict[str, Any]:
  314. with get_db() as conn:
  315. latest_scan = conn.execute("SELECT * FROM scan_records ORDER BY started_at DESC LIMIT 1").fetchone()
  316. service_total = conn.execute("SELECT COUNT(*) AS total FROM windows_services").fetchone()["total"]
  317. process_total = conn.execute("SELECT COUNT(*) AS total FROM windows_processes").fetchone()["total"]
  318. pending_services = conn.execute(
  319. "SELECT COUNT(*) AS total FROM windows_services WHERE confirm_status = 'PENDING'"
  320. ).fetchone()["total"]
  321. pending_processes = conn.execute(
  322. "SELECT COUNT(*) AS total FROM windows_processes WHERE confirm_status = 'PENDING'"
  323. ).fetchone()["total"]
  324. missing_services = conn.execute(
  325. "SELECT COUNT(*) AS total FROM windows_services WHERE is_present_now = 0"
  326. ).fetchone()["total"]
  327. missing_processes = conn.execute(
  328. "SELECT COUNT(*) AS total FROM windows_processes WHERE is_present_now = 0"
  329. ).fetchone()["total"]
  330. return {
  331. "latest_scan": latest_scan,
  332. "service_total": service_total,
  333. "process_total": process_total,
  334. "pending_services": pending_services,
  335. "pending_processes": pending_processes,
  336. "missing_services": missing_services,
  337. "missing_processes": missing_processes,
  338. }
  339. @app.get("/api/tags")
  340. def tags() -> dict[str, Any]:
  341. with get_db() as conn:
  342. rows = all_tags(conn)
  343. return {"items": rows}
  344. @app.post("/api/tags")
  345. def tag_create(payload: TagCreate) -> dict[str, Any]:
  346. now = now_iso()
  347. try:
  348. with get_db() as conn:
  349. cursor = conn.execute(
  350. """
  351. INSERT INTO tags (name, description, is_controllable, is_builtin, created_at, updated_at)
  352. VALUES (?, ?, ?, 0, ?, ?)
  353. """,
  354. (payload.name.strip(), payload.description, 1 if payload.is_controllable else 0, now, now),
  355. )
  356. tag_id = cursor.lastrowid
  357. row = conn.execute("SELECT * FROM tags WHERE id = ?", (tag_id,)).fetchone()
  358. except sqlite3.IntegrityError as exc:
  359. raise HTTPException(status_code=409, detail="Tag name already exists") from exc
  360. return bool_tag(row)
  361. @app.patch("/api/tags/{tag_id}")
  362. def tag_update(tag_id: int, payload: TagUpdate) -> dict[str, Any]:
  363. now = now_iso()
  364. try:
  365. with get_db() as conn:
  366. existing = conn.execute("SELECT * FROM tags WHERE id = ?", (tag_id,)).fetchone()
  367. if not existing:
  368. raise HTTPException(status_code=404, detail="Tag not found")
  369. conn.execute(
  370. """
  371. UPDATE tags
  372. SET name = ?, description = ?, is_controllable = ?, updated_at = ?
  373. WHERE id = ?
  374. """,
  375. (payload.name.strip(), payload.description, 1 if payload.is_controllable else 0, now, tag_id),
  376. )
  377. row = conn.execute("SELECT * FROM tags WHERE id = ?", (tag_id,)).fetchone()
  378. except sqlite3.IntegrityError as exc:
  379. raise HTTPException(status_code=409, detail="Tag name already exists") from exc
  380. return bool_tag(row)
  381. @app.delete("/api/tags/{tag_id}")
  382. def tag_delete(tag_id: int) -> dict[str, Any]:
  383. with get_db() as conn:
  384. row = conn.execute("SELECT * FROM tags WHERE id = ?", (tag_id,)).fetchone()
  385. if not row:
  386. raise HTTPException(status_code=404, detail="Tag not found")
  387. if row["is_builtin"]:
  388. raise HTTPException(status_code=400, detail="Built-in tags cannot be deleted")
  389. cursor = conn.execute("DELETE FROM tags WHERE id = ?", (tag_id,))
  390. return {"deleted": cursor.rowcount}
  391. @app.get("/api/sensors")
  392. def sensors() -> dict[str, Any]:
  393. return collect_sensors()
  394. @app.get("/api/smart/scan")
  395. def smart_scan() -> dict[str, Any]:
  396. return scan_devices()
  397. @app.get("/api/smart/devices")
  398. def smart_devices(include_jmb39x: bool = True, jmb39x_slots: int = Query(default=8, ge=0, le=16)) -> dict[str, Any]:
  399. return collect_all_smart(include_jmb39x=include_jmb39x, jmb39x_slots=jmb39x_slots)
  400. @app.get("/api/smart/device")
  401. def smart_device(device: str, device_type: str | None = None) -> dict[str, Any]:
  402. return get_device_smart(device, device_type)
  403. @app.post("/api/scans/run")
  404. def run_scan() -> dict[str, Any]:
  405. return run_full_scan()
  406. @app.get("/api/scans")
  407. def scan_history(page: int = 1, page_size: int = 20) -> dict[str, Any]:
  408. offset = (page - 1) * page_size
  409. with get_db() as conn:
  410. total = conn.execute("SELECT COUNT(*) AS total FROM scan_records").fetchone()["total"]
  411. rows = conn.execute(
  412. "SELECT * FROM scan_records ORDER BY started_at DESC LIMIT ? OFFSET ?",
  413. (page_size, offset),
  414. ).fetchall()
  415. return {"items": rows, "total": total, "page": page, "page_size": page_size}
  416. @app.get("/api/scans/{scan_id}")
  417. def scan_detail(scan_id: int) -> dict[str, Any]:
  418. with get_db() as conn:
  419. scan = conn.execute("SELECT * FROM scan_records WHERE id = ?", (scan_id,)).fetchone()
  420. if not scan:
  421. raise HTTPException(status_code=404, detail="Scan not found")
  422. return scan
  423. @app.get("/api/services")
  424. def services(
  425. keyword: str | None = None,
  426. confirm_status: str | None = None,
  427. present: bool | None = None,
  428. page: int = Query(default=1, ge=1),
  429. page_size: int = Query(default=20, ge=1, le=200),
  430. ) -> dict[str, Any]:
  431. return list_items(
  432. "windows_services",
  433. keyword,
  434. confirm_status,
  435. present,
  436. page,
  437. page_size,
  438. ["name", "display_name", "binary_path", "description"],
  439. )
  440. @app.patch("/api/services/batch")
  441. def service_batch_update(payload: BatchStatusUpdate) -> dict[str, Any]:
  442. return update_batch("windows_services", payload)
  443. @app.post("/api/services/import-ai")
  444. def service_import_ai(payload: AiImportRequest) -> dict[str, Any]:
  445. return import_ai_results("windows_services", "service", payload)
  446. @app.post("/api/services/ai-prompt")
  447. def service_ai_prompt(payload: PromptRequest) -> dict[str, Any]:
  448. return prompt_response(rows_for_prompt("windows_services", "service", payload))
  449. @app.put("/api/services/{service_id}/tags")
  450. def service_tags_update(service_id: int, payload: TagAssignRequest) -> dict[str, Any]:
  451. return set_item_tags("service", "windows_services", service_id, payload)
  452. @app.post("/api/services/{service_id}/start")
  453. def service_start(service_id: int) -> dict[str, Any]:
  454. item = ensure_control_allowed("windows_services", service_id)
  455. if not item.get("is_present_now"):
  456. raise HTTPException(status_code=400, detail="This service was not present in the latest scan")
  457. result = start_service(item["name"])
  458. with get_db() as conn:
  459. conn.execute(
  460. "UPDATE windows_services SET status = ?, updated_at = ? WHERE id = ?",
  461. (result.get("status") or "running", now_iso(), service_id),
  462. )
  463. return result
  464. @app.post("/api/services/{service_id}/stop")
  465. def service_stop(service_id: int) -> dict[str, Any]:
  466. item = ensure_control_allowed("windows_services", service_id)
  467. if not item.get("is_present_now"):
  468. raise HTTPException(status_code=400, detail="This service was not present in the latest scan")
  469. result = stop_service(item["name"])
  470. with get_db() as conn:
  471. conn.execute(
  472. "UPDATE windows_services SET status = ?, updated_at = ? WHERE id = ?",
  473. (result.get("status") or "stopped", now_iso(), service_id),
  474. )
  475. return result
  476. @app.post("/api/services/{service_id}/restart")
  477. def service_restart(service_id: int) -> dict[str, Any]:
  478. item = ensure_control_allowed("windows_services", service_id)
  479. if not item.get("is_present_now"):
  480. raise HTTPException(status_code=400, detail="This service was not present in the latest scan")
  481. result = restart_service(item["name"])
  482. with get_db() as conn:
  483. conn.execute(
  484. "UPDATE windows_services SET status = ?, updated_at = ? WHERE id = ?",
  485. (result.get("status") or "running", now_iso(), service_id),
  486. )
  487. return result
  488. @app.get("/api/services/{service_id}")
  489. def service_detail(service_id: int) -> dict[str, Any]:
  490. return get_item("windows_services", service_id)
  491. @app.patch("/api/services/{service_id}")
  492. def service_update(service_id: int, payload: StatusUpdate) -> dict[str, Any]:
  493. return update_one("windows_services", service_id, payload)
  494. @app.get("/api/processes")
  495. def processes(
  496. keyword: str | None = None,
  497. confirm_status: str | None = None,
  498. present: bool | None = None,
  499. page: int = Query(default=1, ge=1),
  500. page_size: int = Query(default=20, ge=1, le=200),
  501. ) -> dict[str, Any]:
  502. return list_items(
  503. "windows_processes",
  504. keyword,
  505. confirm_status,
  506. present,
  507. page,
  508. page_size,
  509. ["name", "exe_path", "cmdline", "username"],
  510. )
  511. @app.patch("/api/processes/batch")
  512. def process_batch_update(payload: BatchStatusUpdate) -> dict[str, Any]:
  513. return update_batch("windows_processes", payload)
  514. @app.post("/api/processes/import-ai")
  515. def process_import_ai(payload: AiImportRequest) -> dict[str, Any]:
  516. return import_ai_results("windows_processes", "process", payload)
  517. @app.post("/api/processes/ai-prompt")
  518. def process_ai_prompt(payload: PromptRequest) -> dict[str, Any]:
  519. return prompt_response(rows_for_prompt("windows_processes", "process", payload))
  520. @app.put("/api/processes/{process_id}/tags")
  521. def process_tags_update(process_id: int, payload: TagAssignRequest) -> dict[str, Any]:
  522. return set_item_tags("process", "windows_processes", process_id, payload)
  523. @app.post("/api/processes/{process_id}/start")
  524. def process_start(process_id: int) -> dict[str, Any]:
  525. item = ensure_control_allowed("windows_processes", process_id)
  526. result = start_process(item)
  527. with get_db() as conn:
  528. conn.execute(
  529. "UPDATE windows_processes SET last_pid = ?, is_present_now = 1, status = ?, updated_at = ? WHERE id = ?",
  530. (result.get("pid"), "running", now_iso(), process_id),
  531. )
  532. return result
  533. @app.post("/api/processes/{process_id}/stop")
  534. def process_stop(process_id: int) -> dict[str, Any]:
  535. item = ensure_control_allowed("windows_processes", process_id)
  536. if not item.get("is_present_now"):
  537. raise HTTPException(status_code=400, detail="This process was not present in the latest scan")
  538. result = stop_process(item)
  539. with get_db() as conn:
  540. conn.execute(
  541. "UPDATE windows_processes SET is_present_now = 0, status = ?, updated_at = ? WHERE id = ?",
  542. ("stopped", now_iso(), process_id),
  543. )
  544. return result
  545. @app.get("/api/processes/{process_id}")
  546. def process_detail(process_id: int) -> dict[str, Any]:
  547. return get_item("windows_processes", process_id)
  548. @app.patch("/api/processes/{process_id}")
  549. def process_update(process_id: int, payload: StatusUpdate) -> dict[str, Any]:
  550. return update_one("windows_processes", process_id, payload)