palisec 0.4.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.
palisec/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ """Palisec: your agent asks before every transaction and sends only on ALLOW.
2
+
3
+ Docs: https://palisec.tech/docs/sdk/python
4
+ """
5
+
6
+ __version__ = "0.4.0"
7
+
8
+ from .client import DEFAULT_BASE_URL, Palisec, Sender, Transport, redact, safe_op_typed_data, urllib_transport # noqa: E402
9
+ from .codes import REASON_CODES, RETRYABLE # noqa: E402
10
+ from .errors import ( # noqa: E402
11
+ PalisecApprovalError,
12
+ PalisecConfigError,
13
+ PalisecDeniedError,
14
+ PalisecError,
15
+ PalisecTimeoutError,
16
+ )
17
+ from .models import SUPPORTED_CHAINS, Check, Intent, LogEvent, Operation, SendResult # noqa: E402
18
+ from . import webhooks # noqa: E402
19
+
20
+ __all__ = [
21
+ "DEFAULT_BASE_URL",
22
+ "REASON_CODES",
23
+ "RETRYABLE",
24
+ "SUPPORTED_CHAINS",
25
+ "Check",
26
+ "Intent",
27
+ "LogEvent",
28
+ "Operation",
29
+ "Palisec",
30
+ "PalisecApprovalError",
31
+ "PalisecConfigError",
32
+ "PalisecDeniedError",
33
+ "PalisecError",
34
+ "PalisecTimeoutError",
35
+ "Sender",
36
+ "SendResult",
37
+ "Transport",
38
+ "redact",
39
+ "safe_op_typed_data",
40
+ "urllib_transport",
41
+ "webhooks",
42
+ "__version__",
43
+ ]
palisec/client.py ADDED
@@ -0,0 +1,492 @@
1
+ """Async client for the Palisec authorization API.
2
+
3
+ The SDK holds no security logic of its own: every decision is made and recorded server-side.
4
+ ``send_transaction`` enforces that decision in your process by sending only on ALLOW.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import inspect
11
+ import json
12
+ import logging
13
+ import random
14
+ import re
15
+ import time
16
+ import urllib.error
17
+ import urllib.parse
18
+ import urllib.request
19
+ import uuid
20
+ from typing import Any, Awaitable, Callable, Optional, Protocol, Tuple, Union
21
+
22
+ from . import __version__
23
+ from .codes import RETRYABLE
24
+ from .errors import (
25
+ PalisecApprovalError,
26
+ PalisecConfigError,
27
+ PalisecDeniedError,
28
+ PalisecError,
29
+ PalisecTimeoutError,
30
+ )
31
+ from .models import SUPPORTED_CHAINS, Intent, LogEvent, Operation, SendResult
32
+
33
+ _KEY = re.compile(r"^ps_(live|test)_[0-9a-f]{48}$")
34
+ _KEY_ANYWHERE = re.compile(r"ps_(?:live|test)_[0-9a-f]{8,}")
35
+ _ADDRESS = re.compile(r"^0x[0-9a-fA-F]{40}$")
36
+ _HEX = re.compile(r"^0x([0-9a-fA-F]{2})*$")
37
+ _OP_ID = re.compile(r"^[0-9a-fA-F-]{36}$")
38
+ _LOCAL = re.compile(r"^http://(localhost|127\.0\.0\.1)(:\d+)?/")
39
+ _RETRY_STATUS = frozenset({429, 502, 503, 504})
40
+ DEFAULT_BASE_URL = "https://palisec.tech/api/v1"
41
+
42
+ _log = logging.getLogger("palisec")
43
+
44
+ #: (method, url, headers, body, timeout_seconds) -> (status, text). Raise TimeoutError on timeout
45
+ #: and OSError on network failure. The default uses urllib in a worker thread.
46
+ Transport = Callable[[str, str, dict, Optional[bytes], float], Awaitable[Tuple[int, str]]]
47
+
48
+
49
+ def redact(text: str) -> str:
50
+ """Masks Palisec API keys anywhere in a string, for logs and error reports."""
51
+ return _KEY_ANYWHERE.sub(lambda m: f"{m.group(0)[:12]}...[redacted]", text)
52
+
53
+
54
+ class Sender(Protocol):
55
+ """What ``send_transaction`` needs from a wallet. ``palisec.web3.Web3Sender`` adapts web3.py.
56
+
57
+ ``tx`` has ``to``, ``value`` (int wei), ``data`` (hex), ``gas`` (int) and ``chainId``.
58
+ Returns the transaction hash.
59
+ """
60
+
61
+ address: str
62
+
63
+ def send_transaction(self, tx: dict) -> Union[str, Awaitable[str]]: ...
64
+
65
+
66
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
67
+ # Never follow redirects: the Authorization header must not travel to another URL.
68
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[override]
69
+ return None
70
+
71
+
72
+ _opener = urllib.request.build_opener(_NoRedirect)
73
+
74
+
75
+ async def urllib_transport(method: str, url: str, headers: dict, body: Optional[bytes], timeout: float) -> Tuple[int, str]:
76
+ def go() -> Tuple[int, str]:
77
+ req = urllib.request.Request(url, data=body, method=method, headers=headers)
78
+ try:
79
+ with _opener.open(req, timeout=timeout) as res:
80
+ return res.status, res.read().decode("utf-8", "replace")
81
+ except urllib.error.HTTPError as e:
82
+ return e.code, e.read().decode("utf-8", "replace")
83
+ except urllib.error.URLError as e:
84
+ if isinstance(e.reason, TimeoutError) or "timed out" in str(e.reason):
85
+ raise TimeoutError(str(e.reason)) from None
86
+ raise ConnectionError(str(e.reason)) from None
87
+
88
+ try:
89
+ return await asyncio.wait_for(asyncio.to_thread(go), timeout + 1)
90
+ except asyncio.TimeoutError:
91
+ raise TimeoutError("request timed out") from None
92
+
93
+
94
+ async def _maybe_await(value: Any) -> Any:
95
+ return await value if inspect.isawaitable(value) else value
96
+
97
+
98
+ class Palisec:
99
+ """Async client. Use as ``async with Palisec(api_key=...) as palisec:`` or call ``aclose`` (a no-op today).
100
+
101
+ Keep the API key server-side. ``max_retries`` applies to network errors, 429 and 5xx, and only
102
+ on calls that are safe to repeat.
103
+ """
104
+
105
+ def __init__(
106
+ self,
107
+ api_key: str,
108
+ *,
109
+ chain_id: Optional[int] = None,
110
+ base_url: str = DEFAULT_BASE_URL,
111
+ timeout: float = 15.0,
112
+ max_retries: int = 2,
113
+ logger: Optional[Callable[[LogEvent], None]] = None,
114
+ transport: Optional[Transport] = None,
115
+ ) -> None:
116
+ match = _KEY.match(api_key) if isinstance(api_key, str) else None
117
+ if not match:
118
+ raise PalisecConfigError("api_key must be a Palisec agent key (ps_live_ or ps_test_ followed by 48 hex characters)")
119
+ # The key decides the network, so a mainnet key is never pointed at testnet by accident, or the reverse.
120
+ key_chain = 4663 if match.group(1) == "live" else 46630
121
+ if chain_id is None:
122
+ chain_id = key_chain
123
+ if chain_id not in SUPPORTED_CHAINS:
124
+ raise PalisecConfigError(f"chain_id {chain_id} is not supported; supported: {', '.join(map(str, SUPPORTED_CHAINS))}")
125
+ if chain_id != key_chain:
126
+ kind = "mainnet (ps_live_)" if key_chain == 4663 else "testnet (ps_test_)"
127
+ raise PalisecConfigError(f"This is a {kind} key, so chain_id must be {key_chain}, not {chain_id}")
128
+ base = base_url.rstrip("/")
129
+ if not base.startswith("https://") and not _LOCAL.match(base + "/"):
130
+ raise PalisecConfigError("base_url must use HTTPS (plain HTTP is allowed only for localhost)")
131
+ self.chain_id = chain_id
132
+ self._base = base
133
+ self._key = api_key
134
+ self._timeout = float(timeout)
135
+ self._max_retries = max(0, min(int(max_retries), 5))
136
+ self._logger = logger
137
+ self._transport: Transport = transport or urllib_transport
138
+
139
+ def __repr__(self) -> str:
140
+ return f"Palisec(chain_id={self.chain_id}, base_url={self._base!r}, api_key='{self._key[:12]}...')"
141
+
142
+ async def __aenter__(self) -> "Palisec":
143
+ return self
144
+
145
+ async def __aexit__(self, *exc: Any) -> None:
146
+ await self.aclose()
147
+
148
+ async def aclose(self) -> None:
149
+ return None
150
+
151
+ # -- internals -----------------------------------------------------------------------------
152
+
153
+ def _emit(self, event: LogEvent) -> None:
154
+ if self._logger:
155
+ self._logger(event)
156
+ elif _log.isEnabledFor(logging.DEBUG):
157
+ _log.debug("palisec %s", dict(event))
158
+
159
+ def _body(self, intent: Intent) -> dict:
160
+ if not _ADDRESS.match(intent.to or ""):
161
+ raise PalisecConfigError("to must be a 20-byte hex address")
162
+ data = intent.data or "0x"
163
+ if not _HEX.match(data):
164
+ raise PalisecConfigError("data must be 0x-prefixed hex bytes")
165
+ value = int(intent.value)
166
+ if value < 0:
167
+ raise PalisecConfigError("value must not be negative")
168
+ deadline = int(time.time()) + min(max(int(intent.deadline_seconds), 1), 3600)
169
+ return {
170
+ "request_id": intent.request_id or str(uuid.uuid4()),
171
+ "chain_id": self.chain_id,
172
+ "to": intent.to,
173
+ "value_wei": str(value),
174
+ "data": data,
175
+ "gas_limit": intent.gas,
176
+ "deadline": deadline,
177
+ }
178
+
179
+ async def _request(self, method: str, path: str, *, body: Any = None, idempotency_key: Optional[str] = None, retry: bool) -> dict:
180
+ attempts = self._max_retries + 1 if retry else 1
181
+ last: Optional[PalisecError] = None
182
+ for attempt in range(1, attempts + 1):
183
+ started = time.monotonic()
184
+ self._emit({"type": "request", "method": method, "path": path, "attempt": attempt})
185
+ headers = {
186
+ "authorization": f"Bearer {self._key}",
187
+ "accept": "application/json",
188
+ "user-agent": f"palisec-python/{__version__}",
189
+ }
190
+ payload = None
191
+ if body is not None:
192
+ headers["content-type"] = "application/json"
193
+ payload = json.dumps(body).encode()
194
+ if idempotency_key:
195
+ headers["idempotency-key"] = idempotency_key
196
+ try:
197
+ status, text = await self._transport(method, f"{self._base}{path}", headers, payload, self._timeout)
198
+ except TimeoutError:
199
+ last = PalisecTimeoutError(f"{method} {path} timed out after {self._timeout:g} s")
200
+ if not retry:
201
+ raise last from None
202
+ except OSError:
203
+ last = PalisecError(f"Network error calling {method} {path}", "PS_SDK_NETWORK", None, None, True)
204
+ if not retry:
205
+ raise last from None
206
+ else:
207
+ try:
208
+ data = json.loads(text) if text else {}
209
+ except ValueError:
210
+ data = {}
211
+ if not isinstance(data, dict):
212
+ data = {}
213
+ err = data.get("error") if isinstance(data.get("error"), dict) else None
214
+ request_id = data.get("request_id")
215
+ event: LogEvent = {
216
+ "type": "response",
217
+ "method": method,
218
+ "path": path,
219
+ "attempt": attempt,
220
+ "status": status,
221
+ "request_id": request_id,
222
+ "duration_ms": int((time.monotonic() - started) * 1000),
223
+ }
224
+ if err and err.get("code"):
225
+ event["code"] = err["code"]
226
+ self._emit(event)
227
+ if 200 <= status < 300:
228
+ return data
229
+ code = (err or {}).get("code") or ("PS_AUTH_001" if status == 401 else "PS_STATE_001")
230
+ retryable = (err or {}).get("retryable")
231
+ if retryable is None:
232
+ retryable = RETRYABLE.get(code, status in _RETRY_STATUS)
233
+ last = PalisecError(redact((err or {}).get("message") or f"HTTP {status}"), code, status, request_id, bool(retryable))
234
+ if not (retry and status in _RETRY_STATUS):
235
+ raise last
236
+ if attempt < attempts:
237
+ wait = min(0.25 * 2 ** (attempt - 1), 4.0) + random.random() / 10
238
+ self._emit({"type": "retry", "method": method, "path": path, "attempt": attempt, "duration_ms": int(wait * 1000)})
239
+ await asyncio.sleep(wait)
240
+ assert last is not None
241
+ self._emit({"type": "error", "method": method, "path": path, "attempt": attempts, "code": last.code})
242
+ raise last
243
+
244
+ @staticmethod
245
+ def _intent(intent: Optional[Intent], kwargs: dict) -> Intent:
246
+ if intent is not None and kwargs:
247
+ raise PalisecConfigError("pass an Intent or keyword arguments, not both")
248
+ return intent if intent is not None else Intent(**kwargs)
249
+
250
+ # -- API -----------------------------------------------------------------------------------
251
+
252
+ async def authorize(self, intent: Optional[Intent] = None, **kwargs: Any) -> Operation:
253
+ """Asks whether this transaction may be sent and records the decision with its budget
254
+ reservation. Returns ALLOW, DENY or REQUIRES_HUMAN_SIGNATURE; does not raise on DENY.
255
+
256
+ Safe to retry: the request ID is the idempotency key, so a retry returns the original
257
+ decision instead of a second one.
258
+ """
259
+ body = self._body(self._intent(intent, kwargs))
260
+ raw = await self._request("POST", "/operations", body=body, idempotency_key=body["request_id"], retry=True)
261
+ return Operation.from_api(raw)
262
+
263
+ async def evaluate(self, intent: Optional[Intent] = None, **kwargs: Any) -> Operation:
264
+ """Dry run: the same evaluation against live state, reserving and recording nothing."""
265
+ body = self._body(self._intent(intent, kwargs))
266
+ return Operation.from_api(await self._request("POST", "/authorizations/evaluate", body=body, retry=True))
267
+
268
+ async def get_operation(self, operation_id: str) -> Operation:
269
+ """Reads one of this agent's operations."""
270
+ if not _OP_ID.match(operation_id or ""):
271
+ raise PalisecConfigError("operation_id must be an operation's id")
272
+ return Operation.from_api(await self._request("GET", f"/operations/{operation_id}", retry=True))
273
+
274
+ async def who_am_i(self) -> dict:
275
+ """The integration this key belongs to: agent, protected account, chain, scopes and bound policy."""
276
+ return await self._request("GET", "/integration", retry=True)
277
+
278
+ async def get_policy(self) -> dict:
279
+ """The exact active policy version this agent is evaluated against (scope policy:read)."""
280
+ return await self._request("GET", "/integration/policy", retry=True)
281
+
282
+ async def list_audit_events(self, *, limit: int = 50, before: Optional[str] = None) -> dict:
283
+ """Audit events this agent caused, newest first (scope audit:read). Returns events and next_before."""
284
+ q = urllib.parse.urlencode({"limit": max(1, min(int(limit), 200)), **({"before": before} if before else {})})
285
+ return await self._request("GET", f"/integration/audit-events?{q}", retry=True)
286
+
287
+ async def list_operations(self, *, limit: int = 20, before: Optional[str] = None, decision: Optional[str] = None) -> dict:
288
+ """This agent's own operations, newest first (scope operations:read)."""
289
+ q = urllib.parse.urlencode({"limit": max(1, min(int(limit), 100)), **({"before": before} if before else {}), **({"decision": decision} if decision else {})})
290
+ raw = await self._request("GET", f"/integration/operations?{q}", retry=True)
291
+ return {"operations": [Operation.from_api(o) for o in raw.get("operations", [])], "next_before": raw.get("next_before")}
292
+
293
+ @property
294
+ def transactions(self) -> "_Transactions":
295
+ """2.0 naming: `propose` is `authorize` (records a decision), `evaluate` is the dry run."""
296
+ return _Transactions(self)
297
+
298
+ async def cancel(self, operation_id: str) -> Operation:
299
+ """Withdraws an operation still waiting for approval. Never retried automatically.
300
+ Authorized operations keep their budget until they expire."""
301
+ if not _OP_ID.match(operation_id or ""):
302
+ raise PalisecConfigError("operation_id must be an operation's id")
303
+ return Operation.from_api(await self._request("POST", f"/operations/{operation_id}/cancel", retry=False))
304
+
305
+ async def wait_for_approval(self, operation_id: str, *, timeout: float = 900.0, interval: float = 5.0) -> Operation:
306
+ """Waits for an approver's decision on a held operation. Returns the approved operation
307
+ (now carrying an authorization); raises PalisecApprovalError if it is rejected, expires or
308
+ is withdrawn, and PalisecTimeoutError if ``timeout`` seconds pass first."""
309
+ until = time.monotonic() + timeout
310
+ interval = max(float(interval), 1.0)
311
+ while True:
312
+ op = await self.get_operation(operation_id)
313
+ if op.state == "approved":
314
+ return op
315
+ if op.state != "pending_approval":
316
+ raise PalisecApprovalError(op)
317
+ if time.monotonic() + interval > until:
318
+ raise PalisecTimeoutError(f"No approval decision for {operation_id} within {timeout:g} s")
319
+ await asyncio.sleep(interval)
320
+
321
+ async def send_transaction(
322
+ self,
323
+ sender: Sender,
324
+ intent: Optional[Intent] = None,
325
+ *,
326
+ wait_for_approval: bool = False,
327
+ approval_timeout: float = 900.0,
328
+ **kwargs: Any,
329
+ ) -> SendResult:
330
+ """Authorizes, then sends with ``sender`` only if allowed.
331
+
332
+ Raises PalisecDeniedError on DENY (nothing is sent). A held operation is awaited when
333
+ ``wait_for_approval`` is true, otherwise returned unsent with ``hash=None``. The sender
334
+ must be the agent's registered account. This enforces the decision in your process only:
335
+ until the on-chain module ships, a key used outside Palisec can still transact.
336
+ """
337
+ it = self._intent(intent, kwargs)
338
+ if it.request_id is None:
339
+ it = Intent(**{**it.__dict__, "request_id": str(uuid.uuid4())})
340
+ op = await self.authorize(it)
341
+ if op.decision == "DENY":
342
+ raise PalisecDeniedError(op)
343
+ if op.state == "pending_approval":
344
+ if not wait_for_approval:
345
+ return SendResult(operation=op, hash=None)
346
+ assert op.operation_id is not None
347
+ op = await self.wait_for_approval(op.operation_id, timeout=approval_timeout)
348
+ if not op.allowed:
349
+ raise PalisecDeniedError(op)
350
+ if op.expires_at is not None and op.expires_at.timestamp() <= time.time():
351
+ raise PalisecTimeoutError("The authorization expired before sending")
352
+ account = (op.details or {}).get("account")
353
+ sender_address = getattr(sender, "address", None)
354
+ if not isinstance(sender_address, str) or not _ADDRESS.match(sender_address):
355
+ raise PalisecConfigError("The sender has no valid address")
356
+ if isinstance(account, str) and account.lower() != sender_address.lower():
357
+ raise PalisecConfigError(f"The sender {sender_address} is not the agent's registered account {account}")
358
+ tx = {"to": it.to, "value": int(it.value), "data": it.data or "0x", "gas": it.gas, "chainId": self.chain_id}
359
+ tx_hash = await _maybe_await(sender.send_transaction(tx))
360
+ return SendResult(operation=op, hash=str(tx_hash))
361
+
362
+ # ───────── PALISEC smart accounts: on-chain enforcement ─────────
363
+
364
+ async def prepare_execution(self, operation_id: str) -> dict:
365
+ """Builds the one user operation PALISEC will co-sign for an allowed or approved operation.
366
+ Returns ``user_operation``, ``safe_op_hash``, ``max_cost_wei`` and ``valid_until``. Nothing is sent."""
367
+ if not _OP_ID.match(operation_id or ""):
368
+ raise PalisecConfigError("operation_id must be an operation's id")
369
+ return await self._request("POST", f"/operations/{operation_id}/user-operation", retry=True)
370
+
371
+ async def submit_execution(self, operation_id: str, signature: str) -> dict:
372
+ """Sends the agent's signature; PALISEC co-signs once and submits through the bundler. Never retried."""
373
+ sig = signature if signature.startswith("0x") else "0x" + signature
374
+ if not re.fullmatch(r"0x[0-9a-fA-F]{130}", sig):
375
+ raise PalisecConfigError("signature must be 65 bytes of hex")
376
+ await self._request("POST", f"/operations/{operation_id}/submit", body={"signature": sig}, retry=False)
377
+ return await self.get_execution(operation_id)
378
+
379
+ async def get_execution(self, operation_id: str) -> dict:
380
+ """``status`` is not_prepared, prepared, submitted, executed or reverted, with ``transaction_hash`` once known."""
381
+ return await self._request("GET", f"/operations/{operation_id}/execution", retry=True)
382
+
383
+ async def execute_with_smart_account(
384
+ self,
385
+ sign_typed_data: Callable[[dict], Union[str, Awaitable[str]]],
386
+ intent: Optional[Intent] = None,
387
+ *,
388
+ wait_for_approval: bool = False,
389
+ approval_timeout: float = 900.0,
390
+ receipt_timeout: float = 90.0,
391
+ **kwargs: Any,
392
+ ) -> dict:
393
+ """Authorizes, then executes through the agent's PALISEC smart account.
394
+
395
+ ``sign_typed_data`` signs EIP-712 data with the agent's key, for example with eth-account::
396
+
397
+ acct = Account.from_key(agent_key)
398
+ sign = lambda td: acct.sign_typed_data(full_message=td).signature.hex()
399
+
400
+ PALISEC co-signs the same operation and the Safe checks both signatures on chain, so the
401
+ agent's key alone cannot move funds. Raises PalisecDeniedError on DENY. Returns
402
+ ``{"operation": Operation, "execution": dict}``.
403
+ """
404
+ it = self._intent(intent, kwargs)
405
+ if it.request_id is None:
406
+ it = Intent(**{**it.__dict__, "request_id": str(uuid.uuid4())})
407
+ op = await self.authorize(it)
408
+ if op.decision == "DENY":
409
+ raise PalisecDeniedError(op)
410
+ if op.state == "pending_approval":
411
+ if not wait_for_approval:
412
+ return {"operation": op, "execution": {"operation_id": op.operation_id, "status": "not_prepared"}}
413
+ assert op.operation_id is not None
414
+ op = await self.wait_for_approval(op.operation_id, timeout=approval_timeout)
415
+ if not op.allowed or op.operation_id is None:
416
+ raise PalisecDeniedError(op)
417
+ prepared = await self.prepare_execution(op.operation_id)
418
+ signature = await _maybe_await(sign_typed_data(safe_op_typed_data(prepared["user_operation"], self.chain_id)))
419
+ execution = await self.submit_execution(op.operation_id, str(signature))
420
+ until = time.monotonic() + receipt_timeout
421
+ while execution.get("status") == "submitted" and time.monotonic() < until:
422
+ await asyncio.sleep(3.0)
423
+ execution = await self.get_execution(op.operation_id)
424
+ return {"operation": op, "execution": execution}
425
+
426
+
427
+ _SAFE_4337_MODULE = "0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226"
428
+ _ENTRY_POINT_V07 = "0x0000000071727De22E5E9d8BAf0edAc6f37da032"
429
+
430
+
431
+ def safe_op_typed_data(user_operation: dict, chain_id: int) -> dict:
432
+ """The EIP-712 data the agent signs for a prepared user operation, with integers as ints."""
433
+ u = user_operation
434
+ return {
435
+ "domain": {"chainId": chain_id, "verifyingContract": _SAFE_4337_MODULE},
436
+ "types": {
437
+ "EIP712Domain": [{"name": "chainId", "type": "uint256"}, {"name": "verifyingContract", "type": "address"}],
438
+ "SafeOp": [
439
+ {"name": "safe", "type": "address"},
440
+ {"name": "nonce", "type": "uint256"},
441
+ {"name": "initCode", "type": "bytes"},
442
+ {"name": "callData", "type": "bytes"},
443
+ {"name": "verificationGasLimit", "type": "uint128"},
444
+ {"name": "callGasLimit", "type": "uint128"},
445
+ {"name": "preVerificationGas", "type": "uint256"},
446
+ {"name": "maxPriorityFeePerGas", "type": "uint128"},
447
+ {"name": "maxFeePerGas", "type": "uint128"},
448
+ {"name": "paymasterAndData", "type": "bytes"},
449
+ {"name": "validAfter", "type": "uint48"},
450
+ {"name": "validUntil", "type": "uint48"},
451
+ {"name": "entryPoint", "type": "address"},
452
+ ],
453
+ },
454
+ "primaryType": "SafeOp",
455
+ "message": {
456
+ "safe": u["sender"],
457
+ "nonce": int(u["nonce"], 16),
458
+ "initCode": "0x",
459
+ "callData": u["callData"],
460
+ "verificationGasLimit": int(u["verificationGasLimit"], 16),
461
+ "callGasLimit": int(u["callGasLimit"], 16),
462
+ "preVerificationGas": int(u["preVerificationGas"], 16),
463
+ "maxPriorityFeePerGas": int(u["maxPriorityFeePerGas"], 16),
464
+ "maxFeePerGas": int(u["maxFeePerGas"], 16),
465
+ "paymasterAndData": "0x",
466
+ "validAfter": int(u["validAfter"]),
467
+ "validUntil": int(u["validUntil"]),
468
+ "entryPoint": _ENTRY_POINT_V07,
469
+ },
470
+ }
471
+
472
+
473
+ class _Transactions:
474
+ """Aliases grouped under the 2.0 naming. Existing method names keep working."""
475
+
476
+ def __init__(self, client: Palisec) -> None:
477
+ self._c = client
478
+
479
+ async def evaluate(self, intent: Optional[Intent] = None, **kwargs: Any) -> Operation:
480
+ return await self._c.evaluate(intent, **kwargs)
481
+
482
+ async def propose(self, intent: Optional[Intent] = None, **kwargs: Any) -> Operation:
483
+ return await self._c.authorize(intent, **kwargs)
484
+
485
+ async def get(self, operation_id: str) -> Operation:
486
+ return await self._c.get_operation(operation_id)
487
+
488
+ async def wait_for_approval(self, operation_id: str, **kwargs: Any) -> Operation:
489
+ return await self._c.wait_for_approval(operation_id, **kwargs)
490
+
491
+ async def cancel(self, operation_id: str) -> Operation:
492
+ return await self._c.cancel(operation_id)
palisec/codes.py ADDED
@@ -0,0 +1,44 @@
1
+ """Stable reason codes (spec 5.7). Mirrors packages/policy-schema/src/codes.ts; a test keeps them equal."""
2
+
3
+ from __future__ import annotations
4
+
5
+ REASON_CODES: dict[str, str] = {
6
+ "PS_AUTH_001": "Authentication failed",
7
+ "PS_POLICY_001": "No valid active policy",
8
+ "PS_POLICY_002": "Explicit deny rule matched",
9
+ "PS_TARGET_001": "Target contract not allowed",
10
+ "PS_METHOD_001": "Function selector not allowed",
11
+ "PS_BUDGET_001": "Budget limit exceeded",
12
+ "PS_RATE_001": "Rate limit exceeded",
13
+ "PS_LOOP_001": "Repeated intent or calldata detected",
14
+ "PS_REPLAY_001": "Duplicate or expired authorization",
15
+ "PS_ATTEST_001": "Enclave attestation invalid",
16
+ "PS_SIM_001": "Simulation failed",
17
+ "PS_FEE_001": "Fee estimation unavailable or invalid",
18
+ "PS_HUMAN_001": "Human approval required",
19
+ "PS_PAUSED_001": "Agent or account is paused",
20
+ "PS_STATE_001": "Authoritative state unavailable",
21
+ "PS_CHAIN_001": "Chain or bundler unavailable",
22
+ "PS_REQUEST_001": "Request failed schema validation",
23
+ }
24
+
25
+ #: Whether a client may retry the same request after the condition clears.
26
+ RETRYABLE: dict[str, bool] = {
27
+ "PS_AUTH_001": False,
28
+ "PS_POLICY_001": False,
29
+ "PS_POLICY_002": False,
30
+ "PS_TARGET_001": False,
31
+ "PS_METHOD_001": False,
32
+ "PS_BUDGET_001": True,
33
+ "PS_RATE_001": True,
34
+ "PS_LOOP_001": False,
35
+ "PS_REPLAY_001": False,
36
+ "PS_ATTEST_001": True,
37
+ "PS_SIM_001": False,
38
+ "PS_FEE_001": True,
39
+ "PS_HUMAN_001": False,
40
+ "PS_PAUSED_001": True,
41
+ "PS_STATE_001": True,
42
+ "PS_CHAIN_001": True,
43
+ "PS_REQUEST_001": False,
44
+ }
palisec/errors.py ADDED
@@ -0,0 +1,69 @@
1
+ """Typed errors. Match on ``code``, never on the message."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Optional
6
+
7
+ if TYPE_CHECKING:
8
+ from .models import Operation
9
+
10
+
11
+ class PalisecError(Exception):
12
+ """Every failure carries a stable ``code``: a ``PS_`` reason code or ``PS_SDK_CONFIG``,
13
+ ``PS_SDK_TIMEOUT`` or ``PS_SDK_NETWORK``."""
14
+
15
+ def __init__(
16
+ self,
17
+ message: str,
18
+ code: str,
19
+ status: Optional[int] = None,
20
+ request_id: Optional[str] = None,
21
+ retryable: bool = False,
22
+ ) -> None:
23
+ super().__init__(message)
24
+ self.message = message
25
+ self.code = code
26
+ self.status = status
27
+ self.request_id = request_id
28
+ self.retryable = retryable
29
+
30
+ def __repr__(self) -> str:
31
+ return f"{type(self).__name__}(code={self.code!r}, status={self.status!r}, message={self.message!r})"
32
+
33
+
34
+ class PalisecConfigError(PalisecError):
35
+ """The client or wallet is configured in a way that cannot work (bad key, wrong chain, wrong account)."""
36
+
37
+ def __init__(self, message: str) -> None:
38
+ super().__init__(message, "PS_SDK_CONFIG")
39
+
40
+
41
+ class PalisecDeniedError(PalisecError):
42
+ """The policy denied the operation. Nothing was authorized; do not send the transaction."""
43
+
44
+ def __init__(self, operation: "Operation") -> None:
45
+ super().__init__(
46
+ operation.message,
47
+ operation.reason_code or "PS_POLICY_001",
48
+ 200,
49
+ operation.request_id,
50
+ operation.retryable,
51
+ )
52
+ self.operation = operation
53
+
54
+
55
+ class PalisecApprovalError(PalisecError):
56
+ """A held operation ended without approval: rejected, expired or withdrawn."""
57
+
58
+ def __init__(self, operation: "Operation") -> None:
59
+ code = "PS_HUMAN_001" if operation.state == "rejected" else "PS_REPLAY_001"
60
+ super().__init__(f"Approval ended as {operation.state}", code, 200, operation.request_id, False)
61
+ self.operation = operation
62
+
63
+
64
+ class PalisecTimeoutError(PalisecError):
65
+ """The request or the wait did not finish in time. Retrying ``authorize`` with the same
66
+ request ID is safe: it returns the original decision."""
67
+
68
+ def __init__(self, message: str) -> None:
69
+ super().__init__(message, "PS_SDK_TIMEOUT", None, None, True)
palisec/models.py ADDED
@@ -0,0 +1,126 @@
1
+ """Typed models. Integers are Python ints (wei never passes through a float)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime
7
+ from typing import Any, Literal, Optional, TypedDict
8
+
9
+ Decision = Literal["ALLOW", "DENY", "REQUIRES_HUMAN_SIGNATURE"]
10
+ OperationState = Literal[
11
+ "authorized",
12
+ "denied",
13
+ "pending_approval",
14
+ "approved",
15
+ "rejected",
16
+ "cancelled",
17
+ "expired",
18
+ "authorization_expired",
19
+ "not_recorded",
20
+ ]
21
+
22
+ #: Chains this release accepts: Robinhood Chain (4663, real funds, where the deployment enables it) and
23
+ #: Robinhood Chain Testnet (46630). A ps_live_ key is a mainnet agent's; a ps_test_ key, testnet's.
24
+ SUPPORTED_CHAINS: tuple[int, ...] = (4663, 46630)
25
+ MAINNET = 4663
26
+ TESTNET = 46630
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Intent:
31
+ """A transaction the agent intends to send, described before it is signed.
32
+
33
+ ``gas_limit`` is the gas you will send with; Palisec bounds the fee as gas_limit x gas price.
34
+ Default: 21000 for a plain transfer, 250000 otherwise. ``request_id`` is unique per intended
35
+ transaction and doubles as the idempotency key (default: a random UUID).
36
+ """
37
+
38
+ to: str
39
+ value: int = 0
40
+ data: str = "0x"
41
+ gas_limit: Optional[int] = None
42
+ request_id: Optional[str] = None
43
+ deadline_seconds: int = 120
44
+
45
+ @property
46
+ def gas(self) -> int:
47
+ if self.gas_limit is not None:
48
+ return int(self.gas_limit)
49
+ return 21_000 if self.data in ("", "0x") else 250_000
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Check:
54
+ id: str
55
+ label: str
56
+ status: Literal["pass", "fail", "review", "skipped"]
57
+ detail: str
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Operation:
62
+ """A recorded decision. Palisec authorizes; it does not sign or broadcast."""
63
+
64
+ operation_id: Optional[str]
65
+ request_id: str
66
+ decision: Decision
67
+ state: OperationState
68
+ reason_code: Optional[str]
69
+ message: str
70
+ retryable: bool
71
+ policy_id: Optional[str]
72
+ policy_version: Optional[int]
73
+ authorization_id: Optional[str]
74
+ expires_at: Optional[datetime]
75
+ checks: tuple[Check, ...] = field(default_factory=tuple)
76
+ dry_run: bool = False
77
+ #: Present when read back from the API: the account, target, value and exposure evaluated.
78
+ details: Optional[dict[str, Any]] = None
79
+
80
+ @property
81
+ def allowed(self) -> bool:
82
+ """True when the operation carries a usable authorization (allowed, or approved by a human)."""
83
+ return self.state in ("authorized", "approved") and self.authorization_id is not None
84
+
85
+ @classmethod
86
+ def from_api(cls, raw: dict[str, Any]) -> "Operation":
87
+ expires = raw.get("expires_at")
88
+ return cls(
89
+ operation_id=raw.get("operation_id"),
90
+ request_id=raw.get("request_id", ""),
91
+ decision=raw["decision"],
92
+ state=raw["state"],
93
+ reason_code=raw.get("reason_code"),
94
+ message=raw.get("message", ""),
95
+ retryable=bool(raw.get("retryable", False)),
96
+ policy_id=raw.get("policy_id"),
97
+ policy_version=raw.get("policy_version"),
98
+ authorization_id=raw.get("authorization_id"),
99
+ expires_at=datetime.fromisoformat(expires.replace("Z", "+00:00")) if expires else None,
100
+ checks=tuple(
101
+ Check(id=c.get("id", ""), label=c.get("label", ""), status=c.get("status", "skipped"), detail=c.get("detail", ""))
102
+ for c in raw.get("checks") or []
103
+ ),
104
+ dry_run=bool(raw.get("dry_run", False)),
105
+ details=raw.get("details"),
106
+ )
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class SendResult:
111
+ operation: Operation
112
+ #: The transaction hash, or None when the operation is held for a human approver.
113
+ hash: Optional[str]
114
+
115
+
116
+ class LogEvent(TypedDict, total=False):
117
+ """Structured log event. Never contains the API key, request bodies or calldata."""
118
+
119
+ type: Literal["request", "response", "retry", "error"]
120
+ method: str
121
+ path: str
122
+ attempt: int
123
+ status: int
124
+ request_id: Optional[str]
125
+ duration_ms: int
126
+ code: str
palisec/py.typed ADDED
File without changes
palisec/web3.py ADDED
@@ -0,0 +1,58 @@
1
+ """web3.py adapter for ``Palisec.send_transaction``.
2
+
3
+ No web3 import: works with ``Web3`` or ``AsyncWeb3`` (v6 or v7) and an ``eth_account`` LocalAccount.
4
+
5
+ from web3 import AsyncWeb3, AsyncHTTPProvider
6
+ from eth_account import Account
7
+ from palisec.web3 import Web3Sender
8
+
9
+ w3 = AsyncWeb3(AsyncHTTPProvider("https://rpc.testnet.chain.robinhood.com"))
10
+ sender = Web3Sender(w3, Account.from_key(os.environ["AGENT_KEY"]))
11
+ result = await palisec.send_transaction(sender, to=TOKEN, data=calldata, gas_limit=90_000)
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import inspect
17
+ from typing import Any
18
+
19
+ from .errors import PalisecConfigError
20
+
21
+
22
+ async def _v(value: Any) -> Any:
23
+ return await value if inspect.isawaitable(value) else value
24
+
25
+
26
+ class Web3Sender:
27
+ """Signs locally with the account and sends the raw transaction through ``w3``.
28
+
29
+ Checks that the RPC is on the chain Palisec authorized before signing, and pays the RPC's
30
+ current gas price, the price Palisec bounded the fee on.
31
+ """
32
+
33
+ def __init__(self, w3: Any, account: Any) -> None:
34
+ self._w3 = w3
35
+ self._account = account
36
+ self.address: str = account.address
37
+
38
+ async def send_transaction(self, tx: dict) -> str:
39
+ eth = self._w3.eth
40
+ chain_id = int(await _v(eth.chain_id))
41
+ if chain_id != tx["chainId"]:
42
+ raise PalisecConfigError(f"The RPC is on chain {chain_id}, but Palisec authorized chain {tx['chainId']}")
43
+ nonce = await _v(eth.get_transaction_count(self.address, "pending"))
44
+ gas_price = int(await _v(eth.gas_price))
45
+ signed = self._account.sign_transaction(
46
+ {
47
+ "to": tx["to"],
48
+ "value": tx["value"],
49
+ "data": tx["data"],
50
+ "gas": tx["gas"],
51
+ "gasPrice": gas_price,
52
+ "nonce": nonce,
53
+ "chainId": chain_id,
54
+ }
55
+ )
56
+ raw = getattr(signed, "raw_transaction", None) or getattr(signed, "rawTransaction")
57
+ sent = await _v(eth.send_raw_transaction(raw))
58
+ return "0x" + bytes(sent).hex() if not isinstance(sent, str) else sent
palisec/webhooks.py ADDED
@@ -0,0 +1,41 @@
1
+ """Verify Palisec webhook deliveries.
2
+
3
+ ``palisec-signature: v1=<hex HMAC-SHA256(secret, "<timestamp>.<raw body>")>``. Pass the raw body
4
+ exactly as received. Stale timestamps (default 5 minutes) are rejected so a captured delivery cannot
5
+ be replayed, and the comparison is constant-time. Deduplicate on ``palisec-event-id``: retries reuse it.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import hmac
12
+ import json
13
+ import time
14
+ from typing import Any, Mapping, Optional, Union
15
+
16
+
17
+ class WebhookVerificationError(Exception):
18
+ """The delivery is not authentic, is malformed, or is too old."""
19
+
20
+
21
+ def _header(headers: Mapping[str, Any], name: str) -> Optional[str]:
22
+ for k, v in headers.items():
23
+ if k.lower() == name:
24
+ return v[0] if isinstance(v, (list, tuple)) else v
25
+ return None
26
+
27
+
28
+ def verify(secret: str, raw_body: Union[str, bytes], headers: Mapping[str, Any], *, tolerance: int = 300, now: Optional[int] = None) -> dict:
29
+ """Returns the parsed event if the signature is valid; raises WebhookVerificationError otherwise."""
30
+ body = raw_body.decode("utf-8") if isinstance(raw_body, bytes) else raw_body
31
+ ts = _header(headers, "palisec-timestamp")
32
+ sig = _header(headers, "palisec-signature")
33
+ if not ts or not ts.isdigit() or len(ts) > 12 or not sig or not sig.startswith("v1="):
34
+ raise WebhookVerificationError("Missing or malformed Palisec signature headers")
35
+ current = int(time.time()) if now is None else now
36
+ if abs(current - int(ts)) > tolerance:
37
+ raise WebhookVerificationError("Webhook timestamp is outside the tolerance window")
38
+ expected = hmac.new(secret.encode(), f"{ts}.{body}".encode(), hashlib.sha256).hexdigest()
39
+ if not hmac.compare_digest(expected, sig[3:]):
40
+ raise WebhookVerificationError("Webhook signature does not match")
41
+ return json.loads(body)
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Palisec
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.1
2
+ Name: palisec
3
+ Version: 0.4.0
4
+ Summary: Python client for Palisec: ask before every agent transaction, send only on ALLOW.
5
+ Home-page: https://palisec.tech/docs/sdk/python
6
+ Author: Palisec
7
+ License: MIT
8
+ Requires-Python: >=3.10
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Framework :: AsyncIO
12
+ Classifier: Typing :: Typed
13
+ Project-URL: Homepage, https://palisec.tech
14
+ Project-URL: Documentation, https://palisec.tech/docs/sdk/python
15
+ Project-URL: Changelog, https://palisec.tech/changelog
16
+ Description-Content-Type: text/markdown
17
+
18
+ # palisec
19
+
20
+ Python client for [Palisec](https://palisec.tech): your agent asks before every transaction and sends only on ALLOW.
21
+ Async, typed, and no third-party dependencies. Python 3.10 or later.
22
+
23
+ ```bash
24
+ pip install palisec
25
+ ```
26
+
27
+ Alternative, straight from palisec.tech: `pip install https://palisec.tech/sdk/palisec-0.4.0-py3-none-any.whl`.
28
+
29
+ ```python
30
+ import os
31
+ from palisec import Palisec, PalisecDeniedError
32
+
33
+ async with Palisec(os.environ["PALISEC_API_KEY"]) as palisec: # server-side only
34
+ try:
35
+ result = await palisec.send_transaction(sender, to=TOKEN, data=calldata, gas_limit=90_000)
36
+ if result.hash is None:
37
+ print("held for a human approver:", result.operation.operation_id)
38
+ except PalisecDeniedError as e:
39
+ print(e.code, e.message) # nothing was sent
40
+ ```
41
+
42
+ `sender` is the agent's own account. With web3.py:
43
+
44
+ ```python
45
+ from web3 import AsyncWeb3, AsyncHTTPProvider
46
+ from eth_account import Account
47
+ from palisec.web3 import Web3Sender
48
+
49
+ w3 = AsyncWeb3(AsyncHTTPProvider("https://rpc.testnet.chain.robinhood.com"))
50
+ sender = Web3Sender(w3, Account.from_key(os.environ["AGENT_KEY"]))
51
+ ```
52
+
53
+ - `authorize(...)` records a decision: `ALLOW`, `DENY` or `REQUIRES_HUMAN_SIGNATURE`. It does not raise on DENY. Safe to retry: the request ID is the idempotency key.
54
+ - `evaluate(...)` is a dry run that reserves nothing.
55
+ - `wait_for_approval(id)`, `get_operation(id)`, `cancel(id)` (withdraws a pending approval; never retried).
56
+ - Errors are `PalisecError` subclasses with a stable `code` (`PS_…`). Retries happen only for network errors, 429 and 5xx, and only on calls that are safe to repeat.
57
+ - Log events never contain your API key, request bodies or calldata; `redact()` masks keys in any string.
58
+
59
+ Palisec runs on Robinhood Chain mainnet (4663) and testnet (46630); a `ps_live_` key is mainnet, a `ps_test_` key testnet. Agents with a PALISEC smart account are enforced on chain (`execute_with_smart_account`); an agent that sends from a plain key is enforced only in its own process. Docs: https://palisec.tech/docs/sdk/python
@@ -0,0 +1,12 @@
1
+ palisec/__init__.py,sha256=ooHxZwiIebyjIO8KTJFqGtXYEteJfmzEtIKnsWQi1c4,1073
2
+ palisec/client.py,sha256=CuZKDkk0ZSk9fDx8WURkin1Jnn6rtA679pA1ov359OY,23699
3
+ palisec/codes.py,sha256=Gq5oAyPE_Nm5FXqq93YL57_zPMRcOzedh14xDW9Me9I,1611
4
+ palisec/errors.py,sha256=tlXorrltmO6WzkY5r5HQL0mowPwxKwre6o35Avo5DbM,2309
5
+ palisec/models.py,sha256=epGH17If6fAvLc8mAHnJRZrRkGOYId7JTdKX8IzgGN0,4101
6
+ palisec/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ palisec/web3.py,sha256=XE_jfHN5jHJVKLzkbIJaTLHYluVY3ltVBXn52Plm2Sg,2143
8
+ palisec/webhooks.py,sha256=wYHWCQ2IMaOaTI7MHYxWN0gnTi2JfLrZiBc6HgZwvZA,1854
9
+ palisec-0.4.0.dist-info/LICENSE,sha256=HeExKMsWLXbW1sjnKISMJ2cxbJCLv2NK416y3-UsFi0,1064
10
+ palisec-0.4.0.dist-info/METADATA,sha256=QwvrnuFoRVXvD8Vo_Ni6DbiwzdGiNCxzBEwVMsE0u3U,2677
11
+ palisec-0.4.0.dist-info/WHEEL,sha256=OX8IaTqM9PS0p-mBDQ_iZJHSmfWuVtfPp79Ef9lE-lE,84
12
+ palisec-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: palisec-build
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any