decidio-verify 0.23.0__py3-none-any.whl

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,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())
decidio_verify/jcs.py ADDED
@@ -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
@@ -0,0 +1,772 @@
1
+ """Standalone offline verifier for Decidio Authority Receipts.
2
+
3
+ Verifies a receipt OFFLINE, using only the public DID embedded in it: no network, no DID resolver, no context fetching,
4
+ no Decidio account. Its one dependency is `cryptography` (Ed25519). The Decidio SDK (`pip install decidio`) depends on this
5
+ package and runs this same module as `python -m decidio.verify` and `python -m decidio verify`.
6
+
7
+ decidio-verify [--issuer <did:key>] receipt.json [more.json ...]
8
+ python -m decidio_verify [--issuer <did:key>] receipt.json [more.json ...]
9
+
10
+ THE RECEIPT FORMAT is a W3C Verifiable Credential secured with a `DataIntegrityProof` using the `eddsa-jcs-2022`
11
+ cryptosuite (Data Integrity EdDSA Cryptosuites v1.0, W3C Recommendation, 15 May 2025). Verifying it needs only SHA-256,
12
+ Ed25519, base58 and RFC 8785 canonicalisation (`decidio_verify.jcs`).
13
+
14
+ WHAT THIS CHECKS, in this order (the order decides which reason you get back, and it is the same in the npm verifier,
15
+ @decidio/verify, so both give the same answer about the same file):
16
+ 1. issuer - the DID is an Ed25519 did:key and, when you pin one, is the issuer you expected. A valid signature by SOME
17
+ key is not proof of WHO issued it, so pinning is the real check.
18
+ 2. content binding (in addition to the standard proof) - re-derive sha256((prevHash or "") + recordCanonical) and
19
+ require it to equal the receipt's contentHash. It has its own failure reason, because "the content was changed" and
20
+ "the signature is broken" are different findings for whoever holds the receipt.
21
+ 3. signature - the standard eddsa-jcs-2022 proof over the whole document AND the proof options.
22
+ Chain ordering is checked by verify_chain(). Revocation and status need the network and are out of scope by design: a
23
+ receipt is tamper-evidence, not a liveness check.
24
+
25
+ STRICTER THAN THE RECOMMENDATION, on purpose:
26
+ - proofValue must be a string. It is the only proof field outside the signed bytes, so accepting another form would let
27
+ two different files carry one signature.
28
+ - prevHash must be a string or null.
29
+ - a number beyond 2^53 is refused: its exact signed value cannot be reproduced. (Decidio receipts carry no numbers.)
30
+ - the document's @context must equal the proof's. The Recommendation leaves extra document @context entries unsigned;
31
+ Decidio's issuer always copies it across unchanged, so nothing genuine is refused.
32
+ - a receipt with duplicate JSON keys is refused (see _parse_strict)."""
33
+ from __future__ import annotations
34
+
35
+ import hashlib
36
+ import json
37
+ import re as _re_mod
38
+ import sys
39
+ from types import MappingProxyType
40
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple
41
+
42
+ from .jcs import jcs_bytes
43
+
44
+ _B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
45
+
46
+
47
+
48
+
49
+ CRYPTOSUITE = "eddsa-jcs-2022"
50
+ _LEGACY_CRYPTOSUITE = "eddsa-2022"
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+ _XSD_DATE_TIME_STAMP = _re_mod.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})\Z", _re_mod.ASCII)
61
+ _XSD_FIELDS = _re_mod.compile(r"^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|([+-])(\d{2}):(\d{2}))\Z", _re_mod.ASCII)
62
+
63
+
64
+ def _is_calendrical_date_time_stamp(s: str) -> bool:
65
+ """XSD dateTimeStamp, checked calendrically: the regex holds the shape, this holds the fields - month 1-12, a real day
66
+ for that month and year, hour 0-23, minute 0-59, second 0-59, an offset within -14:00..+14:00."""
67
+ m = _XSD_FIELDS.match(s)
68
+ if not m:
69
+ return False
70
+ y, mo, d, h, mi, se = (int(m.group(i)) for i in range(1, 7))
71
+ if y < 1 or mo < 1 or mo > 12 or d < 1 or h > 23 or mi > 59 or se > 59:
72
+ return False
73
+ leap = (y % 4 == 0 and y % 100 != 0) or y % 400 == 0
74
+ dim = [31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mo - 1]
75
+ if d > dim:
76
+ return False
77
+ if m.group(8) != "Z":
78
+ oh, om = int(m.group(10)), int(m.group(11))
79
+ if oh > 14 or om > 59 or (oh == 14 and om != 0):
80
+ return False
81
+ return True
82
+
83
+
84
+ def _b58decode(s: str) -> bytes:
85
+ out = [0]
86
+ for ch in s:
87
+ val = _B58.find(ch)
88
+ if val < 0:
89
+ raise ValueError("invalid base58")
90
+ carry = val
91
+ for i in range(len(out)):
92
+ carry += out[i] * 58
93
+ out[i] = carry & 0xFF
94
+ carry >>= 8
95
+ while carry:
96
+ out.append(carry & 0xFF)
97
+ carry >>= 8
98
+ for ch in s:
99
+ if ch == _B58[0]:
100
+ out.append(0)
101
+ else:
102
+ break
103
+ return bytes(reversed(out))
104
+
105
+
106
+ def _sha256(s: str) -> str:
107
+ return hashlib.sha256(s.encode("utf-8")).hexdigest()
108
+
109
+
110
+ def _prev_hash_prefix(prev: Optional[str]) -> str:
111
+ """Content-binding prefix: `sha256((prevHash or "") + canonical)`. `prevHash` must already be a string or None."""
112
+ return "" if prev is None else prev
113
+
114
+
115
+ def _derive_hash(canonical: str, prev: Optional[str]) -> str:
116
+ return _sha256(_prev_hash_prefix(prev) + canonical)
117
+
118
+
119
+ def _field(obj: Any, key: str) -> Any:
120
+ """Read a field of a receipt that may not be a JSON object at all: a non-object yields None (and the reason that follows)
121
+ rather than an exception."""
122
+ return obj.get(key) if isinstance(obj, dict) else None
123
+
124
+
125
+ def _hash_data(unsecured_document: Dict[str, Any], proof_config: Dict[str, Any]) -> bytes:
126
+ """Data Integrity §3.3.4 — the 64-byte signing input: SHA-256 of the canonical proof config,
127
+ then SHA-256 of the canonical document. CONFIG FIRST; the order is normative. The 64 bytes are
128
+ signed directly (Ed25519 hashes internally — they are not hashed again)."""
129
+ return (
130
+ hashlib.sha256(jcs_bytes(proof_config)).digest()
131
+ + hashlib.sha256(jcs_bytes(unsecured_document)).digest()
132
+ )
133
+
134
+
135
+ def _as_context_list(value: Any) -> List[Any]:
136
+ """An @context value as a list: a scalar is wrapped, a list is used as is, and a missing @context becomes [None] so it
137
+ fails the comparison rather than passing it vacuously."""
138
+ return list(value) if isinstance(value, list) else [value]
139
+
140
+
141
+ def _same_context_entry(proof_entry: Any, doc_entry: Any) -> bool:
142
+ """Whether a document @context entry equals the proof's. Only scalar entries can match (Decidio's issuer only ever
143
+ writes strings), and a bool never equals a number, so `1` and `true` are different entries."""
144
+ if isinstance(proof_entry, (dict, list)) or isinstance(doc_entry, (dict, list)):
145
+ return False
146
+ if isinstance(proof_entry, bool) != isinstance(doc_entry, bool):
147
+ return False
148
+ return bool(proof_entry == doc_entry)
149
+
150
+
151
+ def read_record_kind(record_canonical: str) -> Optional[str]:
152
+ """The record kind sealed into the canonical record (approval / denial / decision), or None. Read from the receipt's
153
+ own bytes, never fetched."""
154
+ try:
155
+ p = json.loads(record_canonical)
156
+ except Exception:
157
+ return None
158
+ kind = p.get("recordKind") if isinstance(p, dict) else None
159
+ return kind if isinstance(kind, str) else None
160
+
161
+
162
+ def read_sealed_state(record_canonical: str) -> Optional[Dict[str, Any]]:
163
+ """Read the decision-state fields back out of the sealed canonical payload.
164
+
165
+ A receipt for an approved, executed action can still read ``result: routed_to_human`` with ``confirmation: pending``:
166
+ confirmation lands AFTER the seal and a sealed record is immutable, so it is never written back. That is correct, but
167
+ "VALID" reads as "approved and executed" unless the boundary is stated, so these fields are surfaced rather than left
168
+ in the JSON for the reader to infer.
169
+
170
+ This is a reporting aid, never a verification input: `recordCanonical` is content-bound against `contentHash` before
171
+ this is called, so nothing here can change a verdict. An unparseable payload, or a kind with no authority block,
172
+ reports nothing."""
173
+ try:
174
+ p = json.loads(record_canonical)
175
+ except Exception:
176
+ return None
177
+ if not isinstance(p, dict):
178
+ return None
179
+ authority = p.get("authority") if isinstance(p.get("authority"), dict) else None
180
+ confirmation = p.get("confirmation") if isinstance(p.get("confirmation"), dict) else None
181
+ s: Dict[str, Any] = {}
182
+ if authority is not None and (isinstance(authority.get("result"), str) or authority.get("result") is None):
183
+ s["result"] = authority.get("result")
184
+ if confirmation is not None and (isinstance(confirmation.get("status"), str) or confirmation.get("status") is None):
185
+ s["confirmation"] = confirmation.get("status")
186
+ if "ratifiedBy" in p:
187
+ s["ratified"] = p.get("ratifiedBy") is not None
188
+ nominated = p.get("nominatedDeciders", p.get("deciders"))
189
+ if isinstance(nominated, list):
190
+ s["nominated_deciders"] = len(nominated)
191
+ return s or None
192
+
193
+
194
+ def verify_receipt(vc: Dict[str, Any], expected_issuer: Optional[str] = None) -> Dict[str, Any]:
195
+
196
+
197
+
198
+
199
+ if expected_issuer is not None and expected_issuer.strip() == "":
200
+ return {"valid": False, "issuer": str(vc.get("issuer") or ""), "content_bound": False, "record_id": None,
201
+ "reason": 'an empty --issuer/expected_issuer was supplied - that is not an unpinned check, it is a '
202
+ 'missing pin (an unset environment variable interpolates to ""). Omit the argument entirely '
203
+ 'to verify unpinned on purpose.'}
204
+ try:
205
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
206
+ except ImportError as e:
207
+
208
+
209
+
210
+
211
+ raise ImportError("verifying needs the `cryptography` package, which decidio-verify depends on; reinstall: pip install --upgrade decidio-verify") from e
212
+
213
+ try:
214
+ issuer_raw = _field(vc, "issuer")
215
+ did = "" if issuer_raw is None else str(issuer_raw)
216
+ if not did.startswith("did:key:z"):
217
+ return {"valid": False, "issuer": did, "content_bound": False, "reason": "unsupported issuer DID (expected did:key Ed25519)"}
218
+ if expected_issuer and did != expected_issuer:
219
+
220
+
221
+
222
+ cs0 = _field(vc, "credentialSubject") or {}
223
+ rc0 = _field(cs0, "recordCanonical")
224
+ ch0 = _field(cs0, "contentHash")
225
+ ph0 = _field(cs0, "prevHash")
226
+ bound0 = isinstance(rc0, str) and isinstance(ch0, str) and _derive_hash(rc0, ph0 if isinstance(ph0, str) else None) == ch0
227
+ rid0 = _field(cs0, "recordId")
228
+ return {"valid": False, "issuer": did, "content_bound": bound0,
229
+ "record_id": rid0 if isinstance(rid0, str) else None,
230
+ "reason": "issuer DID is not the expected issuer (the receipt itself may be internally consistent - it was just not issued by who you pinned)"}
231
+
232
+
233
+ mc = _b58decode(did[len("did:key:z"):])
234
+ if len(mc) < 2 or mc[0] != 0xED or mc[1] != 0x01:
235
+ return {"valid": False, "issuer": did, "content_bound": False, "reason": "issuer DID is not Ed25519"}
236
+ pub = Ed25519PublicKey.from_public_bytes(bytes(mc[2:]))
237
+
238
+ cs = _field(vc, "credentialSubject")
239
+ cs = {} if cs is None else cs
240
+
241
+
242
+
243
+
244
+ prev = _field(cs, "prevHash")
245
+ if prev is not None and not isinstance(prev, str):
246
+ return {"valid": False, "issuer": did, "content_bound": False, "record_id": _field(cs, "recordId"),
247
+ "reason": "prevHash must be a string or null (an array/object cannot be hashed unambiguously)"}
248
+ if not isinstance(_field(cs, "contentHash"), str) or not isinstance(_field(cs, "recordId"), str):
249
+ return {"valid": False, "issuer": did, "content_bound": False,
250
+ "reason": "recordId and contentHash must be strings"}
251
+
252
+
253
+
254
+
255
+
256
+
257
+ canonical = _field(cs, "recordCanonical")
258
+ content_bound = isinstance(canonical, str) and _derive_hash(canonical, prev) == _field(cs, "contentHash")
259
+ if not content_bound:
260
+ return {"valid": False, "issuer": did, "content_bound": False, "record_id": _field(cs, "recordId"),
261
+ "reason": "contentHash does not match recordCanonical (content tampered)"}
262
+
263
+ proof = _field(vc, "proof")
264
+ proof = {} if proof is None else proof
265
+ base = {"issuer": did, "content_bound": content_bound, "record_id": _field(cs, "recordId")}
266
+ if _field(proof, "type") != "DataIntegrityProof":
267
+ return {"valid": False, **base, "reason": "unsupported proof (expected DataIntegrityProof)"}
268
+
269
+
270
+
271
+
272
+ if _field(proof, "cryptosuite") == _LEGACY_CRYPTOSUITE:
273
+ return {"valid": False, **base, "reason": "receipt uses Decidio's pre-standard format (eddsa-2022); not verifiable under the published spec — ask for a re-sealed receipt"}
274
+ if _field(proof, "cryptosuite") != CRYPTOSUITE:
275
+ return {"valid": False, **base, "reason": f"unsupported cryptosuite (expected {CRYPTOSUITE})"}
276
+
277
+
278
+
279
+
280
+
281
+
282
+
283
+ _purpose = _field(proof, "proofPurpose")
284
+ if _purpose != "assertionMethod":
285
+ return {"valid": False, **base,
286
+ "reason": f'proofPurpose is {_purpose!r}, not "assertionMethod" - this proof was made for a different purpose, so it is not an issuance of this credential'}
287
+ _vm = _field(proof, "verificationMethod")
288
+ if not isinstance(_vm, str) or not _vm.startswith(f"{did}#"):
289
+ return {"valid": False, **base,
290
+ "reason": f"verificationMethod {_vm!r} does not identify a key of the issuer ({did}) - the signature was checked against the issuer's key, but the proof names a different one"}
291
+
292
+
293
+ _msid = did[len("did:key:"):]
294
+ if _vm != f"{did}#{_msid}":
295
+ return {"valid": False, **base,
296
+ "reason": f"verificationMethod {_vm!r} is not the issuer's did:key method identifier (expected {did}#{_msid}) - did:key has exactly one verification method, and this proof names a fragment that does not exist"}
297
+
298
+
299
+
300
+
301
+
302
+
303
+ _created = _field(proof, "created")
304
+ if not isinstance(_created, str) or not _XSD_DATE_TIME_STAMP.match(_created):
305
+ return {"valid": False, **base,
306
+ "reason": f'proof has no usable "created" timestamp ({_created!r}) - a sealed assertion must say when it was made'}
307
+ if not _is_calendrical_date_time_stamp(_created):
308
+ return {"valid": False, **base,
309
+ "reason": f'proof "created" timestamp {_created!r} is not a real date-time (a field is out of range) - a sealed assertion cannot have been made at a time that does not exist'}
310
+
311
+
312
+
313
+
314
+
315
+
316
+
317
+ pv = _field(proof, "proofValue")
318
+ if not isinstance(pv, str) or not pv.startswith("z"):
319
+ return {"valid": False, **base, "reason": "missing/invalid proofValue (expected base58-btc multibase)"}
320
+
321
+
322
+
323
+
324
+
325
+
326
+ unsecured_document = {k: v for k, v in vc.items() if k != "proof"}
327
+ proof_config = {k: v for k, v in proof.items() if k != "proofValue"}
328
+ if proof_config.get("@context") is not None:
329
+ pc = _as_context_list(proof_config.get("@context"))
330
+ dc = _as_context_list(unsecured_document.get("@context"))
331
+
332
+
333
+
334
+
335
+
336
+
337
+
338
+ if len(dc) != len(pc):
339
+ return {"valid": False, **base, "reason": "@context does not match between document and proof (one carries entries the other does not cover)"}
340
+ for i, want in enumerate(pc):
341
+ if not _same_context_entry(want, dc[i]):
342
+ return {"valid": False, **base, "reason": "proof @context does not match the document @context"}
343
+ unsecured_document["@context"] = proof_config.get("@context")
344
+
345
+ signature = _b58decode(pv[1:])
346
+
347
+
348
+
349
+
350
+ try:
351
+ signing_input = _hash_data(unsecured_document, proof_config)
352
+ except ValueError as e:
353
+
354
+
355
+
356
+
357
+
358
+
359
+
360
+ if str(e).startswith("JCS: integer"):
361
+
362
+
363
+
364
+ return {"valid": False, **base, "reason": "receipt contains an integer beyond 2^53 - its exact signed value cannot be reproduced, so it is not verifiable"}
365
+ raise
366
+ try:
367
+
368
+
369
+
370
+
371
+
372
+ pub.verify(bytes(signature), signing_input)
373
+ valid = True
374
+ except Exception:
375
+ valid = False
376
+
377
+
378
+
379
+ rc = _field(cs, "recordCanonical")
380
+ sealed_state = read_sealed_state(rc) if (valid and content_bound and isinstance(rc, str)) else None
381
+ return {"valid": valid, **base, "d_number": _field(cs, "dNumber"), "prev_hash": _field(cs, "prevHash"),
382
+ "reason": None if valid else "signature does not verify against issuer DID",
383
+ "sealed_state": sealed_state,
384
+ "record_kind": (read_record_kind(rc) if (valid and content_bound and isinstance(rc, str)) else None)}
385
+ except Exception as e:
386
+ return {"valid": False, "issuer": str(_field(vc, "issuer") or ""), "content_bound": False, "reason": str(e)}
387
+
388
+
389
+ def verify_chain(vcs: List[Dict[str, Any]], expected_issuer: Optional[str] = None) -> Dict[str, Any]:
390
+ """Verify an ordered chain: each receipt's prevHash must equal the prior contentHash, and every
391
+ receipt must independently verify. Proves tamper-evident ordering."""
392
+ if not vcs:
393
+ return {"valid": False, "length": 0, "reason": "no receipts supplied"}
394
+
395
+
396
+ issuers = {str(_field(vc, "issuer") or "") for vc in vcs}
397
+ if len(issuers) > 1:
398
+ return {"valid": False, "length": 0, "reason": f"these receipts come from {len(issuers)} DIFFERENT issuers - a chain must be issued end to end by one issuer"}
399
+ prev: Optional[str] = None
400
+ anchor = "segment"
401
+ for i, vc in enumerate(vcs):
402
+ r = verify_receipt(vc, expected_issuer)
403
+ if not r["valid"]:
404
+ return {"valid": False, "length": i, "reason": f'receipt {i} ({r.get("record_id") or "?"}) invalid: {r.get("reason")}'}
405
+ cs = _field(vc, "credentialSubject")
406
+ cs = {} if cs is None else cs
407
+
408
+
409
+ if i == 0:
410
+ anchor = "genesis" if _field(cs, "prevHash") is None else "segment"
411
+ elif _field(cs, "prevHash") != prev:
412
+
413
+
414
+
415
+
416
+ return {"valid": False, "length": i, "reason": f"receipt {i} does not follow receipt {i - 1} directly (prevHash mismatch - either receipts between them are missing from this set, or the order/content is wrong; each receipt shown above verified individually)"}
417
+ prev = _field(cs, "contentHash")
418
+ return {"valid": True, "length": len(vcs), "anchor": anchor}
419
+
420
+
421
+ def _parse_strict(text: str, path: str) -> Dict[str, Any]:
422
+ """Parse a receipt, refusing duplicate object keys.
423
+
424
+ RFC 8785 §3.1 requires duplicate-free input, and mainstream parsers silently keep one of the duplicates (Python's and
425
+ JavaScript's keep the last). So a file holding `"issuer":"did:key:zEVIL","issuer":"<real>"` would verify while a human
426
+ reading it top-down sees the other value. `object_pairs_hook` sees the pairs before they are collapsed."""
427
+ def no_duplicates(pairs: List[Any]) -> Dict[str, Any]:
428
+ seen = set()
429
+ for key, _value in pairs:
430
+ if key in seen:
431
+
432
+
433
+
434
+ raise ValueError(
435
+ f"{path}: duplicate JSON key {key!r} - RFC 8785 requires duplicate-free input, "
436
+ "and different parsers disagree on which value is real"
437
+ )
438
+ seen.add(key)
439
+ return dict(pairs)
440
+
441
+ return json.loads(text, object_pairs_hook=no_duplicates)
442
+
443
+
444
+ def _load_strict(path: str) -> Dict[str, Any]:
445
+ """File-path convenience over _parse_strict, kept for library callers. The CLI reads files
446
+ itself first — an unreadable file is an I/O problem, not a verdict — then parses the text."""
447
+ with open(path, encoding="utf-8") as fh:
448
+ return _parse_strict(fh.read(), path)
449
+
450
+
451
+
452
+
453
+
454
+
455
+
456
+
457
+
458
+
459
+
460
+ KNOWN_ISSUERS: Tuple[Mapping[str, str], ...] = (
461
+ MappingProxyType({"did": "did:key:z6MkmLGeR5NjJ87a1yU5ygqju49CtnUrt38esqM54Y9tXnKq", "host": "decidio-api.onrender.com", "label": "Decidio staging lab"}),
462
+ MappingProxyType({"did": "did:key:z6MkpBwpAT98VAqg2UpiSGJZieg7DGQpoNkdioDUEo4kQXnJ", "host": "decidio-prod-api.onrender.com", "label": "Decidio production"}),
463
+ )
464
+
465
+
466
+ def help_text(command: str = "decidio-verify") -> str:
467
+ """The help text of the door named `command`."""
468
+ anchors = "; ".join(f'{k["did"]} ({k["label"]}, {k["host"]})' for k in KNOWN_ISSUERS)
469
+ return f"""{command} — verify Decidio Authority Receipts OFFLINE (no network, no account)
470
+
471
+ usage: {command} [--issuer <did:key>] <receipt.json> [more.json ...]
472
+
473
+ One file -> verify that receipt (signature + content binding).
474
+ Many files -> verify each AND their chain order (segment semantics).
475
+ Every run prints its TRUST ANCHOR first - the issuer the verdict is pinned to:
476
+ (no flag) the built-in Decidio issuer: {anchors}.
477
+ A receipt from any other issuer is refused (exit 2) until you pin one - its own
478
+ issuer field is a claim, never a trust anchor.
479
+ --issuer <did:key> pin the expected issuer yourself (a self-hosted Decidio: take the DID from that
480
+ host's /api/did, never from the receipt). Wins over the built-in anchor.
481
+ --allow-unpinned structural check only; the verdict carries the UNPINNED warning.
482
+
483
+ Exit codes: 0 all verified / 1 verification failed or file unreadable / 2 usage error, or no trust
484
+ anchor for these receipts.
485
+ The Decidio SDK runs the same implementation as `python -m decidio verify`."""
486
+
487
+
488
+ USAGE = help_text()
489
+
490
+
491
+ def main(argv: Optional[List[str]] = None, command: str = "decidio-verify") -> int:
492
+ """The standalone door. `command` is the name its help and refusals print (`python -m decidio.verify` passes its own)."""
493
+ args = list(argv if argv is not None else sys.argv[1:])
494
+
495
+
496
+
497
+
498
+ if args and args[0] in ("--version", "-v", "-V", "version"):
499
+ from . import __version__
500
+ print(__version__)
501
+ return 0
502
+ if args and args[0] in ("--help", "-h", "help"):
503
+ print(help_text(command))
504
+ return 0
505
+ if not args:
506
+ print(help_text(command), file=sys.stderr)
507
+ return 2
508
+ return run(args, command)
509
+
510
+
511
+ def built_in_anchor(files: List[str], read_text: Callable[[str], str], known: Sequence[Mapping[str, str]] = KNOWN_ISSUERS) -> Dict[str, Any]:
512
+ """With no --issuer: the built-in anchor these receipts select ({"anchor": entry}), or why none applies
513
+ ({"refusal": text}). The receipts' own `issuer` fields only CHOOSE among `known` - a claim can never add an anchor - and
514
+ every receipt is then verified against the chosen DID exactly as with --issuer, so a file naming a built-in DID without
515
+ holding its key still fails on the signature. Files that do not parse are left to the verdict, which names them."""
516
+ claimed: List[str] = []
517
+ for f in files:
518
+ try:
519
+ vc = _parse_strict(read_text(f), f)
520
+ except Exception:
521
+ continue
522
+ d = str(_field(vc, "issuer") or "") if isinstance(vc, dict) else ""
523
+ if d not in claimed:
524
+ claimed.append(d)
525
+ outside = [d for d in claimed if not any(k["did"] == d for k in known)]
526
+ if outside:
527
+ who = "the receipt names" if len(claimed) == 1 else "these receipts name"
528
+ return {"refusal": f"{who} {', '.join(d or '(no issuer)' for d in outside)} as issuer, which is not a built-in Decidio issuer"}
529
+ if len(claimed) > 1:
530
+ return {"refusal": f"these receipts name {len(claimed)} different issuers - verify each issuer's receipts separately"}
531
+ anchor = next((k for k in known if k["did"] in claimed), known[0] if known else None)
532
+ return {"anchor": anchor} if anchor is not None else {"refusal": "no built-in issuer is configured"}
533
+
534
+
535
+ def pin_required_message(command: str, why: Optional[str] = None) -> str:
536
+ """The refusal a CLI door prints when no trust anchor applies: a receipt from an issuer this verifier does not
537
+ know, with no --issuer given."""
538
+ built_in = "; ".join(f'{k["did"]} ({k["label"]}, {k["host"]})' for k in KNOWN_ISSUERS)
539
+ return "\n".join([
540
+ f"✘ {command} needs --issuer <did:key>" + (f" here: {why}" if why else "") + " — without a pin, VALID only proves the file agrees with itself (any keyholder could have issued it).",
541
+ f" Built in (used when no --issuer is given): {built_in}.",
542
+ " A receipt's own issuer field is a claim, never a trust anchor. For any other Decidio (self-hosted), take its DID from",
543
+ " that host's /api/did - not from the receipt - and pin it:",
544
+ f" {command} --issuer <did:key:...> <receipt.json>",
545
+ " To check structure only, say so: --allow-unpinned (the verdict then carries the UNPINNED warning).",
546
+ ])
547
+
548
+
549
+ def run(args: List[str], command: str = "decidio-verify",
550
+ remembered: Optional[Callable[[], Optional[Tuple[str, str]]]] = None,
551
+ no_anchor_hint: Optional[str] = None) -> int:
552
+ """The flag and file grammar and the verdict rendering, shared by every door. The SDK's `python -m decidio verify` enters
553
+ here directly, so a file named "version" stays a file there; the standalone doors (`decidio-verify`,
554
+ `python -m decidio_verify`, `python -m decidio.verify`) answer --version/--help in main() above.
555
+
556
+ With no --issuer the trust anchor is `remembered()` when given - a door may pass a DID this computer remembered for its
557
+ host, as (did, where-it-came-from), or None, and raise ValueError(message) when that store cannot be read - and then the
558
+ built-in KNOWN_ISSUERS; `no_anchor_hint` is the door's extra line when neither applies."""
559
+
560
+
561
+
562
+
563
+
564
+
565
+
566
+ usage = f"usage: {command} [--issuer <did:key>] <receipt.json> [more.json ...] (or --allow-unpinned)"
567
+ expected_issuer: Optional[str] = None
568
+ allow_unpinned = False
569
+ files: List[str] = []
570
+ i = 0
571
+ while i < len(args):
572
+ a = args[i]
573
+ if a == "--allow-unpinned":
574
+ allow_unpinned = True
575
+ i += 1
576
+ continue
577
+ if a == "--":
578
+
579
+
580
+ files.extend(args[i + 1:])
581
+ break
582
+ if a == "--issuer":
583
+ v = args[i + 1] if i + 1 < len(args) else None
584
+
585
+
586
+ if v is None or v == "" or v.startswith("-"):
587
+ print("✘ --issuer needs a did:key value (a bare or EMPTY --issuer must not silently verify unpinned).", file=sys.stderr)
588
+ return 2
589
+
590
+
591
+
592
+
593
+ if expected_issuer is not None and expected_issuer != v:
594
+ print(f"✘ --issuer given twice with different values ({expected_issuer} then {v}) — refusing to choose which one you meant to pin to.", file=sys.stderr)
595
+ return 2
596
+ expected_issuer = v
597
+ i += 2
598
+ continue
599
+ if a.startswith("--issuer="):
600
+ v = a[len("--issuer="):]
601
+ if not v:
602
+ print("✘ --issuer needs a did:key value (a bare or EMPTY --issuer must not silently verify unpinned).", file=sys.stderr)
603
+ return 2
604
+ if expected_issuer is not None and expected_issuer != v:
605
+ print(f"✘ --issuer given twice with different values ({expected_issuer} then {v}) — refusing to choose which one you meant to pin to.", file=sys.stderr)
606
+ return 2
607
+ expected_issuer = v
608
+ elif a.startswith("-"):
609
+ print(f'✘ unknown option "{a}" — refusing to guess (a flag you meant to matter must never be silently ignored).', file=sys.stderr)
610
+ print(usage, file=sys.stderr)
611
+ return 2
612
+ else:
613
+ files.append(a)
614
+ i += 1
615
+ if not files:
616
+ print(usage, file=sys.stderr)
617
+ return 2
618
+
619
+
620
+ if expected_issuer is not None and allow_unpinned:
621
+ print("✘ --allow-unpinned and --issuer together — an unpinned check and a pinned one are different questions; ask one.", file=sys.stderr)
622
+ return 2
623
+
624
+
625
+ texts: Dict[str, str] = {}
626
+ for f in files:
627
+ try:
628
+ with open(f, encoding="utf-8") as fh:
629
+ texts[f] = fh.read()
630
+ except OSError as e:
631
+ detail = "no such file" if isinstance(e, FileNotFoundError) else (e.strerror or str(e))
632
+ print(f"✘ cannot read {f}: {detail} (nothing was verified)", file=sys.stderr)
633
+ return 1
634
+
635
+
636
+
637
+ anchor_note: Optional[str] = "--issuer" if expected_issuer is not None else None
638
+ if expected_issuer is None and not allow_unpinned:
639
+ mem: Optional[Tuple[str, str]] = None
640
+ if remembered is not None:
641
+ try:
642
+ mem = remembered()
643
+ except ValueError as e:
644
+ print(f"✘ {e}", file=sys.stderr)
645
+ return 2
646
+ if mem:
647
+ expected_issuer, anchor_note = mem
648
+ else:
649
+ pick = built_in_anchor(files, texts.__getitem__)
650
+ if "refusal" in pick:
651
+ print(pin_required_message(command, pick["refusal"]), file=sys.stderr)
652
+ if no_anchor_hint:
653
+ print(no_anchor_hint, file=sys.stderr)
654
+ return 2
655
+ expected_issuer = pick["anchor"]["did"]
656
+ anchor_note = f'built in: {pick["anchor"]["label"]}, {pick["anchor"]["host"]}'
657
+ try:
658
+ import cryptography
659
+ except ImportError:
660
+ print("✘ the open verifier needs the `cryptography` package, which decidio-verify depends on; reinstall: pip install --upgrade decidio-verify", file=sys.stderr)
661
+ return 1
662
+
663
+
664
+
665
+
666
+ if expected_issuer:
667
+ print(f"trust anchor: {expected_issuer} ({anchor_note or '--issuer'})")
668
+ else:
669
+ print("trust anchor: NONE - unpinned, a structural check only (any keyholder could have issued these files)")
670
+ vcs = []
671
+ parsed_files = []
672
+ any_parse_failed = False
673
+ for f in files:
674
+ try:
675
+ vcs.append(_parse_strict(texts[f], f))
676
+ parsed_files.append(f)
677
+ except ValueError as e:
678
+ any_parse_failed = True
679
+ msg = str(e)
680
+ print(f"INVALID {f}{msg[len(f):] if msg.startswith(f) else ': ' + msg}")
681
+ if not vcs:
682
+ return 1
683
+ all_ok = not any_parse_failed
684
+ any_valid = False
685
+ for f, vc in zip(parsed_files, vcs):
686
+ r = verify_receipt(vc, expected_issuer)
687
+ all_ok = all_ok and r["valid"]
688
+ any_valid = any_valid or r["valid"]
689
+ print(f'{"VALID " if r["valid"] else "INVALID"} {f}')
690
+
691
+
692
+ unpinned = "" if expected_issuer else " (UNPINNED - this only proves internal consistency; ANY keyholder could have issued it. Pass --issuer <your workspace DID> to verify WHO)"
693
+ print(f' record: {r.get("record_id") or "?"} kind: {r.get("record_kind") or "?"} issuer: {r["issuer"]}{unpinned}')
694
+
695
+
696
+ bound = "true" if r["content_bound"] else "false"
697
+ print(f' content-bound: {bound}' + (f' reason: {r.get("reason")}' if r.get("reason") else ""))
698
+
699
+
700
+ s = r.get("sealed_state")
701
+ if s:
702
+ bits: List[str] = []
703
+ if "result" in s:
704
+ bits.append(f'gate: {s["result"] if s["result"] is not None else "-"}')
705
+ if "confirmation" in s:
706
+ bits.append(f'confirmation: {s["confirmation"] if s["confirmation"] is not None else "-"}')
707
+ if "ratified" in s:
708
+ bits.append(f'ratified: {"yes" if s["ratified"] else "no"}')
709
+ if "nominated_deciders" in s:
710
+ bits.append(f'nominated deciders: {s["nominated_deciders"]}')
711
+ if bits:
712
+ print(" as sealed - " + " ".join(bits))
713
+
714
+
715
+
716
+
717
+
718
+
719
+
720
+
721
+
722
+
723
+ if s.get("ratified") is True and s.get("nominated_deciders") == 0:
724
+ print(' ("nominated deciders" lists anyone nominated in ADVANCE - none here; the person '
725
+ 'who adjudicated is recorded separately, as the ratifier)')
726
+ if any_parse_failed and len(files) > 1:
727
+ print(f"\nchain: not checked - {len(files) - len(vcs)} file(s) failed to parse (see above); re-run with readable receipts to verify ordering.")
728
+ elif len(vcs) > 1:
729
+ c = verify_chain(vcs, expected_issuer)
730
+ all_ok = all_ok and c["valid"]
731
+ if c["valid"] and c.get("anchor") == "segment":
732
+ note = " - segment: ordering proven from the FIRST file forward; history before it is not covered by these receipts"
733
+ elif c["valid"]:
734
+ note = " - from genesis"
735
+ else:
736
+ note = ""
737
+ print(f'\nchain: {"intact" if c["valid"] else "broken"} ({c["length"]}/{len(vcs)})' + note
738
+ + (f' - {c["reason"]}' if c.get("reason") else ""))
739
+
740
+
741
+
742
+
743
+
744
+
745
+ if any_valid:
746
+ print("\nwhat VALID proves: the CLAIMS in this record were sealed by that issuer and none of"
747
+ "\n them has changed since. NOT the bytes: the signature covers the record's CANONICAL"
748
+ "\n form (JCS), so reformatting the file - reindenting, minifying, reordering keys -"
749
+ "\n still verifies, and should, because none of that alters a single claim. If you need"
750
+ "\n byte-for-byte custody, hash the file yourself and keep that hash; this proves the"
751
+ "\n CONTENT, which is what an auditor is actually asking about."
752
+ "\nwhat it does NOT prove: that the approved action ran. Execution is confirmed AFTER the"
753
+ "\n seal, and a sealed receipt is immutable, so the \"as sealed\" fields above are a snapshot"
754
+ "\n taken when the record was sealed - not current status. Ask the issuer for that."
755
+ "\n This check is cryptographic, not semantic: it does not evaluate business rules, timestamp"
756
+ "\n plausibility, or whether the record was later superseded or revoked.")
757
+ return 0 if all_ok else 1
758
+
759
+
760
+ def utf8_streams() -> None:
761
+ """UTF-8 out on the standalone doors (the verdict lines carry ✔ and ✘)."""
762
+ for _stream in (sys.stdout, sys.stderr):
763
+ try:
764
+ if hasattr(_stream, "reconfigure"):
765
+ _stream.reconfigure(encoding="utf-8", errors="replace")
766
+ except Exception:
767
+ pass
768
+
769
+
770
+ if __name__ == "__main__":
771
+ utf8_streams()
772
+ raise SystemExit(main())
@@ -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,11 @@
1
+ decidio_verify/__init__.py,sha256=RMdXPzeVTKc9THinXbAojlRQkAPkJt7l5ergP0oFYco,1210
2
+ decidio_verify/__main__.py,sha256=92dVnuXxYtck_tbZ_4VAuY0U_k4Wj7cBoD7LvmWdSQQ,434
3
+ decidio_verify/jcs.py,sha256=z8JE_iLaG1q3081nZtxe6fWrCZAJLIuDS5_zFSnHMv4,6947
4
+ decidio_verify/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ decidio_verify/verify.py,sha256=bHu-J95dTuGZ-0L_4oOBdHsNTPcc_l0OzR4Zr4dhLbc,33787
6
+ decidio_verify-0.23.0.dist-info/METADATA,sha256=85EGHRMb52tFBr_x8A3NL7o3_WVKfhB9f-A09Ga9fmQ,5009
7
+ decidio_verify-0.23.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ decidio_verify-0.23.0.dist-info/entry_points.txt,sha256=UKG4rtwraQZ3wrKWW42w-ZXgy5yErrLdTc87NqTGW_w,64
9
+ decidio_verify-0.23.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
10
+ decidio_verify-0.23.0.dist-info/licenses/NOTICE,sha256=AH_PNKbN25W8tRFI7yMHU_NVeMAILIYRZJrZG9dcvK0,222
11
+ decidio_verify-0.23.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ decidio-verify = decidio_verify.__main__:main
@@ -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).