Skip to content

A fast, keyboard-driven TUI API client & webhook inspector. No cloud, no Electron, 100% local-first.

fix: enforce TLS verification by default, add custom headers support, and parse chunked webhooks (v0.1.3)

4yk520700cfaeb84
diff --git a/app.py b/app.py
index d3401fd..763b7ef 100644
--- a/app.py
+++ b/app.py
@@ -1,510 +1,623 @@
-from textual.app import App, ComposeResult
-from textual.containers import Horizontal, Vertical
-from textual.widgets import (
- Footer, Input, Button, Select, Tabs, Tab, TextArea, ListView, ListItem, Label
-)
-from textual.binding import Binding
-
-from network import NetworkEngine
-from webhook_server import WebhookServer
-from storage import StorageManager
-
-import os
-from pathlib import Path
-
-class GhostmanApp(App):
- DEFAULT_CSS = """
-/* Theme & Global Layout */
-Screen {
- background: #0b0e14;
- color: #e6edf3;
-}
-
-#header-bar {
- height: 3;
- background: #161b22;
- border-bottom: solid #00ff9f;
- padding: 0 1;
- align: left middle;
-}
-
-#title-label {
- text-style: bold;
- color: #00ff9f;
-}
-
-#subtitle-label {
- color: #8b949e;
- margin-left: 2;
-}
-
-#main-container {
- height: 1fr;
-}
-
-/* Sidebar */
-#sidebar {
- width: 32;
- background: #0d1117;
- border-right: solid #30363d;
- padding: 1;
-}
-
-#sidebar-header {
- height: 3;
- margin-bottom: 1;
- align: left middle;
-}
-
-#sidebar-title {
- text-style: bold;
- color: #58a6ff;
- width: 1fr;
-}
-
-#requests-list {
- height: 1fr;
- background: transparent;
-}
-
-/* Buttons */
-Button, Button.-style-default, Button.-style-flat {
- border: none !important;
- border-top: none !important;
- border-bottom: none !important;
- border-left: none !important;
- border-right: none !important;
- height: 3;
- min-width: 8;
- content-align: center middle;
- text-style: bold;
-}
-
-#new-req-btn {
- width: 8;
- background: #21262d;
- color: #58a6ff;
-}
-
-#new-req-btn:hover {
- background: #30363d;
-}
-
-#send-btn {
- width: 12;
- background: #238636;
- color: #ffffff;
- margin-left: 1;
-}
-
-#send-btn:hover {
- background: #2ea043;
-}
-
-#save-btn {
- width: 10;
- background: #1f6feb;
- color: #ffffff;
- margin-left: 1;
-}
-
-#save-btn:hover {
- background: #388bfd;
-}
-
-/* Main Request Bar */
-#content-area {
- width: 1fr;
- padding: 1;
-}
-
-#request-bar {
- height: 3;
- margin-bottom: 1;
- layout: horizontal;
-}
-
-Select {
- width: 14;
- margin-right: 1;
- border: none !important;
-}
-
-SelectCurrent {
- border: solid #30363d !important;
- border-top: solid #30363d !important;
- border-bottom: solid #30363d !important;
- border-left: solid #30363d !important;
- border-right: solid #30363d !important;
- height: 3;
- background: #161b22;
- color: #f0f6fc;
-}
-
-SelectCurrent:focus {
- border: solid #58a6ff !important;
-}
-
-/* Dropdown Menu */
-SelectOverlay, OptionList {
- border: solid #30363d !important;
- background: #161b22;
-}
-
-SelectOverlay:focus, OptionList:focus {
- border: solid #58a6ff !important;
-}
-
-OptionList > .option-list--option-highlighted {
- background: #1f6feb !important;
- color: #ffffff !important;
-}
-
-Input, #url-input {
- width: 1fr;
- background: #161b22;
- border: solid #30363d !important;
- border-top: solid #30363d !important;
- border-bottom: solid #30363d !important;
- color: #f0f6fc;
- height: 3;
-}
-
-Input:focus, #url-input:focus {
- border: solid #58a6ff !important;
-}
-
-/* Tabs & Panes */
-#tabs {
- margin-bottom: 1;
-}
-
-TextArea, TextArea:focus, #body-input, #body-input:focus {
- height: 1fr;
- background: #161b22;
- border: solid #30363d !important;
- color: #79c0ff;
-}
-
-#tab-response-pane {
- height: 1fr;
- background: #0d1117;
- border: solid #30363d;
- padding: 1;
-}
-
-#response-area, #response-area:focus {
- height: 1fr;
- background: #0d1117;
- border: none !important;
- color: #e6edf3;
-}
-
-#metrics-bar {
- height: 1;
- margin-bottom: 1;
- color: #8b949e;
- text-style: bold;
-}
-
-#tab-webhook-pane {
- height: 1fr;
- background: #0d1117;
- padding: 1;
-}
-
-#webhook-status {
- height: 3;
- padding: 0 1;
- align: left middle;
- background: #161b22;
- border: solid #30363d;
- margin-bottom: 1;
-}
-
-#webhook-toggle-btn {
- width: 20;
- margin-left: 2;
- background: #21262d;
- color: #e6edf3;
-}
-
-#webhook-toggle-btn:hover {
- background: #30363d;
-}
-
-/* Footer */
-#footer-bar {
- height: 1;
- background: #161b22;
- color: #8b949e;
- padding: 0 1;
-}
-
-"""
- ENABLE_COMMAND_PALETTE = False
-
- BINDINGS = [
- Binding("ctrl+s", "send_request", "Send Request", priority=True),
- Binding("ctrl+w", "toggle_webhook", "Toggle Webhook Server", priority=True),
- Binding("ctrl+n", "new_request", "New Request", priority=True),
- Binding("ctrl+k", "save_request", "Save Request", priority=True),
- Binding("ctrl+q", "quit", "Quit", priority=True)
- ]
-
- METHODS = [
- ("GET", "GET"),
- ("POST", "POST"),
- ("PUT", "PUT"),
- ("DELETE", "DELETE"),
- ("PATCH", "PATCH")
- ]
-
- def __init__(self):
- super().__init__()
- self.network = NetworkEngine()
- self.storage = StorageManager()
- self.collections = self.storage.load_collections()
- self.webhook_server = WebhookServer(
- host="127.0.0.1",
- port=9090,
- on_hook_received=self.handle_incoming_webhook
- )
-
- def compose(self) -> ComposeResult:
- with Horizontal(id="header-bar"):
- yield Label("[GHOSTMAN]", id="title-label")
- yield Label("Terminal API & Webhook Studio (Local-First)", id="subtitle-label")
-
- with Horizontal(id="main-container"):
- with Vertical(id="sidebar"):
- with Horizontal(id="sidebar-header"):
- yield Label("COLLECTIONS", id="sidebar-title")
- yield Button("+ NEW", id="new-req-btn")
- yield ListView(id="requests-list")
-
- with Vertical(id="content-area"):
- with Horizontal(id="request-bar"):
- yield Select(self.METHODS, value="GET", allow_blank=False, id="method-select")
- yield Input(placeholder="Request URL (e.g. https://api.github.com)...", id="url-input")
- yield Button("SEND", id="send-btn")
- yield Button("SAVE", id="save-btn")
-
- yield Tabs(
- Tab("Body & Payload", id="tab-body"),
- Tab("Response", id="tab-response"),
- Tab("Live Webhooks", id="tab-webhook"),
- id="tabs"
- )
-
- with Vertical(id="tab-body-pane"):
- yield TextArea(id="body-input", language="json", text='{\n "hello": "world"\n}')
-
- with Vertical(id="tab-response-pane"):
- yield Label("Status: Idle", id="metrics-bar")
- yield TextArea(id="response-area", read_only=True, language="json", text="")
-
- with Vertical(id="tab-webhook-pane"):
- with Horizontal(id="webhook-status"):
- yield Label("Webhook Receiver: [OFFLINE] (Port 9090)", id="webhook-status-label")
- yield Button("START RECEIVER", id="webhook-toggle-btn")
- yield Label("Send requests to http://127.0.0.1:9090 to inspect payloads live:")
- yield ListView(id="webhook-list")
-
- yield Footer()
-
- async def on_mount(self):
- self.populate_sidebar()
- self.query_one("#tab-response-pane").display = False
- self.query_one("#tab-webhook-pane").display = False
- self.query_one("#url-input").value = "https://jsonplaceholder.typicode.com/posts/1"
-
- async def on_unmount(self):
- try:
- if self.webhook_server and self.webhook_server.is_running:
- await self.webhook_server.stop()
- except Exception:
- pass
-
- def populate_sidebar(self):
- try:
- list_view = self.query_one("#requests-list", ListView)
- list_view.clear()
- if not isinstance(self.collections, list):
- return
- for col in self.collections:
- if not isinstance(col, dict):
- continue
- for req in col.get("requests", []):
- if not isinstance(req, dict):
- continue
- method = req.get("method", "GET").upper()
- name = req.get("name", "Request")
- item = ListItem(Label(f"[{method}] {name}"))
- item.req_data = req
- list_view.append(item)
- except Exception as e:
- self.notify(f"Error updating sidebar: {e}", severity="error")
-
- def on_list_view_selected(self, event: ListView.Selected):
- item = event.item
- if not item:
- return
- if hasattr(item, "req_data"):
- req = item.req_data
- method = req.get("method", "GET").upper()
- if method in [m[0] for m in self.METHODS]:
- self.query_one("#method-select", Select).value = method
- self.query_one("#url-input", Input).value = req.get("url", "")
- self.query_one("#body-input", TextArea).text = req.get("body", "") or ""
- self.notify(f"Selected: {req.get('name')}", timeout=2)
- elif hasattr(item, "hook_data"):
- hook = item.hook_data
- h_method = hook.get("method", "GET").upper()
- if h_method in [m[0] for m in self.METHODS]:
- self.query_one("#method-select", Select).value = h_method
- self.query_one("#body-input", TextArea).text = hook.get("raw_body", "") or ""
- self.query_one("#tabs", Tabs).active = "tab-body"
- self.notify(f"Loaded hook payload ({hook.get('path', '/')})", timeout=2)
-
- def on_tabs_tab_activated(self, event: Tabs.TabActivated):
- tab_id = event.tab.id
- self.query_one("#tab-body-pane").display = (tab_id == "tab-body")
- self.query_one("#tab-response-pane").display = (tab_id == "tab-response")
- self.query_one("#tab-webhook-pane").display = (tab_id == "tab-webhook")
-
- async def action_send_request(self):
- await self.send_http_request()
-
- def action_save_request(self):
- self.save_current_request()
-
- def action_new_request(self):
- self.query_one("#method-select", Select).value = "GET"
- self.query_one("#url-input", Input).value = ""
- self.query_one("#body-input", TextArea).text = ""
- self.query_one("#tabs", Tabs).active = "tab-body"
- self.query_one("#url-input", Input).focus()
- self.notify("New request ready")
-
- async def on_button_pressed(self, event: Button.Pressed):
- btn_id = event.button.id
- if btn_id == "send-btn":
- await self.send_http_request()
- elif btn_id == "save-btn":
- self.save_current_request()
- elif btn_id == "new-req-btn":
- self.action_new_request()
- elif btn_id == "webhook-toggle-btn":
- await self.action_toggle_webhook()
-
- def save_current_request(self):
- try:
- url = self.query_one("#url-input", Input).value.strip()
- if not url:
- self.notify("Cannot save request without URL", severity="warning")
- return
- method = self.query_one("#method-select", Select).value
- body = self.query_one("#body-input", TextArea).text
-
- path_part = url.split("://")[-1].split("?")[0].strip("/")
- name = path_part.split("/")[-1] if "/" in path_part else path_part
- name = name or "Endpoint"
-
- new_req = {
- "name": f"{method} {name[:18]}",
- "method": method,
- "url": url,
- "headers": {"Content-Type": "application/json"} if body else {},
- "body": body
- }
-
- if not self.collections or not isinstance(self.collections, list):
- self.collections = [{"name": "My Collection", "requests": []}]
- if "requests" not in self.collections[0] or not isinstance(self.collections[0]["requests"], list):
- self.collections[0]["requests"] = []
- self.collections[0]["requests"].append(new_req)
- self.storage.save_collections(self.collections)
- self.populate_sidebar()
- self.notify(f"Saved: {new_req['name']}", timeout=2)
- except Exception as e:
- self.notify(f"Error saving request: {e}", severity="error")
-
- async def send_http_request(self):
- try:
- method = self.query_one("#method-select", Select).value
- url = self.query_one("#url-input", Input).value.strip()
- body = self.query_one("#body-input", TextArea).text
-
- if not url:
- self.notify("URL cannot be empty", severity="error")
- return
-
- if not url.startswith("http://") and not url.startswith("https://"):
- url = "https://" + url
- self.query_one("#url-input", Input).value = url
-
- self.query_one("#tabs", Tabs).active = "tab-response"
- metrics = self.query_one("#metrics-bar", Label)
- response_box = self.query_one("#response-area", TextArea)
-
- metrics.update(f"Sending {method} to {url}...")
- response_box.text = "Waiting for response..."
-
- req_body = body if method in ["POST", "PUT", "PATCH", "DELETE"] else None
-
- res = await self.network.execute_request(method, url, body=req_body)
-
- if res["success"]:
- code = res["status_code"]
- color = "green" if code < 400 else "red"
- reason = res.get('reason') or ('OK' if code == 200 else '')
- metrics.update(
- f"[{color}]{code} {reason}[/] | {res['elapsed_ms']}ms | {res['size_bytes']} bytes"
- )
- response_box.text = res["body"]
- else:
- metrics.update(f"[red]Failed[/] | {res['elapsed_ms']}ms")
- response_box.text = res["body"]
- except Exception as e:
- self.notify(f"Request error: {e}", severity="error")
-
- async def action_toggle_webhook(self):
- btn = self.query_one("#webhook-toggle-btn", Button)
- lbl = self.query_one("#webhook-status-label", Label)
-
- if not self.webhook_server.is_running:
- try:
- await self.webhook_server.start()
- lbl.update("[green][ONLINE][/] (Listening on http://127.0.0.1:9090)")
- btn.label = "STOP RECEIVER"
- btn.variant = "error"
- self.notify("Webhook listener started on :9090")
- except Exception as e:
- self.notify(f"Could not bind port 9090: {e}", severity="error")
- else:
- try:
- await self.webhook_server.stop()
- except Exception:
- pass
- lbl.update("Webhook Receiver: [OFFLINE] (Port 9090)")
- btn.label = "START RECEIVER"
- btn.variant = "default"
- self.notify("Webhook listener stopped")
-
- def handle_incoming_webhook(self, hook: dict):
- try:
- self.call_from_thread(self._add_webhook_to_ui, hook)
- except RuntimeError:
- self._add_webhook_to_ui(hook)
-
- def _add_webhook_to_ui(self, hook: dict):
- try:
- list_view = self.query_one("#webhook-list", ListView)
- label_text = f"[{hook['timestamp']}] {hook['method']} {hook['path']} ({len(hook.get('raw_body', ''))}B)"
- item = ListItem(Label(f"[cyan]{label_text}[/] -> {hook.get('body', '')[:40]}..."))
- item.hook_data = hook
- list_view.append(item)
- self.notify(f"Hook received: {hook['path']}", timeout=2)
- except Exception:
- pass
+from textual.app import App, ComposeResult
+from textual.containers import Horizontal, Vertical
+from textual.widgets import (
+ Footer, Input, Button, Select, Tabs, Tab, TextArea, ListView, ListItem, Label
+)
+from textual.binding import Binding
+
+from network import NetworkEngine
+from webhook_server import WebhookServer
+from storage import StorageManager
+
+import os
+import json
+from pathlib import Path
+
+class GhostmanApp(App):
+ DEFAULT_CSS = """
+/* Theme & Global Layout */
+Screen {
+ background: #0b0e14;
+ color: #e6edf3;
+}
+
+#header-bar {
+ height: 3;
+ background: #161b22;
+ border-bottom: solid #00ff9f;
+ padding: 0 1;
+ align: left middle;
+}
+
+#title-label {
+ text-style: bold;
+ color: #00ff9f;
+}
+
+#subtitle-label {
+ color: #8b949e;
+ margin-left: 2;
+ width: 1fr;
+}
+
+#ssl-badge {
+ color: #3fb950;
+ text-style: bold;
+ margin-right: 1;
+ padding: 0 1;
+ background: #161b22;
+ border: solid #238636;
+}
+
+#ssl-badge.insecure {
+ color: #f85149;
+ border: solid #da3633;
+}
+
+#main-container {
+ height: 1fr;
+}
+
+/* Sidebar */
+#sidebar {
+ width: 32;
+ background: #0d1117;
+ border-right: solid #30363d;
+ padding: 1;
+}
+
+#sidebar-header {
+ height: 3;
+ margin-bottom: 1;
+ align: left middle;
+}
+
+#sidebar-title {
+ text-style: bold;
+ color: #58a6ff;
+ width: 1fr;
+}
+
+#requests-list {
+ height: 1fr;
+ background: transparent;
+}
+
+/* Buttons */
+Button, Button.-style-default, Button.-style-flat {
+ border: none !important;
+ border-top: none !important;
+ border-bottom: none !important;
+ border-left: none !important;
+ border-right: none !important;
+ height: 3;
+ min-width: 8;
+ content-align: center middle;
+ text-style: bold;
+}
+
+#new-req-btn {
+ width: 8;
+ background: #21262d;
+ color: #58a6ff;
+}
+
+#new-req-btn:hover {
+ background: #30363d;
+}
+
+#send-btn {
+ width: 12;
+ background: #238636;
+ color: #ffffff;
+ margin-left: 1;
+}
+
+#send-btn:hover {
+ background: #2ea043;
+}
+
+#save-btn {
+ width: 10;
+ background: #1f6feb;
+ color: #ffffff;
+ margin-left: 1;
+}
+
+#save-btn:hover {
+ background: #388bfd;
+}
+
+/* Main Request Bar */
+#content-area {
+ width: 1fr;
+ padding: 1;
+}
+
+#request-bar {
+ height: 3;
+ margin-bottom: 1;
+ layout: horizontal;
+}
+
+Select {
+ width: 14;
+ margin-right: 1;
+ border: none !important;
+}
+
+SelectCurrent {
+ border: solid #30363d !important;
+ border-top: solid #30363d !important;
+ border-bottom: solid #30363d !important;
+ border-left: solid #30363d !important;
+ border-right: solid #30363d !important;
+ height: 3;
+ background: #161b22;
+ color: #f0f6fc;
+}
+
+SelectCurrent:focus {
+ border: solid #58a6ff !important;
+}
+
+/* Dropdown Menu */
+SelectOverlay, OptionList {
+ border: solid #30363d !important;
+ background: #161b22;
+}
+
+SelectOverlay:focus, OptionList:focus {
+ border: solid #58a6ff !important;
+}
+
+OptionList > .option-list--option-highlighted {
+ background: #1f6feb !important;
+ color: #ffffff !important;
+}
+
+Input, #url-input {
+ width: 1fr;
+ background: #161b22;
+ border: solid #30363d !important;
+ border-top: solid #30363d !important;
+ border-bottom: solid #30363d !important;
+ color: #f0f6fc;
+ height: 3;
+}
+
+Input:focus, #url-input:focus {
+ border: solid #58a6ff !important;
+}
+
+/* Tabs & Panes */
+#tabs {
+ margin-bottom: 1;
+}
+
+TextArea, TextArea:focus, #body-input, #body-input:focus, #headers-input, #headers-input:focus {
+ height: 1fr;
+ background: #161b22;
+ border: solid #30363d !important;
+ color: #79c0ff;
+}
+
+#tab-headers-pane {
+ height: 1fr;
+ background: #0d1117;
+ padding: 0;
+}
+
+#tab-response-pane {
+ height: 1fr;
+ background: #0d1117;
+ border: solid #30363d;
+ padding: 1;
+}
+
+#response-area, #response-area:focus {
+ height: 1fr;
+ background: #0d1117;
+ border: none !important;
+ color: #e6edf3;
+}
+
+#metrics-bar {
+ height: 1;
+ margin-bottom: 1;
+ color: #8b949e;
+ text-style: bold;
+}
+
+#tab-webhook-pane {
+ height: 1fr;
+ background: #0d1117;
+ padding: 1;
+}
+
+#webhook-status {
+ height: 3;
+ padding: 0 1;
+ align: left middle;
+ background: #161b22;
+ border: solid #30363d;
+ margin-bottom: 1;
+}
+
+#webhook-toggle-btn {
+ width: 20;
+ margin-left: 2;
+ background: #21262d;
+ color: #e6edf3;
+}
+
+#webhook-toggle-btn:hover {
+ background: #30363d;
+}
+
+/* Footer */
+#footer-bar {
+ height: 1;
+ background: #161b22;
+ color: #8b949e;
+ padding: 0 1;
+}
+
+"""
+ ENABLE_COMMAND_PALETTE = False
+
+ BINDINGS = [
+ Binding("ctrl+s", "send_request", "Send Request", priority=True),
+ Binding("ctrl+w", "toggle_webhook", "Toggle Webhook", priority=True),
+ Binding("ctrl+t", "toggle_ssl", "Toggle TLS Verify", priority=True),
+ Binding("ctrl+n", "new_request", "New Request", priority=True),
+ Binding("ctrl+k", "save_request", "Save Request", priority=True),
+ Binding("ctrl+q", "quit", "Quit", priority=True)
+ ]
+
+ METHODS = [
+ ("GET", "GET"),
+ ("POST", "POST"),
+ ("PUT", "PUT"),
+ ("DELETE", "DELETE"),
+ ("PATCH", "PATCH")
+ ]
+
+ def __init__(self):
+ super().__init__()
+ self.verify_ssl: bool = True
+ self.network = NetworkEngine(verify_ssl=True)
+ self.storage = StorageManager()
+ self.collections = self.storage.load_collections()
+ self.webhook_server = WebhookServer(
+ host="127.0.0.1",
+ port=9090,
+ on_hook_received=self.handle_incoming_webhook
+ )
+
+ def compose(self) -> ComposeResult:
+ with Horizontal(id="header-bar"):
+ yield Label("[GHOSTMAN]", id="title-label")
+ yield Label("Terminal API & Webhook Studio (Local-First)", id="subtitle-label")
+ yield Label("[TLS: ON]", id="ssl-badge")
+
+ with Horizontal(id="main-container"):
+ with Vertical(id="sidebar"):
+ with Horizontal(id="sidebar-header"):
+ yield Label("COLLECTIONS", id="sidebar-title")
+ yield Button("+ NEW", id="new-req-btn")
+ yield ListView(id="requests-list")
+
+ with Vertical(id="content-area"):
+ with Horizontal(id="request-bar"):
+ yield Select(self.METHODS, value="GET", allow_blank=False, id="method-select")
+ yield Input(placeholder="Request URL (e.g. https://api.github.com)...", id="url-input")
+ yield Button("SEND", id="send-btn")
+ yield Button("SAVE", id="save-btn")
+
+ yield Tabs(
+ Tab("Headers", id="tab-headers"),
+ Tab("Body & Payload", id="tab-body"),
+ Tab("Response", id="tab-response"),
+ Tab("Live Webhooks", id="tab-webhook"),
+ id="tabs"
+ )
+
+ with Vertical(id="tab-headers-pane"):
+ yield TextArea(
+ id="headers-input",
+ language="yaml",
+ text=""
+ )
+
+ with Vertical(id="tab-body-pane"):
+ yield TextArea(id="body-input", language="json", text='{\n "hello": "world"\n}')
+
+ with Vertical(id="tab-response-pane"):
+ yield Label("Status: Idle", id="metrics-bar")
+ yield TextArea(id="response-area", read_only=True, language="json", text="")
+
+ with Vertical(id="tab-webhook-pane"):
+ with Horizontal(id="webhook-status"):
+ yield Label("Webhook Receiver: [OFFLINE] (Port 9090)", id="webhook-status-label")
+ yield Button("START RECEIVER", id="webhook-toggle-btn")
+ yield Label("Send requests to http://127.0.0.1:9090 to inspect payloads live:")
+ yield ListView(id="webhook-list")
+
+ yield Footer()
+
+ async def on_mount(self):
+ self.populate_sidebar()
+ self.query_one("#tab-headers-pane").display = False
+ self.query_one("#tab-response-pane").display = False
+ self.query_one("#tab-webhook-pane").display = False
+ self.query_one("#url-input").value = "https://jsonplaceholder.typicode.com/posts/1"
+
+ async def on_unmount(self):
+ try:
+ if self.webhook_server and self.webhook_server.is_running:
+ await self.webhook_server.stop()
+ except Exception:
+ pass
+
+ @staticmethod
+ def parse_headers_text(raw: str) -> dict:
+ """Parse headers from either Key: Value lines or a JSON object."""
+ if not raw or not raw.strip():
+ return {}
+ text = raw.strip()
+ if text.startswith("{") and text.endswith("}"):
+ try:
+ parsed = json.loads(text)
+ if isinstance(parsed, dict):
+ return {str(k): str(v) for k, v in parsed.items()}
+ except Exception:
+ pass
+ headers = {}
+ for line in text.splitlines():
+ line = line.strip()
+ if not line or line.startswith(("#", "//")):
+ continue
+ if ":" in line:
+ k, v = line.split(":", 1)
+ headers[k.strip()] = v.strip()
+ return headers
+
+ @staticmethod
+ def format_headers_text(headers: dict) -> str:
+ """Format a headers dictionary into standard Key: Value lines."""
+ if not headers or not isinstance(headers, dict):
+ return ""
+ return "\n".join(f"{k}: {v}" for k, v in headers.items())
+
+ def populate_sidebar(self):
+ try:
+ list_view = self.query_one("#requests-list", ListView)
+ list_view.clear()
+ if not isinstance(self.collections, list):
+ return
+ for col in self.collections:
+ if not isinstance(col, dict):
+ continue
+ for req in col.get("requests", []):
+ if not isinstance(req, dict):
+ continue
+ method = req.get("method", "GET").upper()
+ name = req.get("name", "Request")
+ item = ListItem(Label(f"[{method}] {name}"))
+ item.req_data = req
+ list_view.append(item)
+ except Exception as e:
+ self.notify(f"Error updating sidebar: {e}", severity="error")
+
+ def on_list_view_selected(self, event: ListView.Selected):
+ item = event.item
+ if not item:
+ return
+ if hasattr(item, "req_data"):
+ req = item.req_data
+ method = req.get("method", "GET").upper()
+ if method in [m[0] for m in self.METHODS]:
+ self.query_one("#method-select", Select).value = method
+ self.query_one("#url-input", Input).value = req.get("url", "")
+ self.query_one("#body-input", TextArea).text = req.get("body", "") or ""
+
+ # Load saved headers into the headers editor
+ req_headers = req.get("headers", {})
+ self.query_one("#headers-input", TextArea).text = self.format_headers_text(req_headers)
+
+ self.notify(f"Selected: {req.get('name')}", timeout=2)
+ elif hasattr(item, "hook_data"):
+ hook = item.hook_data
+ h_method = hook.get("method", "GET").upper()
+ if h_method in [m[0] for m in self.METHODS]:
+ self.query_one("#method-select", Select).value = h_method
+ self.query_one("#body-input", TextArea).text = hook.get("raw_body", "") or ""
+
+ # Load captured hook headers
+ hook_headers = hook.get("headers", {})
+ self.query_one("#headers-input", TextArea).text = self.format_headers_text(hook_headers)
+
+ self.query_one("#tabs", Tabs).active = "tab-body"
+ self.notify(f"Loaded hook payload ({hook.get('path', '/')})", timeout=2)
+
+ def on_tabs_tab_activated(self, event: Tabs.TabActivated):
+ tab_id = event.tab.id
+ self.query_one("#tab-headers-pane").display = (tab_id == "tab-headers")
+ self.query_one("#tab-body-pane").display = (tab_id == "tab-body")
+ self.query_one("#tab-response-pane").display = (tab_id == "tab-response")
+ self.query_one("#tab-webhook-pane").display = (tab_id == "tab-webhook")
+
+ async def action_send_request(self):
+ await self.send_http_request()
+
+ def action_save_request(self):
+ self.save_current_request()
+
+ def action_new_request(self):
+ self.query_one("#method-select", Select).value = "GET"
+ self.query_one("#url-input", Input).value = ""
+ self.query_one("#headers-input", TextArea).text = ""
+ self.query_one("#body-input", TextArea).text = ""
+ self.query_one("#tabs", Tabs).active = "tab-body"
+ self.query_one("#url-input", Input).focus()
+ self.notify("New request ready")
+
+ def action_toggle_ssl(self):
+ """Toggle SSL/TLS Certificate Verification (Ctrl+T)"""
+ self.verify_ssl = not self.verify_ssl
+ badge = self.query_one("#ssl-badge", Label)
+ if self.verify_ssl:
+ badge.update("[TLS: ON]")
+ badge.remove_class("insecure")
+ self.notify("TLS Certificate Verification ENABLED (Secure)", timeout=3)
+ else:
+ badge.update("[TLS: OFF]")
+ badge.add_class("insecure")
+ self.notify("TLS Certificate Verification DISABLED (Insecure)", severity="warning", timeout=3)
+
+ async def on_button_pressed(self, event: Button.Pressed):
+ btn_id = event.button.id
+ if btn_id == "send-btn":
+ await self.send_http_request()
+ elif btn_id == "save-btn":
+ self.save_current_request()
+ elif btn_id == "new-req-btn":
+ self.action_new_request()
+ elif btn_id == "webhook-toggle-btn":
+ await self.action_toggle_webhook()
+
+ def save_current_request(self):
+ try:
+ url = self.query_one("#url-input", Input).value.strip()
+ if not url:
+ self.notify("Cannot save request without URL", severity="warning")
+ return
+ method = self.query_one("#method-select", Select).value
+ body = self.query_one("#body-input", TextArea).text
+
+ raw_headers = self.query_one("#headers-input", TextArea).text
+ req_headers = self.parse_headers_text(raw_headers)
+
+ # Smart Content-Type detection if not explicitly set
+ if body and not any(k.lower() == "content-type" for k in req_headers):
+ try:
+ json.loads(body)
+ req_headers["Content-Type"] = "application/json"
+ except Exception:
+ if body.strip().startswith("<") and body.strip().endswith(">"):
+ req_headers["Content-Type"] = "application/xml"
+ else:
+ req_headers["Content-Type"] = "text/plain"
+
+ path_part = url.split("://")[-1].split("?")[0].strip("/")
+ name = path_part.split("/")[-1] if "/" in path_part else path_part
+ name = name or "Endpoint"
+
+ new_req = {
+ "name": f"{method} {name[:18]}",
+ "method": method,
+ "url": url,
+ "headers": req_headers,
+ "body": body
+ }
+
+ if not self.collections or not isinstance(self.collections, list):
+ self.collections = [{"name": "My Collection", "requests": []}]
+ if "requests" not in self.collections[0] or not isinstance(self.collections[0]["requests"], list):
+ self.collections[0]["requests"] = []
+ self.collections[0]["requests"].append(new_req)
+ self.storage.save_collections(self.collections)
+ self.populate_sidebar()
+ self.notify(f"Saved: {new_req['name']}", timeout=2)
+ except Exception as e:
+ self.notify(f"Error saving request: {e}", severity="error")
+
+ async def send_http_request(self):
+ try:
+ method = self.query_one("#method-select", Select).value
+ url = self.query_one("#url-input", Input).value.strip()
+ body = self.query_one("#body-input", TextArea).text
+
+ raw_headers = self.query_one("#headers-input", TextArea).text
+ req_headers = self.parse_headers_text(raw_headers)
+
+ if not url:
+ self.notify("URL cannot be empty", severity="error")
+ return
+
+ if not url.startswith("http://") and not url.startswith("https://"):
+ url = "https://" + url
+ self.query_one("#url-input", Input).value = url
+
+ self.query_one("#tabs", Tabs).active = "tab-response"
+ metrics = self.query_one("#metrics-bar", Label)
+ response_box = self.query_one("#response-area", TextArea)
+
+ metrics.update(f"Sending {method} to {url}...")
+ response_box.text = "Waiting for response..."
+
+ req_body = body if method in ["POST", "PUT", "PATCH", "DELETE"] else None
+
+ # Execute with full headers and TLS verification mode
+ res = await self.network.execute_request(
+ method=method,
+ url=url,
+ headers=req_headers,
+ body=req_body,
+ verify_ssl=self.verify_ssl
+ )
+
+ if res["success"]:
+ code = res["status_code"]
+ color = "green" if code < 400 else "red"
+ reason = res.get('reason') or ('OK' if code == 200 else '')
+ metrics.update(
+ f"[{color}]{code} {reason}[/] | {res['elapsed_ms']}ms | {res['size_bytes']} bytes"
+ )
+ response_box.text = res["body"]
+ else:
+ metrics.update(f"[red]Failed[/] | {res['elapsed_ms']}ms")
+ response_box.text = res["body"]
+ except Exception as e:
+ self.notify(f"Request error: {e}", severity="error")
+
+ async def action_toggle_webhook(self):
+ btn = self.query_one("#webhook-toggle-btn", Button)
+ lbl = self.query_one("#webhook-status-label", Label)
+
+ if not self.webhook_server.is_running:
+ try:
+ await self.webhook_server.start()
+ lbl.update("[green][ONLINE][/] (Listening on http://127.0.0.1:9090)")
+ btn.label = "STOP RECEIVER"
+ btn.variant = "error"
+ self.notify("Webhook listener started on :9090")
+ except Exception as e:
+ self.notify(f"Could not bind port 9090: {e}", severity="error")
+ else:
+ try:
+ await self.webhook_server.stop()
+ except Exception:
+ pass
+ lbl.update("Webhook Receiver: [OFFLINE] (Port 9090)")
+ btn.label = "START RECEIVER"
+ btn.variant = "default"
+ self.notify("Webhook listener stopped")
+
+ def handle_incoming_webhook(self, hook: dict):
+ try:
+ self.call_from_thread(self._add_webhook_to_ui, hook)
+ except RuntimeError:
+ self._add_webhook_to_ui(hook)
+
+ def _add_webhook_to_ui(self, hook: dict):
+ try:
+ list_view = self.query_one("#webhook-list", ListView)
+ label_text = f"[{hook['timestamp']}] {hook['method']} {hook['path']} ({len(hook.get('raw_body', ''))}B)"
+ item = ListItem(Label(f"[cyan]{label_text}[/] -> {hook.get('body', '')[:40]}..."))
+ item.hook_data = hook
+ list_view.append(item)
+ self.notify(f"Hook received: {hook['path']}", timeout=2)
+ except Exception:
+ pass
diff --git a/network.py b/network.py
index ecb8b68..2fc790d 100644
--- a/network.py
+++ b/network.py
@@ -1,27 +1,51 @@
import time
import json
+from typing import Optional, Union
import httpx
class NetworkEngine:
- def __init__(self, timeout: float = 15.0):
+ def __init__(self, timeout: float = 15.0, verify_ssl: bool = True, ca_bundle: Optional[str] = None):
self.timeout = timeout
+ self.verify_ssl = verify_ssl
+ self.ca_bundle = ca_bundle
- async def execute_request(self, method: str, url: str, headers: dict = None, body: str = None):
+ async def execute_request(
+ self,
+ method: str,
+ url: str,
+ headers: dict = None,
+ body: str = None,
+ verify_ssl: Optional[bool] = None,
+ ca_bundle: Optional[str] = None
+ ):
start_time = time.perf_counter()
headers = dict(headers) if headers else {}
if not any(k.lower() == "user-agent" for k in headers):
- headers["User-Agent"] = "Ghostman/0.1.0"
+ headers["User-Agent"] = "Ghostman/0.1.3"
if body and not any(k.lower() == "content-type" for k in headers):
try:
json.loads(body)
headers["Content-Type"] = "application/json"
except Exception:
- pass
+ if body.strip().startswith("<") and body.strip().endswith(">"):
+ headers["Content-Type"] = "application/xml"
+ else:
+ headers["Content-Type"] = "text/plain"
+
+ # Determine SSL verification mode (defaults to True for MITM protection)
+ if ca_bundle:
+ verify_target: Union[bool, str] = ca_bundle
+ elif verify_ssl is not None:
+ verify_target = verify_ssl
+ elif self.ca_bundle:
+ verify_target = self.ca_bundle
+ else:
+ verify_target = self.verify_ssl
try:
- async with httpx.AsyncClient(verify=False, timeout=self.timeout, follow_redirects=True) as client:
+ async with httpx.AsyncClient(verify=verify_target, timeout=self.timeout, follow_redirects=True) as client:
res = await client.request(
method=method.upper(),
url=url,
@@ -48,6 +72,20 @@ class NetworkEngine:
"is_json": is_json,
"size_bytes": len(res.content)
}
+ except httpx.ConnectError as e:
+ elapsed_ms = (time.perf_counter() - start_time) * 1000
+ err_msg = str(e)
+ if "certificate" in err_msg.lower() or "ssl" in err_msg.lower() or "tls" in err_msg.lower():
+ err_display = f"SSL/TLS Certificate Verification Failed: {e}"
+ else:
+ err_display = f"Connection Failed: {e}"
+ return {
+ "success": False,
+ "error": str(e),
+ "elapsed_ms": round(elapsed_ms, 2),
+ "status_code": 0,
+ "body": err_display
+ }
except Exception as e:
elapsed_ms = (time.perf_counter() - start_time) * 1000
return {
diff --git a/pyproject.toml b/pyproject.toml
index efa71a6..d14af87 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ghostman"
-version = "0.1.1"
+version = "0.1.3"
description = "A fast, keyboard-driven terminal API client and webhook inspector"
readme = "README.md"
authors = [{ name = "4yk5" }]
diff --git a/styles.tcss b/styles.tcss
index a52c751..131b5d7 100644
--- a/styles.tcss
+++ b/styles.tcss
@@ -20,6 +20,21 @@ Screen {
#subtitle-label {
color: #8b949e;
margin-left: 2;
+ width: 1fr;
+}
+
+#ssl-badge {
+ color: #3fb950;
+ text-style: bold;
+ margin-right: 1;
+ padding: 0 1;
+ background: #161b22;
+ border: solid #238636;
+}
+
+#ssl-badge.insecure {
+ color: #f85149;
+ border: solid #da3633;
}
#main-container {
@@ -163,13 +178,19 @@ Input:focus, #url-input:focus {
margin-bottom: 1;
}
-TextArea, TextArea:focus, #body-input, #body-input:focus {
+TextArea, TextArea:focus, #body-input, #body-input:focus, #headers-input, #headers-input:focus {
height: 1fr;
background: #161b22;
border: solid #30363d !important;
color: #79c0ff;
}
+#tab-headers-pane {
+ height: 1fr;
+ background: #0d1117;
+ padding: 0;
+}
+
#tab-response-pane {
height: 1fr;
background: #0d1117;
diff --git a/tests/test_all.py b/tests/test_all.py
index 6edd029..7a0b082 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -84,6 +84,18 @@ async def run_tests():
assert not app.webhook_server.is_running
print(" [+] TUI Interactions: OK")
+ # Audit Vulnerability Verification Suites
+ from tests.test_vulnerabilities_fixed import (
+ test_tls_verification_default_and_toggle,
+ test_saved_and_custom_headers_propagation,
+ test_chunked_transfer_encoding_webhook,
+ test_tui_headers_and_ssl_controls,
+ )
+ await test_tls_verification_default_and_toggle()
+ await test_saved_and_custom_headers_propagation()
+ await test_chunked_transfer_encoding_webhook()
+ await test_tui_headers_and_ssl_controls()
+
print("\nAll tests passed successfully.")
if __name__ == "__main__":
diff --git a/tests/test_vulnerabilities_fixed.py b/tests/test_vulnerabilities_fixed.py
new file mode 100644
index 0000000..10457f5
--- /dev/null
+++ b/tests/test_vulnerabilities_fixed.py
@@ -0,0 +1,255 @@
+import asyncio
+import os
+import sys
+import json
+import httpx
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+if sys.platform == "win32":
+ try:
+ sys.stdout.reconfigure(encoding="utf-8")
+ sys.stderr.reconfigure(encoding="utf-8")
+ except Exception:
+ pass
+
+from app import GhostmanApp
+from network import NetworkEngine
+from webhook_server import WebhookServer
+from storage import StorageManager
+from textual.widgets import Input, TextArea, Select, ListView, Tabs, Label
+
+
+async def test_tls_verification_default_and_toggle():
+ print("[*] 1. Testing TLS Certificate Verification Default & Toggles...")
+
+ # NetworkEngine must default to verify_ssl=True (no hardcoded verify=False)
+ net = NetworkEngine()
+ assert net.verify_ssl is True, "VULNERABILITY: NetworkEngine did not default to verify_ssl=True!"
+
+ # Testing self-signed or invalid SSL domain: must fail under verify_ssl=True
+ try:
+ res = await net.execute_request("GET", "https://self-signed.badssl.com/")
+ assert not res["success"], "VULNERABILITY: Untrusted self-signed certificate was accepted under verify_ssl=True!"
+ assert "ssl" in res["body"].lower() or "certificate" in res["body"].lower() or "failed" in res["body"].lower()
+ except Exception as e:
+ # Rejection by httpx/ssl is expected and secure
+ pass
+
+ # When verify_ssl=False is explicitly specified, it should bypass verification
+ res_insecure = await net.execute_request(
+ "GET", "https://self-signed.badssl.com/", verify_ssl=False
+ )
+ # The request should succeed or reach the server without TLS certificate rejection
+ assert "Certificate Verification Failed" not in res_insecure.get("body", "")
+
+ print(" [+] TLS Certificate Verification: PASS")
+
+
+async def test_saved_and_custom_headers_propagation():
+ print("[*] 2. Testing Custom & Saved HTTP Headers Propagation...")
+
+ # Start local WebhookServer to inspect actual received headers
+ received_hooks = []
+ ws = WebhookServer(port=9095, on_hook_received=lambda h: received_hooks.append(h))
+ await ws.start()
+
+ try:
+ net = NetworkEngine()
+ custom_headers = {
+ "Authorization": "Bearer gh_secret_token_12345",
+ "X-Custom-Trace-Id": "trace-uuid-abcdef",
+ "Accept": "application/vnd.github.v3+json",
+ }
+
+ res = await net.execute_request(
+ "POST",
+ "http://127.0.0.1:9095/header-check",
+ headers=custom_headers,
+ body='{"test": true}'
+ )
+ assert res["success"], f"Request to local server failed: {res.get('error')}"
+
+ await asyncio.sleep(0.15)
+ assert len(received_hooks) == 1, "WebhookServer did not capture the request"
+
+ captured_headers = received_hooks[0]["headers"]
+ # Case-insensitive header lookup
+ lower_headers = {k.lower(): v for k, v in captured_headers.items()}
+
+ assert lower_headers.get("authorization") == "Bearer gh_secret_token_12345", (
+ "VULNERABILITY: Authorization header was not sent!"
+ )
+ assert lower_headers.get("x-custom-trace-id") == "trace-uuid-abcdef", (
+ "VULNERABILITY: X-Custom-Trace-Id header was not sent!"
+ )
+ assert lower_headers.get("accept") == "application/vnd.github.v3+json", (
+ "VULNERABILITY: Accept header was not sent!"
+ )
+
+ # Header parsing and formatting utilities
+ header_text = "Authorization: Bearer secret\nContent-Type: application/xml\nUser-Agent: Custom"
+ parsed = GhostmanApp.parse_headers_text(header_text)
+ assert parsed["Authorization"] == "Bearer secret"
+ assert parsed["Content-Type"] == "application/xml"
+ assert parsed["User-Agent"] == "Custom"
+
+ # JSON header input support
+ json_header_text = '{"Authorization": "Bearer token", "X-Key": "val"}'
+ parsed_json = GhostmanApp.parse_headers_text(json_header_text)
+ assert parsed_json["Authorization"] == "Bearer token"
+ assert parsed_json["X-Key"] == "val"
+
+ # Roundtrip format
+ formatted = GhostmanApp.format_headers_text(parsed)
+ re_parsed = GhostmanApp.parse_headers_text(formatted)
+ assert re_parsed == parsed
+
+ finally:
+ await ws.stop()
+
+ print(" [+] Custom & Saved Headers: PASS")
+
+
+async def test_chunked_transfer_encoding_webhook():
+ print("[*] 3. Testing Chunked Transfer Encoding Webhook Reception...")
+
+ received_hooks = []
+ ws = WebhookServer(port=9096, on_hook_received=lambda h: received_hooks.append(h))
+ await ws.start()
+
+ try:
+ # 1. Standard RFC 7230 Chunked Body
+ raw_http = (
+ b"POST /chunked-endpoint HTTP/1.1\r\n"
+ b"Host: 127.0.0.1:9096\r\n"
+ b"Transfer-Encoding: chunked\r\n"
+ b"Content-Type: text/plain\r\n"
+ b"Connection: close\r\n"
+ b"\r\n"
+ b"7\r\n"
+ b"Mozilla\r\n"
+ b"9\r\n"
+ b"Developer\r\n"
+ b"7\r\n"
+ b"Network\r\n"
+ b"0\r\n"
+ b"\r\n"
+ )
+
+ reader, writer = await asyncio.open_connection("127.0.0.1", 9096)
+ writer.write(raw_http)
+ await writer.drain()
+ resp = await reader.read(1024)
+ writer.close()
+ await writer.wait_closed()
+
+ await asyncio.sleep(0.15)
+ assert len(received_hooks) == 1, "WebhookServer did not capture chunked request!"
+ assert received_hooks[0]["raw_body"] == "MozillaDeveloperNetwork", (
+ f"VULNERABILITY: Chunked payload was not properly reconstructed! Got: {received_hooks[0]['raw_body']}"
+ )
+
+ # 2. Chunked JSON with Chunk Extensions (e.g., "11;ext=foo")
+ json_chunked = (
+ b"POST /chunked-json HTTP/1.1\r\n"
+ b"Host: 127.0.0.1:9096\r\n"
+ b"Transfer-Encoding: chunked\r\n"
+ b"Content-Type: application/json\r\n"
+ b"Connection: close\r\n"
+ b"\r\n"
+ b"9;ext=part1\r\n"
+ b"{\"event\":\r\n"
+ b"a;ext=part2\r\n"
+ b" \"deploy\"}\r\n"
+ b"0\r\n"
+ b"X-Trailer: test\r\n"
+ b"\r\n"
+ )
+
+ reader2, writer2 = await asyncio.open_connection("127.0.0.1", 9096)
+ writer2.write(json_chunked)
+ await writer2.drain()
+ resp2 = await reader2.read(1024)
+ writer2.close()
+ await writer2.wait_closed()
+
+ await asyncio.sleep(0.15)
+ assert len(received_hooks) == 2, "WebhookServer did not capture second chunked request!"
+ assert json.loads(received_hooks[1]["raw_body"]) == {"event": "deploy"}, (
+ f"VULNERABILITY: Chunked JSON payload failed! Got: {received_hooks[1]['raw_body']}"
+ )
+
+ finally:
+ await ws.stop()
+
+ print(" [+] Chunked Transfer Encoding: PASS")
+
+
+async def test_tui_headers_and_ssl_controls():
+ print("[*] 4. Testing TUI Headers Tab & SSL Toggle Integration...")
+
+ app = GhostmanApp()
+ async with app.run_test() as pilot:
+ # Check TLS badge initial state
+ ssl_badge = app.query_one("#ssl-badge", Label)
+ assert "[TLS: ON]" in str(ssl_badge.render())
+ assert app.verify_ssl is True
+
+ # Toggle TLS verify via hotkey (Ctrl+T)
+ await pilot.press("ctrl+t")
+ await pilot.pause(0.1)
+ assert app.verify_ssl is False
+ assert "[TLS: OFF]" in str(ssl_badge.render())
+
+ # Toggle back to secure
+ await pilot.press("ctrl+t")
+ await pilot.pause(0.1)
+ assert app.verify_ssl is True
+ assert "[TLS: ON]" in str(ssl_badge.render())
+
+ # Test Headers input in UI
+ headers_input = app.query_one("#headers-input", TextArea)
+ headers_input.text = "Authorization: Bearer my-ui-token\nX-Client: Ghostman"
+
+ # Switch to Headers tab
+ tabs = app.query_one("#tabs", Tabs)
+ tabs.active = "tab-headers"
+ await pilot.pause(0.1)
+ assert app.query_one("#tab-headers-pane").display is True
+
+ # Save current request with headers
+ app.query_one("#url-input", Input).value = "https://httpbin.org/headers"
+ app.action_save_request()
+ await pilot.pause(0.1)
+
+ # Check saved request in collections has the headers
+ saved_req = app.collections[0]["requests"][-1]
+ assert saved_req["headers"].get("Authorization") == "Bearer my-ui-token"
+ assert saved_req["headers"].get("X-Client") == "Ghostman"
+
+ # Action new request clears headers
+ app.action_new_request()
+ await pilot.pause(0.1)
+ assert app.query_one("#headers-input", TextArea).text == ""
+
+ print(" [+] TUI Headers & SSL Controls: PASS")
+
+
+async def main():
+ print("\n" + "=" * 60)
+ print("RUNNING GHOSTMAN AUDIT VULNERABILITY VERIFICATION (v0.1.3)")
+ print("=" * 60)
+
+ await test_tls_verification_default_and_toggle()
+ await test_saved_and_custom_headers_propagation()
+ await test_chunked_transfer_encoding_webhook()
+ await test_tui_headers_and_ssl_controls()
+
+ print("\n" + "=" * 60)
+ print("ALL 3 AUDIT ISSUES RESOLVED AND VERIFIED 100% PASSING!")
+ print("=" * 60 + "\n")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/webhook_server.py b/webhook_server.py
index 480ec75..6b5e678 100644
--- a/webhook_server.py
+++ b/webhook_server.py
@@ -40,6 +40,7 @@ class WebhookServer:
headers = {}
content_length = 0
+ transfer_encoding = ""
while True:
header_line = await reader.readline()
if not header_line or header_line in (b"\r\n", b"\n"):
@@ -47,17 +48,49 @@ class WebhookServer:
decoded_header = header_line.decode("utf-8", errors="ignore").strip()
if ":" in decoded_header:
k, v = decoded_header.split(":", 1)
- k_clean = k.strip().title()
+ k_clean = k.strip()
v_clean = v.strip()
headers[k_clean] = v_clean
- if k_clean.lower() == "content-length":
+ lower_k = k_clean.lower()
+ if lower_k == "content-length":
try:
content_length = int(v_clean)
except ValueError:
content_length = 0
+ elif lower_k == "transfer-encoding":
+ transfer_encoding = v_clean.lower()
body_bytes = b""
- if content_length > 0:
+ # Support Chunked Transfer Encoding (RFC 7230 / RFC 9112)
+ if "chunked" in transfer_encoding:
+ chunks = []
+ while True:
+ size_line = await reader.readline()
+ if not size_line:
+ break
+ # Strip any chunk extensions (e.g., "1a;ext=val")
+ size_str = size_line.decode("utf-8", errors="ignore").split(";")[0].strip()
+ if not size_str:
+ continue
+ try:
+ chunk_size = int(size_str, 16)
+ except ValueError:
+ break
+ if chunk_size == 0:
+ # Consume trailer headers until empty CRLF line
+ while True:
+ trailer = await reader.readline()
+ if not trailer or trailer in (b"\r\n", b"\n"):
+ break
+ break
+
+ chunk_data = await reader.readexactly(chunk_size)
+ chunks.append(chunk_data)
+
+ # Consume trailing CRLF after chunk data
+ await reader.readline()
+ body_bytes = b"".join(chunks)
+ elif content_length > 0:
body_bytes = await reader.readexactly(content_length)
body_str = body_bytes.decode("utf-8", errors="ignore")