-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaip_client.py
More file actions
340 lines (268 loc) · 10.1 KB
/
aip_client.py
File metadata and controls
340 lines (268 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
"""
AIP Client - Simple Python client for Agent Identity Protocol.
Usage:
from aip_client import AIPClient
# Register a new agent
client = AIPClient.register("moltbook", "my_agent")
# Or load existing credentials
client = AIPClient.from_file("aip_credentials.json")
# Prove your identity
signature = client.sign_challenge(challenge)
# Verify another agent
is_valid = client.verify(other_did, challenge, signature)
# Vouch for someone
vouch_id = client.vouch(other_did, scope="CODE_SIGNING")
"""
import json
import base64
import hashlib
import requests
from typing import Optional, Dict, Any, Tuple
from pathlib import Path
class AIPClient:
"""Client for interacting with AIP service."""
DEFAULT_SERVICE = "https://aip-service.fly.dev"
def __init__(
self,
did: str,
public_key: str,
private_key: str,
service_url: str = DEFAULT_SERVICE
):
self.did = did
self.public_key = public_key
self.private_key = private_key
self.service_url = service_url.rstrip("/")
self._signing_key = None
@classmethod
def register(
cls,
platform: str,
platform_id: str,
service_url: str = DEFAULT_SERVICE
) -> "AIPClient":
"""
Register a new agent with AIP.
Generates an Ed25519 keypair client-side and registers the DID.
Args:
platform: Platform name (e.g., "moltbook", "github")
platform_id: Your username on that platform
service_url: AIP service URL (default: production)
Returns:
AIPClient instance with credentials
Raises:
AIPError: If registration fails
"""
try:
from nacl.signing import SigningKey
except ImportError:
raise AIPError("PyNaCl required for registration: pip install pynacl")
# Generate Ed25519 keypair client-side
signing_key = SigningKey.generate()
verify_key = signing_key.verify_key
private_key_b64 = base64.b64encode(signing_key.encode()).decode()
public_key_b64 = base64.b64encode(verify_key.encode()).decode()
# Derive DID from public key (sha256 of pubkey bytes, first 32 hex chars)
key_hash = hashlib.sha256(verify_key.encode()).hexdigest()[:32]
did = f"did:aip:{key_hash}"
response = requests.post(
f"{service_url}/register",
json={
"did": did,
"public_key": public_key_b64,
"platform": platform,
"username": platform_id,
}
)
if response.status_code != 200:
raise AIPError(f"Registration failed: {response.text}")
return cls(
did=did,
public_key=public_key_b64,
private_key=private_key_b64,
service_url=service_url
)
@classmethod
def from_file(cls, path: str, service_url: str = DEFAULT_SERVICE) -> "AIPClient":
"""Load credentials from a JSON file."""
with open(path) as f:
data = json.load(f)
return cls(
did=data["did"],
public_key=data["public_key"],
private_key=data["private_key"],
service_url=service_url
)
def save(self, path: str) -> None:
"""Save credentials to a JSON file."""
with open(path, "w") as f:
json.dump({
"did": self.did,
"public_key": self.public_key,
"private_key": self.private_key
}, f, indent=2)
def _get_signing_key(self):
"""Get Ed25519 signing key from private key."""
if self._signing_key is None:
private_bytes = base64.b64decode(self.private_key)
# Try different crypto libraries
try:
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
self._signing_key = Ed25519PrivateKey.from_private_bytes(private_bytes[:32])
self._crypto_lib = "cryptography"
except ImportError:
try:
import nacl.signing
self._signing_key = nacl.signing.SigningKey(private_bytes[:32])
self._crypto_lib = "nacl"
except ImportError:
raise AIPError("No crypto library available. Install 'cryptography' or 'pynacl'")
return self._signing_key
def sign(self, message: bytes) -> str:
"""Sign a message and return base64 signature."""
key = self._get_signing_key()
if self._crypto_lib == "cryptography":
signature = key.sign(message)
else:
signature = key.sign(message).signature
return base64.b64encode(signature).decode()
def sign_challenge(self, challenge: str) -> str:
"""Sign a challenge string."""
return self.sign(challenge.encode())
def get_challenge(self, target_did: str) -> str:
"""Request a verification challenge for a DID."""
response = requests.post(
f"{self.service_url}/challenge",
params={"did": target_did}
)
if response.status_code != 200:
raise AIPError(f"Challenge request failed: {response.text}")
return response.json()["challenge"]
def verify(self, target_did: str) -> Dict[str, Any]:
"""
Complete verification flow for another agent.
Args:
target_did: DID to verify
Returns:
Verification result dict with 'verified', 'platform', etc.
"""
# Get challenge
challenge = self.get_challenge(target_did)
# The target needs to sign this - this is for demo
# In practice, you'd send the challenge to them
response = requests.post(
f"{self.service_url}/verify_challenge",
json={
"did": target_did,
"challenge": challenge,
"signature": "" # They provide this
}
)
return response.json()
def lookup(self, did: str) -> Dict[str, Any]:
"""Look up a DID's registration info."""
response = requests.get(f"{self.service_url}/lookup/{did}")
if response.status_code != 200:
raise AIPError(f"Lookup failed: {response.text}")
return response.json()
def vouch(
self,
target_did: str,
scope: str = "GENERAL",
statement: Optional[str] = None,
ttl_days: Optional[int] = None
) -> str:
"""
Create a vouch for another agent.
Args:
target_did: DID to vouch for
scope: Trust scope (GENERAL, CODE_SIGNING, FINANCIAL, etc.)
statement: Optional trust statement
ttl_days: Optional expiration in days
Returns:
Vouch ID
"""
# Build payload to sign
payload = f"{self.did}|{target_did}|{scope}|{statement or ''}"
signature = self.sign(payload.encode())
data = {
"voucher_did": self.did,
"target_did": target_did,
"scope": scope,
"statement": statement,
"signature": signature
}
if ttl_days:
data["ttl_days"] = ttl_days
response = requests.post(f"{self.service_url}/vouch", json=data)
if response.status_code != 200:
raise AIPError(f"Vouch failed: {response.text}")
return response.json()["vouch_id"]
def get_trust_path(
self,
target_did: str,
scope: Optional[str] = None,
max_depth: int = 5
) -> Dict[str, Any]:
"""
Find trust path to another agent.
Returns path info including trust_score (decays with hops).
"""
params = {
"source_did": self.did,
"target_did": target_did,
"max_depth": max_depth
}
if scope:
params["scope"] = scope
response = requests.get(f"{self.service_url}/trust-path", params=params)
if response.status_code != 200:
raise AIPError(f"Trust path lookup failed: {response.text}")
return response.json()
def get_certificate(self, vouch_id: str) -> Dict[str, Any]:
"""Get a portable vouch certificate for offline verification."""
response = requests.get(f"{self.service_url}/vouch/certificate/{vouch_id}")
if response.status_code != 200:
raise AIPError(f"Certificate fetch failed: {response.text}")
return response.json()
def get_trust(self, did: str, scope: Optional[str] = None) -> Dict[str, Any]:
"""
Quick trust lookup for a DID.
Returns:
- registered: whether DID exists
- vouched_by: list of DIDs that vouch for them
- scopes: what scopes they're trusted for
- vouch_count: total active vouches
Example:
trust = client.get_trust("did:aip:abc123")
if trust["vouch_count"] > 0:
print(f"Vouched by: {trust['vouched_by']}")
"""
params = {}
if scope:
params["scope"] = scope
response = requests.get(f"{self.service_url}/trust/{did}", params=params)
if response.status_code != 200:
raise AIPError(f"Trust lookup failed: {response.text}")
return response.json()
def is_trusted(self, did: str, scope: Optional[str] = None) -> bool:
"""
Simple check: does this DID have any vouches?
Args:
did: DID to check
scope: Optional scope filter
Returns:
True if DID is registered and has at least one vouch
"""
trust = self.get_trust(did, scope)
return trust.get("registered", False) and trust.get("vouch_count", 0) > 0
class AIPError(Exception):
"""Error from AIP operations."""
pass
# Convenience functions
def register(platform: str, platform_id: str) -> AIPClient:
"""Register a new agent."""
return AIPClient.register(platform, platform_id)
def load(path: str) -> AIPClient:
"""Load credentials from file."""
return AIPClient.from_file(path)