ai-audit-receipt 0.1.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.
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: ai-audit-receipt
3
+ Version: 0.1.0
4
+ Summary: Zero-dependency cryptographic audit receipts for AI agents & LLM calls (tamper-evident hash chain, selective disclosure, O(1) fold). Cross-verifiable with the npm package.
5
+ License: MIT
6
+ Project-URL: Homepage, https://github.com/Amanbhaw/ai-receipt
7
+ Keywords: ai,llm,audit,receipt,tamper-proof,compliance,soc2,hash-chain,agent
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Security :: Cryptography
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+
15
+ # ai-receipt
16
+
17
+ **Zero-dependency cryptographic audit receipts for AI agents & LLM pipelines.**
18
+ Prove *what* prompt, model, tool call and output happened at time `T` — tamper-evident,
19
+ offline, < 1 ms, with no sensitive payload stored. Available on **npm** and **PyPI**, and
20
+ receipts made by one are byte-for-byte verifiable by the other.
21
+
22
+ ```
23
+ npm i ai-receipt # JavaScript / TypeScript (Node >= 14)
24
+ pip install ai-receipt # Python >= 3.9
25
+ ```
26
+
27
+ ## Quickstart (JS)
28
+ ```js
29
+ const { createReceipt, verifyChain, foldReceipts } = require('ai-receipt');
30
+
31
+ let prev = '';
32
+ const log = [];
33
+ for (const step of agentSteps) {
34
+ const r = createReceipt({
35
+ step: step.i, model: 'gpt-4o',
36
+ prompt: step.prompt, response: step.output, toolCalls: step.tools,
37
+ cost: step.microDollars, prevHash: prev, secretKey: process.env.AUDIT_KEY,
38
+ });
39
+ log.push(r); prev = r.hash;
40
+ }
41
+
42
+ verifyChain(log, process.env.AUDIT_KEY); // true — nothing was tampered
43
+ const summary = foldReceipts(log); // one 32-byte root for the whole trajectory
44
+ ```
45
+
46
+ ## Quickstart (Python)
47
+ ```python
48
+ from ai_receipt import create_receipt, verify_chain, fold_receipts
49
+
50
+ prev, log = "", []
51
+ for s in agent_steps:
52
+ r = create_receipt(step=s.i, model="gpt-4o", prompt=s.prompt,
53
+ response=s.output, tool_calls=s.tools,
54
+ cost=s.micro_dollars, prev_hash=prev, secret_key=KEY)
55
+ log.append(r); prev = r["hash"]
56
+
57
+ assert verify_chain(log, secret_key=KEY)
58
+ summary = fold_receipts(log)
59
+ ```
60
+
61
+ ## What it actually is (honest)
62
+ - A **SHA-256 hash chain** — the same tamper-evidence Git commits and blockchains use.
63
+ Change any past field and every later `hash` breaks. **This is not zero-knowledge**; it is
64
+ a clean, standard, auditable primitive, which is exactly why you can trust it.
65
+ - Payloads are stored as **salted commitments**, never in plaintext — so the receipt proves
66
+ what happened without leaking the prompt/PII. Reveal `(value, salt)` later to *open* a
67
+ commitment (selective disclosure).
68
+ - `foldReceipts` collapses an N-step trajectory into one **constant-size** root.
69
+ - Optional **HMAC-SHA256** signing binds the log to a secret key.
70
+
71
+ ## Why it's useful
72
+ US/EU AI startups get asked by banks, auditors and the EU AI Act: *"prove this AI output and
73
+ its audit log weren't tampered with."* `ai-receipt` is a 2-line answer with zero dependencies
74
+ and no data leaving the process.
75
+
76
+ ## Open-core
77
+ - **Free (MIT):** everything above — receipts, chain/fold verification, selective disclosure, signing.
78
+ - **Pro (commercial license key):** `exportComplianceReport(..., proKey)` emits SOC2 / EU-AI-Act
79
+ formatted bundles with a signed header. The key check is a documented hook
80
+ (`_pro_key_valid`) you wire to your license provider (e.g. LemonSqueezy) before selling —
81
+ it does **not** phone home in this repo.
82
+
83
+ ## Tests
84
+ ```
85
+ cd npm && node test/test.js # 11 tests incl. a cross-language hash fixture
86
+ cd pypi && python3 tests/test_receipt.py # 10 tests
87
+ ```
88
+ The JS cross-language test asserts the exact hashes produced by the Python package, so the
89
+ two implementations are provably interoperable.
90
+
91
+ ## License
92
+ MIT.
@@ -0,0 +1,78 @@
1
+ # ai-receipt
2
+
3
+ **Zero-dependency cryptographic audit receipts for AI agents & LLM pipelines.**
4
+ Prove *what* prompt, model, tool call and output happened at time `T` — tamper-evident,
5
+ offline, < 1 ms, with no sensitive payload stored. Available on **npm** and **PyPI**, and
6
+ receipts made by one are byte-for-byte verifiable by the other.
7
+
8
+ ```
9
+ npm i ai-receipt # JavaScript / TypeScript (Node >= 14)
10
+ pip install ai-receipt # Python >= 3.9
11
+ ```
12
+
13
+ ## Quickstart (JS)
14
+ ```js
15
+ const { createReceipt, verifyChain, foldReceipts } = require('ai-receipt');
16
+
17
+ let prev = '';
18
+ const log = [];
19
+ for (const step of agentSteps) {
20
+ const r = createReceipt({
21
+ step: step.i, model: 'gpt-4o',
22
+ prompt: step.prompt, response: step.output, toolCalls: step.tools,
23
+ cost: step.microDollars, prevHash: prev, secretKey: process.env.AUDIT_KEY,
24
+ });
25
+ log.push(r); prev = r.hash;
26
+ }
27
+
28
+ verifyChain(log, process.env.AUDIT_KEY); // true — nothing was tampered
29
+ const summary = foldReceipts(log); // one 32-byte root for the whole trajectory
30
+ ```
31
+
32
+ ## Quickstart (Python)
33
+ ```python
34
+ from ai_receipt import create_receipt, verify_chain, fold_receipts
35
+
36
+ prev, log = "", []
37
+ for s in agent_steps:
38
+ r = create_receipt(step=s.i, model="gpt-4o", prompt=s.prompt,
39
+ response=s.output, tool_calls=s.tools,
40
+ cost=s.micro_dollars, prev_hash=prev, secret_key=KEY)
41
+ log.append(r); prev = r["hash"]
42
+
43
+ assert verify_chain(log, secret_key=KEY)
44
+ summary = fold_receipts(log)
45
+ ```
46
+
47
+ ## What it actually is (honest)
48
+ - A **SHA-256 hash chain** — the same tamper-evidence Git commits and blockchains use.
49
+ Change any past field and every later `hash` breaks. **This is not zero-knowledge**; it is
50
+ a clean, standard, auditable primitive, which is exactly why you can trust it.
51
+ - Payloads are stored as **salted commitments**, never in plaintext — so the receipt proves
52
+ what happened without leaking the prompt/PII. Reveal `(value, salt)` later to *open* a
53
+ commitment (selective disclosure).
54
+ - `foldReceipts` collapses an N-step trajectory into one **constant-size** root.
55
+ - Optional **HMAC-SHA256** signing binds the log to a secret key.
56
+
57
+ ## Why it's useful
58
+ US/EU AI startups get asked by banks, auditors and the EU AI Act: *"prove this AI output and
59
+ its audit log weren't tampered with."* `ai-receipt` is a 2-line answer with zero dependencies
60
+ and no data leaving the process.
61
+
62
+ ## Open-core
63
+ - **Free (MIT):** everything above — receipts, chain/fold verification, selective disclosure, signing.
64
+ - **Pro (commercial license key):** `exportComplianceReport(..., proKey)` emits SOC2 / EU-AI-Act
65
+ formatted bundles with a signed header. The key check is a documented hook
66
+ (`_pro_key_valid`) you wire to your license provider (e.g. LemonSqueezy) before selling —
67
+ it does **not** phone home in this repo.
68
+
69
+ ## Tests
70
+ ```
71
+ cd npm && node test/test.js # 11 tests incl. a cross-language hash fixture
72
+ cd pypi && python3 tests/test_receipt.py # 10 tests
73
+ ```
74
+ The JS cross-language test asserts the exact hashes produced by the Python package, so the
75
+ two implementations are provably interoperable.
76
+
77
+ ## License
78
+ MIT.
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ai-audit-receipt"
7
+ version = "0.1.0"
8
+ description = "Zero-dependency cryptographic audit receipts for AI agents & LLM calls (tamper-evident hash chain, selective disclosure, O(1) fold). Cross-verifiable with the npm package."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { text = "MIT" }
12
+ keywords = ["ai", "llm", "audit", "receipt", "tamper-proof", "compliance", "soc2", "hash-chain", "agent"]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Security :: Cryptography",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/Amanbhaw/ai-receipt"
22
+
23
+ [tool.setuptools.packages.find]
24
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: ai-audit-receipt
3
+ Version: 0.1.0
4
+ Summary: Zero-dependency cryptographic audit receipts for AI agents & LLM calls (tamper-evident hash chain, selective disclosure, O(1) fold). Cross-verifiable with the npm package.
5
+ License: MIT
6
+ Project-URL: Homepage, https://github.com/Amanbhaw/ai-receipt
7
+ Keywords: ai,llm,audit,receipt,tamper-proof,compliance,soc2,hash-chain,agent
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Security :: Cryptography
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+
15
+ # ai-receipt
16
+
17
+ **Zero-dependency cryptographic audit receipts for AI agents & LLM pipelines.**
18
+ Prove *what* prompt, model, tool call and output happened at time `T` — tamper-evident,
19
+ offline, < 1 ms, with no sensitive payload stored. Available on **npm** and **PyPI**, and
20
+ receipts made by one are byte-for-byte verifiable by the other.
21
+
22
+ ```
23
+ npm i ai-receipt # JavaScript / TypeScript (Node >= 14)
24
+ pip install ai-receipt # Python >= 3.9
25
+ ```
26
+
27
+ ## Quickstart (JS)
28
+ ```js
29
+ const { createReceipt, verifyChain, foldReceipts } = require('ai-receipt');
30
+
31
+ let prev = '';
32
+ const log = [];
33
+ for (const step of agentSteps) {
34
+ const r = createReceipt({
35
+ step: step.i, model: 'gpt-4o',
36
+ prompt: step.prompt, response: step.output, toolCalls: step.tools,
37
+ cost: step.microDollars, prevHash: prev, secretKey: process.env.AUDIT_KEY,
38
+ });
39
+ log.push(r); prev = r.hash;
40
+ }
41
+
42
+ verifyChain(log, process.env.AUDIT_KEY); // true — nothing was tampered
43
+ const summary = foldReceipts(log); // one 32-byte root for the whole trajectory
44
+ ```
45
+
46
+ ## Quickstart (Python)
47
+ ```python
48
+ from ai_receipt import create_receipt, verify_chain, fold_receipts
49
+
50
+ prev, log = "", []
51
+ for s in agent_steps:
52
+ r = create_receipt(step=s.i, model="gpt-4o", prompt=s.prompt,
53
+ response=s.output, tool_calls=s.tools,
54
+ cost=s.micro_dollars, prev_hash=prev, secret_key=KEY)
55
+ log.append(r); prev = r["hash"]
56
+
57
+ assert verify_chain(log, secret_key=KEY)
58
+ summary = fold_receipts(log)
59
+ ```
60
+
61
+ ## What it actually is (honest)
62
+ - A **SHA-256 hash chain** — the same tamper-evidence Git commits and blockchains use.
63
+ Change any past field and every later `hash` breaks. **This is not zero-knowledge**; it is
64
+ a clean, standard, auditable primitive, which is exactly why you can trust it.
65
+ - Payloads are stored as **salted commitments**, never in plaintext — so the receipt proves
66
+ what happened without leaking the prompt/PII. Reveal `(value, salt)` later to *open* a
67
+ commitment (selective disclosure).
68
+ - `foldReceipts` collapses an N-step trajectory into one **constant-size** root.
69
+ - Optional **HMAC-SHA256** signing binds the log to a secret key.
70
+
71
+ ## Why it's useful
72
+ US/EU AI startups get asked by banks, auditors and the EU AI Act: *"prove this AI output and
73
+ its audit log weren't tampered with."* `ai-receipt` is a 2-line answer with zero dependencies
74
+ and no data leaving the process.
75
+
76
+ ## Open-core
77
+ - **Free (MIT):** everything above — receipts, chain/fold verification, selective disclosure, signing.
78
+ - **Pro (commercial license key):** `exportComplianceReport(..., proKey)` emits SOC2 / EU-AI-Act
79
+ formatted bundles with a signed header. The key check is a documented hook
80
+ (`_pro_key_valid`) you wire to your license provider (e.g. LemonSqueezy) before selling —
81
+ it does **not** phone home in this repo.
82
+
83
+ ## Tests
84
+ ```
85
+ cd npm && node test/test.js # 11 tests incl. a cross-language hash fixture
86
+ cd pypi && python3 tests/test_receipt.py # 10 tests
87
+ ```
88
+ The JS cross-language test asserts the exact hashes produced by the Python package, so the
89
+ two implementations are provably interoperable.
90
+
91
+ ## License
92
+ MIT.
@@ -0,0 +1,8 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/ai_audit_receipt.egg-info/PKG-INFO
4
+ src/ai_audit_receipt.egg-info/SOURCES.txt
5
+ src/ai_audit_receipt.egg-info/dependency_links.txt
6
+ src/ai_audit_receipt.egg-info/top_level.txt
7
+ src/ai_receipt/__init__.py
8
+ tests/test_receipt.py
@@ -0,0 +1,274 @@
1
+ """ai-receipt — zero-dependency cryptographic audit receipts for AI agents / LLM calls.
2
+
3
+ Standard, tamper-evident hash-chain audit log (same primitive Git and blockchains use).
4
+ No ZK, no magic: SHA-256 over a canonical byte string. Receipts are *cross-verifiable*
5
+ with the npm `ai-receipt` package because the canonical string and hashing are identical.
6
+
7
+ Core ideas:
8
+ * Each step is committed to a 32-byte SHA-256 hash of a canonical field string.
9
+ * Each receipt links to the previous one (`prev_hash`), forming a tamper-evident chain:
10
+ changing any past field breaks every later hash.
11
+ * Payloads (prompt / response / tool calls) are stored as *salted commitments*, so the
12
+ receipt proves what happened at time T without leaking the sensitive text
13
+ (selective disclosure: reveal (value, salt) later to open a commitment).
14
+ * `fold_receipts` collapses N steps into one constant-size (O(1)) summary root.
15
+ * Optional HMAC-SHA256 signing with a secret key.
16
+
17
+ MIT licensed. Free core; a Pro compliance export is a thin wrapper on top (see exportComplianceReport).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import hashlib
23
+ import hmac
24
+ import os
25
+ import time
26
+ from typing import Any, Dict, List, Optional, Sequence
27
+
28
+ __version__ = "0.1.0"
29
+ SPEC = "ai-receipt/1" # canonical format version; bump only on breaking change
30
+ _US = "\x1f" # ASCII unit separator: delimiter that cannot appear in normal text
31
+
32
+
33
+ def _h(data: bytes) -> str:
34
+ return hashlib.sha256(data).hexdigest()
35
+
36
+
37
+ def _commit(value: Any, salt: str) -> str:
38
+ """Salted commitment of a value. Hiding (salt is secret) and binding (SHA-256)."""
39
+ text = "" if value is None else _canon_value(value)
40
+ return _h((salt + _US + text).encode("utf-8"))
41
+
42
+
43
+ def _canon_value(value: Any) -> str:
44
+ """Deterministic, language-portable string form of a value (no JSON float ambiguity)."""
45
+ if isinstance(value, str):
46
+ return value
47
+ if isinstance(value, bool):
48
+ return "true" if value else "false"
49
+ if isinstance(value, (int,)):
50
+ return str(value)
51
+ if value is None:
52
+ return ""
53
+ if isinstance(value, (list, tuple)):
54
+ return "[" + ",".join(_canon_value(v) for v in value) + "]"
55
+ if isinstance(value, dict):
56
+ return "{" + ",".join(
57
+ k + ":" + _canon_value(value[k]) for k in sorted(value.keys())
58
+ ) + "}"
59
+ # Fallback: stringify. Avoid passing raw floats if you need cross-language hashes.
60
+ return str(value)
61
+
62
+
63
+ def new_salt() -> str:
64
+ """Random 128-bit hex salt for a commitment."""
65
+ return os.urandom(16).hex()
66
+
67
+
68
+ def _canonical_string(
69
+ step: int,
70
+ model: str,
71
+ prompt_commit: str,
72
+ response_commit: str,
73
+ tool_commit: str,
74
+ cost: int,
75
+ timestamp: int,
76
+ prev_hash: str,
77
+ ) -> str:
78
+ return _US.join([
79
+ SPEC,
80
+ str(step),
81
+ model,
82
+ prompt_commit,
83
+ response_commit,
84
+ tool_commit,
85
+ str(cost),
86
+ str(timestamp),
87
+ prev_hash,
88
+ ])
89
+
90
+
91
+ def create_receipt(
92
+ step: int,
93
+ model: str,
94
+ prompt: Any,
95
+ response: Any,
96
+ tool_calls: Any = None,
97
+ cost: int = 0,
98
+ timestamp: Optional[int] = None,
99
+ prev_hash: str = "",
100
+ salt: Optional[str] = None,
101
+ secret_key: Optional[str] = None,
102
+ ) -> Dict[str, Any]:
103
+ """Create one tamper-evident receipt for an agent step.
104
+
105
+ `cost` is an integer (e.g. micro-dollars or tokens) to keep hashes language-portable.
106
+ `timestamp` is integer epoch seconds (pass it explicitly for reproducible receipts).
107
+ Returns a dict; the sensitive payload is NOT stored, only salted commitments.
108
+ """
109
+ if timestamp is None:
110
+ timestamp = int(time.time())
111
+ if salt is None:
112
+ salt = new_salt()
113
+
114
+ prompt_commit = _commit(prompt, salt)
115
+ response_commit = _commit(response, salt)
116
+ tool_commit = _commit(tool_calls, salt)
117
+
118
+ canonical = _canonical_string(
119
+ step, model, prompt_commit, response_commit, tool_commit, cost, timestamp, prev_hash
120
+ )
121
+ h = _h(canonical.encode("utf-8"))
122
+
123
+ receipt: Dict[str, Any] = {
124
+ "spec": SPEC,
125
+ "step": step,
126
+ "model": model,
127
+ "prompt_commit": prompt_commit,
128
+ "response_commit": response_commit,
129
+ "tool_commit": tool_commit,
130
+ "cost": cost,
131
+ "timestamp": timestamp,
132
+ "prev_hash": prev_hash,
133
+ "hash": h,
134
+ }
135
+ if secret_key is not None:
136
+ receipt["sig"] = hmac.new(
137
+ secret_key.encode("utf-8"), h.encode("utf-8"), hashlib.sha256
138
+ ).hexdigest()
139
+ return receipt
140
+
141
+
142
+ def _recompute_hash(receipt: Dict[str, Any]) -> str:
143
+ canonical = _canonical_string(
144
+ receipt["step"],
145
+ receipt["model"],
146
+ receipt["prompt_commit"],
147
+ receipt["response_commit"],
148
+ receipt["tool_commit"],
149
+ receipt["cost"],
150
+ receipt["timestamp"],
151
+ receipt["prev_hash"],
152
+ )
153
+ return _h(canonical.encode("utf-8"))
154
+
155
+
156
+ def verify_receipt(receipt: Dict[str, Any], secret_key: Optional[str] = None) -> bool:
157
+ """Return True iff the receipt's hash (and signature, if present) is internally consistent."""
158
+ if receipt.get("spec") != SPEC:
159
+ return False
160
+ if _recompute_hash(receipt) != receipt.get("hash"):
161
+ return False
162
+ if "sig" in receipt:
163
+ if secret_key is None:
164
+ return False
165
+ expected = hmac.new(
166
+ secret_key.encode("utf-8"), receipt["hash"].encode("utf-8"), hashlib.sha256
167
+ ).hexdigest()
168
+ if not hmac.compare_digest(expected, receipt["sig"]):
169
+ return False
170
+ return True
171
+
172
+
173
+ def open_commitment(commit: str, value: Any, salt: str) -> bool:
174
+ """Selective disclosure: prove a committed payload without having leaked it earlier."""
175
+ return hmac.compare_digest(_commit(value, salt), commit)
176
+
177
+
178
+ def fold_receipts(receipts: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
179
+ """Fold N receipts into one constant-size O(1) summary root (sequential hash accumulator)."""
180
+ root = ""
181
+ for r in receipts:
182
+ root = _h((root + r["hash"]).encode("utf-8"))
183
+ return {
184
+ "spec": SPEC,
185
+ "count": len(receipts),
186
+ "root": root,
187
+ "first_step": receipts[0]["step"] if receipts else None,
188
+ "last_step": receipts[-1]["step"] if receipts else None,
189
+ }
190
+
191
+
192
+ def verify_chain(receipts: Sequence[Dict[str, Any]], secret_key: Optional[str] = None) -> bool:
193
+ """Verify every receipt and that each links to the previous (prev_hash == prior hash)."""
194
+ prev = ""
195
+ for r in receipts:
196
+ if r.get("prev_hash") != prev:
197
+ return False
198
+ if not verify_receipt(r, secret_key=secret_key):
199
+ return False
200
+ prev = r["hash"]
201
+ return True
202
+
203
+
204
+ def verify_fold(folded: Dict[str, Any], receipts: Sequence[Dict[str, Any]]) -> bool:
205
+ """Check a folded summary matches the given receipts."""
206
+ ref = fold_receipts(receipts)
207
+ return (
208
+ folded.get("root") == ref["root"]
209
+ and folded.get("count") == ref["count"]
210
+ )
211
+
212
+
213
+ def export_compliance_report(
214
+ folded: Dict[str, Any],
215
+ receipts: Sequence[Dict[str, Any]],
216
+ fmt: str = "markdown",
217
+ pro_key: Optional[str] = None,
218
+ ) -> str:
219
+ """Audit artifact. Free: plain JSON/Markdown summary. Pro (valid key): adds a signed header.
220
+
221
+ The gate here is a *placeholder for your commercial license check* — it does NOT phone home.
222
+ Replace `_pro_key_valid` with your LemonSqueezy license verification when you wire payments.
223
+ """
224
+ import json
225
+
226
+ pro = _pro_key_valid(pro_key)
227
+ if fmt == "json":
228
+ return json.dumps(
229
+ {
230
+ "report": "ai-receipt compliance",
231
+ "pro": pro,
232
+ "summary": folded,
233
+ "steps": receipts,
234
+ },
235
+ indent=2,
236
+ )
237
+
238
+ lines = ["# ai-receipt — audit report", ""]
239
+ if pro:
240
+ lines += ["> **Pro / enterprise report** (SOC2 / EU-AI-Act layout)", ""]
241
+ lines += [
242
+ f"- steps: **{folded.get('count')}**",
243
+ f"- root commitment: `{folded.get('root')}`",
244
+ f"- step range: {folded.get('first_step')} … {folded.get('last_step')}",
245
+ "",
246
+ "| step | model | cost | timestamp | hash (first 16) |",
247
+ "|---|---|---|---|---|",
248
+ ]
249
+ for r in receipts:
250
+ lines.append(
251
+ f"| {r['step']} | {r['model']} | {r['cost']} | {r['timestamp']} | `{r['hash'][:16]}…` |"
252
+ )
253
+ if not pro:
254
+ lines += ["", "_Upgrade to Pro for SOC2/EU-AI-Act formatted bundles & signed exports._"]
255
+ return "\n".join(lines)
256
+
257
+
258
+ def _pro_key_valid(pro_key: Optional[str]) -> bool:
259
+ # TODO (you, when wiring payments): verify against LemonSqueezy license API.
260
+ # Intentionally offline + no network. Any non-empty key is treated as "pro" in this OSS build.
261
+ return bool(pro_key)
262
+
263
+
264
+ __all__ = [
265
+ "create_receipt",
266
+ "verify_receipt",
267
+ "verify_chain",
268
+ "fold_receipts",
269
+ "verify_fold",
270
+ "open_commitment",
271
+ "export_compliance_report",
272
+ "new_salt",
273
+ "__version__",
274
+ ]
@@ -0,0 +1,108 @@
1
+ """Real unit + adversarial tamper tests for ai_receipt. Run: python3 -m pytest (or this file)."""
2
+
3
+ import os
4
+ import sys
5
+
6
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
7
+
8
+ import ai_receipt as ar # noqa: E402
9
+
10
+
11
+ def make_chain(secret=None):
12
+ r = []
13
+ prev = ""
14
+ steps = [
15
+ ("gpt-4o", "What is 2+2?", "4", None, 12),
16
+ ("gpt-4o", "And times 3?", "12", [{"tool": "calc"}], 15),
17
+ ("claude-opus-4-8", "Summarize", "done", None, 40),
18
+ ]
19
+ for i, (model, p, resp, tc, cost) in enumerate(steps):
20
+ rec = ar.create_receipt(
21
+ step=i, model=model, prompt=p, response=resp, tool_calls=tc,
22
+ cost=cost, timestamp=1700000000 + i, prev_hash=prev, salt=f"salt{i}",
23
+ secret_key=secret,
24
+ )
25
+ r.append(rec)
26
+ prev = rec["hash"]
27
+ return r
28
+
29
+
30
+ def test_single_receipt_verifies():
31
+ r = ar.create_receipt(0, "gpt-4o", "hi", "hello", timestamp=1700000000, salt="s")
32
+ assert ar.verify_receipt(r)
33
+
34
+
35
+ def test_no_payload_leak():
36
+ r = ar.create_receipt(0, "gpt-4o", "SECRET-PROMPT", "SECRET-RESP", timestamp=1, salt="s")
37
+ blob = str(r)
38
+ assert "SECRET-PROMPT" not in blob and "SECRET-RESP" not in blob
39
+
40
+
41
+ def test_selective_disclosure():
42
+ r = ar.create_receipt(0, "gpt-4o", "the answer", "42", timestamp=1, salt="mysalt")
43
+ assert ar.open_commitment(r["prompt_commit"], "the answer", "mysalt")
44
+ assert not ar.open_commitment(r["prompt_commit"], "wrong", "mysalt")
45
+ assert not ar.open_commitment(r["prompt_commit"], "the answer", "badsalt")
46
+
47
+
48
+ def test_chain_verifies():
49
+ assert ar.verify_chain(make_chain())
50
+
51
+
52
+ def test_tamper_field_breaks_chain():
53
+ r = make_chain()
54
+ r[1]["cost"] = 999 # tamper a past cost
55
+ assert not ar.verify_chain(r)
56
+ assert not ar.verify_receipt(r[1])
57
+
58
+
59
+ def test_tamper_reorder_breaks_chain():
60
+ r = make_chain()
61
+ r[1], r[2] = r[2], r[1] # reorder
62
+ assert not ar.verify_chain(r)
63
+
64
+
65
+ def test_insert_fake_step_breaks_chain():
66
+ r = make_chain()
67
+ fake = ar.create_receipt(99, "gpt-4o", "x", "y", timestamp=5, salt="z", prev_hash=r[1]["hash"])
68
+ r.insert(2, fake)
69
+ assert not ar.verify_chain(r) # fake's prev is fine but next link now broken
70
+
71
+
72
+ def test_hmac_signing():
73
+ r = make_chain(secret="topsecret")
74
+ assert ar.verify_chain(r, secret_key="topsecret")
75
+ assert not ar.verify_chain(r, secret_key="wrongkey")
76
+ # signed receipt without key must fail
77
+ assert not ar.verify_receipt(r[0])
78
+
79
+
80
+ def test_fold_is_constant_size_and_binds():
81
+ r = make_chain()
82
+ f = ar.fold_receipts(r)
83
+ assert len(f["root"]) == 64 and f["count"] == 3
84
+ assert ar.verify_fold(f, r)
85
+ # Any change to a receipt hash must change the fold root (binding).
86
+ r2 = make_chain()
87
+ r2[0] = dict(r2[0], hash="00" * 32)
88
+ assert ar.fold_receipts(r2)["root"] != f["root"]
89
+ assert not ar.verify_fold(f, r2)
90
+
91
+
92
+ def test_report_pro_gate():
93
+ r = make_chain()
94
+ f = ar.fold_receipts(r)
95
+ free = ar.export_compliance_report(f, r)
96
+ pro = ar.export_compliance_report(f, r, pro_key="LS-xxxx")
97
+ assert "Upgrade to Pro" in free
98
+ assert "Pro / enterprise" in pro
99
+
100
+
101
+ if __name__ == "__main__":
102
+ fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
103
+ passed = 0
104
+ for fn in fns:
105
+ fn()
106
+ print(f" ok {fn.__name__}")
107
+ passed += 1
108
+ print(f"\n{passed}/{len(fns)} tests passed")