ether-core 0.1.0__py3-none-any.whl

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 (104) hide show
  1. ether/__init__.py +32 -0
  2. ether/assets/wordlists/common_dirs.txt.gz +0 -0
  3. ether/assets/wordlists/common_params.txt.gz +0 -0
  4. ether/assets/wordlists/common_passwords.txt.gz +0 -0
  5. ether/assets/wordlists/common_usernames.txt.gz +0 -0
  6. ether/assets/wordlists/subdomains_500.txt.gz +0 -0
  7. ether/cli/__init__.py +5 -0
  8. ether/cli/__main__.py +8 -0
  9. ether/cli/commands/__init__.py +1 -0
  10. ether/cli/commands/doctor.py +21 -0
  11. ether/cli/commands/graph.py +311 -0
  12. ether/cli/commands/logs.py +45 -0
  13. ether/cli/commands/mcp.py +49 -0
  14. ether/cli/commands/run.py +146 -0
  15. ether/cli/commands/session.py +61 -0
  16. ether/cli/commands/telemetry.py +51 -0
  17. ether/cli/commands/tool.py +131 -0
  18. ether/cli/context.py +71 -0
  19. ether/cli/formatters.py +39 -0
  20. ether/cli/router.py +368 -0
  21. ether/common/__init__.py +201 -0
  22. ether/common/algorithms.py +407 -0
  23. ether/common/canonicalize.py +93 -0
  24. ether/common/context.py +25 -0
  25. ether/common/crypto.py +183 -0
  26. ether/common/embeddings.py +93 -0
  27. ether/common/exceptions.py +13 -0
  28. ether/common/logging.py +386 -0
  29. ether/common/secure_memory.py +159 -0
  30. ether/common/ssrf.py +93 -0
  31. ether/core/__init__.py +25 -0
  32. ether/core/diagnostics.py +368 -0
  33. ether/core/executor.py +296 -0
  34. ether/core/sandbox.py +118 -0
  35. ether/core/session.py +956 -0
  36. ether/gateway/__init__.py +21 -0
  37. ether/gateway/gate.py +392 -0
  38. ether/gateway/network.py +98 -0
  39. ether/gateway/preflight.py +802 -0
  40. ether/graph/__init__.py +13 -0
  41. ether/graph/analytics.py +334 -0
  42. ether/graph/store.py +1615 -0
  43. ether/graph/telemetry.py +334 -0
  44. ether/graph/timeline.py +185 -0
  45. ether/mcp/__init__.py +5 -0
  46. ether/mcp/server.py +382 -0
  47. ether/paths.py +176 -0
  48. ether/py.typed +0 -0
  49. ether/registry/__init__.py +7 -0
  50. ether/registry/adapter.py +194 -0
  51. ether/registry/manifest.py +53 -0
  52. ether/registry/registry.py +150 -0
  53. ether/registry/wordlists.py +156 -0
  54. ether/schemas/__init__.py +50 -0
  55. ether/schemas/base.py +122 -0
  56. ether/schemas/credential.py +50 -0
  57. ether/schemas/dns.py +116 -0
  58. ether/schemas/host_internal.py +58 -0
  59. ether/schemas/network.py +142 -0
  60. ether/schemas/power.py +68 -0
  61. ether/schemas/vulnerability.py +221 -0
  62. ether/schemas/web.py +172 -0
  63. ether_core-0.1.0.dist-info/METADATA +440 -0
  64. ether_core-0.1.0.dist-info/RECORD +104 -0
  65. ether_core-0.1.0.dist-info/WHEEL +4 -0
  66. ether_core-0.1.0.dist-info/entry_points.txt +2 -0
  67. ether_core-0.1.0.dist-info/licenses/LICENSE +21 -0
  68. tools/__init__.py +0 -0
  69. tools/dnspython/__init__.py +1 -0
  70. tools/dnspython/adapter.py +302 -0
  71. tools/dnspython/cli.py +202 -0
  72. tools/dnspython/manifest.toml +138 -0
  73. tools/ffuf/__init__.py +1 -0
  74. tools/ffuf/adapter.py +183 -0
  75. tools/ffuf/manifest.toml +121 -0
  76. tools/gobuster/__init__.py +0 -0
  77. tools/gobuster/adapter.py +90 -0
  78. tools/gobuster/manifest.toml +104 -0
  79. tools/http_probe/adapter.py +256 -0
  80. tools/http_probe/manifest.toml +40 -0
  81. tools/netexec/__init__.py +1 -0
  82. tools/netexec/adapter.py +163 -0
  83. tools/netexec/manifest.toml +83 -0
  84. tools/nikto/__init__.py +0 -0
  85. tools/nikto/adapter.py +145 -0
  86. tools/nikto/manifest.toml +108 -0
  87. tools/nmap/__init__.py +0 -0
  88. tools/nmap/adapter.py +97 -0
  89. tools/nmap/manifest.toml +159 -0
  90. tools/nuclei/__init__.py +1 -0
  91. tools/nuclei/adapter.py +171 -0
  92. tools/nuclei/manifest.toml +117 -0
  93. tools/searchsploit/__init__.py +1 -0
  94. tools/searchsploit/adapter.py +139 -0
  95. tools/searchsploit/manifest.toml +103 -0
  96. tools/sqlmap/__init__.py +1 -0
  97. tools/sqlmap/adapter.py +214 -0
  98. tools/sqlmap/manifest.toml +89 -0
  99. tools/subfinder/__init__.py +0 -0
  100. tools/subfinder/adapter.py +71 -0
  101. tools/subfinder/manifest.toml +104 -0
  102. tools/whois/__init__.py +0 -0
  103. tools/whois/adapter.py +80 -0
  104. tools/whois/manifest.toml +95 -0
ether/mcp/server.py ADDED
@@ -0,0 +1,382 @@
1
+ """Native Model Context Protocol (MCP) server implementation for Ether."""
2
+
3
+ import asyncio
4
+ import json
5
+ import logging
6
+ from typing import Any, Dict, List, Optional, Union
7
+ from uuid import UUID
8
+
9
+ from mcp.server.mcpserver import MCPServer
10
+
11
+ from ether.common import sanitize_untrusted_output
12
+ from ether.core.session import ExecutionCompleted, ExecutionFailed
13
+ from ether.gateway.gate import ActionGateway, GatePolicy
14
+ from ether.graph.store import GraphStore
15
+ from ether.graph.telemetry import GraphTelemetryCompiler
16
+ from ether.registry.registry import ToolRegistry
17
+ from ether.schemas.power import ActionRequest
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ def create_mcp_server(
23
+ store: GraphStore,
24
+ default_session_id: Optional[str] = None,
25
+ policy: GatePolicy = GatePolicy.SAFE,
26
+ gateway: Optional[ActionGateway] = None,
27
+ registry: Optional[ToolRegistry] = None,
28
+ execution_session: Optional[Any] = None,
29
+ ) -> MCPServer:
30
+ """Construct an MCP server instance exposing canonical security tools."""
31
+ server = MCPServer("ether")
32
+
33
+ reg = registry or ToolRegistry()
34
+ if not reg.tools:
35
+ reg.load_tools()
36
+ gw = gateway or ActionGateway(registry=reg, store=store, policy=policy)
37
+ gw.store = store
38
+ exec_sess = execution_session or gw.create_session()
39
+
40
+ async def _resolve_session(session_id: Optional[str]) -> str:
41
+ """Resolve target session ID from argument, default, or active sandbox."""
42
+ if session_id:
43
+ return session_id
44
+ if default_session_id:
45
+ return default_session_id
46
+ _, sess_id = await store.get_or_create_default_session()
47
+ return sess_id
48
+
49
+ @server.tool()
50
+ async def query_graph(
51
+ session_id: Optional[str] = None,
52
+ schema_type: Optional[str] = None,
53
+ limit: int = 100,
54
+ include_stale: bool = False,
55
+ ) -> str:
56
+ """Query normalized cybersecurity findings and entities in the graph.
57
+
58
+ Args:
59
+ session_id: Target session ID (optional, defaults to active session).
60
+ schema_type: Filter by schema type (e.g. 'network.host', 'network.service').
61
+ limit: Maximum number of nodes to return (default: 100).
62
+ include_stale: Whether to include decayed stale nodes (default: False).
63
+ """
64
+ sess_id = await _resolve_session(session_id)
65
+ if schema_type:
66
+ raw_nodes = await store.query(
67
+ schema_type, session_id=sess_id, include_stale=include_stale
68
+ )
69
+ else:
70
+ raw_nodes = await store.get_all_nodes(sess_id, include_stale=include_stale)
71
+
72
+ limited_nodes: List[Dict[str, Any]] = []
73
+ for n in raw_nodes[:limit]:
74
+ try:
75
+ pik_data = json.loads(n.get("pik_json") or "{}")
76
+ except Exception:
77
+ pik_data = {}
78
+ try:
79
+ finding_data = json.loads(n.get("data_json") or "{}")
80
+ except Exception:
81
+ finding_data = {}
82
+ limited_nodes.append(
83
+ {
84
+ "id": n["id"],
85
+ "schema_type": n["schema_type"],
86
+ "pik": pik_data,
87
+ "data": finding_data,
88
+ "status": n.get("status", "confirmed"),
89
+ "action_id": n.get("action_id"),
90
+ "created_at": n.get("created_at"),
91
+ "updated_at": n.get("updated_at"),
92
+ }
93
+ )
94
+
95
+ return json.dumps(
96
+ {
97
+ "session_id": sess_id,
98
+ "total": len(raw_nodes),
99
+ "returned": len(limited_nodes),
100
+ "nodes": limited_nodes,
101
+ },
102
+ indent=2,
103
+ )
104
+
105
+ @server.tool()
106
+ async def inspect_entity(
107
+ entity_id: str,
108
+ session_id: Optional[str] = None,
109
+ ) -> str:
110
+ """Inspect detailed attributes, PIK, and relational edges for a specific entity node.
111
+
112
+ Args:
113
+ entity_id: Deterministic SHA-256 node ID.
114
+ session_id: Target session ID (optional, defaults to active session).
115
+ """
116
+ sess_id = await _resolve_session(session_id)
117
+ node = await store.get_node(sess_id, entity_id)
118
+ if not node:
119
+ return json.dumps({"error": "NotFound", "message": f"Entity '{entity_id}' not found."})
120
+
121
+ # Fetch incident edges
122
+ all_edges = await store.get_all_edges(sess_id)
123
+ incident_edges = [
124
+ e for e in all_edges if e["source_id"] == entity_id or e["target_id"] == entity_id
125
+ ]
126
+
127
+ try:
128
+ pik_data = json.loads(node.get("pik_json") or "{}")
129
+ except Exception:
130
+ pik_data = {}
131
+ try:
132
+ finding_data = json.loads(node.get("data_json") or "{}")
133
+ except Exception:
134
+ finding_data = {}
135
+
136
+ return json.dumps(
137
+ {
138
+ "session_id": sess_id,
139
+ "entity": {
140
+ "id": node["id"],
141
+ "schema_type": node["schema_type"],
142
+ "pik": pik_data,
143
+ "data": finding_data,
144
+ "status": node.get("status", "confirmed"),
145
+ "action_id": node.get("action_id"),
146
+ "created_at": node.get("created_at"),
147
+ "updated_at": node.get("updated_at"),
148
+ },
149
+ "edges": incident_edges,
150
+ },
151
+ indent=2,
152
+ )
153
+
154
+ @server.tool()
155
+ async def get_diff(
156
+ session_id: Optional[str] = None,
157
+ action_id: Optional[str] = None,
158
+ baseline_timestamp: Optional[str] = None,
159
+ ) -> str:
160
+ """Retrieve zero-token set-theoretic delta envelope for an action or baseline timestamp.
161
+
162
+ Args:
163
+ session_id: Target session ID (optional, defaults to active session).
164
+ action_id: Filter changes produced by a specific action execution run.
165
+ baseline_timestamp: Filter changes produced since an ISO or epoch timestamp.
166
+ """
167
+ sess_id = await _resolve_session(session_id)
168
+ compiler = GraphTelemetryCompiler(store, sess_id, execution_session=exec_sess)
169
+ diff = await compiler.compute_graph_diff(
170
+ baseline_timestamp=baseline_timestamp, action_id=action_id
171
+ )
172
+ return json.dumps(diff, indent=2)
173
+
174
+ @server.tool()
175
+ async def search_findings_semantic(
176
+ query: str,
177
+ session_id: Optional[str] = None,
178
+ limit: int = 10,
179
+ schema_type: Optional[str] = None,
180
+ min_score: float = 0.0,
181
+ ) -> str:
182
+ """Search finding entities in the graph using natural language offline vector similarity.
183
+
184
+ Args:
185
+ query: Natural language search query (e.g. 'Apache HTTP Server path traversal').
186
+ session_id: Target session ID (optional, defaults to active session).
187
+ limit: Maximum findings to return (default: 10).
188
+ schema_type: Optional filter by schema type (e.g. 'vulnerability.found').
189
+ min_score: Minimum cosine similarity score between 0.0 and 1.0 (default: 0.0).
190
+ """
191
+ sess_id = await _resolve_session(session_id)
192
+ results = await store.semantic_search(
193
+ session_id=sess_id,
194
+ query=query,
195
+ limit=limit,
196
+ schema_type=schema_type,
197
+ min_score=min_score,
198
+ )
199
+
200
+ formatted_results = []
201
+ for r in results:
202
+ pik_data = r.get("pik")
203
+ if not pik_data and r.get("pik_json"):
204
+ try:
205
+ pik_data = json.loads(r["pik_json"])
206
+ except Exception:
207
+ pik_data = {}
208
+
209
+ finding_data = r.get("data")
210
+ if not finding_data and r.get("data_json"):
211
+ try:
212
+ finding_data = json.loads(r["data_json"])
213
+ except Exception:
214
+ finding_data = {}
215
+
216
+ formatted_results.append(
217
+ {
218
+ "id": r["id"],
219
+ "schema_type": r["schema_type"],
220
+ "similarity": r.get("similarity", 0.0),
221
+ "distance": r.get("distance", 1.0),
222
+ "status": r.get("status", "confirmed"),
223
+ "pik": pik_data,
224
+ "data": finding_data,
225
+ "created_at": r.get("created_at"),
226
+ "updated_at": r.get("updated_at"),
227
+ }
228
+ )
229
+
230
+ return json.dumps(
231
+ {
232
+ "session_id": sess_id,
233
+ "query": query,
234
+ "total_matched": len(formatted_results),
235
+ "findings": formatted_results,
236
+ },
237
+ indent=2,
238
+ )
239
+
240
+ @server.tool()
241
+ async def execute_tool(
242
+ tool_name: str,
243
+ target: str,
244
+ arguments: Optional[Dict[str, Any]] = None,
245
+ session_id: Optional[str] = None,
246
+ timeout_seconds: Union[int, float] = 120,
247
+ include_raw: bool = False,
248
+ ) -> str:
249
+ """Execute a security tool action under process supervision and policy gating.
250
+
251
+ Args:
252
+ tool_name: Registered security tool name (e.g. 'nmap', 'ffuf', 'whois').
253
+ target: Target host, domain, IP, or URL.
254
+ arguments: Tool parameters or flags (e.g. {"flags": ["-sV", "-p80"]}).
255
+ session_id: Target investigation session ID.
256
+ timeout_seconds: Seconds to await execution before detaching to background (default: 120).
257
+ include_raw: Whether to include sanitized untrusted stdout inside <untrusted_scan_output> tags.
258
+ """
259
+ sess_id = await _resolve_session(session_id)
260
+ registry = gw.registry
261
+ if not registry.get_tool(tool_name):
262
+ return json.dumps(
263
+ {
264
+ "error": "ToolNotFound",
265
+ "message": f"Tool '{tool_name}' is not registered in Ether arsenal.",
266
+ "remediation": "Check registered tools via 'ether tool list'.",
267
+ },
268
+ indent=2,
269
+ )
270
+
271
+ args_dict = arguments or {}
272
+ raw_flags = args_dict.get("flags", [])
273
+ if isinstance(raw_flags, list):
274
+ flags_str = " ".join(str(f) for f in raw_flags)
275
+ flags_list = [str(f) for f in raw_flags]
276
+ else:
277
+ flags_str = str(raw_flags)
278
+ flags_list = [flags_str] if flags_str else []
279
+
280
+ # Preflight verification gate
281
+ report = gw.preflight_verify(tool_name=tool_name, target=target, flags=flags_str)
282
+ if not report.is_valid:
283
+ error_list = [
284
+ {
285
+ "title": e.title,
286
+ "description": e.description,
287
+ "remediation": e.remediation_hint,
288
+ }
289
+ for e in report.errors
290
+ ]
291
+ return json.dumps(
292
+ {
293
+ "error": "PreflightGateRejected",
294
+ "message": f"Execution of '{tool_name}' against '{target}' rejected by policy {gw.policy.value}.",
295
+ "errors": error_list,
296
+ "remediation": error_list[0]["remediation"]
297
+ if error_list
298
+ else "Adjust target scope or policy.",
299
+ },
300
+ indent=2,
301
+ )
302
+
303
+ # Target finding inference and persistence
304
+ target_finding = gw.infer_target_finding(target)
305
+ target_node_id = await store.upsert_finding(sess_id, target_finding)
306
+
307
+ action = ActionRequest(
308
+ session_id=UUID(sess_id),
309
+ tool_name=tool_name,
310
+ target_entity_id=target_node_id,
311
+ params={"target": target, "flags": flags_list},
312
+ )
313
+
314
+ try:
315
+ action_id = await exec_sess.dispatch(action)
316
+ except Exception as e:
317
+ return json.dumps(
318
+ {
319
+ "error": type(e).__name__,
320
+ "message": str(e),
321
+ "remediation": "Verify tool arguments and input schema requirements.",
322
+ },
323
+ indent=2,
324
+ )
325
+
326
+ async def _await_events() -> tuple[int, Optional[str]]:
327
+ exit_code = 0
328
+ err_msg = None
329
+ async for event in exec_sess.subscribe(action_id):
330
+ if isinstance(event, ExecutionCompleted):
331
+ exit_code = 0
332
+ elif isinstance(event, ExecutionFailed):
333
+ exit_code = 1
334
+ err_msg = event.error
335
+ return exit_code, err_msg
336
+
337
+ try:
338
+ exit_code, err_msg = await asyncio.wait_for(_await_events(), timeout=timeout_seconds)
339
+ compiler = GraphTelemetryCompiler(store, sess_id, execution_session=exec_sess)
340
+ diff = await compiler.compute_graph_diff(action_id=str(action_id))
341
+ result: Dict[str, Any] = {
342
+ "status": "completed" if exit_code == 0 else "failed",
343
+ "action_id": str(action_id),
344
+ "exit_code": exit_code,
345
+ "error": err_msg,
346
+ "diff": diff,
347
+ "status_breakdown": diff.get("status_breakdown", {}),
348
+ "summary": f"Execution of {tool_name} completed with {diff['total_delta_count']} new or updated findings.",
349
+ }
350
+ if include_raw:
351
+ raw_text = "".join(exec_sess.get_output_history(action_id))
352
+ result["untrusted_output"] = sanitize_untrusted_output(raw_text)
353
+ return json.dumps(result, indent=2)
354
+ except asyncio.TimeoutError:
355
+ return json.dumps(
356
+ {
357
+ "status": "running",
358
+ "action_id": str(action_id),
359
+ "message": f"Execution exceeded {timeout_seconds}s deadline and is continuing in background. Use get_diff(action_id='{action_id}') to inspect findings.",
360
+ "tokens_consumed": 0,
361
+ },
362
+ indent=2,
363
+ )
364
+
365
+ @server.tool()
366
+ async def abort_action(action_id: str) -> str:
367
+ """Abort or cancel an active execution by action ID.
368
+
369
+ Args:
370
+ action_id: Active action UUID string to cancel.
371
+ """
372
+ try:
373
+ act_uuid = UUID(action_id)
374
+ except Exception:
375
+ return json.dumps(
376
+ {"error": "InvalidActionId", "message": f"Invalid action UUID: '{action_id}'"}
377
+ )
378
+
379
+ success = await exec_sess.kill_job(act_uuid)
380
+ return json.dumps({"action_id": action_id, "aborted": success}, indent=2)
381
+
382
+ return server
ether/paths.py ADDED
@@ -0,0 +1,176 @@
1
+ """Centralized path resolution and data directory management for Ether."""
2
+
3
+ import os
4
+ from typing import Optional
5
+
6
+ ENV_DATA_DIR = "ETHER_DATA_DIR"
7
+ DEFAULT_DATA_DIR_NAME = ".ether"
8
+
9
+
10
+ def get_default_data_dir() -> str:
11
+ """Return the absolute path to the Ether unified data directory.
12
+
13
+ Priority:
14
+ 1. ETHER_DATA_DIR environment variable
15
+ 2. ~/.ether directory in user's home folder
16
+ """
17
+ env_dir = os.environ.get(ENV_DATA_DIR)
18
+ if env_dir:
19
+ base_dir = os.path.abspath(os.path.expanduser(env_dir))
20
+ else:
21
+ base_dir = os.path.abspath(os.path.expanduser(f"~/{DEFAULT_DATA_DIR_NAME}"))
22
+
23
+ try:
24
+ os.makedirs(base_dir, mode=0o700, exist_ok=True)
25
+ except OSError:
26
+ pass
27
+ return base_dir
28
+
29
+
30
+ def get_default_db_path(data_dir: Optional[str] = None) -> str:
31
+ """Return the default SQLite database path."""
32
+ base = data_dir if data_dir is not None else get_default_data_dir()
33
+ return os.path.join(base, "ether.db")
34
+
35
+
36
+ def get_default_settings_path(data_dir: Optional[str] = None) -> str:
37
+ """Return the default settings.json path."""
38
+ base = data_dir if data_dir is not None else get_default_data_dir()
39
+ return os.path.join(base, "settings.json")
40
+
41
+
42
+ def get_default_scratchpad_path(data_dir: Optional[str] = None) -> str:
43
+ """Return the default scratchpad markdown file path."""
44
+ base = data_dir if data_dir is not None else get_default_data_dir()
45
+ return os.path.join(base, "scratchpad.md")
46
+
47
+
48
+ def get_default_checkpoints_dir(data_dir: Optional[str] = None) -> str:
49
+ """Return the default learning mode checkpoint export directory."""
50
+ base = data_dir if data_dir is not None else get_default_data_dir()
51
+ checkpoints_dir = os.path.join(base, "checkpoints")
52
+ try:
53
+ os.makedirs(checkpoints_dir, mode=0o700, exist_ok=True)
54
+ except OSError:
55
+ pass
56
+ return checkpoints_dir
57
+
58
+
59
+ def get_default_exports_dir(data_dir: Optional[str] = None) -> str:
60
+ """Return the default session database export directory."""
61
+ base = data_dir if data_dir is not None else get_default_data_dir()
62
+ exports_dir = os.path.join(base, "exports")
63
+ try:
64
+ os.makedirs(exports_dir, mode=0o700, exist_ok=True)
65
+ except OSError:
66
+ pass
67
+ return exports_dir
68
+
69
+
70
+ def get_default_reports_dir(data_dir: Optional[str] = None) -> str:
71
+ """Return the default session markdown report export directory."""
72
+ base = data_dir if data_dir is not None else get_default_data_dir()
73
+ reports_dir = os.path.join(base, "reports")
74
+ try:
75
+ os.makedirs(reports_dir, mode=0o700, exist_ok=True)
76
+ except OSError:
77
+ pass
78
+ return reports_dir
79
+
80
+
81
+ def get_default_logs_dir(data_dir: Optional[str] = None) -> str:
82
+ """Return the default action execution logs directory."""
83
+ base = data_dir if data_dir is not None else get_default_data_dir()
84
+ logs_dir = os.path.join(base, "logs")
85
+ try:
86
+ os.makedirs(logs_dir, mode=0o700, exist_ok=True)
87
+ except OSError:
88
+ pass
89
+ return logs_dir
90
+
91
+
92
+ def get_action_log_path(action_id: str, data_dir: Optional[str] = None) -> str:
93
+ """Return the absolute path for an action execution log file."""
94
+ logs_dir = get_default_logs_dir(data_dir)
95
+ return os.path.join(logs_dir, f"{action_id}.log")
96
+
97
+
98
+ def get_system_log_path(data_dir: Optional[str] = None) -> str:
99
+ """Return the absolute path for the centralized application system log (~/.ether/logs/ether.log)."""
100
+ logs_dir = get_default_logs_dir(data_dir)
101
+ return os.path.join(logs_dir, "ether.log")
102
+
103
+
104
+ def get_default_wordlists_dir(data_dir: Optional[str] = None) -> str:
105
+ """Return the default wordlists directory (~/.ether/wordlists)."""
106
+ base = data_dir if data_dir is not None else get_default_data_dir()
107
+ wordlists_dir = os.path.join(base, "wordlists")
108
+ try:
109
+ os.makedirs(wordlists_dir, mode=0o700, exist_ok=True)
110
+ except OSError:
111
+ pass
112
+ return wordlists_dir
113
+
114
+
115
+ def get_wordlist_path(name: str, data_dir: Optional[str] = None) -> str:
116
+ """Return the absolute path for a named wordlist in the wordlists directory."""
117
+ wordlists_dir = get_default_wordlists_dir(data_dir)
118
+ filename = name if name.endswith(".txt") else f"{name}.txt"
119
+ return os.path.join(wordlists_dir, filename)
120
+
121
+
122
+ def get_git_branch(target_dir: Optional[str] = None) -> str:
123
+ """Resolve the active git branch purely from filesystem metadata without spawning child subprocesses."""
124
+ cur = os.path.abspath(target_dir or os.getcwd())
125
+ while True:
126
+ git_candidate = os.path.join(cur, ".git")
127
+ if os.path.isdir(git_candidate):
128
+ head_path = os.path.join(git_candidate, "HEAD")
129
+ try:
130
+ with open(head_path, "r", encoding="utf-8") as f:
131
+ content = f.read().strip()
132
+ if content.startswith("ref: refs/heads/"):
133
+ return content.split("ref: refs/heads/", 1)[1].strip()
134
+ elif content:
135
+ # Detached HEAD - return short SHA
136
+ return content[:7]
137
+ except Exception:
138
+ return ""
139
+ elif os.path.isfile(git_candidate):
140
+ # Git worktree or submodule reference: "gitdir: /path/to/.git/worktrees/name"
141
+ try:
142
+ with open(git_candidate, "r", encoding="utf-8") as f:
143
+ line = f.readline().strip()
144
+ if line.startswith("gitdir:"):
145
+ git_dir = line.split("gitdir:", 1)[1].strip()
146
+ if not os.path.isabs(git_dir):
147
+ git_dir = os.path.abspath(os.path.join(cur, git_dir))
148
+ head_path = os.path.join(git_dir, "HEAD")
149
+ if os.path.exists(head_path):
150
+ with open(head_path, "r", encoding="utf-8") as hf:
151
+ content = hf.read().strip()
152
+ if content.startswith("ref: refs/heads/"):
153
+ return content.split("ref: refs/heads/", 1)[1].strip()
154
+ elif content:
155
+ return content[:7]
156
+ except Exception:
157
+ return ""
158
+ parent = os.path.dirname(cur)
159
+ if parent == cur:
160
+ break
161
+ cur = parent
162
+ return ""
163
+
164
+
165
+ def atomic_create_file(path: str, content: str = "") -> None:
166
+ """Atomically create a private file with mode 0o600 (-rw-------) preventing TOCTOU vulnerabilities."""
167
+ base_dir = os.path.dirname(os.path.abspath(path))
168
+ if base_dir:
169
+ os.makedirs(base_dir, mode=0o700, exist_ok=True)
170
+ flags = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
171
+ fd = os.open(path, flags, 0o600)
172
+ try:
173
+ if content:
174
+ os.write(fd, content.encode("utf-8"))
175
+ finally:
176
+ os.close(fd)
ether/py.typed ADDED
File without changes
@@ -0,0 +1,7 @@
1
+ """Pluggable adapter registry and manifest discovery."""
2
+
3
+ from ether.registry.adapter import ToolAdapter
4
+ from ether.registry.manifest import Manifest
5
+ from ether.registry.registry import ToolRegistry
6
+
7
+ __all__ = ["Manifest", "ToolAdapter", "ToolRegistry"]