mishmar 0.2.0__tar.gz

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.
mishmar-0.2.0/LICENSE ADDED
@@ -0,0 +1,174 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
mishmar-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: mishmar
3
+ Version: 0.2.0
4
+ Summary: Mishmar client: sign and submit proposals to the engine that guards your trading agent
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://mishmar.io
7
+ Project-URL: Source, https://github.com/mishmar-io/mishmar
8
+ Keywords: trading,agents,risk,guardrails,hyperliquid,binance
9
+ Classifier: Development Status :: 2 - Pre-Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Office/Business :: Financial
13
+ Requires-Python: >=3.11
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: cryptography>=41
17
+ Provides-Extra: test
18
+ Requires-Dist: pytest>=8; extra == "test"
19
+ Dynamic: license-file
20
+
21
+ # mishmar (Python)
22
+
23
+ The Python client for [Mishmar](https://mishmar.io): build a proposal, sign
24
+ it with the agent's key, send it to the engine, read the decision.
25
+
26
+ ```python
27
+ from datetime import timedelta
28
+ from mishmar import AgentKey, Client, Proposal
29
+
30
+ key = AgentKey.parse("msk_…") # shown once when the engine issued the key
31
+ client = Client("http://localhost:8080/v1", key, key_id="key_…")
32
+
33
+ decision = client.propose(Proposal(
34
+ trading_account_id="ta_…", symbol="BTC", side="buy", size="0.25",
35
+ order_type="market", valid_for=timedelta(minutes=5),
36
+ ))
37
+ print(decision["verdict"]) # allow | require_approval | block
38
+
39
+ # Pull a resting order this agent placed through Mishmar: a cancel names the
40
+ # order by the clientOrderId its decision carries, and has no side or size.
41
+ client.propose(Proposal(
42
+ trading_account_id="ta_…", symbol="BTC", kind="cancel",
43
+ target_client_order_id=decision["proposal"]["clientOrderId"],
44
+ ))
45
+ ```
46
+
47
+ Sizes, prices and leverage are decimal **strings** and are signed exactly as
48
+ written: `"0.5"` and `"0.50"` are the same quantity but different signatures.
49
+ Never pass a float.
50
+
51
+ A call the engine did nothing with goes again by itself: `503 unavailable`
52
+ while the engine restarts and `429 rate_limited` (after its `Retry-After`),
53
+ for up to 45 s, then the last answer is raised as `EngineError`. Nothing else
54
+ is retried. `Client(..., retries=None)` turns that off; `retries=Retries(budget=90)`
55
+ tunes it.
56
+
57
+ Run the tests, which include the cross-language vectors in `../spec/vectors`:
58
+
59
+ ```
60
+ pip install -e ".[test]"
61
+ python -m pytest
62
+ ```
63
+
64
+ ## The signer as a child process
65
+
66
+ With the `mishmar` binary installed (or fetched with `download_binary`),
67
+ `Signer` runs it as a child process and the bot holds no secret: the child
68
+ has the agent's key and shares, signs each proposal, and sends it one-shot
69
+ where it can. Reads go through the child too.
70
+
71
+ ```python
72
+ from mishmar import Signer
73
+
74
+ with Signer() as s: # ~/.mishmar/agent.json
75
+ d = s.order("ta_…", "BTC", "buy", "0.001", price="79500")
76
+ if d["verdict"] == "require_approval":
77
+ d = s.wait(d["id"])
78
+ s.cancel("ta_…", "BTC", d["proposal"]["clientOrderId"])
79
+ ```
80
+
81
+ The child stops when this process ends, however it ends: it runs with
82
+ `--exit-on-stdin-close` and a pipe on its stdin. To share one signer among
83
+ several processes, or keep it connected across restarts, run it on its own
84
+ (`mishmar signer run --local unix:/run/mishmar/signer.sock`) and attach with
85
+ `Signer.connect("unix:/run/mishmar/signer.sock")`; `stop()` then leaves it
86
+ running. One signer runs per config, so a second `Signer()` on a config in
87
+ use fails and names the process that holds it.
@@ -0,0 +1,67 @@
1
+ # mishmar (Python)
2
+
3
+ The Python client for [Mishmar](https://mishmar.io): build a proposal, sign
4
+ it with the agent's key, send it to the engine, read the decision.
5
+
6
+ ```python
7
+ from datetime import timedelta
8
+ from mishmar import AgentKey, Client, Proposal
9
+
10
+ key = AgentKey.parse("msk_…") # shown once when the engine issued the key
11
+ client = Client("http://localhost:8080/v1", key, key_id="key_…")
12
+
13
+ decision = client.propose(Proposal(
14
+ trading_account_id="ta_…", symbol="BTC", side="buy", size="0.25",
15
+ order_type="market", valid_for=timedelta(minutes=5),
16
+ ))
17
+ print(decision["verdict"]) # allow | require_approval | block
18
+
19
+ # Pull a resting order this agent placed through Mishmar: a cancel names the
20
+ # order by the clientOrderId its decision carries, and has no side or size.
21
+ client.propose(Proposal(
22
+ trading_account_id="ta_…", symbol="BTC", kind="cancel",
23
+ target_client_order_id=decision["proposal"]["clientOrderId"],
24
+ ))
25
+ ```
26
+
27
+ Sizes, prices and leverage are decimal **strings** and are signed exactly as
28
+ written: `"0.5"` and `"0.50"` are the same quantity but different signatures.
29
+ Never pass a float.
30
+
31
+ A call the engine did nothing with goes again by itself: `503 unavailable`
32
+ while the engine restarts and `429 rate_limited` (after its `Retry-After`),
33
+ for up to 45 s, then the last answer is raised as `EngineError`. Nothing else
34
+ is retried. `Client(..., retries=None)` turns that off; `retries=Retries(budget=90)`
35
+ tunes it.
36
+
37
+ Run the tests, which include the cross-language vectors in `../spec/vectors`:
38
+
39
+ ```
40
+ pip install -e ".[test]"
41
+ python -m pytest
42
+ ```
43
+
44
+ ## The signer as a child process
45
+
46
+ With the `mishmar` binary installed (or fetched with `download_binary`),
47
+ `Signer` runs it as a child process and the bot holds no secret: the child
48
+ has the agent's key and shares, signs each proposal, and sends it one-shot
49
+ where it can. Reads go through the child too.
50
+
51
+ ```python
52
+ from mishmar import Signer
53
+
54
+ with Signer() as s: # ~/.mishmar/agent.json
55
+ d = s.order("ta_…", "BTC", "buy", "0.001", price="79500")
56
+ if d["verdict"] == "require_approval":
57
+ d = s.wait(d["id"])
58
+ s.cancel("ta_…", "BTC", d["proposal"]["clientOrderId"])
59
+ ```
60
+
61
+ The child stops when this process ends, however it ends: it runs with
62
+ `--exit-on-stdin-close` and a pipe on its stdin. To share one signer among
63
+ several processes, or keep it connected across restarts, run it on its own
64
+ (`mishmar signer run --local unix:/run/mishmar/signer.sock`) and attach with
65
+ `Signer.connect("unix:/run/mishmar/signer.sock")`; `stop()` then leaves it
66
+ running. One signer runs per config, so a second `Signer()` on a config in
67
+ use fails and names the process that holds it.
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mishmar"
7
+ version = "0.2.0"
8
+ description = "Mishmar client: sign and submit proposals to the engine that guards your trading agent"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.11"
12
+ dependencies = ["cryptography>=41"]
13
+ keywords = ["trading", "agents", "risk", "guardrails", "hyperliquid", "binance"]
14
+ classifiers = [
15
+ "Development Status :: 2 - Pre-Alpha",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Topic :: Office/Business :: Financial",
19
+ ]
20
+
21
+ [project.optional-dependencies]
22
+ test = ["pytest>=8"]
23
+
24
+ [project.urls]
25
+ Homepage = "https://mishmar.io"
26
+ Source = "https://github.com/mishmar-io/mishmar"
27
+
28
+ [tool.setuptools.packages.find]
29
+ where = ["src"]
30
+
31
+ [tool.pytest.ini_options]
32
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,27 @@
1
+ """The Mishmar client: sign and submit proposals, read decisions, answer the signer channel."""
2
+
3
+ from .agentkey import AgentKey, request_signing_bytes, verify, verify_request
4
+ from .canon import canonical_json
5
+ from .client import DEFAULT_RETRIES, Client, EngineError, Retries
6
+ from .proposal import Proposal, VenueMessage, is_decimal, new_nonce, rfc3339
7
+ from .signer import Signer, download_binary, find_binary
8
+
9
+ __all__ = [
10
+ "DEFAULT_RETRIES",
11
+ "AgentKey",
12
+ "Client",
13
+ "EngineError",
14
+ "Proposal",
15
+ "Retries",
16
+ "Signer",
17
+ "VenueMessage",
18
+ "canonical_json",
19
+ "download_binary",
20
+ "find_binary",
21
+ "is_decimal",
22
+ "new_nonce",
23
+ "request_signing_bytes",
24
+ "rfc3339",
25
+ "verify",
26
+ "verify_request",
27
+ ]
@@ -0,0 +1,31 @@
1
+ """Times as the contract writes them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import UTC, datetime
6
+ from typing import Any
7
+
8
+
9
+ def rfc3339(dt: datetime) -> str:
10
+ """Format a time as the contract wants it: UTC, Z suffix, fraction trimmed."""
11
+ if dt.tzinfo is None:
12
+ raise ValueError("times must be timezone-aware")
13
+ dt = dt.astimezone(UTC)
14
+ text = dt.strftime("%Y-%m-%dT%H:%M:%S")
15
+ if dt.microsecond:
16
+ text += "." + f"{dt.microsecond:06d}".rstrip("0")
17
+ return text + "Z"
18
+
19
+
20
+ def parse_time(value: Any) -> datetime:
21
+ """A timezone-aware datetime from a datetime or an RFC 3339 string."""
22
+ if isinstance(value, datetime):
23
+ if value.tzinfo is None:
24
+ raise ValueError("times must be timezone-aware")
25
+ return value
26
+ if isinstance(value, str):
27
+ dt = datetime.fromisoformat(value)
28
+ if dt.tzinfo is None:
29
+ raise ValueError(f"time {value!r} has no offset")
30
+ return dt
31
+ raise TypeError(f"not a time: {value!r}")
@@ -0,0 +1,188 @@
1
+ """The agent's identity: an Ed25519 key whose public half the engine stores.
2
+
3
+ The engine shows the secret once, as ``msk_<prefix>_<seed>``: a label, then
4
+ the 32-byte seed in base64url without padding. The key id (``key_…``) is
5
+ separate and public.
6
+
7
+ The key signs two things: proposals (see proposal.py) and, under the
8
+ contract's agentAuth scheme, every other agent-facing request: four headers
9
+ carry the key id, the time, a nonce and an Ed25519 signature over the canonical
10
+ JSON of ``{bodySha256, keyId, method, nonce, path, query, signedAt}``. The bytes
11
+ are pinned in spec/vectors/agent-request-signing.json.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import base64
17
+ import hashlib
18
+ import secrets
19
+ from datetime import UTC, datetime
20
+
21
+ from cryptography.exceptions import InvalidSignature
22
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (
23
+ Ed25519PrivateKey,
24
+ Ed25519PublicKey,
25
+ )
26
+ from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
27
+
28
+ from ._time import rfc3339
29
+ from .canon import canonical_json
30
+
31
+ SEED_SIZE = 32
32
+
33
+ HEADER_KEY_ID = "X-Mishmar-Key-Id"
34
+ HEADER_SIGNED_AT = "X-Mishmar-Signed-At"
35
+ HEADER_NONCE = "X-Mishmar-Nonce"
36
+ HEADER_SIGNATURE = "X-Mishmar-Signature"
37
+
38
+
39
+ def _b64url_decode(s: str) -> bytes:
40
+ return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
41
+
42
+
43
+ def new_nonce() -> str:
44
+ """A fresh nonce: 16 random bytes, hex."""
45
+ return secrets.token_hex(16)
46
+
47
+
48
+ def request_signing_bytes(
49
+ *,
50
+ key_id: str,
51
+ method: str,
52
+ path: str,
53
+ query: str = "",
54
+ body: bytes = b"",
55
+ nonce: str,
56
+ signed_at: str,
57
+ ) -> bytes:
58
+ """What the agent signs for a request. ``path`` is without the server
59
+ prefix (``/agent/decisions``), ``query`` the raw query string without the
60
+ ``?``, ``signed_at`` exactly as the header carries it."""
61
+ fields: dict[str, str] = {
62
+ "keyId": key_id,
63
+ "method": method.upper(),
64
+ "nonce": nonce,
65
+ "path": path,
66
+ "signedAt": signed_at,
67
+ }
68
+ if query:
69
+ fields["query"] = query
70
+ if body:
71
+ fields["bodySha256"] = hashlib.sha256(body).hexdigest()
72
+ return canonical_json(fields)
73
+
74
+
75
+ class AgentKey:
76
+ """The agent's private key."""
77
+
78
+ def __init__(self, private: Ed25519PrivateKey):
79
+ self._private = private
80
+
81
+ @classmethod
82
+ def parse(cls, secret: str) -> AgentKey:
83
+ """Read the secret the engine showed when the key was issued."""
84
+ # msk_<prefix>_<seed>: the seed is base64url and may itself contain
85
+ # '_', so split on the first two underscores only.
86
+ parts = secret.strip().split("_", 2)
87
+ if len(parts) != 3 or parts[0] != "msk":
88
+ raise ValueError("malformed agent secret: expected msk_<prefix>_<seed>")
89
+ try:
90
+ seed = _b64url_decode(parts[2])
91
+ except ValueError as err:
92
+ raise ValueError(
93
+ "malformed agent secret: the seed is not base64url"
94
+ ) from err
95
+ if len(seed) != SEED_SIZE:
96
+ raise ValueError("malformed agent secret: the seed is not 32 bytes")
97
+ return cls.from_seed(seed)
98
+
99
+ @classmethod
100
+ def from_seed(cls, seed: bytes) -> AgentKey:
101
+ return cls(Ed25519PrivateKey.from_private_bytes(seed))
102
+
103
+ def sign(self, message: bytes) -> str:
104
+ """The base64 (standard, padded) Ed25519 signature of message."""
105
+ return base64.b64encode(self._private.sign(message)).decode("ascii")
106
+
107
+ def sign_request(
108
+ self,
109
+ key_id: str,
110
+ method: str,
111
+ path: str,
112
+ *,
113
+ query: str = "",
114
+ body: bytes = b"",
115
+ nonce: str | None = None,
116
+ signed_at: datetime | None = None,
117
+ ) -> dict[str, str]:
118
+ """The four agentAuth headers for a request; a nonce and the time are
119
+ made here when not given."""
120
+ nonce = nonce or new_nonce()
121
+ signed_at_text = rfc3339(signed_at or datetime.now(UTC))
122
+ message = request_signing_bytes(
123
+ key_id=key_id,
124
+ method=method,
125
+ path=path,
126
+ query=query,
127
+ body=body,
128
+ nonce=nonce,
129
+ signed_at=signed_at_text,
130
+ )
131
+ return {
132
+ HEADER_KEY_ID: key_id,
133
+ HEADER_SIGNED_AT: signed_at_text,
134
+ HEADER_NONCE: nonce,
135
+ HEADER_SIGNATURE: self.sign(message),
136
+ }
137
+
138
+ @property
139
+ def public_key(self) -> bytes:
140
+ return self._private.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)
141
+
142
+ @property
143
+ def public_key_b64(self) -> str:
144
+ """The public half as the API stores and returns it."""
145
+ return base64.b64encode(self.public_key).decode("ascii")
146
+
147
+
148
+ def secret(prefix: str, seed: bytes) -> str:
149
+ """Render a seed the way the engine shows it."""
150
+ return prefix + "_" + base64.urlsafe_b64encode(seed).rstrip(b"=").decode("ascii")
151
+
152
+
153
+ def verify(public_key_b64: str, message: bytes, signature_b64: str) -> bool:
154
+ """Check a base64 signature over message with a public key in the API's form."""
155
+ try:
156
+ public = Ed25519PublicKey.from_public_bytes(
157
+ base64.b64decode(public_key_b64, validate=True)
158
+ )
159
+ public.verify(base64.b64decode(signature_b64, validate=True), message)
160
+ return True
161
+ except (ValueError, InvalidSignature):
162
+ return False
163
+
164
+
165
+ def verify_request(
166
+ public_key_b64: str,
167
+ *,
168
+ key_id: str,
169
+ method: str,
170
+ path: str,
171
+ query: str,
172
+ body: bytes,
173
+ nonce: str,
174
+ signed_at: str,
175
+ signature_b64: str,
176
+ ) -> bool:
177
+ """The engine's side of agentAuth: check the headers against the request.
178
+ Freshness and nonce replay are the caller's checks."""
179
+ message = request_signing_bytes(
180
+ key_id=key_id,
181
+ method=method,
182
+ path=path,
183
+ query=query,
184
+ body=body,
185
+ nonce=nonce,
186
+ signed_at=signed_at,
187
+ )
188
+ return verify(public_key_b64, message, signature_b64)
@@ -0,0 +1,46 @@
1
+ """Canonical JSON: the bytes an agent signs and the engine verifies.
2
+
3
+ The rules match Go's encoding/json, which the engine uses (see canon/ in the
4
+ repo root and spec/vectors): one object, keys sorted, no whitespace, keys
5
+ whose value is None left out at every depth, strings with Go's escapes.
6
+ Python's json module agrees on everything but the HTML-safe escapes, which
7
+ are added here. Numbers never appear in what Mishmar signs, so they are
8
+ refused rather than formatted differently from Go.
9
+ """
10
+
11
+ import json
12
+ from typing import Any
13
+
14
+ # What Go escapes beyond the JSON minimum: HTML-significant characters and
15
+ # the two line separators. Python with ensure_ascii=False writes them raw.
16
+ _GO_ESCAPES = {
17
+ "<": "\\u003c",
18
+ ">": "\\u003e",
19
+ "&": "\\u0026",
20
+ "
": "\\u2028",
21
+ "
": "\\u2029",
22
+ }
23
+
24
+
25
+ def _strip(value: Any) -> Any:
26
+ if isinstance(value, bool) or value is None or isinstance(value, str):
27
+ return value
28
+ if isinstance(value, dict):
29
+ return {k: _strip(v) for k, v in value.items() if v is not None}
30
+ if isinstance(value, (list, tuple)):
31
+ return [_strip(v) for v in value]
32
+ if isinstance(value, (int, float)):
33
+ raise TypeError(
34
+ f"canonical_json: numbers are not signed by Mishmar; send {value!r} as a decimal string"
35
+ )
36
+ raise TypeError(f"canonical_json: cannot encode {type(value).__name__}")
37
+
38
+
39
+ def canonical_json(value: Any) -> bytes:
40
+ """Return the canonical UTF-8 encoding of value."""
41
+ text = json.dumps(
42
+ _strip(value), sort_keys=True, separators=(",", ":"), ensure_ascii=False
43
+ )
44
+ for raw, escaped in _GO_ESCAPES.items():
45
+ text = text.replace(raw, escaped)
46
+ return text.encode("utf-8")