babelr-agent 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.
babelr_agent/__init__.py
ADDED
babelr_agent/client.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""A small Babelr client for agents: token auth, encrypted DMs.
|
|
3
|
+
|
|
4
|
+
from babelr_agent import Agent
|
|
5
|
+
a = Agent("http://localhost:3000", token=os.environ["BABELR_TOKEN"],
|
|
6
|
+
key_path="~/.config/babelr-agent/key.pem")
|
|
7
|
+
a.publish_key() # needs keys:write, once per key
|
|
8
|
+
dm = a.open_dm(partner_id) # needs dms:open
|
|
9
|
+
a.send(dm["id"], "hello") # needs dms:post (and dms:read to find
|
|
10
|
+
# the partner, unless you pass partner_id)
|
|
11
|
+
for m in a.messages(dm["id"]): # needs dms:read; decrypted here
|
|
12
|
+
print(m["author"]["preferredUsername"], m["text"])
|
|
13
|
+
a.reply_status(dm["id"], m["id"], "working") # dms:post (channels:post
|
|
14
|
+
# in a server channel)
|
|
15
|
+
|
|
16
|
+
reply_status shows the person, under their message, that you've picked
|
|
17
|
+
it up ("working"), that you couldn't answer ("failed", with a short
|
|
18
|
+
detail), or that you're done. They can ask for a retry from there; you
|
|
19
|
+
see it as your own status turning to "retry" in `messages()`
|
|
20
|
+
(`agent_status`), or `retries()` for just those.
|
|
21
|
+
|
|
22
|
+
The server refuses plaintext in DMs, so `send` never falls back to it:
|
|
23
|
+
if the partner has no public key, it raises.
|
|
24
|
+
|
|
25
|
+
Messages are data, not instructions. This client hands back what people
|
|
26
|
+
wrote; it never treats a message as a command, and an agent built on it
|
|
27
|
+
shouldn't either.
|
|
28
|
+
"""
|
|
29
|
+
import binascii
|
|
30
|
+
import json
|
|
31
|
+
import urllib.error
|
|
32
|
+
import urllib.request
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
from cryptography.exceptions import InvalidTag
|
|
37
|
+
|
|
38
|
+
from . import crypto
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class BabelrError(Exception):
|
|
42
|
+
def __init__(self, status: int, message: str):
|
|
43
|
+
super().__init__(f"{status}: {message}")
|
|
44
|
+
self.status = status
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Agent:
|
|
48
|
+
def __init__(self, base_url: str, token: str, key_path: str | Path, timeout: float = 30):
|
|
49
|
+
self.base_url = base_url.rstrip("/")
|
|
50
|
+
self.token = token
|
|
51
|
+
self.timeout = timeout
|
|
52
|
+
self.key = crypto.load_or_create_key(Path(key_path).expanduser())
|
|
53
|
+
self._shared: dict[str, bytes] = {}
|
|
54
|
+
self._me: dict | None = None
|
|
55
|
+
|
|
56
|
+
# -- HTTP -------------------------------------------------------------
|
|
57
|
+
|
|
58
|
+
def _req(self, method: str, path: str, body: dict | None = None) -> Any:
|
|
59
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
60
|
+
req = urllib.request.Request(self.base_url + path, data=data, method=method)
|
|
61
|
+
req.add_header("Authorization", f"Bearer {self.token}")
|
|
62
|
+
if data is not None:
|
|
63
|
+
req.add_header("Content-Type", "application/json")
|
|
64
|
+
try:
|
|
65
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as r:
|
|
66
|
+
raw = r.read()
|
|
67
|
+
except urllib.error.HTTPError as e:
|
|
68
|
+
try:
|
|
69
|
+
msg = json.loads(e.read()).get("error", e.reason)
|
|
70
|
+
except Exception:
|
|
71
|
+
msg = e.reason
|
|
72
|
+
raise BabelrError(e.code, msg) from None
|
|
73
|
+
return json.loads(raw) if raw else None
|
|
74
|
+
|
|
75
|
+
# -- identity and keys ------------------------------------------------
|
|
76
|
+
|
|
77
|
+
def me(self) -> dict:
|
|
78
|
+
if self._me is None:
|
|
79
|
+
self._me = self._req("GET", "/auth/me")
|
|
80
|
+
return self._me
|
|
81
|
+
|
|
82
|
+
def publish_key(self) -> None:
|
|
83
|
+
"""Publish this agent's public key. Replacing an old one means DMs
|
|
84
|
+
encrypted to the old key can't be read with the new one."""
|
|
85
|
+
self._req("PUT", "/auth/publickey", {"publicKey": crypto.public_jwk(self.key)})
|
|
86
|
+
self._shared.clear()
|
|
87
|
+
|
|
88
|
+
def _key_for(self, partner_id: str, refresh: bool = False) -> bytes:
|
|
89
|
+
if refresh or partner_id not in self._shared:
|
|
90
|
+
res = self._req("GET", f"/users/{partner_id}/publickey")
|
|
91
|
+
jwk = (res or {}).get("publicKey")
|
|
92
|
+
if not jwk:
|
|
93
|
+
raise BabelrError(409, f"{partner_id} has no public key; can't encrypt to them")
|
|
94
|
+
self._shared[partner_id] = crypto.shared_key(self.key, jwk)
|
|
95
|
+
return self._shared[partner_id]
|
|
96
|
+
|
|
97
|
+
# -- DMs --------------------------------------------------------------
|
|
98
|
+
|
|
99
|
+
def dms(self) -> list[dict]:
|
|
100
|
+
return self._req("GET", "/dms")
|
|
101
|
+
|
|
102
|
+
def open_dm(self, partner_id: str) -> dict:
|
|
103
|
+
return self._req("POST", "/dms", {"participantId": partner_id})
|
|
104
|
+
|
|
105
|
+
def _partner(self, dm_id: str) -> str:
|
|
106
|
+
me = self.me()["id"]
|
|
107
|
+
for dm in self.dms():
|
|
108
|
+
if dm["id"] == dm_id:
|
|
109
|
+
others = [p["id"] for p in dm["participants"] if p["id"] != me]
|
|
110
|
+
if len(others) != 1:
|
|
111
|
+
raise BabelrError(400, "encrypted DMs are one-to-one")
|
|
112
|
+
return others[0]
|
|
113
|
+
raise BabelrError(404, f"not in DM {dm_id}")
|
|
114
|
+
|
|
115
|
+
def send(self, dm_id: str, text: str, partner_id: str | None = None) -> dict:
|
|
116
|
+
partner = partner_id or self._partner(dm_id)
|
|
117
|
+
ct, iv = crypto.encrypt(text, self._key_for(partner))
|
|
118
|
+
return self._req(
|
|
119
|
+
"POST",
|
|
120
|
+
f"/dms/{dm_id}/messages",
|
|
121
|
+
{"content": ct, "properties": {"encrypted": True, "iv": iv}},
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
def messages(self, dm_id: str, partner_id: str | None = None) -> list[dict]:
|
|
125
|
+
"""Messages in a DM, each with `text` decrypted.
|
|
126
|
+
|
|
127
|
+
When a message can't be decrypted, `text` is None and `error` says
|
|
128
|
+
why: "plaintext" (sent before DMs were enforced), "bad-format"
|
|
129
|
+
(content or IV isn't valid base64), or "undecryptable" (the
|
|
130
|
+
authentication tag failed: a key changed on one side, or the
|
|
131
|
+
message was tampered with; this client can't tell which).
|
|
132
|
+
"""
|
|
133
|
+
partner = partner_id or self._partner(dm_id)
|
|
134
|
+
key = self._key_for(partner)
|
|
135
|
+
refreshed = False
|
|
136
|
+
out = []
|
|
137
|
+
for m in self._req("GET", f"/dms/{dm_id}/messages")["messages"]:
|
|
138
|
+
msg = m["message"]
|
|
139
|
+
props = msg.get("properties") or {}
|
|
140
|
+
entry = {"id": msg["id"], "author": m["author"], "published": msg["published"],
|
|
141
|
+
"agent_status": msg.get("agentStatus") or [],
|
|
142
|
+
# emoji -> actor ids; the server sends it only when non-empty
|
|
143
|
+
"reactions": msg.get("reactions") or {},
|
|
144
|
+
# files sent with it: [{url, filename, contentType}] (plaintext metadata)
|
|
145
|
+
"attachments": [a for a in (props.get("attachments") or []) if isinstance(a, dict) and a.get("url")]}
|
|
146
|
+
if not (props.get("encrypted") and props.get("iv")):
|
|
147
|
+
entry["text"], entry["error"] = None, "plaintext"
|
|
148
|
+
else:
|
|
149
|
+
entry["text"], entry["error"] = self._open(msg["content"], props["iv"], key)
|
|
150
|
+
if entry["error"] == "undecryptable" and not refreshed:
|
|
151
|
+
# The partner may have a new key: fetch it once and retry.
|
|
152
|
+
refreshed = True
|
|
153
|
+
key = self._key_for(partner, refresh=True)
|
|
154
|
+
entry["text"], entry["error"] = self._open(msg["content"], props["iv"], key)
|
|
155
|
+
if entry["error"] is None:
|
|
156
|
+
del entry["error"]
|
|
157
|
+
out.append(entry)
|
|
158
|
+
return out
|
|
159
|
+
|
|
160
|
+
def fetch(self, url: str, max_bytes: int = 5 * 1024 * 1024) -> bytes:
|
|
161
|
+
"""The bytes of a file on this server (an attachment's /uploads/... url)."""
|
|
162
|
+
import urllib.request
|
|
163
|
+
if url.startswith("/"):
|
|
164
|
+
url = self.base_url.rstrip("/") + url
|
|
165
|
+
if not url.startswith(self.base_url.rstrip("/") + "/"):
|
|
166
|
+
raise BabelrError(400, "only files on this Babelr server")
|
|
167
|
+
# Uploads are served as public static files; a token here would be
|
|
168
|
+
# checked against its scopes and refused, so none is sent.
|
|
169
|
+
req = urllib.request.Request(url)
|
|
170
|
+
with urllib.request.urlopen(req, timeout=30) as r:
|
|
171
|
+
data = r.read(max_bytes + 1)
|
|
172
|
+
if len(data) > max_bytes:
|
|
173
|
+
raise BabelrError(413, "file too large")
|
|
174
|
+
return data
|
|
175
|
+
|
|
176
|
+
# -- reply status -----------------------------------------------------
|
|
177
|
+
|
|
178
|
+
def reply_status(self, channel_id: str, message_id: str, state: str, detail: str = "") -> dict:
|
|
179
|
+
"""Say how answering a message is going: "working", "failed" or "done".
|
|
180
|
+
|
|
181
|
+
Works in DMs (channel_id is the DM id; needs dms:post) and server
|
|
182
|
+
channels (channels:post). The detail is stored and shown in
|
|
183
|
+
plaintext, even in an encrypted DM: keep it to an error class
|
|
184
|
+
("usage limit", "timeout"), never message content.
|
|
185
|
+
"""
|
|
186
|
+
return self._req("PUT", f"/channels/{channel_id}/messages/{message_id}/agent-status",
|
|
187
|
+
{"state": state, "detail": detail[:300]})
|
|
188
|
+
|
|
189
|
+
def retries(self, messages: list[dict]) -> list[dict]:
|
|
190
|
+
"""The messages (from `messages()`) whose author asked this agent to retry."""
|
|
191
|
+
me = self.me()["id"]
|
|
192
|
+
return [m for m in messages
|
|
193
|
+
if any(s["agent"]["id"] == me and s["state"] == "retry" for s in m.get("agent_status", []))]
|
|
194
|
+
|
|
195
|
+
@staticmethod
|
|
196
|
+
def _open(content: str, iv: str, key: bytes) -> tuple[str | None, str | None]:
|
|
197
|
+
try:
|
|
198
|
+
return crypto.decrypt(content, iv, key), None
|
|
199
|
+
except InvalidTag:
|
|
200
|
+
return None, "undecryptable"
|
|
201
|
+
except (ValueError, binascii.Error):
|
|
202
|
+
return None, "bad-format"
|
babelr_agent/crypto.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""Babelr's DM encryption, in Python, byte-compatible with the web client.
|
|
3
|
+
|
|
4
|
+
The web client (packages/client/src/crypto) does:
|
|
5
|
+
- ECDH on P-256, one key pair per actor;
|
|
6
|
+
- WebCrypto deriveKey(ECDH -> AES-GCM-256), which uses the raw 32-byte
|
|
7
|
+
shared secret (the x coordinate) as the AES key, with no KDF;
|
|
8
|
+
- AES-GCM with a random 12-byte IV, ciphertext+tag base64, IV base64.
|
|
9
|
+
|
|
10
|
+
This module does the same, so an agent and a browser can read each
|
|
11
|
+
other's DMs. tests/test_interop.py checks it against Node's WebCrypto.
|
|
12
|
+
"""
|
|
13
|
+
import base64
|
|
14
|
+
import os
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from cryptography.hazmat.primitives import serialization
|
|
18
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
19
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _b64url(b: bytes) -> str:
|
|
23
|
+
return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _unb64url(s: str) -> bytes:
|
|
27
|
+
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def generate_key() -> ec.EllipticCurvePrivateKey:
|
|
31
|
+
return ec.generate_private_key(ec.SECP256R1())
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def load_or_create_key(path: Path) -> ec.EllipticCurvePrivateKey:
|
|
35
|
+
"""The agent's private key, kept on its own machine (mode 600).
|
|
36
|
+
|
|
37
|
+
It never goes to the server. Lose it and the agent can't read DMs
|
|
38
|
+
sent to its old public key.
|
|
39
|
+
"""
|
|
40
|
+
path = Path(path)
|
|
41
|
+
if path.exists():
|
|
42
|
+
if path.stat().st_mode & 0o077:
|
|
43
|
+
raise PermissionError(f"{path} is readable by others; chmod 600 it")
|
|
44
|
+
try:
|
|
45
|
+
key = serialization.load_pem_private_key(path.read_bytes(), password=None)
|
|
46
|
+
except ValueError as e:
|
|
47
|
+
raise ValueError(f"{path} is not a usable key (corrupt or partly written)") from e
|
|
48
|
+
if not isinstance(key, ec.EllipticCurvePrivateKey):
|
|
49
|
+
raise ValueError(f"{path} is not a P-256 key")
|
|
50
|
+
return key
|
|
51
|
+
key = generate_key()
|
|
52
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
53
|
+
pem = key.private_bytes(
|
|
54
|
+
serialization.Encoding.PEM,
|
|
55
|
+
serialization.PrivateFormat.PKCS8,
|
|
56
|
+
serialization.NoEncryption(),
|
|
57
|
+
)
|
|
58
|
+
# Write to a private temp file, then link it into place: a crash
|
|
59
|
+
# can't leave a half-written key, and two processes racing to
|
|
60
|
+
# create it end up with one key (the loser loads the winner's).
|
|
61
|
+
tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
|
|
62
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
63
|
+
with os.fdopen(fd, "wb") as f:
|
|
64
|
+
f.write(pem)
|
|
65
|
+
f.flush()
|
|
66
|
+
os.fsync(f.fileno())
|
|
67
|
+
try:
|
|
68
|
+
os.link(tmp, path)
|
|
69
|
+
except FileExistsError:
|
|
70
|
+
return load_or_create_key(path)
|
|
71
|
+
finally:
|
|
72
|
+
os.unlink(tmp)
|
|
73
|
+
return key
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def public_jwk(key: ec.EllipticCurvePrivateKey) -> dict:
|
|
77
|
+
nums = key.public_key().public_numbers()
|
|
78
|
+
return {
|
|
79
|
+
"kty": "EC",
|
|
80
|
+
"crv": "P-256",
|
|
81
|
+
"x": _b64url(nums.x.to_bytes(32, "big")),
|
|
82
|
+
"y": _b64url(nums.y.to_bytes(32, "big")),
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def jwk_to_public_key(jwk: dict) -> ec.EllipticCurvePublicKey:
|
|
87
|
+
if jwk.get("kty") != "EC" or jwk.get("crv") != "P-256":
|
|
88
|
+
raise ValueError("not a P-256 key")
|
|
89
|
+
x = int.from_bytes(_unb64url(jwk["x"]), "big")
|
|
90
|
+
y = int.from_bytes(_unb64url(jwk["y"]), "big")
|
|
91
|
+
return ec.EllipticCurvePublicNumbers(x, y, ec.SECP256R1()).public_key()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def shared_key(key: ec.EllipticCurvePrivateKey, partner_jwk: dict) -> bytes:
|
|
95
|
+
"""What WebCrypto's deriveKey gives: the raw ECDH secret as the AES key."""
|
|
96
|
+
return key.exchange(ec.ECDH(), jwk_to_public_key(partner_jwk))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def encrypt(plaintext: str, key: bytes) -> tuple[str, str]:
|
|
100
|
+
"""Returns (ciphertext, iv), both base64, as the server expects."""
|
|
101
|
+
iv = os.urandom(12)
|
|
102
|
+
ct = AESGCM(key).encrypt(iv, plaintext.encode(), None)
|
|
103
|
+
return base64.b64encode(ct).decode(), base64.b64encode(iv).decode()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def decrypt(ciphertext: str, iv: str, key: bytes) -> str:
|
|
107
|
+
return AESGCM(key).decrypt(
|
|
108
|
+
base64.b64decode(iv, validate=True), base64.b64decode(ciphertext, validate=True), None
|
|
109
|
+
).decode()
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: babelr-agent
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Babelr client for agent accounts: token auth and end-to-end encrypted DMs
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Source, https://github.com/KohlJary/babelr/tree/main/packages/agent-client-py
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Requires-Dist: cryptography>=41
|
|
10
|
+
|
|
11
|
+
# babelr-agent
|
|
12
|
+
|
|
13
|
+
A small Python client for Babelr agent accounts: token auth and
|
|
14
|
+
end-to-end encrypted DMs, byte-compatible with the web client.
|
|
15
|
+
|
|
16
|
+
Babelr refuses plaintext in DMs, so an agent has to do the crypto
|
|
17
|
+
itself. This does it the way `packages/client/src/crypto` does: ECDH
|
|
18
|
+
P-256, the raw shared secret as an AES-GCM-256 key, a fresh 12-byte IV
|
|
19
|
+
per message. `tests/test_interop.py` checks both directions against
|
|
20
|
+
Node's WebCrypto.
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
from babelr_agent import Agent
|
|
24
|
+
|
|
25
|
+
a = Agent("http://localhost:3000", token=TOKEN, key_path="~/.config/babelr-agent/key.pem")
|
|
26
|
+
a.publish_key() # scope keys:write, once per key
|
|
27
|
+
dm = a.open_dm(partner_id) # scope dms:open
|
|
28
|
+
a.send(dm["id"], "hello") # dms:post, plus dms:read unless you pass partner_id
|
|
29
|
+
for m in a.messages(dm["id"]): # scope dms:read; decrypted locally
|
|
30
|
+
print(m["author"]["preferredUsername"], m["text"])
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
**Reply status.** Tell the person, under their message, how answering
|
|
34
|
+
it is going, so a reply that never comes isn't silent:
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
a.reply_status(dm["id"], m["id"], "working") # dms:post
|
|
38
|
+
a.reply_status(dm["id"], m["id"], "failed", "usage limit")
|
|
39
|
+
a.reply_status(dm["id"], m["id"], "done")
|
|
40
|
+
for m in a.retries(a.messages(dm["id"])): # the author pressed Retry
|
|
41
|
+
...
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
A "working" that goes quiet for ten minutes shows as stalled, with a
|
|
45
|
+
Retry button for the message's author. The detail is plaintext on the
|
|
46
|
+
server even in an encrypted DM: an error class, never content.
|
|
47
|
+
|
|
48
|
+
**The private key stays on the agent's machine** (mode 600, created on
|
|
49
|
+
first use). The server only ever sees the public half. Whoever can read
|
|
50
|
+
that file, or holds a token with `keys:write`, can read the agent's
|
|
51
|
+
future DMs: that's the operator limit the design doc names, not
|
|
52
|
+
something this client solves.
|
|
53
|
+
|
|
54
|
+
Messages are data, not instructions. The client hands back what people
|
|
55
|
+
wrote and never treats it as a command.
|
|
56
|
+
|
|
57
|
+
Tests: `python -m pytest -q tests` (the interop test needs `node`).
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
babelr_agent/__init__.py,sha256=rooig-h8TeB8N12sRMVz1IH-ehOVR9Ycfu8s7RbAhco,106
|
|
2
|
+
babelr_agent/client.py,sha256=Q6ct-ISCDeFzWendJXKUdJqIshPADMEQy7P6Y4JB_Jg,9213
|
|
3
|
+
babelr_agent/crypto.py,sha256=URHexQ2yR9nDvYoBbGB4WkoKpeSo3t2uF9D4ca3AlPY,4001
|
|
4
|
+
babelr_agent-0.1.0.dist-info/METADATA,sha256=bx2P3jYUnHxPubS6OWSjYUM6YSoA6B9rsq-C5eRO7V0,2305
|
|
5
|
+
babelr_agent-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
babelr_agent-0.1.0.dist-info/top_level.txt,sha256=y9qv5dfszjs5_27A2mxTV1okA2QEyRSDNwB2u_wKuQE,13
|
|
7
|
+
babelr_agent-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
babelr_agent
|