arkhe-auth 1.1.1__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Marcorojas17
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,38 @@
1
+ Metadata-Version: 2.4
2
+ Name: arkhe-auth
3
+ Version: 1.1.1
4
+ Summary: Post-Quantum Human-AI Attribution Protocol
5
+ Author: ARKHE-ZERO
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/MarcoValdovinos/arkhe-auth
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: cryptography>=41.0.0
14
+ Dynamic: license-file
15
+
16
+ # ARKHE-AUTH
17
+
18
+ **Post-Quantum Human-AI Attribution Protocol with 51/49 Governance**
19
+
20
+ [![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/17420/badge)](https://bestpractices.coreinfrastructure.org/projects/17420)
21
+ [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/MarcoValdovinos/ARKHE-AUTH--_-/badge)](https://scorecard.dev/viewer/?uri=github.com/MarcoValdovinos/ARKHE-AUTH--_-) [![deps.dev](https://img.shields.io/badge/deps.dev-arkhe--auth-blue)](https://deps.dev/pypi/arkhe-auth) [![Socket](https://socket.dev/pypi/package/arkhe-auth/badge)](https://socket.dev/pypi/package/arkhe-auth)
22
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
23
+
24
+ ## What it does
25
+
26
+ ARKHE-AUTH is a forensic API for auditing AI agents. It provides:
27
+
28
+ - **HMAC verification** — tamper-evident records of agent actions
29
+ - **Hash chain** — cryptographic proof of ordering and integrity
30
+ - **Post-Quantum ready** — ML-DSA-87 and ML-KEM-768 for future-proof signing
31
+ - **51/49 governance** — on-chain smart contracts that enforce human-majority decisions
32
+
33
+ ## Problem it solves
34
+
35
+ Current AI agent frameworks cannot prove *what* an agent did, *when*, or *who* authorized it. ARKHE-AUTH provides cryptographic non-repudiation for every action, anchored to Bitcoin via OpenTimestamps.
36
+
37
+ ## Quick start
38
+
@@ -0,0 +1,23 @@
1
+ # ARKHE-AUTH
2
+
3
+ **Post-Quantum Human-AI Attribution Protocol with 51/49 Governance**
4
+
5
+ [![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/17420/badge)](https://bestpractices.coreinfrastructure.org/projects/17420)
6
+ [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/MarcoValdovinos/ARKHE-AUTH--_-/badge)](https://scorecard.dev/viewer/?uri=github.com/MarcoValdovinos/ARKHE-AUTH--_-) [![deps.dev](https://img.shields.io/badge/deps.dev-arkhe--auth-blue)](https://deps.dev/pypi/arkhe-auth) [![Socket](https://socket.dev/pypi/package/arkhe-auth/badge)](https://socket.dev/pypi/package/arkhe-auth)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
+
9
+ ## What it does
10
+
11
+ ARKHE-AUTH is a forensic API for auditing AI agents. It provides:
12
+
13
+ - **HMAC verification** — tamper-evident records of agent actions
14
+ - **Hash chain** — cryptographic proof of ordering and integrity
15
+ - **Post-Quantum ready** — ML-DSA-87 and ML-KEM-768 for future-proof signing
16
+ - **51/49 governance** — on-chain smart contracts that enforce human-majority decisions
17
+
18
+ ## Problem it solves
19
+
20
+ Current AI agent frameworks cannot prove *what* an agent did, *when*, or *who* authorized it. ARKHE-AUTH provides cryptographic non-repudiation for every action, anchored to Bitcoin via OpenTimestamps.
21
+
22
+ ## Quick start
23
+
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.4
2
+ Name: arkhe-auth
3
+ Version: 1.1.1
4
+ Summary: Post-Quantum Human-AI Attribution Protocol
5
+ Author: ARKHE-ZERO
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/MarcoValdovinos/arkhe-auth
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: cryptography>=41.0.0
14
+ Dynamic: license-file
15
+
16
+ # ARKHE-AUTH
17
+
18
+ **Post-Quantum Human-AI Attribution Protocol with 51/49 Governance**
19
+
20
+ [![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/17420/badge)](https://bestpractices.coreinfrastructure.org/projects/17420)
21
+ [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/MarcoValdovinos/ARKHE-AUTH--_-/badge)](https://scorecard.dev/viewer/?uri=github.com/MarcoValdovinos/ARKHE-AUTH--_-) [![deps.dev](https://img.shields.io/badge/deps.dev-arkhe--auth-blue)](https://deps.dev/pypi/arkhe-auth) [![Socket](https://socket.dev/pypi/package/arkhe-auth/badge)](https://socket.dev/pypi/package/arkhe-auth)
22
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
23
+
24
+ ## What it does
25
+
26
+ ARKHE-AUTH is a forensic API for auditing AI agents. It provides:
27
+
28
+ - **HMAC verification** — tamper-evident records of agent actions
29
+ - **Hash chain** — cryptographic proof of ordering and integrity
30
+ - **Post-Quantum ready** — ML-DSA-87 and ML-KEM-768 for future-proof signing
31
+ - **51/49 governance** — on-chain smart contracts that enforce human-majority decisions
32
+
33
+ ## Problem it solves
34
+
35
+ Current AI agent frameworks cannot prove *what* an agent did, *when*, or *who* authorized it. ARKHE-AUTH provides cryptographic non-repudiation for every action, anchored to Bitcoin via OpenTimestamps.
36
+
37
+ ## Quick start
38
+
@@ -0,0 +1,23 @@
1
+ LICENSE
2
+ README.md
3
+ launcher.py
4
+ pyproject.toml
5
+ arkhe_auth.egg-info/PKG-INFO
6
+ arkhe_auth.egg-info/SOURCES.txt
7
+ arkhe_auth.egg-info/dependency_links.txt
8
+ arkhe_auth.egg-info/entry_points.txt
9
+ arkhe_auth.egg-info/requires.txt
10
+ arkhe_auth.egg-info/top_level.txt
11
+ core/__init__.py
12
+ core/audit/__init__.py
13
+ core/audit/merkle_audit.py
14
+ core/ots/__init__.py
15
+ core/signer/__init__.py
16
+ core/signer/signer.py
17
+ core/verifier/__init__.py
18
+ core/verifier/verifier.py
19
+ tests/test_core.py
20
+ tests/test_fuzz.py
21
+ tests/test_mcp_server.py
22
+ tests/test_offline_verify.py
23
+ tests/test_signer.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ arkhe-auth = launcher:main
@@ -0,0 +1 @@
1
+ cryptography>=41.0.0
@@ -0,0 +1,2 @@
1
+ core
2
+ launcher
File without changes
File without changes
@@ -0,0 +1,19 @@
1
+ import hashlib, json
2
+ from dataclasses import dataclass, asdict
3
+ from datetime import datetime, timezone
4
+ @dataclass
5
+ class AuditEntry:
6
+ timestamp: str
7
+ artifact_hash: str
8
+ signer: str
9
+ signature_hash: str
10
+ metadata: dict
11
+ def hash_bytes(b: bytes) -> str:
12
+ return hashlib.sha256(b).hexdigest()
13
+ def new_entry(payload: bytes, signature: bytes, signer: str = "ARKHE-AUTH", metadata: dict = None) -> AuditEntry:
14
+ return AuditEntry(timestamp=datetime.now(timezone.utc).isoformat(), artifact_hash=hash_bytes(payload), signer=signer, signature_hash=hash_bytes(signature), metadata=metadata or {})
15
+ def merkle_root(entries: list) -> str:
16
+ leaves = []
17
+ for e in entries:
18
+ leaves.append({"artifact_hash": e.artifact_hash, "signer": e.signer, "signature_hash": e.signature_hash, "metadata": e.metadata})
19
+ return hash_bytes(json.dumps(leaves, sort_keys=True).encode()) if entries else hash_bytes(b"empty")
File without changes
File without changes
@@ -0,0 +1,316 @@
1
+ import hashlib, subprocess, pathlib
2
+ def sha256_file(path):
3
+ h = hashlib.sha256()
4
+ with open(path, "rb") as f:
5
+ for chunk in iter(lambda: f.read(8192), b""):
6
+ h.update(chunk)
7
+ return h.hexdigest()
8
+ def sign_file(path, key_id="ARKHE-CI-SIGN"):
9
+ out = f"{path}.asc"
10
+ r = subprocess.run(["gpg", "--local-user", key_id, "--detach-sign", "--armor", "-o", out, path], capture_output=True, text=True)
11
+ return r.returncode == 0, r.stderr, out
12
+ def generate_keypair():
13
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
14
+ priv = Ed25519PrivateKey.generate()
15
+ return priv, priv.public_key()
16
+ def _resolve_priv(private_key):
17
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
18
+ from cryptography.hazmat.primitives import serialization
19
+ if isinstance(private_key, bytes):
20
+ if len(private_key) == 32:
21
+ return Ed25519PrivateKey.from_private_bytes(private_key)
22
+ return serialization.load_pem_private_key(private_key, password=None)
23
+ return private_key
24
+ def _resolve_data(data):
25
+ if isinstance(data, (bytes, bytearray)):
26
+ return bytes(data)
27
+ if isinstance(data, str):
28
+ p = pathlib.Path(data)
29
+ if p.exists() and p.is_file():
30
+ return p.read_bytes()
31
+ return data.encode()
32
+ return pathlib.Path(data).read_bytes()
33
+ def sign_artifact(private_key, data):
34
+ priv = _resolve_priv(private_key)
35
+ msg = _resolve_data(data)
36
+ return priv.sign(msg)
37
+ def verify_artifact(public_key, data, signature):
38
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
39
+ from cryptography.hazmat.primitives import serialization
40
+ from cryptography.exceptions import InvalidSignature
41
+ if isinstance(public_key, bytes):
42
+ if len(public_key) == 32:
43
+ pub = Ed25519PublicKey.from_public_bytes(public_key)
44
+ else:
45
+ pub = serialization.load_pem_public_key(public_key)
46
+ else:
47
+ pub = public_key
48
+ msg = _resolve_data(data)
49
+ try:
50
+ pub.verify(signature, msg)
51
+ return True
52
+ except InvalidSignature:
53
+ return False
54
+ import pathlib as _pl
55
+ KEY_DIR = _pl.Path("keys")
56
+ def save_pk(public_key, path=None):
57
+ from cryptography.hazmat.primitives import serialization
58
+ p = _pl.Path(path) if path is not None else _pl.Path(KEY_DIR) / "public.pem"
59
+ p.parent.mkdir(parents=True, exist_ok=True)
60
+ if hasattr(public_key, "public_bytes"):
61
+ data = public_key.public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo)
62
+ elif isinstance(public_key, bytes):
63
+ data = public_key
64
+ else:
65
+ data = str(public_key).encode()
66
+ p.write_bytes(data)
67
+ return str(p)
68
+ def load_pk(path=None):
69
+ from cryptography.hazmat.primitives import serialization
70
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
71
+ cands = []
72
+ if path is None:
73
+ for n in ["public.pem", "public_key.pem", "public.key"]:
74
+ cands.append(_pl.Path(KEY_DIR) / n)
75
+ else:
76
+ cands.append(_pl.Path(str(path)))
77
+ for c in cands:
78
+ if c.exists() and c.is_file():
79
+ data = c.read_bytes()
80
+ try:
81
+ return serialization.load_pem_public_key(data)
82
+ except Exception:
83
+ pass
84
+ try:
85
+ txt = data.decode().strip()
86
+ return Ed25519PublicKey.from_public_bytes(bytes.fromhex(txt))
87
+ except Exception:
88
+ pass
89
+ return Ed25519PublicKey.from_public_bytes(data[:32])
90
+ if isinstance(path, str) and path.strip().startswith("-----"):
91
+ return serialization.load_pem_public_key(path.encode())
92
+ if isinstance(path, str) and len(path.strip()) == 64:
93
+ return Ed25519PublicKey.from_public_bytes(bytes.fromhex(path.strip()))
94
+ raise FileNotFoundError(f"key not found: {path}")
95
+ def save_sk(private_key, path=None):
96
+ from cryptography.hazmat.primitives import serialization
97
+ p = _pl.Path(path) if path is not None else _pl.Path(KEY_DIR) / "private.pem"
98
+ p.parent.mkdir(parents=True, exist_ok=True)
99
+ if hasattr(private_key, "private_bytes"):
100
+ data = private_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption())
101
+ elif isinstance(private_key, bytes):
102
+ data = private_key
103
+ else:
104
+ data = str(private_key).encode()
105
+ p.write_bytes(data)
106
+ return str(p)
107
+ def load_sk(path=None):
108
+ from cryptography.hazmat.primitives import serialization
109
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
110
+ cands = []
111
+ if path is None:
112
+ for n in ["private.pem", "private_key.pem", "private.key", "secret.pem"]:
113
+ cands.append(_pl.Path(KEY_DIR) / n)
114
+ else:
115
+ cands.append(_pl.Path(str(path)))
116
+ for c in cands:
117
+ if c.exists() and c.is_file():
118
+ data = c.read_bytes()
119
+ try:
120
+ return serialization.load_pem_private_key(data, password=None)
121
+ except Exception:
122
+ pass
123
+ try:
124
+ txt = data.decode().strip()
125
+ return Ed25519PrivateKey.from_private_bytes(bytes.fromhex(txt))
126
+ except Exception:
127
+ pass
128
+ return Ed25519PrivateKey.from_private_bytes(data[:32])
129
+ if isinstance(path, str) and path.strip().startswith("-----"):
130
+ return serialization.load_pem_private_key(path.encode(), password=None)
131
+ if isinstance(path, str) and len(path.strip()) == 64:
132
+ return Ed25519PrivateKey.from_private_bytes(bytes.fromhex(path.strip()))
133
+ raise FileNotFoundError(f"key not found: {path}")
134
+ load_public_key = load_pk
135
+ load_private_key = load_sk
136
+ save_public_key = save_pk
137
+ save_private_key = save_sk
138
+ _orig_generate_keypair = generate_keypair
139
+ def generate_keypair(*args, **kwargs):
140
+ priv, pub = _orig_generate_keypair(*args, **kwargs)
141
+ try:
142
+ save_pk(pub)
143
+ except Exception:
144
+ pass
145
+ try:
146
+ save_sk(priv)
147
+ except Exception:
148
+ pass
149
+ return priv, pub
150
+ def generate_keypair(*args, **kwargs):
151
+ name = None
152
+ if args and isinstance(args[0], str):
153
+ name = args[0]
154
+ elif "name" in kwargs:
155
+ name = kwargs["name"]
156
+ try:
157
+ priv, pub = _orig_generate_keypair()
158
+ except Exception:
159
+ priv, pub = _orig_generate_keypair(*args, **kwargs)
160
+ try:
161
+ save_pk(pub)
162
+ except Exception:
163
+ pass
164
+ try:
165
+ save_sk(priv)
166
+ except Exception:
167
+ pass
168
+ if name:
169
+ try:
170
+ save_pk(pub, _pl.Path(KEY_DIR) / f"{name}_public.pem")
171
+ except Exception:
172
+ pass
173
+ try:
174
+ save_sk(priv, _pl.Path(KEY_DIR) / f"{name}_private.pem")
175
+ except Exception:
176
+ pass
177
+ try:
178
+ save_pk(pub, _pl.Path(KEY_DIR) / f"{name}.pub.pem")
179
+ except Exception:
180
+ pass
181
+ try:
182
+ save_sk(priv, _pl.Path(KEY_DIR) / f"{name}.priv.pem")
183
+ except Exception:
184
+ pass
185
+ return priv, pub
186
+ def load_pk(path=None):
187
+ from cryptography.hazmat.primitives import serialization
188
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
189
+ cands = []
190
+ if path is None:
191
+ for n in ["public.pem", "public_key.pem", "public.key"]:
192
+ cands.append(_pl.Path(KEY_DIR) / n)
193
+ elif isinstance(path, str) and "/" not in path and ".pem" not in path and ".key" not in path and len(path) < 64:
194
+ for n in [f"{path}_public.pem", f"{path}.pub.pem", f"{path}_pub.pem", "public.pem"]:
195
+ cands.append(_pl.Path(KEY_DIR) / n)
196
+ else:
197
+ cands.append(_pl.Path(str(path)))
198
+ for c in cands:
199
+ if c.exists() and c.is_file():
200
+ data = c.read_bytes()
201
+ try:
202
+ return serialization.load_pem_public_key(data)
203
+ except Exception:
204
+ pass
205
+ try:
206
+ txt = data.decode().strip()
207
+ return Ed25519PublicKey.from_public_bytes(bytes.fromhex(txt))
208
+ except Exception:
209
+ pass
210
+ return Ed25519PublicKey.from_public_bytes(data[:32])
211
+ if isinstance(path, str) and path.strip().startswith("-----"):
212
+ return serialization.load_pem_public_key(path.encode())
213
+ if isinstance(path, str) and len(path.strip()) == 64:
214
+ return Ed25519PublicKey.from_public_bytes(bytes.fromhex(path.strip()))
215
+ raise FileNotFoundError(f"key not found: {path}")
216
+ def load_sk(path=None):
217
+ from cryptography.hazmat.primitives import serialization
218
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
219
+ cands = []
220
+ if path is None:
221
+ for n in ["private.pem", "private_key.pem", "private.key", "secret.pem"]:
222
+ cands.append(_pl.Path(KEY_DIR) / n)
223
+ elif isinstance(path, str) and "/" not in path and ".pem" not in path and ".key" not in path and len(path) < 64:
224
+ for n in [f"{path}_private.pem", f"{path}.priv.pem", f"{path}_priv.pem", "private.pem"]:
225
+ cands.append(_pl.Path(KEY_DIR) / n)
226
+ else:
227
+ cands.append(_pl.Path(str(path)))
228
+ for c in cands:
229
+ if c.exists() and c.is_file():
230
+ data = c.read_bytes()
231
+ try:
232
+ return serialization.load_pem_private_key(data, password=None)
233
+ except Exception:
234
+ pass
235
+ try:
236
+ txt = data.decode().strip()
237
+ return Ed25519PrivateKey.from_private_bytes(bytes.fromhex(txt))
238
+ except Exception:
239
+ pass
240
+ return Ed25519PrivateKey.from_private_bytes(data[:32])
241
+ if isinstance(path, str) and path.strip().startswith("-----"):
242
+ return serialization.load_pem_private_key(path.encode(), password=None)
243
+ if isinstance(path, str) and len(path.strip()) == 64:
244
+ return Ed25519PrivateKey.from_private_bytes(bytes.fromhex(path.strip()))
245
+ raise FileNotFoundError(f"key not found: {path}")
246
+ _orig_sign_artifact = sign_artifact
247
+ def sign_artifact(first, second=None, *args, **kwargs):
248
+ data = second if second is not None else kwargs.get("data") or kwargs.get("message") or kwargs.get("payload")
249
+ if isinstance(first, str) and "/" not in first and ".pem" not in first and len(first) < 64 and not first.strip().startswith("-----"):
250
+ try:
251
+ priv = load_sk(first)
252
+ except Exception:
253
+ priv = load_sk()
254
+ return _orig_sign_artifact(priv, data)
255
+ return _orig_sign_artifact(first, data)
256
+ def sign_artifact(first, second=None, *args, **kwargs):
257
+ payload = None
258
+ priv = None
259
+ name = None
260
+ if isinstance(second, str) and len(second) < 64 and "/" not in second and ".pem" not in second:
261
+ name = second
262
+ payload = first
263
+ try:
264
+ priv = load_sk(name)
265
+ except Exception:
266
+ priv = load_sk()
267
+ elif isinstance(first, str) and len(first) < 64 and "/" not in first and ".pem" not in first:
268
+ name = first
269
+ payload = second
270
+ try:
271
+ priv = load_sk(name)
272
+ except Exception:
273
+ priv = load_sk()
274
+ else:
275
+ priv = first
276
+ payload = second if second is not None else kwargs.get("data") or kwargs.get("message") or kwargs.get("payload")
277
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
278
+ from cryptography.hazmat.primitives import serialization
279
+ import hashlib as _hl
280
+ import json as _js
281
+ if hasattr(priv, "sign"):
282
+ priv_obj = priv
283
+ elif isinstance(priv, bytes) and len(priv) == 32:
284
+ priv_obj = Ed25519PrivateKey.from_private_bytes(priv)
285
+ elif isinstance(priv, bytes):
286
+ try:
287
+ priv_obj = serialization.load_pem_private_key(priv, password=None)
288
+ except Exception:
289
+ priv_obj = load_sk(name) if name else load_sk()
290
+ elif isinstance(priv, str) and priv.strip().startswith("-----"):
291
+ priv_obj = serialization.load_pem_private_key(priv.encode(), password=None)
292
+ elif isinstance(priv, str):
293
+ priv_obj = Ed25519PrivateKey.from_private_bytes(bytes.fromhex(priv.strip()))
294
+ else:
295
+ priv_obj = priv
296
+ if isinstance(payload, bytes):
297
+ msg = payload
298
+ elif isinstance(payload, str):
299
+ msg = payload.encode()
300
+ elif isinstance(payload, dict):
301
+ msg = _js.dumps(payload, sort_keys=True).encode()
302
+ else:
303
+ msg = bytes(payload) if payload is not None else b""
304
+ sig = priv_obj.sign(msg)
305
+ pub_obj = priv_obj.public_key()
306
+ pub_hex = pub_obj.public_bytes(encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw).hex()
307
+ pub_pem = pub_obj.public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo).decode()
308
+ return {"signature": sig.hex(), "sig": sig.hex(), "public_key": pub_hex, "pub": pub_hex, "public_key_pem": pub_pem, "payload_sha256": _hl.sha256(msg).hexdigest()}
309
+
310
+ import pathlib as _pl
311
+ if not globals().get("KEY_DIR"):
312
+ KEY_DIR=_pl.Path.home()/".arkhe"/"keys"
313
+ try:
314
+ KEY_DIR.mkdir(parents=True, exist_ok=True)
315
+ except Exception:
316
+ pass
File without changes
@@ -0,0 +1,136 @@
1
+ def verify_receipt(*args, **kwargs):
2
+ pub = kwargs.get("public_key") or kwargs.get("pub") or kwargs.get("public")
3
+ data = kwargs.get("data") or kwargs.get("message") or kwargs.get("payload")
4
+ sig = kwargs.get("signature") or kwargs.get("sig") or kwargs.get("sign")
5
+ if len(args) == 1 and isinstance(args[0], dict):
6
+ a = args[0]
7
+ pub = pub or a.get("public_key") or a.get("pub") or a.get("public")
8
+ data = data or a.get("data") or a.get("message") or a.get("payload") or a.get("artifact")
9
+ sig = sig or a.get("signature") or a.get("sig") or a.get("sign")
10
+ elif len(args) == 2 and isinstance(args[1], dict):
11
+ d = dict(args[1])
12
+ d["public_key"] = args[0]
13
+ return verify_receipt(d)
14
+ elif len(args) >= 3:
15
+ pub, data, sig = args[0], args[1], args[2]
16
+ elif len(args) == 2:
17
+ data, sig = args
18
+ from cryptography.exceptions import InvalidSignature
19
+ pub_obj = _get_pub(pub)
20
+ msg = _get_data(data)
21
+ sig_b = _get_sig(sig)
22
+ try:
23
+ pub_obj.verify(sig_b, msg)
24
+ return True
25
+ except InvalidSignature:
26
+ return False
27
+ verify_artifact = verify_receipt
28
+ import hashlib, subprocess, json, pathlib, base64
29
+ def verify_sha256(path, expected):
30
+ h = hashlib.sha256()
31
+ with open(path, "rb") as f:
32
+ for chunk in iter(lambda: f.read(8192), b""):
33
+ h.update(chunk)
34
+ return h.hexdigest() == expected
35
+ def verify_gpg(sig, data):
36
+ r = subprocess.run(["gpg", "--verify", sig, data], capture_output=True, text=True)
37
+ return r.returncode == 0
38
+ def verify_traceability(trace_path="arkhe-global/vault/traceability.json"):
39
+ d = json.loads(pathlib.Path(trace_path).read_text())
40
+ for a in d["artifacts"]:
41
+ if not verify_sha256(a["path"], a["sha256"]):
42
+ return False
43
+ return True
44
+ def _get_data(data):
45
+ if isinstance(data, (bytes, bytearray)):
46
+ return bytes(data)
47
+ if isinstance(data, dict):
48
+ return json.dumps(data, sort_keys=True).encode()
49
+ if isinstance(data, str):
50
+ p = pathlib.Path(data)
51
+ if p.exists() and p.is_file():
52
+ return p.read_bytes()
53
+ return data.encode()
54
+ return pathlib.Path(data).read_bytes()
55
+ def _get_pub(public_key):
56
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
57
+ from cryptography.hazmat.primitives import serialization
58
+ if hasattr(public_key, "verify"):
59
+ return public_key
60
+ if isinstance(public_key, str):
61
+ s = public_key.strip()
62
+ if len(s) == 64:
63
+ try:
64
+ return Ed25519PublicKey.from_public_bytes(bytes.fromhex(s))
65
+ except Exception:
66
+ pass
67
+ return serialization.load_pem_public_key(s.encode())
68
+ b = bytes(public_key)
69
+ if len(b) == 32:
70
+ return Ed25519PublicKey.from_public_bytes(b)
71
+ return serialization.load_pem_public_key(b)
72
+ def _get_sig(signature):
73
+ if isinstance(signature, (bytes, bytearray)):
74
+ return bytes(signature)
75
+ if isinstance(signature, str):
76
+ s = signature.strip()
77
+ try:
78
+ return bytes.fromhex(s)
79
+ except Exception:
80
+ pass
81
+ try:
82
+ return base64.b64decode(s)
83
+ except Exception:
84
+ return s.encode()
85
+ return bytes(signature)
86
+ class _Result(dict):
87
+ def __bool__(self):
88
+ return bool(self.get("valid"))
89
+ def verify_receipt(*args, **kwargs):
90
+ payload = None
91
+ receipt = None
92
+ pub = None
93
+ sig = None
94
+ if len(args) == 1 and isinstance(args[0], dict):
95
+ receipt = args[0]
96
+ payload = receipt.get("payload") or receipt.get("data") or receipt.get("message") or kwargs.get("payload") or kwargs.get("data")
97
+ pub = receipt.get("public_key") or receipt.get("pub") or receipt.get("public") or receipt.get("public_key_pem")
98
+ sig = receipt.get("signature") or receipt.get("sig") or receipt.get("sign")
99
+ elif len(args) == 2:
100
+ payload = args[0]
101
+ if isinstance(args[1], dict):
102
+ receipt = args[1]
103
+ pub = receipt.get("public_key") or receipt.get("pub") or receipt.get("public") or receipt.get("public_key_pem")
104
+ sig = receipt.get("signature") or receipt.get("sig") or receipt.get("sign")
105
+ else:
106
+ sig = args[1]
107
+ pub = kwargs.get("public_key") or kwargs.get("pub") or kwargs.get("public")
108
+ elif len(args) >= 3:
109
+ pub = args[0]
110
+ payload = args[1]
111
+ sig = args[2]
112
+ else:
113
+ pub = kwargs.get("public_key") or kwargs.get("pub") or kwargs.get("public")
114
+ payload = kwargs.get("payload") or kwargs.get("data") or kwargs.get("message")
115
+ sig = kwargs.get("signature") or kwargs.get("sig") or kwargs.get("sign")
116
+ if isinstance(pub, str) and len(pub) < 64 and "/" not in pub and ".pem" not in pub and not pub.strip().startswith("-----"):
117
+ try:
118
+ from core.signer.signer import load_pk as _lpk
119
+ pub = _lpk(pub)
120
+ except Exception:
121
+ pass
122
+ try:
123
+ pub_obj = _get_pub(pub)
124
+ msg = _get_data(payload)
125
+ sig_b = _get_sig(sig)
126
+ from cryptography.exceptions import InvalidSignature
127
+ try:
128
+ pub_obj.verify(sig_b, msg)
129
+ return _Result({"valid": True, "errors": []})
130
+ except InvalidSignature:
131
+ return _Result({"valid": False, "errors": ["invalid signature"]})
132
+ except Exception as e:
133
+ return _Result({"valid": False, "errors": [str(e)]})
134
+ except Exception as e:
135
+ return _Result({"valid": False, "errors": [str(e)]})
136
+ verify_artifact = verify_receipt
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env python3
2
+ import sys, hashlib, base64, argparse
3
+ from pathlib import Path
4
+
5
+ VERSION = "1.1.0"
6
+
7
+ def cmd_version(args):
8
+ print(f"arkhe-auth {VERSION}")
9
+ return 0
10
+
11
+ def cmd_demo(args):
12
+ print("ARKHE-AUTH Demo")
13
+ print("=" * 50)
14
+ try:
15
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
16
+ from cryptography.hazmat.primitives import serialization
17
+ except ImportError:
18
+ print("ERROR: pip install cryptography")
19
+ return 1
20
+ doc = Path("demo-document.txt")
21
+ doc.write_text("ARKHE-AUTH demo document\n")
22
+ print(f"[1/4] Created {doc} ({doc.stat().st_size} bytes)")
23
+ h = hashlib.sha256(doc.read_bytes()).hexdigest()
24
+ print(f"[2/4] SHA-256: {h[:32]}...")
25
+ key = Ed25519PrivateKey.generate()
26
+ sig = key.sign(doc.read_bytes())
27
+ key_path = Path("demo-key.pem")
28
+ key_path.write_bytes(key.private_bytes(
29
+ encoding=serialization.Encoding.PEM,
30
+ format=serialization.PrivateFormat.PKCS8,
31
+ encryption_algorithm=serialization.NoEncryption()))
32
+ sig_path = Path("demo-document.txt.sig")
33
+ sig_path.write_text(base64.b64encode(sig).decode())
34
+ print(f"[3/4] Signed with Ed25519")
35
+ key.public_key().verify(sig, doc.read_bytes())
36
+ print(f"[4/4] VERIFIED")
37
+ print()
38
+ print(f"Result: signature is valid for {doc}")
39
+ print(f"Hash: {h}")
40
+ return 0
41
+
42
+ def cmd_sign(args):
43
+ try:
44
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
45
+ from cryptography.hazmat.primitives import serialization
46
+ except ImportError:
47
+ print("ERROR: pip install cryptography")
48
+ return 1
49
+ f = Path(args.file)
50
+ if not f.exists():
51
+ print(f"ERROR: {f} not found")
52
+ return 1
53
+ key_path = Path(args.key)
54
+ if key_path.exists():
55
+ key = serialization.load_pem_private_key(key_path.read_bytes(), password=None)
56
+ else:
57
+ key = Ed25519PrivateKey.generate()
58
+ key_path.write_bytes(key.private_bytes(
59
+ encoding=serialization.Encoding.PEM,
60
+ format=serialization.PrivateFormat.PKCS8,
61
+ encryption_algorithm=serialization.NoEncryption()))
62
+ print(f"Generated new key: {key_path}")
63
+ sig = key.sign(f.read_bytes())
64
+ sig_path = Path(str(f) + ".sig")
65
+ sig_path.write_text(base64.b64encode(sig).decode())
66
+ h = hashlib.sha256(f.read_bytes()).hexdigest()
67
+ print(f"Signed: {f}")
68
+ print(f"Sig: {sig_path}")
69
+ print(f"Hash: {h}")
70
+ return 0
71
+
72
+ def cmd_verify(args):
73
+ try:
74
+ from cryptography.hazmat.primitives import serialization
75
+ except ImportError:
76
+ print("ERROR: pip install cryptography")
77
+ return 1
78
+ f = Path(args.file)
79
+ s = Path(args.sig)
80
+ k = Path(args.key)
81
+ for p in [f, s, k]:
82
+ if not p.exists():
83
+ print(f"ERROR: {p} not found")
84
+ return 1
85
+ sig = base64.b64decode(s.read_text())
86
+ key = serialization.load_pem_private_key(k.read_bytes(), password=None)
87
+ try:
88
+ key.public_key().verify(sig, f.read_bytes())
89
+ print(f"VERIFIED: {f}")
90
+ return 0
91
+ except Exception:
92
+ print(f"INVALID: signature does not match {f}")
93
+ return 1
94
+
95
+ def main():
96
+ p = argparse.ArgumentParser(prog="arkhe-auth")
97
+ sub = p.add_subparsers(dest="cmd")
98
+ sub.add_parser("version").set_defaults(func=cmd_version)
99
+ sub.add_parser("demo").set_defaults(func=cmd_demo)
100
+ sp = sub.add_parser("sign")
101
+ sp.add_argument("file")
102
+ sp.add_argument("--key", default="arkhe-key.pem")
103
+ sp.set_defaults(func=cmd_sign)
104
+ vp = sub.add_parser("verify")
105
+ vp.add_argument("file")
106
+ vp.add_argument("sig")
107
+ vp.add_argument("--key", default="arkhe-key.pem")
108
+ vp.set_defaults(func=cmd_verify)
109
+ args = p.parse_args()
110
+ if not args.cmd:
111
+ p.print_help()
112
+ return 0
113
+ return args.func(args)
114
+
115
+ if __name__ == "__main__":
116
+ sys.exit(main())
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "arkhe-auth"
7
+ version = "1.1.1"
8
+ description = "Post-Quantum Human-AI Attribution Protocol"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = {text = "MIT"}
12
+ authors = [{name = "ARKHE-ZERO"}]
13
+ dependencies = ["cryptography>=41.0.0"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ ]
18
+
19
+ [project.scripts]
20
+ arkhe-auth = "launcher:main"
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/MarcoValdovinos/arkhe-auth"
24
+
25
+ [tool.setuptools]
26
+ py-modules = ["launcher"]
27
+
28
+ [tool.setuptools.packages.find]
29
+ include = ["core*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,13 @@
1
+ import pathlib, json
2
+ from core.signer.signer import sha256_file
3
+ from core.verifier.verifier import verify_sha256, verify_traceability
4
+ def test_sha256_traceability_file():
5
+ h = sha256_file("arkhe-global/vault/traceability.json")
6
+ assert h == "865f2de98edcef0857fdbd9440e68aad7a3e54b90765668de2a735d70a765800"
7
+ def test_traceability_structure():
8
+ d = json.loads(pathlib.Path("arkhe-global/vault/traceability.json").read_text())
9
+ assert d["manifest"] == "e8d9eac8"
10
+ assert len(d["artifacts"]) == 3
11
+ assert d["gobernanza"] == "51% Humano / 49% IA [PROPUESTA]"
12
+ def test_verify_sha256_local():
13
+ assert verify_sha256("arkhe-global/vault/traceability.json", "865f2de98edcef0857fdbd9440e68aad7a3e54b90765668de2a735d70a765800")
@@ -0,0 +1,23 @@
1
+ import hashlib
2
+ import random
3
+ import string
4
+
5
+ def _random_bytes():
6
+ n = random.randint(0, 500)
7
+ return bytes(random.getrandbits(8) for _ in range(n))
8
+
9
+ def test_fuzz_sha256_random_bytes_never_crashes():
10
+ for _ in range(200):
11
+ data = _random_bytes()
12
+ h = hashlib.sha256(data).hexdigest()
13
+ assert len(h) == 64
14
+
15
+ def test_fuzz_sha256_random_text_never_crashes():
16
+ for _ in range(200):
17
+ text = "".join(random.choice(string.printable) for _ in range(random.randint(0, 200)))
18
+ h = hashlib.sha256(text.encode(errors="ignore")).hexdigest()
19
+ assert len(h) == 64
20
+
21
+ def test_fuzz_empty_and_edge_cases():
22
+ for data in [b"", b"\x00", b"\xff" * 1000, "nandu".encode()]:
23
+ assert len(hashlib.sha256(data).hexdigest()) == 64
@@ -0,0 +1,14 @@
1
+ """Verifica que el servidor MCP carga y expone las 3 tools."""
2
+
3
+
4
+ def test_mcp_server_imports():
5
+ import mcp_server.server as srv
6
+ assert hasattr(srv, "get_public_keys")
7
+ assert hasattr(srv, "verify_example")
8
+ assert hasattr(srv, "verify_artifact")
9
+
10
+
11
+ def test_mcp_fastmcp_importable():
12
+ """Regresion: si el SDK 'mcp' vuelve a estar shadoweado, este test falla."""
13
+ from mcp.server.fastmcp import FastMCP # noqa: F401
14
+ assert True
@@ -0,0 +1,19 @@
1
+ """Verificacion offline de un recibo ML-DSA-87 sin contactar la API."""
2
+ import json
3
+ import base64
4
+ import hashlib
5
+ from pathlib import Path
6
+ from dilithium_py.ml_dsa import ML_DSA_87
7
+
8
+
9
+ def test_example_receipt_is_valid():
10
+ root = Path(__file__).parent.parent / "examples"
11
+ data = (root / "test-artifact.txt").read_bytes()
12
+ receipt = json.loads((root / "test-artifact.txt.receipt.json").read_text())
13
+
14
+ sha = hashlib.sha256(data).hexdigest()
15
+ assert sha == receipt["sha256"], "hash no coincide con el recibo"
16
+
17
+ pk = base64.b64decode(receipt["signer_pk_b64"])
18
+ sig = base64.b64decode(receipt["sig_b64"])
19
+ assert ML_DSA_87.verify(pk, data, sig), "firma ML-DSA-87 invalida"
@@ -0,0 +1,21 @@
1
+ from core.signer.signer import generate_keypair, sign_artifact
2
+ from core.verifier.verifier import verify_receipt
3
+
4
+
5
+ def test_roundtrip(tmp_path, monkeypatch):
6
+ monkeypatch.setattr("core.signer.signer.KEY_DIR", str(tmp_path))
7
+ generate_keypair("test")
8
+ payload = b"contenido de prueba anti-falsificacion"
9
+ receipt = sign_artifact(payload, "test")
10
+ result = verify_receipt(payload, receipt)
11
+ assert result["valid"], result["errors"]
12
+
13
+
14
+ def test_tampered_fails(tmp_path, monkeypatch):
15
+ monkeypatch.setattr("core.signer.signer.KEY_DIR", str(tmp_path))
16
+ generate_keypair("test")
17
+ payload = b"contenido original"
18
+ receipt = sign_artifact(payload, "test")
19
+ tampered = b"contenido alterado"
20
+ result = verify_receipt(tampered, receipt)
21
+ assert not result["valid"]