koi-handler 0.12.5__tar.gz → 0.12.7__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. {koi_handler-0.12.5/src/koi_handler.egg-info → koi_handler-0.12.7}/PKG-INFO +1 -5
  2. {koi_handler-0.12.5 → koi_handler-0.12.7}/pyproject.toml +2 -11
  3. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/main.py +43 -17
  4. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/mcp/server.py +106 -79
  5. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/logger.py +43 -29
  6. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/ui.py +9 -4
  7. {koi_handler-0.12.5 → koi_handler-0.12.7/src/koi_handler.egg-info}/PKG-INFO +1 -5
  8. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi_handler.egg-info/SOURCES.txt +0 -1
  9. koi_handler-0.12.5/src/koi_handler.egg-info/requires.txt +0 -5
  10. {koi_handler-0.12.5 → koi_handler-0.12.7}/LICENSE +0 -0
  11. {koi_handler-0.12.5 → koi_handler-0.12.7}/setup.cfg +0 -0
  12. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/listener.py +0 -0
  13. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/mcp/__init__.py +0 -0
  14. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/mcp/schema.py +0 -0
  15. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/blueprint.py +0 -0
  16. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/download.py +0 -0
  17. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/duplicate.py +0 -0
  18. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/get_processes.py +0 -0
  19. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/get_users.py +0 -0
  20. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/ligolo.py +0 -0
  21. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/loader.py +0 -0
  22. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/network_enum.py +0 -0
  23. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/peas.py +0 -0
  24. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/populate_win.py +0 -0
  25. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/secrets_dump.py +0 -0
  26. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/sharphound.py +0 -0
  27. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/ssh_persist.py +0 -0
  28. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/sysinfo.py +0 -0
  29. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/upload.py +0 -0
  30. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/upload64.py +0 -0
  31. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/wifi_enum.py +0 -0
  32. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/modules/winscalate.py +0 -0
  33. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/session.py +0 -0
  34. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/tunnel/__init__.py +0 -0
  35. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/tunnel/agent_payload.py +0 -0
  36. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/tunnel/engine/__init__.py +0 -0
  37. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/tunnel/engine/__main__.py +0 -0
  38. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/tunnel/engine/agent.py +0 -0
  39. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/tunnel/engine/packet.py +0 -0
  40. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/tunnel/engine/proxy.py +0 -0
  41. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/tunnel/engine/stack.py +0 -0
  42. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/tunnel/engine/tcp.py +0 -0
  43. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/tunnel/engine/transport.py +0 -0
  44. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/tunnel/engine/tun.py +0 -0
  45. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/tunnel/manager.py +0 -0
  46. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/__init__.py +0 -0
  47. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/bash_obfuscate.py +0 -0
  48. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/cache.py +0 -0
  49. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/cli.py +0 -0
  50. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/config.py +0 -0
  51. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/config_ui.py +0 -0
  52. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/connect/__init__.py +0 -0
  53. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/connect/base.py +0 -0
  54. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/connect/ntlm.py +0 -0
  55. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/connect/ssh.py +0 -0
  56. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/connect/winrm.py +0 -0
  57. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/connect/wsman.py +0 -0
  58. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/constants.py +0 -0
  59. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/detect.py +0 -0
  60. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/interact.py +0 -0
  61. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/models.py +0 -0
  62. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/obfuscate_ui.py +0 -0
  63. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/payloads.py +0 -0
  64. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/powerupgrade.py +0 -0
  65. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/ps_obfuscate.py +0 -0
  66. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/tcp.py +0 -0
  67. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/terminal.py +0 -0
  68. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi/utils/tls.py +0 -0
  69. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi_handler.egg-info/dependency_links.txt +0 -0
  70. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi_handler.egg-info/entry_points.txt +0 -0
  71. {koi_handler-0.12.5 → koi_handler-0.12.7}/src/koi_handler.egg-info/top_level.txt +0 -0
@@ -1,11 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: koi-handler
3
- Version: 0.12.5
3
+ Version: 0.12.7
4
4
  Summary: Reverse shell listener
5
5
  Requires-Python: >=3.10
6
6
  License-File: LICENSE
7
- Requires-Dist: mcp>=2.0
8
- Requires-Dist: uvicorn>=0.30
9
- Requires-Dist: starlette>=0.40
10
- Provides-Extra: mcp
11
7
  Dynamic: license-file
@@ -4,19 +4,10 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "koi-handler"
7
- version = "0.12.5"
7
+ version = "0.12.7"
8
8
  description = "Reverse shell listener"
9
9
  requires-python = ">=3.10"
10
- dependencies = [
11
- "mcp>=2.0",
12
- "uvicorn>=0.30",
13
- "starlette>=0.40",
14
- ]
15
-
16
- [project.optional-dependencies]
17
- # Kept as an empty alias so `pipx install "koi-handler[mcp]"` still resolves for
18
- # anyone with it in a script or doc; the deps now live in core.
19
- mcp = []
10
+ dependencies = []
20
11
 
21
12
  [project.scripts]
22
13
  koi = "koi.main:main"
@@ -7,7 +7,7 @@ import sys
7
7
 
8
8
  from koi.listener import Listener
9
9
  from koi.utils.config import CONFIG
10
- from koi.utils.ui import notify, display_art, print_payloads, __version__
10
+ from koi.utils.ui import notify, display_art, print_payloads, __version__, _PKG_NAME
11
11
  from koi.utils.obfuscate_ui import run_obfuscate_ui
12
12
  from koi.utils.logger import review as _review
13
13
  from koi.utils.logger import clear_log as _clear_log
@@ -88,30 +88,61 @@ class _ArtHelpAction(argparse.Action):
88
88
  parser.exit()
89
89
 
90
90
 
91
- def _print_version() -> None:
92
- from koi.utils.ui import accent, bold, dim
93
- print(f"koi {bold(__version__)}")
91
+ def _latest_apt() -> str | None:
92
+ import subprocess
93
+ try:
94
+ out = subprocess.check_output(
95
+ ["apt-cache", "policy", "koi"],
96
+ stderr=subprocess.DEVNULL, timeout=5, text=True,
97
+ )
98
+ for line in out.splitlines():
99
+ if "Candidate:" in line:
100
+ raw = line.split("Candidate:", 1)[1].strip()
101
+ return raw.split("-")[0]
102
+ except Exception:
103
+ pass
104
+ return None
105
+
106
+
107
+ def _latest_github() -> str | None:
108
+ from urllib.request import urlopen, Request
109
+ import json
94
110
  try:
95
- from urllib.request import urlopen, Request
96
- import json
97
111
  req = Request(
98
112
  "https://api.github.com/repos/b3rt1ng/Koi/releases/latest",
99
113
  headers={"User-Agent": "koi/update-check", "Accept": "application/json"},
100
114
  )
101
115
  with urlopen(req, timeout=3) as resp:
102
- latest = json.loads(resp.read())["tag_name"].lstrip("vV")
116
+ return json.loads(resp.read())["tag_name"].lstrip("vV")
117
+ except Exception:
118
+ return None
119
+
120
+
121
+ def _print_version() -> None:
122
+ from koi.utils.ui import accent, bold, dim
123
+ print(f"koi {bold(__version__)}")
124
+ try:
125
+ is_apt = _PKG_NAME == "koi"
126
+ latest = _latest_apt() if is_apt else _latest_github()
127
+ if latest is None:
128
+ print(dim(" could not check for updates"))
129
+ return
103
130
  local = __version__.lstrip("vV")
104
131
  if latest == local:
105
132
  print(dim("up to date"))
106
133
  else:
107
- print(f"\n{accent(f'v{latest}')} is available! {dim('pipx upgrade koi-handler')}")
134
+ if is_apt:
135
+ hint = dim("sudo apt update && sudo apt upgrade koi")
136
+ else:
137
+ hint = dim("pipx upgrade koi-handler")
138
+ print(f"\n{accent(f'v{latest}')} is available!\n{hint}")
108
139
  except Exception:
109
140
  print(dim(" could not check for updates"))
110
141
 
111
142
 
112
143
  def main():
113
144
  parser = argparse.ArgumentParser(
114
- description="koi – multi-session reverse shell listener",
145
+ description="koi, multi-session reverse shell listener",
115
146
  add_help=False,
116
147
  )
117
148
  parser.add_argument("-h", "--help", action=_ArtHelpAction, help="show this help message and exit")
@@ -198,12 +229,7 @@ def main():
198
229
  keep_history=args.keep_history, no_log=not args.logging)
199
230
 
200
231
  if args.mcp:
201
- from koi.mcp.server import KoiMCPServer, missing_dependencies
202
-
203
- if missing := missing_dependencies():
204
- notify('error', f"MCP dependencies missing: {', '.join(missing)}")
205
- notify('status', "Reinstall to restore them: pipx install --force koi-handler")
206
- sys.exit(1)
232
+ from koi.mcp.server import KoiMCPServer
207
233
 
208
234
  listener.mcp_server = KoiMCPServer(
209
235
  listener,
@@ -226,7 +252,7 @@ def main():
226
252
 
227
253
  def koireview():
228
254
  parser = argparse.ArgumentParser(
229
- description="koireview – review a recorded Koi session",
255
+ description="koireview, review a recorded Koi session",
230
256
  add_help=False,
231
257
  )
232
258
  parser.add_argument("-h", "--help", action=_ArtHelpAction, help="show this help message and exit")
@@ -261,7 +287,7 @@ def koireview():
261
287
 
262
288
  def obfuscator():
263
289
  parser = argparse.ArgumentParser(
264
- description="koifuscator – payload obfuscator",
290
+ description="koifuscator, payload obfuscator",
265
291
  add_help=False,
266
292
  )
267
293
  parser.add_argument("-h", "--help", action=_ArtHelpAction, help="show this help message and exit")
@@ -1,19 +1,21 @@
1
- """MCP server over HTTP, not stdio: stdin/stdout belong to the REPL."""
1
+ """MCP server over HTTP, stdlib only: no external SDK needed."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import asyncio
6
5
  import base64
7
6
  import contextlib
7
+ import hmac
8
8
  import io
9
9
  import json
10
10
  import logging
11
11
  import ntpath
12
12
  import posixpath
13
13
  import secrets
14
+ import socketserver
14
15
  import sys
15
16
  import threading
16
17
  import time
18
+ from http.server import BaseHTTPRequestHandler, HTTPServer
17
19
  from pathlib import Path
18
20
  from typing import TYPE_CHECKING, Any, Dict, List, Optional
19
21
 
@@ -62,13 +64,7 @@ _EXEC_ONLY_TOOLS = {
62
64
  "koi_session_write", "koi_session_read", "koi_session_signal",
63
65
  }
64
66
 
65
- _REQUIRED_PACKAGES = ("mcp", "uvicorn", "starlette")
66
-
67
-
68
- def missing_dependencies() -> List[str]:
69
- import importlib.util
70
-
71
- return [n for n in _REQUIRED_PACKAGES if importlib.util.find_spec(n) is None]
67
+ _PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05")
72
68
 
73
69
 
74
70
  def _cap(text: str) -> tuple[str, bool]:
@@ -141,17 +137,19 @@ def _uptime(since: Optional[float]) -> Optional[str]:
141
137
  def _version() -> str:
142
138
  from importlib.metadata import PackageNotFoundError, version
143
139
 
144
- try:
145
- return version("koi-handler")
146
- except PackageNotFoundError:
147
- return "unknown"
140
+ for candidate in ("koi-handler", "koi"):
141
+ try:
142
+ return version(candidate)
143
+ except PackageNotFoundError:
144
+ continue
145
+ return "unknown"
148
146
 
149
147
 
150
148
  def _tool(name: str, description: str, properties=None, required=None, annotations=None) -> Dict[str, Any]:
151
149
  schema: Dict[str, Any] = {"type": "object", "properties": properties or {}}
152
150
  if required:
153
151
  schema["required"] = required
154
- tool: Dict[str, Any] = {"name": name, "description": description, "input_schema": schema}
152
+ tool: Dict[str, Any] = {"name": name, "description": description, "inputSchema": schema}
155
153
  if annotations:
156
154
  tool["annotations"] = annotations
157
155
  return tool
@@ -896,82 +894,111 @@ class KoiMCPServer:
896
894
  "keys (e.g. ctrl_c) with koi_session_signal."
897
895
  )
898
896
 
899
- def _build_app(self):
900
- import mcp.types as types
901
- from mcp.server.lowlevel import Server
897
+ def _dispatch(self, method: str, params: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
898
+ if method == "initialize":
899
+ client_version = (params or {}).get("protocolVersion", _PROTOCOL_VERSIONS[0])
900
+ version = client_version if client_version in _PROTOCOL_VERSIONS else _PROTOCOL_VERSIONS[0]
901
+ return {
902
+ "protocolVersion": version,
903
+ "capabilities": {"tools": {"listChanged": False}, "resources": {"listChanged": False}},
904
+ "serverInfo": {"name": "koi", "version": _version(), "title": "Koi"},
905
+ "instructions": self._instructions(),
906
+ }
902
907
 
903
- async def on_list_tools(ctx, params) -> types.ListToolsResult:
904
- return types.ListToolsResult(tools=[types.Tool(**t) for t in self._list_tools()])
908
+ if method == "tools/list":
909
+ return {"tools": self._list_tools()}
905
910
 
906
- async def on_call_tool(ctx, params) -> types.CallToolResult:
911
+ if method == "tools/call":
912
+ name = (params or {}).get("name", "")
913
+ arguments = (params or {}).get("arguments") or {}
907
914
  try:
908
- text = await asyncio.to_thread(
909
- self.call_tool, params.name, params.arguments or {}
910
- )
915
+ text = self.call_tool(name, arguments)
911
916
  except Exception as exc:
912
- return types.CallToolResult(
913
- content=[types.TextContent(type="text", text=f"{type(exc).__name__}: {exc}")],
914
- is_error=True,
915
- )
916
- return types.CallToolResult(content=[types.TextContent(type="text", text=text)])
917
+ return {
918
+ "content": [{"type": "text", "text": f"{type(exc).__name__}: {exc}"}],
919
+ "isError": True,
920
+ }
921
+ return {"content": [{"type": "text", "text": text}]}
917
922
 
918
- async def on_list_resources(ctx, params) -> types.ListResourcesResult:
919
- return types.ListResourcesResult(
920
- resources=[types.Resource(**r) for r in self.list_resources()]
921
- )
923
+ if method == "resources/list":
924
+ return {"resources": self.list_resources()}
922
925
 
923
- async def on_read_resource(ctx, params) -> types.ReadResourceResult:
924
- uri = str(params.uri)
925
- text = await asyncio.to_thread(self.read_resource, uri)
926
- return types.ReadResourceResult(
927
- contents=[types.TextResourceContents(uri=uri, mime_type="text/plain", text=text)]
928
- )
926
+ if method == "resources/read":
927
+ uri = (params or {}).get("uri", "")
928
+ text = self.read_resource(str(uri))
929
+ return {"contents": [{"uri": str(uri), "mimeType": "text/plain", "text": text}]}
929
930
 
930
- server = Server(
931
- "koi",
932
- version=_version(),
933
- title="Koi",
934
- website_url="https://b3rt1ng.github.io/koi-wiki/",
935
- instructions=self._instructions(),
936
- on_list_tools=on_list_tools,
937
- on_call_tool=on_call_tool,
938
- on_list_resources=on_list_resources,
939
- on_read_resource=on_read_resource,
940
- )
941
- inner = server.streamable_http_app(streamable_http_path="/mcp", host=self.host)
942
-
943
- async def app(scope, receive, send):
944
- scope_type = scope.get("type")
945
- if scope_type == "http":
946
- from starlette.responses import JSONResponse
947
-
948
- headers = dict(scope.get("headers") or [])
949
- provided = headers.get(b"authorization", b"").decode(errors="replace")
950
- if not secrets.compare_digest(provided, f"Bearer {self.token}"):
951
- await JSONResponse({"error": "unauthorized"}, status_code=401)(
952
- scope, receive, send
953
- )
954
- return
955
- elif scope_type != "lifespan":
956
- return
957
- await inner(scope, receive, send)
931
+ if method.startswith("notifications/"):
932
+ return None
933
+
934
+ raise ValueError(f"Method not found: {method}")
935
+
936
+ def _handle_jsonrpc(self, body: bytes) -> Optional[bytes]:
937
+ try:
938
+ msg = json.loads(body)
939
+ except (json.JSONDecodeError, UnicodeDecodeError):
940
+ return json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}).encode()
958
941
 
959
- return app
942
+ req_id = msg.get("id")
943
+ method = msg.get("method", "")
944
+ params = msg.get("params")
945
+
946
+ if req_id is None and method.startswith("notifications/"):
947
+ self._dispatch(method, params)
948
+ return None
949
+
950
+ try:
951
+ result = self._dispatch(method, params)
952
+ except ValueError as exc:
953
+ return json.dumps({"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": str(exc)}}).encode()
954
+ except Exception as exc:
955
+ return json.dumps({"jsonrpc": "2.0", "id": req_id, "error": {"code": -32603, "message": f"{type(exc).__name__}: {exc}"}}).encode()
956
+
957
+ if result is None:
958
+ return None
959
+
960
+ return json.dumps({"jsonrpc": "2.0", "id": req_id, "result": result}).encode()
960
961
 
961
962
  def _serve(self) -> None:
963
+ mcp_server = self
964
+
965
+ class _Handler(BaseHTTPRequestHandler):
966
+ def log_message(self, fmt, *args):
967
+ pass
968
+
969
+ def do_POST(self):
970
+ if self.path != "/mcp":
971
+ self.send_error(404)
972
+ return
973
+ auth = self.headers.get("Authorization", "")
974
+ if not hmac.compare_digest(auth, f"Bearer {mcp_server.token}"):
975
+ self.send_error(401)
976
+ return
977
+ length = int(self.headers.get("Content-Length", 0))
978
+ body = self.rfile.read(length) if length else b""
979
+ resp = mcp_server._handle_jsonrpc(body)
980
+ if resp is None:
981
+ self.send_response(204)
982
+ self.end_headers()
983
+ return
984
+ self.send_response(200)
985
+ self.send_header("Content-Type", "application/json")
986
+ self.send_header("Content-Length", str(len(resp)))
987
+ self.end_headers()
988
+ self.wfile.write(resp)
989
+
990
+ def do_GET(self):
991
+ self.send_error(405)
992
+
993
+ def do_DELETE(self):
994
+ self.send_error(405)
995
+
996
+ class _ThreadedHTTP(socketserver.ThreadingMixIn, HTTPServer):
997
+ daemon_threads = True
998
+
962
999
  try:
963
- import uvicorn
964
-
965
- config = uvicorn.Config(
966
- self._build_app(),
967
- host=self.host,
968
- port=self.port,
969
- log_level="error",
970
- access_log=False,
971
- )
972
- server = uvicorn.Server(config)
973
- server.install_signal_handlers = lambda: None
974
- asyncio.run(server.serve())
1000
+ httpd = _ThreadedHTTP((self.host, self.port), _Handler)
1001
+ httpd.serve_forever()
975
1002
  except Exception as exc:
976
1003
  from koi.utils.ui import notify
977
1004
 
@@ -23,6 +23,7 @@ if TYPE_CHECKING:
23
23
  _LOG_DIR = Path.home() / ".koi" / "logs"
24
24
  _CTRL = re.compile(r"[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f]")
25
25
  _PROMPT_SUFFIXES = ("$", "#", "❯", "% ")
26
+ _PROMPT_FRAGMENTS = ("└─$", "└─#", "┌──(", "PS C:\\", "PS>")
26
27
  _MAX_LOG_BYTES = 50 * 1024 * 1024
27
28
 
28
29
 
@@ -46,7 +47,10 @@ def _printable(text: str) -> bool:
46
47
 
47
48
 
48
49
  def _is_prompt(line: str) -> bool:
49
- return any(line.strip().endswith(sfx) for sfx in _PROMPT_SUFFIXES)
50
+ s = line.strip()
51
+ if any(s.endswith(sfx) for sfx in _PROMPT_SUFFIXES):
52
+ return True
53
+ return any(frag in s for frag in _PROMPT_FRAGMENTS)
50
54
 
51
55
 
52
56
  def _dim_ts(entry: dict) -> str:
@@ -226,14 +230,30 @@ def review(name: str) -> None:
226
230
  notify("error", f"Log not found: {name}")
227
231
  sys.exit(1)
228
232
 
229
- encoding = "utf-8"
230
- input_buf = b""
231
- recent_cmds: set[str] = set()
233
+ encoding = "utf-8"
234
+ input_buf = b""
235
+ output_buf = ""
236
+ accepting_output = False
237
+ last_cmd = ""
238
+
239
+ def _flush_output(ts_str: str) -> None:
240
+ nonlocal output_buf
241
+ for line in output_buf.splitlines():
242
+ stripped = _CTRL.sub("", line).strip()
243
+ if (not stripped or not _printable(stripped)
244
+ or stripped.lower() == last_cmd.lower()
245
+ or _is_prompt(stripped)
246
+ or "__KOI_" in stripped):
247
+ continue
248
+ _render_output_line(ts_str, stripped)
249
+ output_buf = ""
232
250
 
233
- def flush_state() -> None:
234
- nonlocal input_buf
251
+ def _flush_all(ts_str: str) -> None:
252
+ nonlocal input_buf, accepting_output, last_cmd
253
+ _flush_output(ts_str)
235
254
  input_buf = b""
236
- recent_cmds.clear()
255
+ accepting_output = False
256
+ last_cmd = ""
237
257
 
238
258
  print()
239
259
  with open(path, encoding="utf-8") as f:
@@ -246,7 +266,7 @@ def review(name: str) -> None:
246
266
  except json.JSONDecodeError:
247
267
  continue
248
268
 
249
- kind = entry.get("type")
269
+ kind = entry.get("type")
250
270
  ts_str = _dim_ts(entry)
251
271
 
252
272
  if kind == "meta":
@@ -254,33 +274,27 @@ def review(name: str) -> None:
254
274
  _render_meta(entry)
255
275
 
256
276
  elif kind == "input":
257
- input_buf += base64.b64decode(entry["data"])
258
- while b"\n" in input_buf or b"\r" in input_buf:
259
- positions = [(input_buf.find(s), s) for s in (b"\r\n", b"\n", b"\r")]
260
- _, sep = min(
261
- ((i, s) for i, s in positions if i != -1),
262
- key=lambda t: (t[0], -len(t[1])),
263
- )
264
- cmd_bytes, input_buf = input_buf.split(sep, 1)
265
- cmd = _CTRL.sub("", _clean(cmd_bytes, encoding)).strip()
277
+ chunk = base64.b64decode(entry["data"])
278
+ if chunk in (b"\r", b"\n", b"\r\n"):
279
+ _flush_output(ts_str)
280
+ cmd = _CTRL.sub("", _clean(input_buf, encoding)).strip()
266
281
  if cmd and _printable(cmd):
267
282
  _render_cmd(ts_str, cmd)
268
- recent_cmds.add(cmd.lower())
283
+ last_cmd = cmd
284
+ input_buf = b""
285
+ accepting_output = True
286
+ else:
287
+ input_buf += chunk
269
288
 
270
289
  elif kind == "output":
271
- text = _clean(base64.b64decode(entry["data"]), encoding)
272
- for line in text.splitlines():
273
- stripped = _CTRL.sub("", line).strip()
274
- if (not stripped or not _printable(stripped)
275
- or stripped.lower() in recent_cmds
276
- or _is_prompt(stripped)
277
- or "__KOI_" in stripped):
278
- continue
279
- _render_output_line(ts_str, stripped)
280
- recent_cmds.clear()
290
+ if not accepting_output:
291
+ continue
292
+ output_buf += _clean(base64.b64decode(entry["data"]), encoding)
281
293
 
282
294
  elif kind == "event":
283
- flush_state()
295
+ _flush_all(ts_str)
296
+ accepting_output = True
284
297
  _render_event(entry)
285
298
 
299
+ _flush_output(_dim_ts({"ts": time.time()}))
286
300
  print()
@@ -19,10 +19,15 @@ RST = "\033[0m"
19
19
  DIM = "\033[2m"
20
20
  BOLD = "\033[1m"
21
21
 
22
- try:
23
- __version__ = importlib.metadata.version("koi-handler")
24
- except importlib.metadata.PackageNotFoundError:
25
- __version__ = "dev"
22
+ _PKG_NAME: str = "dev"
23
+ __version__: str = "dev"
24
+ for _candidate in ("koi-handler", "koi"):
25
+ try:
26
+ __version__ = importlib.metadata.version(_candidate)
27
+ _PKG_NAME = _candidate
28
+ break
29
+ except importlib.metadata.PackageNotFoundError:
30
+ continue
26
31
 
27
32
  _SPINNER_FRAME_DELAY = 0.08
28
33
 
@@ -1,11 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: koi-handler
3
- Version: 0.12.5
3
+ Version: 0.12.7
4
4
  Summary: Reverse shell listener
5
5
  Requires-Python: >=3.10
6
6
  License-File: LICENSE
7
- Requires-Dist: mcp>=2.0
8
- Requires-Dist: uvicorn>=0.30
9
- Requires-Dist: starlette>=0.40
10
- Provides-Extra: mcp
11
7
  Dynamic: license-file
@@ -65,5 +65,4 @@ src/koi_handler.egg-info/PKG-INFO
65
65
  src/koi_handler.egg-info/SOURCES.txt
66
66
  src/koi_handler.egg-info/dependency_links.txt
67
67
  src/koi_handler.egg-info/entry_points.txt
68
- src/koi_handler.egg-info/requires.txt
69
68
  src/koi_handler.egg-info/top_level.txt
@@ -1,5 +0,0 @@
1
- mcp>=2.0
2
- uvicorn>=0.30
3
- starlette>=0.40
4
-
5
- [mcp]
File without changes
File without changes