@decidio/verify 0.1.0

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.
package/LICENSE ADDED
@@ -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.
package/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # @decidio/verify
2
+
3
+ **Standalone, zero-dependency verifier for Decidio Authority Receipts.** Verify a sealed receipt's signature, content binding, and chain order **offline — with no Decidio dependency**. A record you can verify only with the vendor's software isn't really owned; this is what makes "the customer owns the record" true rather than rhetorical.
4
+
5
+ ```bash
6
+ npx @decidio/verify receipt.json # one receipt
7
+ npx @decidio/verify r1.json r2.json r3.json # each + the chain order
8
+ ```
9
+
10
+ ```ts
11
+ import { verifyReceipt, verifyChain } from "@decidio/verify";
12
+ const r = verifyReceipt(vc); // { valid, issuer, contentBound, recordId, reason? }
13
+ ```
14
+
15
+ ## What it checks (offline, using only the public DID in the receipt)
16
+ 1. **Content binding** — re-derives `sha256((prevHash||"") + recordCanonical)` and confirms it equals the signed `contentHash`, so the signature commits to the actual content (tamper-evident).
17
+ 2. **Signature** — verifies a W3C Data Integrity proof (`DataIntegrityProof`, cryptosuite
18
+ `eddsa-jcs-2022`, Ed25519 via `did:key`) over the WHOLE receipt: the signing input is
19
+ `SHA-256(JCS(proof options))` followed by `SHA-256(JCS(receipt without proof))`, per
20
+ [Data Integrity EdDSA Cryptosuites v1.0](https://www.w3.org/TR/vc-di-eddsa/) §3.3.
21
+ Verification needs only SHA-256, Ed25519, base58 and RFC 8785 — no JSON-LD, no context
22
+ fetching, no DID resolution, no network.
23
+ *Receipts sealed before 2026-08-04 carry a pre-standard Decidio format under the name
24
+ `eddsa-2022`; those are refused with an explicit reason, not reported as tampered.*
25
+ 3. **Chain** (`verifyChain`) — each receipt's `prevHash` links to the prior `contentHash`, and every receipt independently verifies.
26
+
27
+ Signature + content + chain verify **offline**. Revocation/status is a separate, network-bound check by design — a receipt is tamper-evidence, not a liveness check.
28
+
29
+ ## Parity
30
+ A Python verifier ships in `decidio[verify]` (`python -m decidio.verify`). Both verifiers accept the **same** real Decidio seals — proven in the cross-language conformance suite. Zero dependencies beyond `node:crypto` (TS) / `cryptography` (Python).
31
+
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,113 @@
1
+ #!/usr/bin/env node
2
+ // decidio-verify <receipt.json> [<receipt2.json> ...]
3
+ // One file → verify that receipt. Many files → verify each AND the chain order.
4
+ // Exit 0 only if everything verifies. No network, no Decidio dependency.
5
+ import { readFileSync } from "node:fs";
6
+ import { verifyReceipt, verifyChain } from "./verify.js";
7
+ /** Parse a receipt, REFUSING duplicate object keys. RFC 8785 §3.1 requires duplicate-free input,
8
+ * and JSON.parse silently keeps the last one — so a file containing
9
+ * `"issuer":"did:key:zEVIL","issuer":"<real>"` verifies while a human (or any parser that keeps the
10
+ * FIRST duplicate) reads the attacker's value. Same bytes, two different answers: refuse instead. */
11
+ function parseStrict(text, file) {
12
+ const value = JSON.parse(text); // also validates the syntax the scanner below assumes
13
+ // A reviver cannot help here — duplicates are already collapsed by the time it runs — so detect
14
+ // them by re-walking the raw text.
15
+ const dup = findDuplicateKey(text);
16
+ if (dup)
17
+ throw new Error(`${file}: duplicate JSON key ${JSON.stringify(dup)} — RFC 8785 requires duplicate-free input, and different parsers disagree on which value is real`);
18
+ return value;
19
+ }
20
+ /** Minimal string-aware scanner: collects key names per object nesting level and reports the first
21
+ * repeated one. Deliberately simple — it only needs to be correct on well-formed JSON, which
22
+ * JSON.parse has already confirmed by the time this runs.
23
+ *
24
+ * Keys are UNESCAPED before comparison. Comparing raw token text let `"issuer"` and
25
+ * `"issuer"` register as two different keys while JSON.parse had already collapsed them into one
26
+ * holding the LAST value — so the escaped form bypassed this check entirely, and because Python's
27
+ * object_pairs_hook sees keys after unescaping, the two CLIs disagreed on the same file. A
28
+ * cross-language divergence is the one outcome this tool exists to prevent. */
29
+ function findDuplicateKey(text) {
30
+ const stack = [];
31
+ let i = 0;
32
+ const readString = () => {
33
+ let out = "";
34
+ i++; // opening quote
35
+ while (i < text.length) {
36
+ const ch = text[i];
37
+ if (ch === "\\") {
38
+ out += text[i] + text[i + 1];
39
+ i += 2;
40
+ continue;
41
+ }
42
+ if (ch === '"') {
43
+ i++;
44
+ return out;
45
+ }
46
+ out += ch;
47
+ i++;
48
+ }
49
+ return out;
50
+ };
51
+ while (i < text.length) {
52
+ const ch = text[i];
53
+ if (ch === '"') {
54
+ const s = readString();
55
+ // A string immediately followed by ':' (modulo whitespace) is a KEY.
56
+ let j = i;
57
+ while (j < text.length && /\s/.test(text[j]))
58
+ j++;
59
+ if (text[j] === ":" && stack.length > 0) {
60
+ // Unescape via the parser itself — safe because parseStrict already JSON.parse'd the whole
61
+ // file, so this token is known well-formed.
62
+ const key = JSON.parse(`"${s}"`);
63
+ const top = stack[stack.length - 1];
64
+ if (top.has(key))
65
+ return key;
66
+ top.add(key);
67
+ }
68
+ continue;
69
+ }
70
+ if (ch === "{")
71
+ stack.push(new Set());
72
+ else if (ch === "}")
73
+ stack.pop();
74
+ i++;
75
+ }
76
+ return null;
77
+ }
78
+ function main(argv) {
79
+ const args = argv.slice(2);
80
+ // Optional: --issuer did:key:z... → assert the receipt was issued by THIS DID (Decidio's
81
+ // published issuer), not merely validly self-signed by some key.
82
+ const issIdx = args.indexOf("--issuer");
83
+ const expectedIssuer = issIdx >= 0 ? args[issIdx + 1] : undefined;
84
+ const files = args.filter((a, i) => !a.startsWith("--") && !(issIdx >= 0 && i === issIdx + 1));
85
+ if (files.length === 0) {
86
+ console.error("usage: decidio-verify [--issuer <did:key>] <receipt.json> [more.json ...]");
87
+ return 2;
88
+ }
89
+ let vcs;
90
+ try {
91
+ vcs = files.map((f) => parseStrict(readFileSync(f, "utf8"), f));
92
+ }
93
+ catch (e) {
94
+ // A file we cannot read unambiguously is a REFUSAL, reported like any other, not a stack trace.
95
+ console.log(`✘ INVALID ${String(e?.message ?? e)}`);
96
+ return 1;
97
+ }
98
+ let allOk = true;
99
+ vcs.forEach((vc, i) => {
100
+ const r = verifyReceipt(vc, expectedIssuer);
101
+ allOk = allOk && r.valid;
102
+ console.log(`${r.valid ? "✔ VALID " : "✘ INVALID"} ${files[i]}`);
103
+ console.log(` record: ${r.recordId ?? "?"} issuer: ${r.issuer}`);
104
+ console.log(` content-bound: ${r.contentBound}${r.reason ? ` reason: ${r.reason}` : ""}`);
105
+ });
106
+ if (vcs.length > 1) {
107
+ const c = verifyChain(vcs, expectedIssuer);
108
+ allOk = allOk && c.valid;
109
+ console.log(`\nchain: ${c.valid ? "✔ intact" : "✘ broken"} (${c.length}/${vcs.length})${c.reason ? ` — ${c.reason}` : ""}`);
110
+ }
111
+ return allOk ? 0 : 1;
112
+ }
113
+ process.exit(main(process.argv));
@@ -0,0 +1,21 @@
1
+ export declare function jcsCanonicalize(value: unknown): string;
2
+ export interface VerifyResult {
3
+ valid: boolean;
4
+ issuer: string;
5
+ contentBound: boolean;
6
+ recordId?: string;
7
+ dNumber?: string | null;
8
+ prevHash?: string | null;
9
+ reason?: string;
10
+ }
11
+ /** Verify a Decidio Authority Receipt (W3C VC, DataIntegrityProof / eddsa-jcs-2022) offline.
12
+ * Pass `expectedIssuer` (Decidio's published did:key) to assert the receipt was issued by
13
+ * Decidio — a valid signature by *some* key is not proof of *who* issued it. */
14
+ export declare function verifyReceipt(vc: any, expectedIssuer?: string): VerifyResult;
15
+ /** Verify an ordered chain: each receipt's prevHash must equal the prior contentHash,
16
+ * and every receipt must independently verify. Proves tamper-evident ordering. */
17
+ export declare function verifyChain(vcs: any[], expectedIssuer?: string): {
18
+ valid: boolean;
19
+ length: number;
20
+ reason?: string;
21
+ };
package/dist/verify.js ADDED
@@ -0,0 +1,208 @@
1
+ // @decidio/verify — STANDALONE open verifier for Decidio Authority Receipts.
2
+ //
3
+ // Zero dependencies (node:crypto only), zero Decidio coupling. A customer, auditor, or
4
+ // counterparty can verify a sealed receipt OFFLINE, with their own tooling — never only through
5
+ // Decidio's software. That is what makes "the customer owns the record" true rather than rhetorical.
6
+ //
7
+ // The receipt is a W3C Verifiable Credential secured with a DataIntegrityProof using the
8
+ // `eddsa-jcs-2022` cryptosuite (Data Integrity EdDSA Cryptosuites v1.0 — W3C Recommendation,
9
+ // 15 May 2025). That suite was chosen deliberately: verifying needs only SHA-256, Ed25519, base58
10
+ // and RFC 8785 canonicalisation — no JSON-LD expansion, no RDF canonicalisation, no context
11
+ // fetching, no DID resolution, no network. This file is ~150 lines and depends on nothing, which is
12
+ // the proof of that claim: you do not have to trust it, you can re-implement it.
13
+ //
14
+ // It checks, using ONLY the public DID embedded in the receipt:
15
+ // 1. issuer — the DID is Ed25519 and (when you pin one) is the issuer you expected;
16
+ // 2. content binding — re-derive sha256((prevHash||"") + recordCanonical) and confirm it equals
17
+ // the receipt's contentHash, so the signature commits to the actual record content;
18
+ // 3. signature — the standard eddsa-jcs-2022 proof over the whole document.
19
+ // Chain ordering is checked by verifyChain(). (Revocation/status needs the network — out of scope
20
+ // by design; a receipt is tamper-evidence, not a liveness check.)
21
+ import { createPublicKey, verify as edVerify, createHash } from "node:crypto";
22
+ const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
23
+ function b58decode(s) {
24
+ const bytes = [0];
25
+ for (const ch of s) {
26
+ const val = B58.indexOf(ch);
27
+ if (val < 0)
28
+ throw new Error("invalid base58");
29
+ let carry = val;
30
+ for (let i = 0; i < bytes.length; i++) {
31
+ carry += bytes[i] * 58;
32
+ bytes[i] = carry & 0xff;
33
+ carry >>= 8;
34
+ }
35
+ while (carry) {
36
+ bytes.push(carry & 0xff);
37
+ carry >>= 8;
38
+ }
39
+ }
40
+ for (const ch of s) {
41
+ if (ch === B58[0])
42
+ bytes.push(0);
43
+ else
44
+ break;
45
+ }
46
+ return Buffer.from(bytes.reverse());
47
+ }
48
+ // ── RFC 8785 JSON Canonicalization Scheme ─────────────────────────────────────────────────────
49
+ // Inlined so this package keeps its zero-dependency promise. Rules: no whitespace; object keys
50
+ // sorted by UTF-16 code unit of the raw key (JS default sort — NOT localeCompare, and note an
51
+ // astral char sorts by code UNIT, so U+1F600 precedes U+FFFD); numbers via ECMAScript
52
+ // Number::toString (what JSON.stringify emits); minimal string escaping with non-ASCII left as
53
+ // UTF-8; array order preserved; lone surrogates and non-finite numbers are errors.
54
+ function assertNoLoneSurrogate(s) {
55
+ for (let i = 0; i < s.length; i++) {
56
+ const c = s.charCodeAt(i);
57
+ if (c >= 0xd800 && c <= 0xdbff) {
58
+ const next = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
59
+ if (!(next >= 0xdc00 && next <= 0xdfff))
60
+ throw new Error("JCS: unpaired high surrogate");
61
+ i++;
62
+ }
63
+ else if (c >= 0xdc00 && c <= 0xdfff) {
64
+ throw new Error("JCS: unpaired low surrogate");
65
+ }
66
+ }
67
+ }
68
+ export function jcsCanonicalize(value) {
69
+ if (value === null)
70
+ return "null";
71
+ if (typeof value === "boolean")
72
+ return value ? "true" : "false";
73
+ if (typeof value === "number") {
74
+ if (!Number.isFinite(value))
75
+ throw new Error("JCS: non-finite numbers are not valid JSON");
76
+ return JSON.stringify(value);
77
+ }
78
+ if (typeof value === "string") {
79
+ assertNoLoneSurrogate(value);
80
+ return JSON.stringify(value);
81
+ }
82
+ if (Array.isArray(value))
83
+ return `[${value.map(jcsCanonicalize).join(",")}]`;
84
+ if (typeof value === "object") {
85
+ const obj = value;
86
+ const keys = Object.keys(obj).filter((k) => obj[k] !== undefined).sort();
87
+ for (const k of keys)
88
+ assertNoLoneSurrogate(k);
89
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${jcsCanonicalize(obj[k])}`).join(",")}}`;
90
+ }
91
+ throw new Error(`JCS: cannot canonicalise type ${typeof value}`);
92
+ }
93
+ const jcsBytes = (v) => Buffer.from(jcsCanonicalize(v), "utf8");
94
+ const sha256 = (s) => createHash("sha256").update(s, "utf8").digest("hex");
95
+ const deriveHash = (canonical, prevHash) => sha256((prevHash ?? "") + canonical);
96
+ const CRYPTOSUITE = "eddsa-jcs-2022";
97
+ /** Data Integrity §3.3.4 — the 64-byte signing input: SHA-256 of the canonical proof config,
98
+ * followed by SHA-256 of the canonical document. Config FIRST; the order is normative. The 64
99
+ * bytes are signed directly (Ed25519 hashes internally; they are not hashed again). */
100
+ function hashData(unsecuredDocument, proofConfig) {
101
+ return Buffer.concat([
102
+ createHash("sha256").update(jcsBytes(proofConfig)).digest(),
103
+ createHash("sha256").update(jcsBytes(unsecuredDocument)).digest(),
104
+ ]);
105
+ }
106
+ /** Verify a Decidio Authority Receipt (W3C VC, DataIntegrityProof / eddsa-jcs-2022) offline.
107
+ * Pass `expectedIssuer` (Decidio's published did:key) to assert the receipt was issued by
108
+ * Decidio — a valid signature by *some* key is not proof of *who* issued it. */
109
+ export function verifyReceipt(vc, expectedIssuer) {
110
+ try {
111
+ const did = String(vc?.issuer ?? "");
112
+ if (!did.startsWith("did:key:z"))
113
+ return { valid: false, issuer: did, contentBound: false, reason: "unsupported issuer DID (expected did:key Ed25519)" };
114
+ if (expectedIssuer && did !== expectedIssuer)
115
+ return { valid: false, issuer: did, contentBound: false, reason: "issuer DID is not the expected issuer" };
116
+ const mc = b58decode(did.slice("did:key:z".length));
117
+ // did:key Ed25519 = multicodec 0xed01 followed by the 32-byte key (CID v1.0 §2.2.2). The key is
118
+ // read straight out of the identifier, which is why no resolver and no network are needed.
119
+ if (mc[0] !== 0xed || mc[1] !== 0x01)
120
+ return { valid: false, issuer: did, contentBound: false, reason: "issuer DID is not Ed25519" };
121
+ const pub = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: mc.subarray(2).toString("base64url") }, format: "jwk" });
122
+ const cs = vc?.credentialSubject ?? {};
123
+ // TYPE discipline BEFORE content binding: with prevHash as an array, deriveHash yields a
124
+ // different digest, so checking binding first answered "content tampered" for what is really a
125
+ // malformed field — a scarier and different claim than the truth, and it made this verifier
126
+ // disagree with the Python one on the reason for the same file.
127
+ if (cs.prevHash !== null && cs.prevHash !== undefined && typeof cs.prevHash !== "string")
128
+ return { valid: false, issuer: did, contentBound: false, recordId: cs.recordId, reason: "prevHash must be a string or null (an array/object cannot be hashed unambiguously)" };
129
+ if (typeof cs.contentHash !== "string" || typeof cs.recordId !== "string")
130
+ return { valid: false, issuer: did, contentBound: false, reason: "recordId and contentHash must be strings" };
131
+ const contentBound = typeof cs.recordCanonical === "string" && deriveHash(cs.recordCanonical, cs.prevHash ?? null) === cs.contentHash;
132
+ if (!contentBound)
133
+ return { valid: false, issuer: did, contentBound: false, recordId: cs.recordId, reason: "contentHash does not match recordCanonical (content tampered)" };
134
+ const proof = vc?.proof ?? {};
135
+ if (proof.type !== "DataIntegrityProof")
136
+ return { valid: false, issuer: did, contentBound, recordId: cs.recordId, reason: "unsupported proof (expected DataIntegrityProof)" };
137
+ // Receipts sealed before 2026-08-04 used a pre-standard Decidio format under the name
138
+ // `eddsa-2022` (a pre-Recommendation working-draft name) whose signature covered a bespoke
139
+ // delimited string rather than the canonical document. Say so plainly — reporting it as an
140
+ // invalid signature would misrepresent an obsolete format as evidence of tampering.
141
+ if (proof.cryptosuite === "eddsa-2022")
142
+ return { valid: false, issuer: did, contentBound, recordId: cs.recordId, reason: "receipt uses Decidio's pre-standard format (eddsa-2022); not verifiable under the published spec — ask for a re-sealed receipt" };
143
+ if (proof.cryptosuite !== CRYPTOSUITE)
144
+ return { valid: false, issuer: did, contentBound, recordId: cs.recordId, reason: `unsupported cryptosuite (expected ${CRYPTOSUITE})` };
145
+ // proofValue MUST be a string, checked by type and not coerced. It is the ONLY proof field
146
+ // outside the signed bytes (it is stripped to form the proof config), so a coercing check —
147
+ // String(["z…"]) — let anyone with a text editor produce a byte-DIFFERENT receipt file that
148
+ // still read VALID, with no key and no signature break. That is receipt malleability, and an
149
+ // adversarial cross-language differential caught it in the first version of this file.
150
+ if (typeof proof.proofValue !== "string")
151
+ return { valid: false, issuer: did, contentBound, recordId: cs.recordId, reason: "proofValue must be a string (base58-btc multibase)" };
152
+ const proofValue = proof.proofValue;
153
+ if (!proofValue.startsWith("z"))
154
+ return { valid: false, issuer: did, contentBound, recordId: cs.recordId, reason: "missing/invalid proofValue (expected base58-btc multibase)" };
155
+ // A JSON number beyond 2^53 cannot survive parse → double → canonicalise: the parser silently
156
+ // rounds it, so a hand-edited file whose displayed number differs from the SIGNED number would
157
+ // still verify. Refuse rather than report VALID for a document we cannot faithfully reproduce.
158
+ // (Decidio receipts carry no numeric fields at all, so this can only fire on a foreign document.)
159
+ const unsafeNumber = (v) => typeof v === "number" ? Number.isInteger(v) && !Number.isSafeInteger(v)
160
+ : Array.isArray(v) ? v.some(unsafeNumber)
161
+ : v !== null && typeof v === "object" ? Object.values(v).some(unsafeNumber)
162
+ : false;
163
+ if (unsafeNumber(vc))
164
+ return { valid: false, issuer: did, contentBound, recordId: cs.recordId, reason: "receipt contains an integer beyond 2^53 — its exact signed value cannot be reproduced, so it is not verifiable" };
165
+ // §3.3.2: strip `proof` from the document and `proofValue` from the proof options. The @context
166
+ // rule is immediately below — we require EQUALITY, not the REC's prefix; see the note there.
167
+ const { proof: _omit, ...unsecuredDocument } = vc;
168
+ const { proofValue: _pv, ...proofConfig } = proof;
169
+ if (proofConfig["@context"] !== undefined) {
170
+ const pc = [].concat(proofConfig["@context"]);
171
+ const dc = [].concat(unsecuredDocument["@context"]);
172
+ // STRICTER THAN THE REC, deliberately. §3.3.2 requires only a prefix match and then replaces
173
+ // the document's @context with the proof's before hashing — so extra document entries are
174
+ // never signed. That is exploitable without a key: append a context entry (or an inline
175
+ // term-redefining object) to a genuine receipt and it still reads VALID, which lets a
176
+ // JSON-LD-aware consumer be shown a remapped record this verifier certified. Requiring equal
177
+ // length closes it, and cannot reject a genuine receipt: Decidio's issuer always copies the
178
+ // document's @context into the proof unchanged.
179
+ if (dc.length !== pc.length)
180
+ return { valid: false, issuer: did, contentBound, recordId: cs.recordId, reason: "document @context carries entries the proof does not cover" };
181
+ for (let i = 0; i < pc.length; i++) {
182
+ if (pc[i] !== dc[i])
183
+ return { valid: false, issuer: did, contentBound, recordId: cs.recordId, reason: "proof @context does not match the document @context" };
184
+ }
185
+ unsecuredDocument["@context"] = proofConfig["@context"];
186
+ }
187
+ const valid = edVerify(null, hashData(unsecuredDocument, proofConfig), pub, b58decode(proofValue.slice(1)));
188
+ return { valid, issuer: did, contentBound, recordId: cs.recordId, dNumber: cs.dNumber ?? null, prevHash: cs.prevHash ?? null, reason: valid ? undefined : "signature does not verify against issuer DID" };
189
+ }
190
+ catch (e) {
191
+ return { valid: false, issuer: String(vc?.issuer ?? ""), contentBound: false, reason: String(e?.message ?? e) };
192
+ }
193
+ }
194
+ /** Verify an ordered chain: each receipt's prevHash must equal the prior contentHash,
195
+ * and every receipt must independently verify. Proves tamper-evident ordering. */
196
+ export function verifyChain(vcs, expectedIssuer) {
197
+ let prev = null;
198
+ for (let i = 0; i < vcs.length; i++) {
199
+ const r = verifyReceipt(vcs[i], expectedIssuer);
200
+ if (!r.valid)
201
+ return { valid: false, length: i, reason: `receipt ${i} (${r.recordId ?? "?"}) invalid: ${r.reason}` };
202
+ const cs = vcs[i]?.credentialSubject ?? {};
203
+ if ((cs.prevHash ?? null) !== prev)
204
+ return { valid: false, length: i, reason: `receipt ${i} prevHash breaks the chain` };
205
+ prev = cs.contentHash;
206
+ }
207
+ return { valid: true, length: vcs.length };
208
+ }
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@decidio/verify",
3
+ "version": "0.1.0",
4
+ "description": "Standalone, zero-dependency verifier for Decidio Authority Receipts (W3C VC, Ed25519 did:key). Verify a sealed receipt's signature + content binding + chain order offline — no Decidio dependency. `npx @decidio/verify receipt.json`.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "types": "dist/verify.d.ts",
8
+ "main": "dist/verify.js",
9
+ "bin": {
10
+ "decidio-verify": "dist/cli.js"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/verify.d.ts",
15
+ "default": "./dist/verify.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "keywords": [
27
+ "verifiable-credentials",
28
+ "audit",
29
+ "receipts",
30
+ "ed25519",
31
+ "offline-verification"
32
+ ],
33
+ "homepage": "https://decidioai.com/receipt-spec/",
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^22.20.1",
39
+ "typescript": "^5.9.3"
40
+ },
41
+ "scripts": {
42
+ "typecheck": "tsc -p tsconfig.build.json --noEmit",
43
+ "build": "node -e \"fs.rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
44
+ "prepublishOnly": "npm run build"
45
+ }
46
+ }