decidio-verify 0.23.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,5 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.egg-info/
4
+ dist/
5
+ build/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,5 @@
1
+ Decidio
2
+ Copyright 2026 OmniTwin Technologies Inc.
3
+
4
+ "Decidio" is a trademark of OmniTwin Technologies Inc. The Apache License, Version 2.0, under which this software
5
+ is licensed, grants no permission to use it (section 6).
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.5
2
+ Name: decidio-verify
3
+ Version: 0.23.0
4
+ Summary: Standalone offline verifier for Decidio Authority Receipts (W3C VC, eddsa-jcs-2022, Ed25519 did:key). Verify a sealed receipt's signature, content binding and chain order with no Decidio account and no network. `decidio-verify receipt.json`.
5
+ Project-URL: Homepage, https://decidioai.com/receipt-spec/
6
+ Author: OmniTwin Technologies Inc.
7
+ License: Apache-2.0
8
+ License-File: LICENSE
9
+ License-File: NOTICE
10
+ Keywords: audit,ed25519,offline-verification,receipts,verifiable-credentials
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Security
16
+ Requires-Python: >=3.9
17
+ Requires-Dist: cryptography>=42
18
+ Description-Content-Type: text/markdown
19
+
20
+ # decidio-verify
21
+
22
+ **Standalone verifier for Decidio Authority Receipts, in Python.** Check a sealed receipt's signature, content binding and
23
+ chain order **offline**: no Decidio account, no network, no DID resolver. A record you can only verify with the vendor's
24
+ software isn't really owned; this package is what makes "the customer owns the record" true. It is the Python twin of
25
+ [`@decidio/verify`](https://www.npmjs.com/package/@decidio/verify) on npm, and both give the same verdict on the same file.
26
+
27
+ ```bash
28
+ pip install decidio-verify
29
+
30
+ # A receipt from Decidio's hosted service: no flag needed - the trust anchor is built in.
31
+ decidio-verify receipt.json
32
+ decidio-verify r1.json r2.json r3.json # each + the chain order (one issuer end to end)
33
+
34
+ # Any other issuer (a self-hosted Decidio): pin its DID yourself - take it from that host's
35
+ # <api>/api/did, never from the receipt. An explicit --issuer always wins over the built-in anchor.
36
+ decidio-verify --issuer did:key:z6Mk… receipt.json
37
+
38
+ # A structural check only is a named choice, and its verdict carries the UNPINNED warning:
39
+ decidio-verify --allow-unpinned receipt.json
40
+ ```
41
+
42
+ `python -m decidio_verify` is the same command. The Decidio SDK (`pip install decidio`) depends on this package and runs
43
+ the same code as `python -m decidio verify` and `python -m decidio.verify`.
44
+
45
+ **Every run prints its trust anchor first**: the issuer the verdict is pinned to, and where that came from (`--issuer`, or
46
+ `built in: Decidio production, decidio-prod-api.onrender.com`). The built-in list (`KNOWN_ISSUERS`) holds Decidio's own
47
+ deployments, each published at its host's `/api/did`: production,
48
+ `did:key:z6MkpBwpAT98VAqg2UpiSGJZieg7DGQpoNkdioDUEo4kQXnJ` (https://decidio-prod-api.onrender.com/api/did), and staging
49
+ (the lab), `did:key:z6MkmLGeR5NjJ87a1yU5ygqju49CtnUrt38esqM54Y9tXnKq` (https://decidio-api.onrender.com/api/did). The
50
+ receipt's own issuer field only picks between them; the signature must then match. A receipt naming any other issuer is
51
+ refused (exit 2) until you pin one: its `issuer` field is a claim, never a trust anchor.
52
+
53
+ ```python
54
+ from decidio_verify import verify_receipt, verify_chain
55
+
56
+ r = verify_receipt(vc, "did:key:z6Mk…") # {"valid", "issuer", "content_bound", "record_id", "reason"?, ...}
57
+ c = verify_chain([vc1, vc2, vc3], "did:key:z6Mk…") # {"valid", "length", "anchor"?, "reason"?}
58
+ ```
59
+
60
+ Pass the expected issuer: without it, `valid` only proves the file agrees with itself, and any keyholder could have
61
+ issued it.
62
+
63
+ ## What it checks
64
+ 1. **Issuer**: the DID is an Ed25519 `did:key` and, when pinned, the one you expected.
65
+ 2. **Content binding**: re-derives `sha256((prevHash or "") + recordCanonical)` and requires it to equal the signed
66
+ `contentHash`, so "the content was changed" is reported apart from "the signature is broken".
67
+ 3. **Signature**: a W3C Data Integrity proof (`DataIntegrityProof`, cryptosuite `eddsa-jcs-2022`, Ed25519) over the
68
+ whole receipt and its proof options, per [Data Integrity EdDSA Cryptosuites v1.0](https://www.w3.org/TR/vc-di-eddsa/).
69
+ It needs only SHA-256, Ed25519, base58 and RFC 8785 (JCS, `decidio_verify.jcs`).
70
+ 4. **Chain** (`verify_chain`): each receipt's `prevHash` links to the prior `contentHash`, and every receipt verifies.
71
+
72
+ **What VALID proves:** the claims in the record were sealed by that issuer and none has changed since. The signature
73
+ covers the record's canonical form, so reformatting the file still verifies. **What it does not prove:** that the
74
+ approved action ran (execution is confirmed after the seal), or that the record was not later superseded or revoked;
75
+ that status needs the issuer.
76
+
77
+ Exit codes: `0` all verified, `1` verification failed or a file was unreadable, `2` a usage error or no trust anchor.
78
+
79
+ Not in this package yet: the npm verifier's policy-check and bound-request proofs (`verifyCheckEntry`,
80
+ `verifyCheckComplete`, `verifyBoundRequest`). Use `@decidio/verify` for those.
81
+
82
+ ## Licence
83
+ Apache-2.0 (see `LICENSE` and `NOTICE`). Anyone may check a receipt. "Decidio" is a trademark of OmniTwin
84
+ Technologies Inc.
85
+
86
+ The receipt format: https://decidioai.com/receipt-spec/
@@ -0,0 +1,67 @@
1
+ # decidio-verify
2
+
3
+ **Standalone verifier for Decidio Authority Receipts, in Python.** Check a sealed receipt's signature, content binding and
4
+ chain order **offline**: no Decidio account, no network, no DID resolver. A record you can only verify with the vendor's
5
+ software isn't really owned; this package is what makes "the customer owns the record" true. It is the Python twin of
6
+ [`@decidio/verify`](https://www.npmjs.com/package/@decidio/verify) on npm, and both give the same verdict on the same file.
7
+
8
+ ```bash
9
+ pip install decidio-verify
10
+
11
+ # A receipt from Decidio's hosted service: no flag needed - the trust anchor is built in.
12
+ decidio-verify receipt.json
13
+ decidio-verify r1.json r2.json r3.json # each + the chain order (one issuer end to end)
14
+
15
+ # Any other issuer (a self-hosted Decidio): pin its DID yourself - take it from that host's
16
+ # <api>/api/did, never from the receipt. An explicit --issuer always wins over the built-in anchor.
17
+ decidio-verify --issuer did:key:z6Mk… receipt.json
18
+
19
+ # A structural check only is a named choice, and its verdict carries the UNPINNED warning:
20
+ decidio-verify --allow-unpinned receipt.json
21
+ ```
22
+
23
+ `python -m decidio_verify` is the same command. The Decidio SDK (`pip install decidio`) depends on this package and runs
24
+ the same code as `python -m decidio verify` and `python -m decidio.verify`.
25
+
26
+ **Every run prints its trust anchor first**: the issuer the verdict is pinned to, and where that came from (`--issuer`, or
27
+ `built in: Decidio production, decidio-prod-api.onrender.com`). The built-in list (`KNOWN_ISSUERS`) holds Decidio's own
28
+ deployments, each published at its host's `/api/did`: production,
29
+ `did:key:z6MkpBwpAT98VAqg2UpiSGJZieg7DGQpoNkdioDUEo4kQXnJ` (https://decidio-prod-api.onrender.com/api/did), and staging
30
+ (the lab), `did:key:z6MkmLGeR5NjJ87a1yU5ygqju49CtnUrt38esqM54Y9tXnKq` (https://decidio-api.onrender.com/api/did). The
31
+ receipt's own issuer field only picks between them; the signature must then match. A receipt naming any other issuer is
32
+ refused (exit 2) until you pin one: its `issuer` field is a claim, never a trust anchor.
33
+
34
+ ```python
35
+ from decidio_verify import verify_receipt, verify_chain
36
+
37
+ r = verify_receipt(vc, "did:key:z6Mk…") # {"valid", "issuer", "content_bound", "record_id", "reason"?, ...}
38
+ c = verify_chain([vc1, vc2, vc3], "did:key:z6Mk…") # {"valid", "length", "anchor"?, "reason"?}
39
+ ```
40
+
41
+ Pass the expected issuer: without it, `valid` only proves the file agrees with itself, and any keyholder could have
42
+ issued it.
43
+
44
+ ## What it checks
45
+ 1. **Issuer**: the DID is an Ed25519 `did:key` and, when pinned, the one you expected.
46
+ 2. **Content binding**: re-derives `sha256((prevHash or "") + recordCanonical)` and requires it to equal the signed
47
+ `contentHash`, so "the content was changed" is reported apart from "the signature is broken".
48
+ 3. **Signature**: a W3C Data Integrity proof (`DataIntegrityProof`, cryptosuite `eddsa-jcs-2022`, Ed25519) over the
49
+ whole receipt and its proof options, per [Data Integrity EdDSA Cryptosuites v1.0](https://www.w3.org/TR/vc-di-eddsa/).
50
+ It needs only SHA-256, Ed25519, base58 and RFC 8785 (JCS, `decidio_verify.jcs`).
51
+ 4. **Chain** (`verify_chain`): each receipt's `prevHash` links to the prior `contentHash`, and every receipt verifies.
52
+
53
+ **What VALID proves:** the claims in the record were sealed by that issuer and none has changed since. The signature
54
+ covers the record's canonical form, so reformatting the file still verifies. **What it does not prove:** that the
55
+ approved action ran (execution is confirmed after the seal), or that the record was not later superseded or revoked;
56
+ that status needs the issuer.
57
+
58
+ Exit codes: `0` all verified, `1` verification failed or a file was unreadable, `2` a usage error or no trust anchor.
59
+
60
+ Not in this package yet: the npm verifier's policy-check and bound-request proofs (`verifyCheckEntry`,
61
+ `verifyCheckComplete`, `verifyBoundRequest`). Use `@decidio/verify` for those.
62
+
63
+ ## Licence
64
+ Apache-2.0 (see `LICENSE` and `NOTICE`). Anyone may check a receipt. "Decidio" is a trademark of OmniTwin
65
+ Technologies Inc.
66
+
67
+ The receipt format: https://decidioai.com/receipt-spec/
@@ -0,0 +1,30 @@
1
+ """decidio-verify — the standalone, offline verifier for Decidio Authority Receipts.
2
+
3
+ from decidio_verify import verify_receipt, verify_chain
4
+ r = verify_receipt(vc, expected_issuer) # {"valid", "issuer", "content_bound", "record_id", "reason"?, ...}
5
+
6
+ $ decidio-verify receipt.json # or: python -m decidio_verify receipt.json
7
+
8
+ The Python twin of @decidio/verify (npm). A receipt is a W3C Verifiable Credential secured with an
9
+ eddsa-jcs-2022 Data Integrity proof; checking it needs SHA-256, Ed25519, base58 and RFC 8785 (JCS), and
10
+ nothing from Decidio: no account, no network, no DID resolver. The Decidio SDK (`pip install decidio`)
11
+ depends on this package and runs the same code as `python -m decidio verify`.
12
+ """
13
+ from .jcs import jcs_bytes, jcs_canonicalize
14
+ from .verify import (
15
+ CRYPTOSUITE,
16
+ KNOWN_ISSUERS,
17
+ built_in_anchor,
18
+ pin_required_message,
19
+ read_record_kind,
20
+ read_sealed_state,
21
+ verify_chain,
22
+ verify_receipt,
23
+ )
24
+
25
+ __all__ = [
26
+ "verify_receipt", "verify_chain", "read_record_kind", "read_sealed_state", "CRYPTOSUITE",
27
+ "KNOWN_ISSUERS", "built_in_anchor", "pin_required_message",
28
+ "jcs_bytes", "jcs_canonicalize",
29
+ ]
30
+ __version__ = "0.23.0"
@@ -0,0 +1,14 @@
1
+ """`decidio-verify` and `python -m decidio_verify`: verify Decidio Authority Receipts offline."""
2
+ import sys
3
+ from typing import List, Optional
4
+
5
+ from .verify import main as _main, utf8_streams
6
+
7
+
8
+ def main(argv: Optional[List[str]] = None) -> int:
9
+ utf8_streams()
10
+ return _main(argv, "python -m decidio_verify" if sys.argv[0].endswith("__main__.py") else "decidio-verify")
11
+
12
+
13
+ if __name__ == "__main__":
14
+ raise SystemExit(main())
@@ -0,0 +1,170 @@
1
+ """JSON Canonicalization Scheme (RFC 8785), byte-identical to the canonical form Decidio signs.
2
+
3
+ A receipt's signature covers the RFC 8785 form of the receipt, so a verifier must reproduce exactly the bytes the issuer
4
+ hashed: one byte of difference and a genuine receipt fails. Standard library only.
5
+
6
+ RFC 8785, rule by rule:
7
+ §3.2.1 whitespace - none emitted anywhere.
8
+ §3.2.2 literals - null/true/false verbatim (not Python's None/True/False).
9
+ §3.2.2.3 numbers - ECMAScript Number::toString, which is what JSON.stringify emits for a finite number (shortest
10
+ round-tripping form: 1e+30, 1e-7, 0.000001). NaN and Infinity are not JSON and raise.
11
+ §3.2.2.2 strings - minimal escaping (only ", \\ and C0 controls), UTF-8 output with no \\u escaping of non-ASCII.
12
+ A lone surrogate raises.
13
+ §3.2.3 object keys - sorted by UTF-16 code unit of the raw key, not by code point and not by locale: an astral character
14
+ (a surrogate pair, e.g. U+1F600 = D83D DE00) sorts before U+FFFD.
15
+ arrays - element order preserved.
16
+
17
+ Where Python's defaults differ from RFC 8785, and what this module does instead:
18
+ 1. Key order: `sorted()` compares code points; keys are sorted on their big-endian UTF-16 bytes, which compare in
19
+ code-unit order (`surrogatepass` keeps the sort total for keys holding unpaired surrogates).
20
+ 2. Numbers: repr(float) has the shortest digits but not ECMAScript's format (repr(1e-7) is "1e-07", repr(1.0) is "1.0",
21
+ repr(-0.0) is "-0.0"), so the digits are taken from repr() and formatted by Number::toString.
22
+ 3. Escaping: json.dumps escapes all non-ASCII (ensure_ascii=True) or passes lone surrogates through (False); neither is
23
+ the canonical form, so strings are escaped here.
24
+ 4. Literals: str(True) is "True"; true/false/null are emitted.
25
+ 5. Non-finite numbers raise.
26
+ 6. bool is an int in Python, so it is tested first (True must not canonicalise as 1).
27
+ 7. Surrogates: a high surrogate followed by a low one is the astral character it encodes and is emitted as UTF-8;
28
+ any other code point in D800-DFFF is lone and raises.
29
+ 8. Integers: JSON numbers are IEEE-754 doubles, so an int is written as the double it would be (10**21 gives "1e+21")
30
+ and raises if it cannot be represented exactly, rather than signing or checking a different number.
31
+
32
+ None is null and is always kept; any value that is not JSON raises."""
33
+ from __future__ import annotations
34
+
35
+ import math
36
+ from typing import Any
37
+
38
+
39
+ _SHORT_ESCAPES = {
40
+ '"': '\\"',
41
+ "\\": "\\\\",
42
+ "\b": "\\b",
43
+ "\f": "\\f",
44
+ "\n": "\\n",
45
+ "\r": "\\r",
46
+ "\t": "\\t",
47
+ }
48
+
49
+
50
+ def _sort_key(key: str) -> bytes:
51
+ """UTF-16 code-unit order, as RFC 8785 §3.2.3 requires.
52
+
53
+ Big-endian UTF-16 bytes compare in code-unit order, and a prefix sorts first. `surrogatepass` lets a key holding a lone
54
+ surrogate be sorted, so it fails later with the canonicaliser's lone-surrogate error rather than an encoding error here."""
55
+ return key.encode("utf-16-be", "surrogatepass")
56
+
57
+
58
+ def _json_string(s: str) -> str:
59
+ """RFC 8785 §3.2.2.2: minimal escaping; non-ASCII stays literal UTF-8 text; a lone surrogate raises."""
60
+ out = ['"']
61
+ i, n = 0, len(s)
62
+ while i < n:
63
+ ch = s[i]
64
+ cp = ord(ch)
65
+ short = _SHORT_ESCAPES.get(ch)
66
+ if short is not None:
67
+ out.append(short)
68
+ elif cp < 0x20:
69
+
70
+
71
+ out.append("\\u%04x" % cp)
72
+ elif 0xD800 <= cp <= 0xDBFF and i + 1 < n and 0xDC00 <= ord(s[i + 1]) <= 0xDFFF:
73
+
74
+
75
+ out.append(chr(0x10000 + ((cp - 0xD800) << 10) + (ord(s[i + 1]) - 0xDC00)))
76
+ i += 2
77
+ continue
78
+ elif 0xD800 <= cp <= 0xDFFF:
79
+
80
+
81
+
82
+ raise ValueError(f"JCS: unpaired {'high' if cp <= 0xDBFF else 'low'} surrogate U+{cp:04X}")
83
+ else:
84
+ out.append(ch)
85
+ i += 1
86
+ out.append('"')
87
+ return "".join(out)
88
+
89
+
90
+ def _es_number(x: float) -> str:
91
+ """RFC 8785 §3.2.2.3: ECMAScript Number::toString(x, 10), i.e. what JSON.stringify emits.
92
+
93
+ ECMA-262 defines the output from the shortest decimal digit string `s` (k digits) and a decimal-point position `n` such
94
+ that s x 10**(n-k) == x. repr() already gives the shortest round-tripping digits, so they are taken from it and written
95
+ out by ECMAScript's four cases."""
96
+ if math.isnan(x) or math.isinf(x):
97
+ raise ValueError("JCS: non-finite numbers are not valid JSON")
98
+ if x == 0:
99
+ return "0"
100
+ if x < 0:
101
+ return "-" + _es_number(-x)
102
+
103
+ r = repr(x)
104
+ mantissa, _, exp_part = r.partition("e")
105
+ exp10 = int(exp_part) if exp_part else 0
106
+ int_part, _, frac_part = mantissa.partition(".")
107
+ digits = int_part + frac_part
108
+
109
+ n = len(int_part) + exp10
110
+ stripped = digits.lstrip("0")
111
+ n -= len(digits) - len(stripped)
112
+ digits = stripped.rstrip("0")
113
+ k = len(digits)
114
+
115
+
116
+
117
+ if k <= n <= 21:
118
+ return digits + "0" * (n - k)
119
+ if 0 < n <= 21:
120
+ return digits[:n] + "." + digits[n:]
121
+ if -6 < n <= 0:
122
+ return "0." + "0" * -n + digits
123
+ e = n - 1
124
+ sign = "+" if e > 0 else "-"
125
+ lead = digits if k == 1 else digits[0] + "." + digits[1:]
126
+ return f"{lead}e{sign}{abs(e)}"
127
+
128
+
129
+ def _int_number(v: int) -> str:
130
+ """Canonicalise a Python int as the IEEE-754 double RFC 8785 says numbers are; raises if it is not exactly representable."""
131
+ try:
132
+ as_double = float(v)
133
+ except OverflowError:
134
+ raise ValueError(f"JCS: integer {v} exceeds IEEE-754 double range") from None
135
+ if int(as_double) != v:
136
+ raise ValueError(
137
+ f"JCS: integer {v} is not exactly representable as an IEEE-754 double "
138
+ "(RFC 8785 numbers are doubles); canonicalising it would silently sign a different value"
139
+ )
140
+ return _es_number(as_double)
141
+
142
+
143
+ def jcs_canonicalize(value: Any) -> str:
144
+ """Canonicalise a JSON value to its RFC 8785 form. Raises on non-JSON input."""
145
+ if value is None:
146
+ return "null"
147
+ if isinstance(value, bool):
148
+ return "true" if value else "false"
149
+ if isinstance(value, int):
150
+ return _int_number(value)
151
+ if isinstance(value, float):
152
+ return _es_number(value)
153
+ if isinstance(value, str):
154
+ return _json_string(value)
155
+ if isinstance(value, (list, tuple)):
156
+ return "[" + ",".join(jcs_canonicalize(x) for x in value) + "]"
157
+ if isinstance(value, dict):
158
+ for k in value:
159
+
160
+
161
+ if not isinstance(k, str):
162
+ raise TypeError(f"JCS: object keys must be strings, got {type(k).__name__}")
163
+ keys = sorted(value, key=_sort_key)
164
+ return "{" + ",".join(f"{_json_string(k)}:{jcs_canonicalize(value[k])}" for k in keys) + "}"
165
+ raise TypeError(f"JCS: cannot canonicalise type {type(value).__name__}")
166
+
167
+
168
+ def jcs_bytes(value: Any) -> bytes:
169
+ """The canonical form as UTF-8 bytes — what actually gets hashed."""
170
+ return jcs_canonicalize(value).encode("utf-8")
File without changes