hookstride-cli 1.0.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.
- hookstride_cli/__init__.py +3 -0
- hookstride_cli/console.py +514 -0
- hookstride_cli/listen.py +227 -0
- hookstride_cli/main.py +1366 -0
- hookstride_cli-1.0.0.dist-info/METADATA +215 -0
- hookstride_cli-1.0.0.dist-info/RECORD +8 -0
- hookstride_cli-1.0.0.dist-info/WHEEL +4 -0
- hookstride_cli-1.0.0.dist-info/entry_points.txt +2 -0
hookstride_cli/listen.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Opt-in local preview: outbound polling and numeric loopback-only HTTP delivery."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
import uuid
|
|
9
|
+
from datetime import UTC, datetime
|
|
10
|
+
from urllib.parse import unquote
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
MAX_EVENT_BYTES = 64 * 1024
|
|
15
|
+
MAX_RESPONSE_BYTES = 400 * 1024
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ListenStopped(Exception):
|
|
19
|
+
"""A fixed, credential-free failure suitable for terminal output."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class RetryPoll(Exception):
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def local_url(port: int, path: str) -> str:
|
|
27
|
+
decoded = unquote(path)
|
|
28
|
+
if not 1 <= port <= 65535 or not re.fullmatch(r"/[A-Za-z0-9._~/%-]*", path):
|
|
29
|
+
raise ListenStopped("Use a valid loopback port and an absolute HTTP path.")
|
|
30
|
+
if (
|
|
31
|
+
decoded.startswith("//")
|
|
32
|
+
or ".." in decoded.split("/")
|
|
33
|
+
or "\\" in decoded
|
|
34
|
+
or any(ord(ch) < 32 or ord(ch) == 127 for ch in decoded)
|
|
35
|
+
):
|
|
36
|
+
raise ListenStopped("Use a plain local receiver path without traversal.")
|
|
37
|
+
return f"http://127.0.0.1:{port}{path}"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def api_call(client, path, body, *, method="POST"):
|
|
41
|
+
try:
|
|
42
|
+
with client.stream(method, path, json=body) as response:
|
|
43
|
+
if response.status_code in (401, 403, 404):
|
|
44
|
+
raise ListenStopped(
|
|
45
|
+
"Access ended, session expired, or local forwarding is not enabled."
|
|
46
|
+
)
|
|
47
|
+
if response.status_code in (409, 429) or response.status_code >= 500:
|
|
48
|
+
raise RetryPoll()
|
|
49
|
+
if response.status_code == 410:
|
|
50
|
+
raw = bytearray()
|
|
51
|
+
for chunk in response.iter_bytes(chunk_size=8192):
|
|
52
|
+
raw.extend(chunk)
|
|
53
|
+
if len(raw) > 4096:
|
|
54
|
+
break
|
|
55
|
+
try:
|
|
56
|
+
reason = json.loads(raw).get("reason")
|
|
57
|
+
except (ValueError, AttributeError):
|
|
58
|
+
reason = None
|
|
59
|
+
messages = {
|
|
60
|
+
"queue_full": "Local session stopped: preview queue is full. Use a faster receiver.",
|
|
61
|
+
"payload_too_large": "Local session stopped: event exceeds the local payload limit.",
|
|
62
|
+
"delivery_limit": "Local session stopped: delivery retry limit reached.",
|
|
63
|
+
}
|
|
64
|
+
raise ListenStopped(messages.get(reason, "Local session expired or revoked."))
|
|
65
|
+
if not 200 <= response.status_code < 300:
|
|
66
|
+
raise ListenStopped("Local forwarding API rejected the request.")
|
|
67
|
+
raw = bytearray()
|
|
68
|
+
for chunk in response.iter_bytes(chunk_size=8192):
|
|
69
|
+
raw.extend(chunk)
|
|
70
|
+
if len(raw) > MAX_RESPONSE_BYTES:
|
|
71
|
+
raise ListenStopped("Forwarding response exceeds the safety limit.")
|
|
72
|
+
data = json.loads(raw)
|
|
73
|
+
if not isinstance(data, dict):
|
|
74
|
+
raise ValueError
|
|
75
|
+
return data
|
|
76
|
+
except (httpx.HTTPError, httpx.InvalidURL):
|
|
77
|
+
raise RetryPoll() from None
|
|
78
|
+
except (ValueError, TypeError):
|
|
79
|
+
raise ListenStopped("Invalid forwarding response.") from None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def checked_event(item, source_id):
|
|
83
|
+
try:
|
|
84
|
+
event = item["event"]
|
|
85
|
+
event_id = str(uuid.UUID(event["id"]))
|
|
86
|
+
if str(uuid.UUID(event["source_id"])) != source_id:
|
|
87
|
+
raise ValueError
|
|
88
|
+
if not isinstance(event["type"], str) or len(event["type"]) > 160:
|
|
89
|
+
raise ValueError
|
|
90
|
+
if not isinstance(event["data"], dict):
|
|
91
|
+
raise ValueError
|
|
92
|
+
body = json.dumps(event, ensure_ascii=True, separators=(",", ":")).encode()
|
|
93
|
+
if len(body) > MAX_EVENT_BYTES:
|
|
94
|
+
raise ListenStopped("Event exceeds the local payload limit.")
|
|
95
|
+
attempt = item["attempt"]
|
|
96
|
+
if type(attempt) is not int or not 1 <= attempt <= 20:
|
|
97
|
+
raise ValueError
|
|
98
|
+
return event_id, body, attempt
|
|
99
|
+
except (KeyError, TypeError, ValueError, AttributeError):
|
|
100
|
+
raise ListenStopped("Invalid forwarding event.") from None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _forwarding_api_client(origin, token):
|
|
104
|
+
try:
|
|
105
|
+
return httpx.Client(
|
|
106
|
+
base_url=origin,
|
|
107
|
+
headers={"Authorization": "Bearer " + token, "Accept": "application/json"},
|
|
108
|
+
timeout=25,
|
|
109
|
+
follow_redirects=False,
|
|
110
|
+
)
|
|
111
|
+
except (httpx.HTTPError, httpx.InvalidURL, ImportError, ValueError):
|
|
112
|
+
raise ListenStopped(
|
|
113
|
+
"Unable to configure the Hookstride API connection. Check the URL and proxy settings."
|
|
114
|
+
) from None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def run_listener(*, origin, token, project_id, source_id, target, ttl, report, resume=None):
|
|
118
|
+
"""Keep credentials in memory. Never use local HTTP proxies or print bodies."""
|
|
119
|
+
base = f"/control/v1/projects/{project_id}/local-sessions/"
|
|
120
|
+
session_id = None
|
|
121
|
+
stopped = False
|
|
122
|
+
with (
|
|
123
|
+
_forwarding_api_client(origin, token) as api,
|
|
124
|
+
httpx.Client(
|
|
125
|
+
timeout=httpx.Timeout(5, connect=2), follow_redirects=False, trust_env=False
|
|
126
|
+
) as receiver,
|
|
127
|
+
):
|
|
128
|
+
try:
|
|
129
|
+
try:
|
|
130
|
+
if resume:
|
|
131
|
+
active = api_call(api, base, None, method="GET").get("sessions", [])
|
|
132
|
+
if not isinstance(active, list) or any(not isinstance(i, dict) for i in active):
|
|
133
|
+
raise ListenStopped("Invalid session list response.")
|
|
134
|
+
created = next(
|
|
135
|
+
(
|
|
136
|
+
item
|
|
137
|
+
for item in active
|
|
138
|
+
if item.get("id") == resume and item.get("source_id") == source_id
|
|
139
|
+
),
|
|
140
|
+
None,
|
|
141
|
+
)
|
|
142
|
+
if not created:
|
|
143
|
+
raise ListenStopped(
|
|
144
|
+
"Session is no longer active for this token and source."
|
|
145
|
+
)
|
|
146
|
+
else:
|
|
147
|
+
created = api_call(api, base, {"source_id": source_id, "ttl_seconds": ttl})
|
|
148
|
+
except RetryPoll:
|
|
149
|
+
raise ListenStopped(
|
|
150
|
+
"Could not start a session. Check API connectivity and try again."
|
|
151
|
+
) from None
|
|
152
|
+
try:
|
|
153
|
+
session_id = str(uuid.UUID(created["id"]))
|
|
154
|
+
expires = datetime.fromisoformat(created["expires_at"].replace("Z", "+00:00"))
|
|
155
|
+
if expires.tzinfo is None or expires <= datetime.now(UTC):
|
|
156
|
+
raise ValueError
|
|
157
|
+
except (KeyError, TypeError, ValueError, AttributeError):
|
|
158
|
+
raise ListenStopped("Invalid session response.") from None
|
|
159
|
+
report(f"Connected · {target} · Ctrl+C to stop")
|
|
160
|
+
report(f"Session · {session_id} · new verified events only")
|
|
161
|
+
pending_ack = None
|
|
162
|
+
failures = 0
|
|
163
|
+
while datetime.now(UTC) < expires:
|
|
164
|
+
try:
|
|
165
|
+
# A dropped ACK response must not cause a second local POST
|
|
166
|
+
# in this process. ACK is idempotent; repeat it before polling.
|
|
167
|
+
if pending_ack:
|
|
168
|
+
api_call(api, f"{base}{session_id}/events/{pending_ack}/ack/", {})
|
|
169
|
+
report(f"Forwarded · {pending_ack}")
|
|
170
|
+
pending_ack = None
|
|
171
|
+
result = api_call(api, f"{base}{session_id}/poll/", {"wait_seconds": 0})
|
|
172
|
+
events = result.get("events")
|
|
173
|
+
if not isinstance(events, list) or len(events) > 5:
|
|
174
|
+
raise ListenStopped("Invalid event batch.")
|
|
175
|
+
if failures:
|
|
176
|
+
report("Reconnected")
|
|
177
|
+
failures = 0
|
|
178
|
+
if not events:
|
|
179
|
+
time.sleep(2) # Pace empty polls without holding API workers.
|
|
180
|
+
continue
|
|
181
|
+
for item in events:
|
|
182
|
+
if datetime.now(UTC) >= expires:
|
|
183
|
+
raise ListenStopped("Session expired. Start a new session to continue.")
|
|
184
|
+
event_id, body, attempt = checked_event(item, source_id)
|
|
185
|
+
report(f"Received · {event_id} · attempt {attempt}")
|
|
186
|
+
try:
|
|
187
|
+
with receiver.stream(
|
|
188
|
+
"POST",
|
|
189
|
+
target,
|
|
190
|
+
content=body,
|
|
191
|
+
headers={
|
|
192
|
+
"Content-Type": "application/json",
|
|
193
|
+
"X-Hookstride-Local-Event-Id": event_id,
|
|
194
|
+
"X-Hookstride-Local-Session-Id": session_id,
|
|
195
|
+
},
|
|
196
|
+
) as response:
|
|
197
|
+
code = response.status_code
|
|
198
|
+
# Never consume/print an untrusted receiver body.
|
|
199
|
+
except (httpx.HTTPError, httpx.InvalidURL):
|
|
200
|
+
report(
|
|
201
|
+
f"Receiver timeout or connection failure · {event_id} · will retry"
|
|
202
|
+
)
|
|
203
|
+
continue
|
|
204
|
+
if not 200 <= code < 300:
|
|
205
|
+
report(f"Receiver HTTP {code} · {event_id} · will retry")
|
|
206
|
+
continue
|
|
207
|
+
pending_ack = event_id
|
|
208
|
+
api_call(api, f"{base}{session_id}/events/{event_id}/ack/", {})
|
|
209
|
+
report(f"Forwarded · {event_id}")
|
|
210
|
+
pending_ack = None
|
|
211
|
+
except RetryPoll:
|
|
212
|
+
failures += 1
|
|
213
|
+
report("Connection interrupted · reconnecting")
|
|
214
|
+
time.sleep(min(2 ** min(failures, 4), 15))
|
|
215
|
+
raise ListenStopped("Session expired. Start a new session to continue.")
|
|
216
|
+
except KeyboardInterrupt:
|
|
217
|
+
stopped = True
|
|
218
|
+
report("Stopping")
|
|
219
|
+
finally:
|
|
220
|
+
if session_id:
|
|
221
|
+
try:
|
|
222
|
+
api_call(api, f"{base}{session_id}/revoke/", {})
|
|
223
|
+
report("Session revoked")
|
|
224
|
+
except (RetryPoll, ListenStopped):
|
|
225
|
+
report("Revocation not confirmed · session will expire automatically")
|
|
226
|
+
if stopped:
|
|
227
|
+
report("Disconnected")
|