keyhalve 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,17 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ First public release of the KeyHalve SDK for Python — the blind-rail
6
+ document-verification core, as a standalone, platform-agnostic package.
7
+
8
+ - **End-Cell (recommended):** `create_end_cell_intent()` — 3-share key split
9
+ (QR ShareA ⊕ platform ⊕ independent KeyHalve rail); no single party can
10
+ reassemble the key.
11
+ - `verify_intent()` reconstructs across the platform + rail shares, verifying the
12
+ rail's Ed25519 signature against a pinned key (fail-closed).
13
+ - Simpler 2-share `create_split_key_intent()`, plus selective disclosure,
14
+ time-lock, revocation, physical binding (extra), file intents, QR placement.
15
+ - AES-256-GCM, SHA-256 commitment; wire-compatible with `@keyhalve/node-sdk`.
16
+ - `base_url` is required (the issuing platform's API); the KeyHalve rail is the
17
+ only fixed dependency.
keyhalve-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Attestura, LLC (KeyHalve)
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,7 @@
1
+ include LICENSE
2
+ include README.md
3
+ include CHANGELOG.md
4
+ recursive-include keyhalve *.py
5
+ prune tests
6
+ prune check21
7
+ prune .github
@@ -0,0 +1,383 @@
1
+ Metadata-Version: 2.4
2
+ Name: keyhalve
3
+ Version: 0.1.0
4
+ Summary: KeyHalve SDK for Python — End-Cell blind-rail document sealing & verification (client-side AES-256-GCM, 3-share key split, pinned-rail Ed25519 verify).
5
+ Author-email: "KeyHalve (Attestura, LLC)" <dev@keyhalve.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 Attestura, LLC (KeyHalve)
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://keyhalve.com
29
+ Project-URL: Documentation, https://keyhalve.com/docs
30
+ Project-URL: Repository, https://github.com/keyhalve/python-sdk
31
+ Project-URL: Issues, https://github.com/keyhalve/python-sdk/issues
32
+ Project-URL: Changelog, https://github.com/keyhalve/python-sdk/blob/main/CHANGELOG.md
33
+ Keywords: keyhalve,encryption,aes-256-gcm,document-verification,blind-escrow
34
+ Classifier: Development Status :: 5 - Production/Stable
35
+ Classifier: Intended Audience :: Developers
36
+ Classifier: License :: OSI Approved :: MIT License
37
+ Classifier: Operating System :: OS Independent
38
+ Classifier: Programming Language :: Python :: 3
39
+ Classifier: Programming Language :: Python :: 3.9
40
+ Classifier: Programming Language :: Python :: 3.10
41
+ Classifier: Programming Language :: Python :: 3.11
42
+ Classifier: Programming Language :: Python :: 3.12
43
+ Classifier: Topic :: Security :: Cryptography
44
+ Requires-Python: >=3.9
45
+ Description-Content-Type: text/markdown
46
+ License-File: LICENSE
47
+ Requires-Dist: cryptography>=41.0
48
+ Requires-Dist: requests>=2.28
49
+ Provides-Extra: dev
50
+ Requires-Dist: pytest>=7.0; extra == "dev"
51
+ Provides-Extra: binding
52
+ Requires-Dist: Pillow>=10.0; extra == "binding"
53
+ Requires-Dist: numpy>=1.24; extra == "binding"
54
+ Requires-Dist: scipy>=1.10; extra == "binding"
55
+ Provides-Extra: pdf
56
+ Requires-Dist: qrcode>=7.0; extra == "pdf"
57
+ Requires-Dist: Pillow>=10.0; extra == "pdf"
58
+ Requires-Dist: reportlab>=4.0; extra == "pdf"
59
+ Requires-Dist: pypdf>=4.0; extra == "pdf"
60
+ Dynamic: license-file
61
+
62
+ # KeyHalve SDK for Python
63
+
64
+ KeyHalve SDK for Python — the **blind-rail** document-verification core. Seal a
65
+ document so it can be verified later, with the decryption key split so **no single
66
+ party — not the platform, not KeyHalve — can read it.** Payloads are encrypted
67
+ locally; the platform stores only ciphertext, KeyHalve's rail holds one blind
68
+ share, and the verifier reconstructs in the browser.
69
+
70
+ Point `base_url` at the issuing platform's API; the KeyHalve rail is the only
71
+ fixed dependency. (ValidPay's own SDK is the separate `validpay` package.)
72
+
73
+ The encryption format is wire-compatible with the
74
+ [Node.js SDK](https://github.com/keyhalve/node-sdk): a payload
75
+ encrypted by the Python SDK can be decrypted by the Node SDK and vice
76
+ versa.
77
+
78
+ ## Install
79
+
80
+ ```bash
81
+ pip install keyhalve
82
+ ```
83
+
84
+ For physical-binding support (Patent F — image-based binding zones), install
85
+ the optional extras:
86
+
87
+ ```bash
88
+ pip install keyhalve[binding]
89
+ ```
90
+
91
+ Requires Python 3.9+.
92
+
93
+ ## Quick start
94
+
95
+ ```python
96
+ from keyhalve import KeyHalveClient
97
+
98
+ client = KeyHalveClient(api_key="vp_live_xxx")
99
+
100
+ # Seal with End-Cell (recommended). The payload is encrypted locally; the AES
101
+ # key is split THREE ways: result.key is ShareA (rides the QR), one share goes
102
+ # to the platform, one to the independent KeyHalve rail. No single party — not
103
+ # the platform, not KeyHalve — can read or reassemble the key.
104
+ result = client.create_end_cell_intent(
105
+ document_type="check",
106
+ payload={"payee": "John Doe", "amount": 1500.00, "check_number": "10042"},
107
+ # holders defaults to ["keyhalve", "platform"] -> a 3-of-3 split with ShareA
108
+ )
109
+ print(result.retrieval_id) # vp_abc123def456
110
+ print(result.key) # ShareA — embed in the QR / deliver out-of-band
111
+
112
+ # Create up to 100 intents in one round trip.
113
+ results = client.create_intent_batch([
114
+ {"document_type": "check", "payload": {"payee": "Alice", "amount": 500}},
115
+ {"document_type": "check", "payload": {"payee": "Bob", "amount": 750}},
116
+ ])
117
+ for r in results:
118
+ print(r.retrieval_id, r.key)
119
+
120
+ # Verify (retrieve + decrypt). No API key required for this endpoint.
121
+ verification = client.verify_intent(
122
+ retrieval_id="vp_abc123def456",
123
+ key=result.key,
124
+ )
125
+ print(verification.payload) # decrypted dict
126
+ print(verification.issuer) # "Acme Corp"
127
+ print(verification.issuer_verified) # True
128
+ print(verification.status) # "active"
129
+ ```
130
+
131
+ > **Simpler 2-share option:** `create_split_key_intent()` splits the key between
132
+ > the document and the platform only — no independent rail share, so the platform
133
+ > alone could reconstruct. `create_intent()` also defaults to split-key. Prefer
134
+ > **End-Cell** above when independence from the platform matters. `verify_intent()`
135
+ > handles all share models automatically.
136
+
137
+ ### Placing the QR on a document (`embed_qr`)
138
+
139
+ To verify a document, a scannable QR encoding the verify URL has to appear **on**
140
+ it. `embed_qr` builds that QR and stamps it onto a PDF for you — no QR library
141
+ wiring, no base64url juggling, and no fighting PDF coordinates (PDFs measure from
142
+ the bottom-left; everything else from the top-left).
143
+
144
+ It needs the optional PDF extras — the core SDK needs none of them:
145
+
146
+ ```bash
147
+ pip install "keyhalve[pdf]"
148
+ ```
149
+
150
+ ```python
151
+ from keyhalve import KeyHalveClient, QrPlacement, embed_qr
152
+
153
+ client = KeyHalveClient(api_key="vp_live_...")
154
+
155
+ with open("invoice.pdf", "rb") as f:
156
+ original = f.read()
157
+
158
+ res = client.create_file_intent(
159
+ document_type="invoice", file=original, file_content_type="application/pdf",
160
+ )
161
+
162
+ sealed = embed_qr(
163
+ original, res.retrieval_id, res.key,
164
+ # 90pt (1.25in) QR, 36pt in from the bottom-right corner.
165
+ QrPlacement(anchor="bottom-right", x=36, y=36, width=90),
166
+ )
167
+ with open("invoice-sealed.pdf", "wb") as f:
168
+ f.write(sealed)
169
+ ```
170
+
171
+ **The placement contract** — identical to the Node SDK and the developer
172
+ console's "Try it" tool, so a position you pick in the UI maps here 1:1:
173
+
174
+ | field | meaning | default |
175
+ | -------- | ------- | ------- |
176
+ | `anchor` | which page **corner** the insets are measured from (`top-left`/`top-right`/`bottom-left`/`bottom-right`) | `top-left` |
177
+ | `x` | horizontal inset from that corner's vertical edge | — |
178
+ | `y` | vertical inset from that corner's horizontal edge | — |
179
+ | `width` | QR side length (it's square) | — |
180
+ | `units` | `pt` (1/72in) / `mm` / `in` | `pt` |
181
+ | `page` | 1-based page number | `1` |
182
+
183
+ Keep the QR **≥ ~72pt (1in)** so it scans once printed — `embed_qr` warns below
184
+ that and raises if the placement runs off the page. Using a different PDF
185
+ library? The pure helpers `build_verify_url(...)` and
186
+ `resolve_qr_rect(placement, page_w_pt, page_h_pt)` have no dependencies.
187
+
188
+ ### Time-Locked Verification (Patent D)
189
+
190
+ Restrict when a document can be verified by specifying a validity window:
191
+
192
+ ```python
193
+ from datetime import datetime, timezone, timedelta
194
+
195
+ result = client.create_intent(
196
+ document_type="check",
197
+ payload={"payee": "Jane Doe", "amount": 1500.00},
198
+ valid_from=(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
199
+ valid_until=(datetime.now(timezone.utc) + timedelta(days=30)).isoformat(),
200
+ )
201
+
202
+ # Later, when verifying:
203
+ verified = client.verify_intent(result.retrieval_id, result.key)
204
+ print(verified.time_lock_status) # "valid", "not_yet_valid", or "expired"
205
+ print(verified.valid_from) # ISO-8601 timestamp or None
206
+ print(verified.valid_until) # ISO-8601 timestamp or None
207
+ ```
208
+
209
+ Time-lock status is informational — the SDK always returns the decrypted
210
+ payload regardless of the time window. Your application decides how to
211
+ handle `not_yet_valid` or `expired` results. The server stores the
212
+ timestamps but never enforces them; this preserves the blind intermediary
213
+ model (the server never decides whether a document is "still good").
214
+
215
+ The same `valid_from` / `valid_until` keyword arguments are accepted by
216
+ `create_intent_batch` (per-item) and `create_selective_intent`.
217
+
218
+ ### Split-key intents (Patent C) — the default
219
+
220
+ All documents created with SDK v1.1+ use split-key by default: the AES
221
+ key is split into two XOR shares — Share A is returned to the caller
222
+ (typically embedded in the QR code), Share B is stored server-side.
223
+ Neither share alone can decrypt the payload, so the full decryption key
224
+ never exists on any single system.
225
+
226
+ ```python
227
+ result = client.create_intent(
228
+ document_type="ssn_card",
229
+ payload={"ssn": "123-45-6789"},
230
+ )
231
+ # result.key is Share A — verify_intent pairs it with Share B automatically.
232
+
233
+ verified = client.verify_intent(result.retrieval_id, result.key)
234
+ print(verified.payload)
235
+ ```
236
+
237
+ #### Backward compatibility
238
+
239
+ - `create_intent(..., split_key=False)` gives the legacy single-key flow
240
+ (the returned `key` is the full AES key).
241
+ - `create_split_key_intent()` is a deprecated alias for `create_intent()`
242
+ — 1.0.x code keeps working, with a `DeprecationWarning`.
243
+ - `verify_intent` detects legacy vs split-key intents from the API
244
+ response, so it verifies both; `verify_split_key_intent()` also still
245
+ works.
246
+
247
+ ### Platform delegation — `on_behalf_of`
248
+
249
+ If you integrate as a **platform** and seal on behalf of the businesses you
250
+ serve, name the business on each seal. The verifier sees that business as the
251
+ issuer ("who"), attributed *through* your platform ("through whom"), at the
252
+ `delegated` trust rung. Those businesses never touch the platform — no account, no
253
+ login — and the platform stays blind to the document contents.
254
+
255
+ ```python
256
+ result = client.create_intent(
257
+ document_type="lease",
258
+ payload={"unit": "4B", "term": "12mo"},
259
+ on_behalf_of={
260
+ "ref": "landlord_8675309", # YOUR id for this business (dedupe key)
261
+ "name": "Smith Properties LLC", # who the verifier sees
262
+ },
263
+ )
264
+
265
+ verified = client.verify_intent(result.retrieval_id, result.key)
266
+ verified.issuer # "Smith Properties LLC"
267
+ verified.verification_level # "delegated"
268
+ verified.delegated_by # {"platform": "Your Platform", "platform_level": "domain"}
269
+ ```
270
+
271
+ Same `ref` ⇒ same tracked business (its documents and verification counts roll
272
+ up). A sub-issuer surfaces as `delegated` only once **your** platform account is
273
+ domain-verified; until then its documents show as unverified.
274
+
275
+ ### Selective disclosure (Patent E)
276
+
277
+ Each field is encrypted with its own per-field key. A disclosure policy maps
278
+ role names to the fields that role may decrypt. A `full` role with access to
279
+ every field is added automatically.
280
+
281
+ ```python
282
+ result = client.create_selective_intent(
283
+ document_type="check",
284
+ payload={"payee": "Alice", "amount": 1500.00, "memo": "rent"},
285
+ disclosure_policy={"bank": ["amount"], "auditor": ["amount", "payee"]},
286
+ )
287
+
288
+ # Bank sees only 'amount'; other fields come back as REDACTED markers.
289
+ verified = client.verify_selective_intent(result.retrieval_id, result.key, role="bank")
290
+ print(verified.payload)
291
+ ```
292
+
293
+ `create_selective_intent` accepts `split_key=True` to combine Patents C + E.
294
+
295
+ ### Revocation (Patent H — Blind Revocation)
296
+
297
+ Issuers can revoke or reinstate an intent without decrypting it. Verifiers
298
+ of a revoked intent receive `status="revoked"` and no encrypted payload.
299
+
300
+ ```python
301
+ client.revoke_intent("vp_abc123def456", reason="Stop payment")
302
+ client.reinstate_intent("vp_abc123def456", reason="False alarm")
303
+
304
+ history = client.get_revocation_history("vp_abc123def456")
305
+ for event in history:
306
+ print(event["action"], event["reason"], event["performed_at"])
307
+ ```
308
+
309
+ ## API
310
+
311
+ ### `KeyHalveClient(api_key, *, base_url=..., timeout=30.0, session=None)`
312
+
313
+ - `api_key` — your issuing platform API key (required for create endpoints).
314
+ - `base_url` — **required**: the issuing platform API base. The KeyHalve rail is the only fixed dependency.
315
+ - `timeout` — per-request timeout in seconds.
316
+ - `session` — optionally provide a `requests.Session` for connection
317
+ pooling, custom adapters, or mocking in tests.
318
+
319
+ ### `client.create_end_cell_intent(document_type, payload, *, holders=None, valid_from=None, valid_until=None, on_behalf_of=None) -> CreateIntentResult` — recommended
320
+
321
+ KeyHalve's blind-rail flow. Encrypts `payload` and XOR-splits the AES key into
322
+ **ShareA** (returned as `key`, for the QR) plus one share per holder. `holders`
323
+ defaults to `["keyhalve", "platform"]` → a **3-of-3** split: the independent
324
+ KeyHalve rail share + the platform share + ShareA. No single party can read or
325
+ reassemble the key. Verify with `verify_intent`, which fetches the platform +
326
+ rail shares, verifies the rail's Ed25519 signature against a **pinned** key
327
+ (fail-closed), recombines in memory, and decrypts. **The full key never exists
328
+ on any single system.** Requires the API deployment to have End-Cell enabled.
329
+
330
+ ### `client.create_intent(document_type, payload, *, split_key=True) -> CreateIntentResult`
331
+
332
+ Encrypts `payload` (any JSON-serializable value) under a freshly
333
+ generated AES-256 key and registers it. Defaults to **split-key** (2-share):
334
+ the returned `key` is **Share A** and Share B goes to the platform — neither
335
+ alone decrypts, but there is **no independent rail share** (the platform alone
336
+ could reconstruct). For independence from the platform, prefer
337
+ **`create_end_cell_intent`** above. `split_key=False` gives the legacy
338
+ single-key flow. **The full key is never sent to the platform.**
339
+
340
+ ### `client.create_intent_batch(intents) -> list[CreateIntentResult]`
341
+
342
+ Bulk version. `intents` is an iterable of mappings shaped
343
+ `{"document_type": str, "payload": Any}`, with 1–100 items. Each intent
344
+ gets its own unique key. Result order matches input order.
345
+
346
+ ### `client.verify_intent(retrieval_id, key) -> VerifyIntentResult`
347
+
348
+ Fetches the intent (public endpoint, no API key required), decrypts the
349
+ payload locally, and returns issuer metadata + the decrypted payload.
350
+
351
+ ### Errors
352
+
353
+ All SDK and API errors are raised as `KeyHalveError`, which exposes:
354
+
355
+ - `code` — machine-readable code (e.g. `"unauthorized"`, `"not_found"`,
356
+ `"decryption_failed"`, `"invalid_key"`, `"network_error"`).
357
+ - `status` — HTTP status when the error came from the API.
358
+ - `details` — raw error body / extra context when available.
359
+
360
+ ### Low-level crypto
361
+
362
+ For advanced use cases the encryption primitives are exported directly:
363
+
364
+ ```python
365
+ from keyhalve import generate_key, encrypt, decrypt
366
+
367
+ key = generate_key()
368
+ blob = encrypt('{"hello": "world"}', key)
369
+ assert decrypt(blob, key) == '{"hello": "world"}'
370
+ ```
371
+
372
+ Wire format: `base64(iv[12] || authTag[16] || ciphertext)`.
373
+
374
+ ## Development
375
+
376
+ ```bash
377
+ pip install -e ".[dev]"
378
+ pytest
379
+ ```
380
+
381
+ ## License
382
+
383
+ MIT — see `LICENSE`.