@cotal-ai/connector-hermes 0.167.0 → 0.169.0
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.
- package/dist/bridge.d.ts +12 -5
- package/dist/bridge.d.ts.map +1 -1
- package/dist/docs-bundle.bin +0 -0
- package/dist/docs-index.bin +0 -0
- package/dist/index.js +9 -9
- package/dist/launch.d.ts.map +1 -1
- package/dist/launch.js +34 -31
- package/dist/sidecar.d.ts +1 -1
- package/dist/sidecar.d.ts.map +1 -1
- package/package.json +3 -3
- package/plugin/cotal/__init__.py +22 -4
- package/plugin/cotal/_sidecar/docs-bundle.bin +0 -0
- package/plugin/cotal/_sidecar/docs-index.bin +0 -0
- package/plugin/cotal/_sidecar/standalone.cjs +28 -25
- package/plugin/cotal/adapter.py +26 -1
- package/plugin/cotal/bridge_client.py +44 -10
- package/plugin/cotal/control_exchange.py +270 -0
- package/plugin/cotal/hooks.py +41 -46
package/plugin/cotal/adapter.py
CHANGED
|
@@ -97,6 +97,14 @@ class CotalAdapter(BasePlatformAdapter):
|
|
|
97
97
|
is therefore reopened explicitly before the reader is started.
|
|
98
98
|
"""
|
|
99
99
|
self._loop = asyncio.get_running_loop()
|
|
100
|
+
# A bridge socket in a directory that exists and is not private to this user is never dialed,
|
|
101
|
+
# and no retry repairs that. Report it as a permanent fatal instead of calling the platform
|
|
102
|
+
# connected with a reader that will never connect.
|
|
103
|
+
refused = self._client.refusal()
|
|
104
|
+
if refused:
|
|
105
|
+
self._set_fatal_error("cotal_bridge_not_private", refused, retryable=False)
|
|
106
|
+
await self._notify_fatal_error()
|
|
107
|
+
return False
|
|
100
108
|
if is_reconnect:
|
|
101
109
|
# Clear the latched stop and drop the dead reader, so start() below really starts one.
|
|
102
110
|
#
|
|
@@ -108,7 +116,7 @@ class CotalAdapter(BasePlatformAdapter):
|
|
|
108
116
|
# reader, which is exactly the kind of pause an operator would report as the gateway
|
|
109
117
|
# hanging on reconnect. `to_thread` keeps the loop free while the join runs.
|
|
110
118
|
await asyncio.to_thread(self._client.reopen)
|
|
111
|
-
self._client.start(self._on_incoming) # reader thread → _on_incoming
|
|
119
|
+
self._client.start(self._on_incoming, self._on_bridge_refused) # reader thread → _on_incoming
|
|
112
120
|
|
|
113
121
|
# THE BRIDGE MUST BE PROVED LIVE BEFORE THE PLATFORM IS CALLED CONNECTED.
|
|
114
122
|
#
|
|
@@ -136,6 +144,20 @@ class CotalAdapter(BasePlatformAdapter):
|
|
|
136
144
|
hooks.relay("gateway_startup") # present + free
|
|
137
145
|
return True
|
|
138
146
|
|
|
147
|
+
def _on_bridge_refused(self, reason: str) -> None:
|
|
148
|
+
"""The reader found the bridge socket's directory not private after connect (reader thread):
|
|
149
|
+
report the same permanent fatal on the gateway's loop, since the bridge will not dial again."""
|
|
150
|
+
loop = self._loop
|
|
151
|
+
if loop is None or loop.is_closed():
|
|
152
|
+
return
|
|
153
|
+
|
|
154
|
+
def report() -> None:
|
|
155
|
+
self._set_fatal_error("cotal_bridge_not_private", reason, retryable=False)
|
|
156
|
+
self._mark_disconnected()
|
|
157
|
+
asyncio.ensure_future(self._notify_fatal_error())
|
|
158
|
+
|
|
159
|
+
loop.call_soon_threadsafe(report)
|
|
160
|
+
|
|
139
161
|
async def disconnect(self) -> None:
|
|
140
162
|
hooks.relay("gateway_shutdown")
|
|
141
163
|
self._client.close()
|
|
@@ -147,6 +169,9 @@ class CotalAdapter(BasePlatformAdapter):
|
|
|
147
169
|
# The gateway delivers a turn's reply here → route it back to the message's mesh origin. A
|
|
148
170
|
# reply to a message delivered here names it and copies its contextId (it belongs to the
|
|
149
171
|
# asker); otherwise the sidecar pairs a DM reply with its peer's oldest unanswered message.
|
|
172
|
+
refused = self._client.refusal()
|
|
173
|
+
if refused:
|
|
174
|
+
raise RuntimeError(refused) # never report a reply delivered over a bridge that will not dial
|
|
150
175
|
answered = str(reply_to) if reply_to is not None else None
|
|
151
176
|
if answered not in self._answering:
|
|
152
177
|
answered = None
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
"""Persistent client to the Cotal sidecar's bridge socket.
|
|
2
2
|
|
|
3
3
|
The sidecar (``src/sidecar.ts``) owns the mesh endpoint and exposes a unix-socket bridge; this is
|
|
4
|
-
the in-gateway half.
|
|
4
|
+
the in-gateway half. Every (re)connect opens with a ``subscribe`` carrying the bridge token, which
|
|
5
|
+
``control_exchange.bridge_token`` derives from the launch's control key, so the key itself never
|
|
6
|
+
crosses this socket. The socket sits beside the control socket, in a directory only this user can
|
|
7
|
+
enter, and every dial checks that directory first. One background thread owns a blocking ``AF_UNIX`` connection and dispatches
|
|
5
8
|
frames — inbound mesh messages go to the adapter's callback, tool results resolve pending calls.
|
|
6
9
|
Writes are newline-delimited JSON under a lock; it reconnects with backoff so a sidecar restart
|
|
7
10
|
self-heals (re-subscribing on every (re)connect). Wire format mirrors ``src/bridge.ts``.
|
|
@@ -17,7 +20,7 @@ import time
|
|
|
17
20
|
import uuid
|
|
18
21
|
from typing import Any, Callable, Optional
|
|
19
22
|
|
|
20
|
-
from .
|
|
23
|
+
from .control_exchange import bridge_token, control_key, socket_dir_problem
|
|
21
24
|
|
|
22
25
|
_BACKOFF_S = 2.0
|
|
23
26
|
|
|
@@ -30,18 +33,23 @@ _REOPEN_JOIN_SECONDS = 2.0
|
|
|
30
33
|
class BridgeClient:
|
|
31
34
|
def __init__(self, socket_path: str) -> None:
|
|
32
35
|
self._path = socket_path
|
|
33
|
-
# Resolved once, the same
|
|
34
|
-
#
|
|
35
|
-
|
|
36
|
-
if not
|
|
36
|
+
# Resolved once, the same key `hooks.relay` reads: standalone mode exports COTAL_CONTROL_KEY
|
|
37
|
+
# and COTAL_CONTROL_VERSION directly; a managed launch carries both in the launch material only.
|
|
38
|
+
key = control_key()
|
|
39
|
+
if not key:
|
|
37
40
|
raise RuntimeError(
|
|
38
|
-
"no control
|
|
39
|
-
"
|
|
41
|
+
"no control key could be resolved (neither COTAL_CONTROL_KEY nor COTAL_LAUNCH_MATERIAL "
|
|
42
|
+
"carries one) — the bridge socket cannot be authenticated"
|
|
40
43
|
)
|
|
44
|
+
self._token = bridge_token(key)
|
|
41
45
|
self._sock: Optional[socket.socket] = None
|
|
42
46
|
self._lock = threading.Lock()
|
|
43
47
|
self._pending: dict[str, tuple[threading.Event, dict]] = {}
|
|
44
48
|
self._on_incoming: Optional[Callable[[dict], None]] = None
|
|
49
|
+
self._on_refused: Optional[Callable[[str], None]] = None
|
|
50
|
+
# Why this bridge refuses to dial, once its socket's directory has been found present and not
|
|
51
|
+
# private to this user. That is a configuration fault no retry repairs, so it is permanent.
|
|
52
|
+
self._refused: Optional[str] = None
|
|
45
53
|
self._stop = threading.Event()
|
|
46
54
|
self._reader: Optional[threading.Thread] = None
|
|
47
55
|
# Generation of the CURRENT reader. Bumped by close() and reopen(); each reader captures
|
|
@@ -49,14 +57,17 @@ class BridgeClient:
|
|
|
49
57
|
# correctness never depends on guessing whether a dying thread has finished dying.
|
|
50
58
|
self._gen = 0
|
|
51
59
|
|
|
52
|
-
def start(self, on_incoming: Callable[[dict], None]) -> None:
|
|
53
|
-
"""Begin the reader thread. ``on_incoming`` is called (off-loop) for each mesh message
|
|
60
|
+
def start(self, on_incoming: Callable[[dict], None], on_refused: Optional[Callable[[str], None]] = None) -> None:
|
|
61
|
+
"""Begin the reader thread. ``on_incoming`` is called (off-loop) for each mesh message, and
|
|
62
|
+
``on_refused`` (off-loop, once) if the reader stops because the socket's directory is not
|
|
63
|
+
private to this user.
|
|
54
64
|
|
|
55
65
|
A reader is started only when none is installed for the CURRENT generation. Holding the
|
|
56
66
|
lock across the check and the install closes the window where two concurrent starts could
|
|
57
67
|
each see None and put two readers on one socket.
|
|
58
68
|
"""
|
|
59
69
|
self._on_incoming = on_incoming
|
|
70
|
+
self._on_refused = on_refused
|
|
60
71
|
with self._lock:
|
|
61
72
|
if self._reader is not None:
|
|
62
73
|
return
|
|
@@ -87,6 +98,8 @@ class BridgeClient:
|
|
|
87
98
|
# before this re-check: RETIRED_READER_READ_FOREIGN_SOCKET True.
|
|
88
99
|
if self._stop.is_set() or gen != self._gen:
|
|
89
100
|
return
|
|
101
|
+
if self._refused:
|
|
102
|
+
return # the socket's directory is not private: refusal() has reported it
|
|
90
103
|
if self._sock is None:
|
|
91
104
|
continue
|
|
92
105
|
self._send({"t": "subscribe", "token": self._token}) # (re)subscribe after every (re)connect
|
|
@@ -142,6 +155,11 @@ class BridgeClient:
|
|
|
142
155
|
while not self._stop.is_set():
|
|
143
156
|
if gen is not None and gen != self._gen:
|
|
144
157
|
return # retired while dialing: this socket is not wanted
|
|
158
|
+
if self.refusal():
|
|
159
|
+
return # permanent: the reader stops and the adapter reports it
|
|
160
|
+
if socket_dir_problem(self._path):
|
|
161
|
+
time.sleep(_BACKOFF_S) # the directory is not there yet: the sidecar is not up
|
|
162
|
+
continue
|
|
145
163
|
try:
|
|
146
164
|
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
147
165
|
s.connect(self._path)
|
|
@@ -159,6 +177,22 @@ class BridgeClient:
|
|
|
159
177
|
except OSError:
|
|
160
178
|
time.sleep(_BACKOFF_S)
|
|
161
179
|
|
|
180
|
+
def refusal(self) -> Optional[str]:
|
|
181
|
+
"""Why this bridge will not dial, or ``None``. Checks the socket's directory now: a directory
|
|
182
|
+
that is absent reads as a sidecar not up yet and is retried, but one that exists and is not
|
|
183
|
+
private to this user is a permanent refusal, reported once on stderr and to ``on_refused``."""
|
|
184
|
+
if self._refused:
|
|
185
|
+
return self._refused
|
|
186
|
+
problem = socket_dir_problem(self._path)
|
|
187
|
+
if not problem or problem[0]:
|
|
188
|
+
return None
|
|
189
|
+
self._refused = f"{problem[1]}, so the bridge socket {self._path} is not dialed"
|
|
190
|
+
print(f"[cotal-hermes] {self._refused}", file=sys.stderr, flush=True)
|
|
191
|
+
cb = self._on_refused
|
|
192
|
+
if cb:
|
|
193
|
+
cb(self._refused)
|
|
194
|
+
return self._refused
|
|
195
|
+
|
|
162
196
|
def _dispatch(self, line: bytes) -> None:
|
|
163
197
|
try:
|
|
164
198
|
frame = json.loads(line)
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
"""The control exchange, client half, in Python: the counterpart of ``@cotal-ai/core``'s
|
|
2
|
+
``control-exchange.ts`` for the Hermes hooks, plus the bridge token the bridge client presents.
|
|
3
|
+
|
|
4
|
+
The client and the sidecar each prove they hold the launch's control key without sending it::
|
|
5
|
+
|
|
6
|
+
C -> S {"v":1,"nonce":"<Nc>"}\\n
|
|
7
|
+
S -> C {"v":1,"nonce":"<Ns>","mac":"<Ms>"}\\n
|
|
8
|
+
C -> S <Mc> <request JSON>\\n
|
|
9
|
+
S -> C <Mr> <reply JSON>\\n
|
|
10
|
+
|
|
11
|
+
Nonces are 32 random bytes, base64url without padding. Every MAC is HMAC-SHA256 keyed with the
|
|
12
|
+
UTF-8 bytes of the key, base64url without padding (43 characters of ``A-Z a-z 0-9 - _``, checked
|
|
13
|
+
before the constant-time compare), over these exact bytes (``\\0`` is one zero byte; the request
|
|
14
|
+
and reply are the bytes between the single space and the newline)::
|
|
15
|
+
|
|
16
|
+
Ms = HMAC(K, "cotal-control/1\\0server\\0" Nc "\\0" Ns)
|
|
17
|
+
Mc = HMAC(K, "cotal-control/1\\0client\\0" Nc "\\0" Ns "\\0" request)
|
|
18
|
+
Mr = HMAC(K, "cotal-control/1\\0reply\\0" Nc "\\0" Ns "\\0" reply)
|
|
19
|
+
|
|
20
|
+
Every line is bounded in bytes before it is parsed or a MAC is computed over it: the hello and the
|
|
21
|
+
challenge at 1 KiB, the reply's JSON at 4 KiB. The challenge and the reply are decoded strictly as
|
|
22
|
+
UTF-8, as the TypeScript client decodes them. The hooks send no delivery receipt, so the fifth line
|
|
23
|
+
the TypeScript relay can send does not occur here.
|
|
24
|
+
|
|
25
|
+
The bridge socket does not run the exchange. Its client presents :func:`bridge_token`, derived
|
|
26
|
+
from the key, in its first frame, so the key crosses neither socket. That token authenticates the
|
|
27
|
+
client only: the bridge server proves nothing, and the private socket directory is what keeps
|
|
28
|
+
another user off that socket.
|
|
29
|
+
|
|
30
|
+
The version travels with the key (the launch material's ``controlVersion``, or
|
|
31
|
+
``COTAL_CONTROL_VERSION`` beside ``COTAL_CONTROL_KEY``), this module speaks exactly one, and a
|
|
32
|
+
mismatch anywhere is a refusal. Nothing is negotiated and there is no fallback.
|
|
33
|
+
"""
|
|
34
|
+
from __future__ import annotations
|
|
35
|
+
|
|
36
|
+
import base64
|
|
37
|
+
import hashlib
|
|
38
|
+
import hmac
|
|
39
|
+
import json
|
|
40
|
+
import os
|
|
41
|
+
import re
|
|
42
|
+
import secrets
|
|
43
|
+
import socket
|
|
44
|
+
import stat
|
|
45
|
+
import time
|
|
46
|
+
from typing import Any
|
|
47
|
+
|
|
48
|
+
CONTROL_PROTOCOL_VERSION = 1
|
|
49
|
+
# How long a client waits, from connect, for the server to prove it holds the key.
|
|
50
|
+
CLIENT_PROOF_DEADLINE_S = 1.0
|
|
51
|
+
_MAX_HANDSHAKE_LINE = 1024
|
|
52
|
+
# The hooks' replies are ``{}``; the cap only bounds what a proven but runaway server can send.
|
|
53
|
+
_MAX_REPLY_JSON = 4096
|
|
54
|
+
_BASE64URL_43 = re.compile(r"[A-Za-z0-9_-]{43}")
|
|
55
|
+
_MAC_CHARS = 43
|
|
56
|
+
# What JavaScript's String.prototype.trim removes, so that "set" and "has whitespace around it" mean
|
|
57
|
+
# the same here as in the TypeScript readers. Python's own str.strip() removes a different set.
|
|
58
|
+
_JS_WHITESPACE = "\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"
|
|
59
|
+
# The direct variables the TypeScript reader refuses beside a material file (session-env.ts
|
|
60
|
+
# DIRECT_MATERIAL_VARS): one launch carries one set of connection material.
|
|
61
|
+
_DIRECT_MATERIAL_VARS = (
|
|
62
|
+
"COTAL_CREDS",
|
|
63
|
+
"COTAL_SERVERS",
|
|
64
|
+
"COTAL_TOKEN",
|
|
65
|
+
"COTAL_OWNER",
|
|
66
|
+
"COTAL_ACTOR",
|
|
67
|
+
"COTAL_SENTINEL_CREDS",
|
|
68
|
+
"COTAL_BEARER_CMD",
|
|
69
|
+
"COTAL_EVENTS_REQUIRED",
|
|
70
|
+
"COTAL_CONTROL_KEY",
|
|
71
|
+
"COTAL_CONTROL_VERSION",
|
|
72
|
+
"COTAL_CONTROL_TOKEN",
|
|
73
|
+
"COTAL_LINK",
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class ControlConfigError(Exception):
|
|
78
|
+
"""The launch carries a control key this module cannot use (no version, or another one)."""
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class ExchangeRefused(Exception):
|
|
82
|
+
"""The peer did not prove it holds the key, or spoke another version. Nothing it sent is used."""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _b64(raw: bytes) -> str:
|
|
86
|
+
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _mac(key: str, role: str, nc: str, ns: str, body: bytes | None = None) -> str:
|
|
90
|
+
msg = f"cotal-control/{CONTROL_PROTOCOL_VERSION}\0{role}\0{nc}\0{ns}".encode("ascii")
|
|
91
|
+
if body is not None:
|
|
92
|
+
msg += b"\0" + body
|
|
93
|
+
return _b64(hmac.new(key.encode("utf-8"), msg, hashlib.sha256).digest())
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _mac_matches(presented: Any, expected: str) -> bool:
|
|
97
|
+
if not isinstance(presented, str) or not _BASE64URL_43.fullmatch(presented):
|
|
98
|
+
return False
|
|
99
|
+
return hmac.compare_digest(presented.encode("ascii"), expected.encode("ascii"))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _is_version(value: Any) -> bool:
|
|
103
|
+
"""The version this module speaks, as a JSON number. JSON has one number type, so ``1.0`` is 1
|
|
104
|
+
here as it is to the TypeScript readers; ``True`` equals 1 in Python, and is not a version."""
|
|
105
|
+
return type(value) in (int, float) and value == CONTROL_PROTOCOL_VERSION
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def env_set(name: str) -> str | None:
|
|
109
|
+
"""A variable's value when it is set, which means it holds something besides whitespace."""
|
|
110
|
+
value = os.environ.get(name)
|
|
111
|
+
return value if value and value.strip(_JS_WHITESPACE) else None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _usable_key(key: Any, where: str) -> str:
|
|
115
|
+
if not isinstance(key, str) or not key.strip(_JS_WHITESPACE):
|
|
116
|
+
raise ControlConfigError(f"{where} is not a non-empty string")
|
|
117
|
+
if key != key.strip(_JS_WHITESPACE):
|
|
118
|
+
raise ControlConfigError(f"{where} has whitespace around it; a key is used as given, never trimmed")
|
|
119
|
+
return key
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def bridge_token(key: str) -> str:
|
|
123
|
+
"""The token the bridge client presents: HMAC-SHA256 keyed with the UTF-8 bytes of the control
|
|
124
|
+
key over ``cotal-hermes-bridge/<version>``, base64url without padding. Mirrors ``bridgeToken``
|
|
125
|
+
in ``src/bridge.ts``; a sidecar of another version derives another token and drops the frame."""
|
|
126
|
+
return _b64(hmac.new(key.encode("utf-8"), f"cotal-hermes-bridge/{CONTROL_PROTOCOL_VERSION}".encode("ascii"), hashlib.sha256).digest())
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def control_key() -> str | None:
|
|
130
|
+
"""This launch's control key, or ``None`` when it carries none.
|
|
131
|
+
|
|
132
|
+
A managed launch carries the key and its version in the launch material
|
|
133
|
+
(``COTAL_LAUNCH_MATERIAL``, fields ``controlKey`` and ``controlVersion``); a standalone launch
|
|
134
|
+
exports ``COTAL_CONTROL_KEY`` and ``COTAL_CONTROL_VERSION``. Reads them by the rule the TypeScript
|
|
135
|
+
readers apply, which the hooks-control smoke checks in both languages over the same vectors. A
|
|
136
|
+
variable counts as set when it holds anything besides whitespace. Raises
|
|
137
|
+
:class:`ControlConfigError` for a material file beside any direct material variable, for half a
|
|
138
|
+
pair, for a key with whitespace around it, for a version other than the one this module speaks
|
|
139
|
+
(``COTAL_CONTROL_VERSION`` is exactly ``1``), for a material file that is
|
|
140
|
+
unreadable, malformed or readable beyond its owner, for a material field that is present but not
|
|
141
|
+
usable (``null`` included), and for ``COTAL_CONTROL_TOKEN`` or ``controlToken``, where a release
|
|
142
|
+
before the exchange put the key for a hook that sends it.
|
|
143
|
+
"""
|
|
144
|
+
if env_set("COTAL_CONTROL_TOKEN"):
|
|
145
|
+
raise ControlConfigError(
|
|
146
|
+
"COTAL_CONTROL_TOKEN is the control key variable of a release before the control exchange; "
|
|
147
|
+
"set COTAL_CONTROL_KEY and COTAL_CONTROL_VERSION instead"
|
|
148
|
+
)
|
|
149
|
+
path = (os.environ.get("COTAL_LAUNCH_MATERIAL") or "").strip(_JS_WHITESPACE)
|
|
150
|
+
if not path:
|
|
151
|
+
direct = env_set("COTAL_CONTROL_KEY")
|
|
152
|
+
direct_version = env_set("COTAL_CONTROL_VERSION")
|
|
153
|
+
if direct is None:
|
|
154
|
+
if direct_version is not None:
|
|
155
|
+
raise ControlConfigError("COTAL_CONTROL_VERSION is set without COTAL_CONTROL_KEY")
|
|
156
|
+
return None
|
|
157
|
+
key = _usable_key(direct, "COTAL_CONTROL_KEY")
|
|
158
|
+
if direct_version != str(CONTROL_PROTOCOL_VERSION):
|
|
159
|
+
raise ControlConfigError("COTAL_CONTROL_VERSION does not name the control protocol version this plugin speaks")
|
|
160
|
+
return key
|
|
161
|
+
both = [name for name in _DIRECT_MATERIAL_VARS if env_set(name)]
|
|
162
|
+
if both:
|
|
163
|
+
raise ControlConfigError(
|
|
164
|
+
f"this launch carries connection material both in COTAL_LAUNCH_MATERIAL and as {', '.join(both)}; "
|
|
165
|
+
"one launch carries one, so drop one of them"
|
|
166
|
+
)
|
|
167
|
+
try:
|
|
168
|
+
if os.name != "nt" and (os.stat(path).st_mode & 0o077):
|
|
169
|
+
raise ControlConfigError("the launch material is readable beyond its owner")
|
|
170
|
+
with open(path, encoding="utf-8") as fh:
|
|
171
|
+
material = json.load(fh)
|
|
172
|
+
except (OSError, ValueError) as exc:
|
|
173
|
+
raise ControlConfigError("the launch material cannot be read as JSON") from exc
|
|
174
|
+
if not isinstance(material, dict):
|
|
175
|
+
raise ControlConfigError("the launch material is not a JSON object")
|
|
176
|
+
if "controlToken" in material:
|
|
177
|
+
raise ControlConfigError("the launch material carries controlToken, the control key field of a release before the control exchange")
|
|
178
|
+
has_key, has_version = "controlKey" in material, "controlVersion" in material
|
|
179
|
+
if not has_key and not has_version:
|
|
180
|
+
return None
|
|
181
|
+
if not has_key:
|
|
182
|
+
raise ControlConfigError("the launch material has a controlVersion without a usable controlKey")
|
|
183
|
+
key = _usable_key(material["controlKey"], "the launch material's controlKey")
|
|
184
|
+
if not has_version or not _is_version(material["controlVersion"]):
|
|
185
|
+
raise ControlConfigError("the launch material's controlVersion is not the control protocol version this plugin speaks")
|
|
186
|
+
return key
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def socket_dir_problem(path: str) -> tuple[bool, str] | None:
|
|
190
|
+
"""``None`` when the socket's directory is a real directory owned by this user with no group or
|
|
191
|
+
other access. Otherwise ``(absent, reason)``: an absent directory reads like a server that is not
|
|
192
|
+
up yet, any other failure counts as no endpoint. Checked right before every dial."""
|
|
193
|
+
if os.name == "nt":
|
|
194
|
+
return None
|
|
195
|
+
directory = os.path.dirname(path) or "."
|
|
196
|
+
try:
|
|
197
|
+
st = os.lstat(directory)
|
|
198
|
+
except FileNotFoundError:
|
|
199
|
+
return (True, "the control socket's directory does not exist")
|
|
200
|
+
except OSError as exc:
|
|
201
|
+
return (False, f"the control socket's directory cannot be checked: {exc.strerror}")
|
|
202
|
+
if not stat.S_ISDIR(st.st_mode) or st.st_uid != os.getuid() or (st.st_mode & 0o077):
|
|
203
|
+
return (False, "the control socket's directory is not private to this user")
|
|
204
|
+
return None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _read_line(sock: socket.socket, buf: bytearray, deadline: float, cap: int) -> bytes:
|
|
208
|
+
"""One newline-terminated line, without its newline. A line longer than ``cap`` bytes is refused
|
|
209
|
+
whether or not its newline has arrived, so a whole oversized line in one chunk is refused too."""
|
|
210
|
+
while b"\n" not in buf:
|
|
211
|
+
remaining = deadline - time.monotonic()
|
|
212
|
+
if remaining <= 0:
|
|
213
|
+
raise ExchangeRefused("deadline passed before a full line arrived")
|
|
214
|
+
if len(buf) > cap:
|
|
215
|
+
raise ExchangeRefused("oversized line")
|
|
216
|
+
sock.settimeout(remaining)
|
|
217
|
+
try:
|
|
218
|
+
chunk = sock.recv(65536)
|
|
219
|
+
except socket.timeout as exc:
|
|
220
|
+
raise ExchangeRefused("deadline passed before a full line arrived") from exc
|
|
221
|
+
if not chunk:
|
|
222
|
+
raise ExchangeRefused("the connection closed before a full line arrived")
|
|
223
|
+
buf.extend(chunk)
|
|
224
|
+
line, _, rest = bytes(buf).partition(b"\n")
|
|
225
|
+
if len(line) > cap:
|
|
226
|
+
raise ExchangeRefused("oversized line")
|
|
227
|
+
buf[:] = rest
|
|
228
|
+
return line
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class ClientExchange:
|
|
232
|
+
"""One client exchange on a connected socket. :meth:`open` proves both ends and sends the
|
|
233
|
+
request; :meth:`reply` reads and verifies the one MAC'd reply (control socket only)."""
|
|
234
|
+
|
|
235
|
+
def __init__(self, sock: socket.socket, key: str) -> None:
|
|
236
|
+
self._sock = sock
|
|
237
|
+
self._key = key
|
|
238
|
+
self._nc = _b64(secrets.token_bytes(32))
|
|
239
|
+
self._ns = ""
|
|
240
|
+
self._buf = bytearray()
|
|
241
|
+
|
|
242
|
+
def open(self, request: dict) -> None:
|
|
243
|
+
deadline = time.monotonic() + CLIENT_PROOF_DEADLINE_S
|
|
244
|
+
self._sock.sendall((json.dumps({"v": CONTROL_PROTOCOL_VERSION, "nonce": self._nc}) + "\n").encode("ascii"))
|
|
245
|
+
line = _read_line(self._sock, self._buf, deadline, _MAX_HANDSHAKE_LINE)
|
|
246
|
+
try:
|
|
247
|
+
hello = json.loads(line.decode("utf-8"))
|
|
248
|
+
except ValueError as exc: # UnicodeDecodeError is a ValueError
|
|
249
|
+
raise ExchangeRefused("the server's challenge is not UTF-8 JSON") from exc
|
|
250
|
+
if not isinstance(hello, dict) or not _is_version(hello.get("v")):
|
|
251
|
+
raise ExchangeRefused("the server speaks another control protocol version")
|
|
252
|
+
ns = hello.get("nonce")
|
|
253
|
+
if not isinstance(ns, str) or not _BASE64URL_43.fullmatch(ns):
|
|
254
|
+
raise ExchangeRefused("the server's nonce is malformed")
|
|
255
|
+
if not _mac_matches(hello.get("mac"), _mac(self._key, "server", self._nc, ns)):
|
|
256
|
+
raise ExchangeRefused("the server did not prove it holds the key")
|
|
257
|
+
self._ns = ns
|
|
258
|
+
body = json.dumps(request).encode("utf-8")
|
|
259
|
+
self._sock.sendall(_mac(self._key, "client", self._nc, ns, body).encode("ascii") + b" " + body + b"\n")
|
|
260
|
+
|
|
261
|
+
def reply(self, timeout_s: float) -> str:
|
|
262
|
+
"""The reply's JSON text, once its MAC verifies and it decodes as UTF-8."""
|
|
263
|
+
line = _read_line(self._sock, self._buf, time.monotonic() + timeout_s, _MAC_CHARS + 1 + _MAX_REPLY_JSON)
|
|
264
|
+
mac, sep, body = line.partition(b" ")
|
|
265
|
+
if not sep or len(mac) != _MAC_CHARS or not _mac_matches(mac.decode("latin-1"), _mac(self._key, "reply", self._nc, self._ns, body)):
|
|
266
|
+
raise ExchangeRefused("the reply's MAC does not verify")
|
|
267
|
+
try:
|
|
268
|
+
return body.decode("utf-8")
|
|
269
|
+
except UnicodeDecodeError as exc:
|
|
270
|
+
raise ExchangeRefused("the reply is not UTF-8") from exc
|
package/plugin/cotal/hooks.py
CHANGED
|
@@ -1,56 +1,38 @@
|
|
|
1
1
|
"""Hermes lifecycle hooks → Cotal presence (the relay.ts pattern, in Python).
|
|
2
2
|
|
|
3
3
|
Each hook makes a one-shot connection to connector-core's control socket
|
|
4
|
-
(``COTAL_CONTROL_SOCKET``)
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
descendant of the gateway
|
|
10
|
-
|
|
4
|
+
(``COTAL_CONTROL_SOCKET``) and runs the control exchange (``control_exchange.py``): the hook and
|
|
5
|
+
the sidecar each prove they hold the launch's control key without sending it, then the hook sends
|
|
6
|
+
``{"event": {"hook_event_name": ...}}`` and reads the MAC'd reply, which the TS ``hermesHookHandle``
|
|
7
|
+
produced while turning the event into a presence change. The socket PATH comes from the launch env;
|
|
8
|
+
the KEY and its version come from the launch-material file that env points at
|
|
9
|
+
(``COTAL_LAUNCH_MATERIAL``), so that no descendant of the gateway inherits a control-plane secret.
|
|
10
|
+
Standalone mode mints and exports ``COTAL_CONTROL_KEY`` and ``COTAL_CONTROL_VERSION`` itself, so
|
|
11
|
+
that path is read first and is not deprecated. Before each dial the hook checks that the socket's
|
|
12
|
+
directory is private to this user; a directory that is not counts as no endpoint.
|
|
11
13
|
|
|
12
14
|
Hooks must never block the gateway, so the connection has a short timeout and every socket error is
|
|
13
|
-
swallowed. A
|
|
14
|
-
|
|
15
|
-
does anything, so it warns once on stderr (the
|
|
15
|
+
swallowed. A key that cannot be resolved, a directory that is not private, or a server that does not
|
|
16
|
+
prove itself is NOT swallowed the same way: each means presence relays silently do nothing, which
|
|
17
|
+
looks exactly like a healthy seat that never does anything, so it warns once on stderr (the
|
|
18
|
+
launcher's log) and then stays quiet.
|
|
16
19
|
|
|
17
20
|
Hermes hook callback signatures vary by version; these take ``*args, **kwargs`` and best-effort
|
|
18
21
|
extract what they need, so a signature change degrades to "no detail" rather than an exception.
|
|
19
22
|
"""
|
|
20
23
|
from __future__ import annotations
|
|
21
24
|
|
|
22
|
-
import json
|
|
23
25
|
import os
|
|
24
26
|
import socket
|
|
25
27
|
import sys
|
|
26
28
|
from typing import Any
|
|
27
29
|
|
|
30
|
+
from .control_exchange import ClientExchange, ControlConfigError, ExchangeRefused, control_key, socket_dir_problem
|
|
31
|
+
|
|
28
32
|
_TIMEOUT_S = 2.0
|
|
29
33
|
_warned = False
|
|
30
34
|
|
|
31
35
|
|
|
32
|
-
def _material_token() -> str | None:
|
|
33
|
-
"""The control token out of this launch's material file, or ``None``.
|
|
34
|
-
|
|
35
|
-
Refuses a file other local users can read, for the same reason the TypeScript reader does: a
|
|
36
|
-
material file readable beyond its owner is the disclosure the file carrier exists to prevent.
|
|
37
|
-
Every failure here returns ``None`` and lets the caller warn, because a hook is not allowed to
|
|
38
|
-
raise into the gateway.
|
|
39
|
-
"""
|
|
40
|
-
path = os.environ.get("COTAL_LAUNCH_MATERIAL")
|
|
41
|
-
if not path:
|
|
42
|
-
return None
|
|
43
|
-
try:
|
|
44
|
-
if os.name != "nt" and (os.stat(path).st_mode & 0o077):
|
|
45
|
-
return None
|
|
46
|
-
with open(path, encoding="utf-8") as fh:
|
|
47
|
-
material = json.load(fh)
|
|
48
|
-
except (OSError, ValueError):
|
|
49
|
-
return None
|
|
50
|
-
token = material.get("controlToken") if isinstance(material, dict) else None
|
|
51
|
-
return token if isinstance(token, str) and token else None
|
|
52
|
-
|
|
53
|
-
|
|
54
36
|
def _warn_once(message: str) -> None:
|
|
55
37
|
global _warned
|
|
56
38
|
if _warned:
|
|
@@ -64,28 +46,41 @@ def relay(event_name: str, **fields: Any) -> None:
|
|
|
64
46
|
path = os.environ.get("COTAL_CONTROL_SOCKET")
|
|
65
47
|
if not path:
|
|
66
48
|
return # not a Cotal-managed gateway at all; nothing to relay to
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
49
|
+
try:
|
|
50
|
+
key = control_key()
|
|
51
|
+
except ControlConfigError as exc:
|
|
52
|
+
_warn_once(f"{exc} - presence relays are disabled for this session")
|
|
53
|
+
return
|
|
54
|
+
if not key:
|
|
70
55
|
# This is the failure that has no other symptom: the seat joins, the sidecar and the bridge
|
|
71
56
|
# work, and presence never moves off its first value. Say so once rather than never.
|
|
72
57
|
_warn_once(
|
|
73
|
-
"control socket is configured but no control
|
|
74
|
-
"(neither
|
|
58
|
+
"control socket is configured but no control key could be resolved "
|
|
59
|
+
"(neither COTAL_CONTROL_KEY nor COTAL_LAUNCH_MATERIAL carries one) - "
|
|
75
60
|
"presence relays are disabled for this session"
|
|
76
61
|
)
|
|
77
62
|
return
|
|
78
|
-
|
|
63
|
+
problem = socket_dir_problem(path)
|
|
64
|
+
if problem:
|
|
65
|
+
absent, reason = problem
|
|
66
|
+
if not absent:
|
|
67
|
+
_warn_once(f"{reason}, so the hook connected to nothing - presence relays are disabled for this session")
|
|
68
|
+
return
|
|
79
69
|
try:
|
|
80
70
|
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
81
|
-
s.settimeout(_TIMEOUT_S)
|
|
82
|
-
s.connect(path)
|
|
83
|
-
s.sendall((json.dumps(payload) + "\n").encode())
|
|
84
71
|
try:
|
|
85
|
-
s.
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
72
|
+
s.settimeout(_TIMEOUT_S)
|
|
73
|
+
s.connect(path)
|
|
74
|
+
exchange = ClientExchange(s, key)
|
|
75
|
+
exchange.open({"event": {"hook_event_name": event_name, **fields}})
|
|
76
|
+
try:
|
|
77
|
+
exchange.reply(_TIMEOUT_S) # verified and discarded: the event is what mattered
|
|
78
|
+
except (OSError, ExchangeRefused):
|
|
79
|
+
pass
|
|
80
|
+
finally:
|
|
81
|
+
s.close()
|
|
82
|
+
except ExchangeRefused:
|
|
83
|
+
_warn_once("the control socket did not prove it holds this session's key, so nothing was relayed")
|
|
89
84
|
except OSError:
|
|
90
85
|
pass
|
|
91
86
|
|