@saihm/erasure-receipt 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,78 @@
1
+ # @saihm/erasure-receipt
2
+
3
+ **Prove a record was erased — not hidden.** Build and verify tamper-evident **cryptographic-erasure
4
+ receipts** (GDPR Art. 17) for [SAIHM](https://saihm.coti.global). Zero dependencies (`node:crypto` only).
5
+
6
+ SAIHM erases a record by destroying the *wrapped key* that decrypts it: the stored ciphertext
7
+ becomes unrecoverable noise, so the record is *gone, not merely de-indexed*. This library turns the
8
+ protocol's own seal + `forget` results into a small, portable receipt a compliance reviewer can
9
+ read, **re-verify**, and archive.
10
+
11
+ ```bash
12
+ npm install @saihm/erasure-receipt
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```js
18
+ import { buildErasureReceipt, verifyReceipt } from '@saihm/erasure-receipt';
19
+
20
+ // After you seal a record and honour an erasure request via @saihm/client-pro:
21
+ const receipt = buildErasureReceipt({
22
+ cellId, // the erased record's public id
23
+ commitmentHash, // the record's public commitment (e.g. remember().commitmentHash)
24
+ forget, // the forget() result: { complete, steps: [{ success }], epoch }
25
+ // epoch is the SAIHM protocol epoch, in HOURS (as the endpoint reports it)
26
+ copiesRemaining, // records with this id still readable after erasure (you verify == 0)
27
+ endpoint, // 'local blind sandbox' or your hosted endpoint host
28
+ });
29
+
30
+ const { valid, reasons } = verifyReceipt(receipt);
31
+ // valid === true only when the hash matches the body AND the erasure is irreversible
32
+ // (wrapped key destroyed AND zero copies remain). Otherwise `reasons` explains why.
33
+ ```
34
+
35
+ ## What's in a receipt
36
+
37
+ The receipt carries only **public** material — no plaintext, no secret:
38
+
39
+ ```json
40
+ {
41
+ "schema": "saihm.erasure-receipt/v1",
42
+ "action": "cryptographic-erasure",
43
+ "basis": "GDPR Art. 17 (right to erasure)",
44
+ "record": { "cellId": "9c29fce8…", "commitmentHash": "c3999ac2…" },
45
+ "result": { "keyDestroyed": true, "copiesRemaining": 0, "irreversible": true },
46
+ "erasedAt": "2026-06-24T05:28:08.000Z",
47
+ "endpoint": "local blind sandbox",
48
+ "note": "The endpoint holds ciphertext only; destroying the wrapped key leaves the stored bytes as unrecoverable noise…",
49
+ "receiptHash": "31228b4b…"
50
+ }
51
+ ```
52
+
53
+ - **`receiptHash`** is a SHA-256 over a **canonical (key-sorted)** serialization of the body, so the
54
+ receipt is **tamper-evident** — any change to the body changes the hash. `verifyReceipt`
55
+ re-serializes canonically and re-hashes; never re-hash pretty-printed JSON.
56
+ - The core claim is also **reproducible**: re-read the store with this `cellId` and confirm nothing
57
+ survives.
58
+ - `verifyReceipt` returns `{ valid: false, reasons: [...] }` if the hash doesn't match the body, if
59
+ any copy survives, or if the wrapped key was not destroyed.
60
+
61
+ ## Why this matters
62
+
63
+ For real personal data, "removed from search" is not erasure — the bytes are still there. This
64
+ library records erasure with the properties a compliance reviewer asks about: **key-destruction, not
65
+ de-indexing**; **targeted** (only the requested record); **provable** (a portable, tamper-evident,
66
+ reproducible receipt an auditor can re-verify); **non-custodial** (records are sealed client-side;
67
+ the endpoint only ever holds ciphertext).
68
+
69
+ ## See also
70
+
71
+ - [`@saihm/client-pro`](https://www.npmjs.com/package/@saihm/client-pro) — the sealing client that
72
+ produces the `remember` / `forget` results this receipt is built from.
73
+ - Runnable demo + all SAIHM demos: <https://citw2.github.io/saihm-demos/>.
74
+ - Join the protocol: <https://saihm.coti.global/join>.
75
+
76
+ ## License
77
+
78
+ Apache-2.0 © SAIHM
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@saihm/erasure-receipt",
3
+ "version": "0.1.0",
4
+ "description": "Tamper-evident, verifiable cryptographic-erasure receipts (GDPR Art. 17) for SAIHM: build a receipt from a seal + forget, and verify any receipt you are handed. Zero-dependency (node:crypto only).",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "author": "SAIHM",
8
+ "main": "./src/receipt.mjs",
9
+ "types": "./src/receipt.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./src/receipt.d.ts",
13
+ "import": "./src/receipt.mjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "src/receipt.mjs",
18
+ "src/receipt.d.ts",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "engines": {
23
+ "node": ">=18"
24
+ },
25
+ "scripts": {
26
+ "test": "node --test"
27
+ },
28
+ "keywords": [
29
+ "saihm",
30
+ "gdpr",
31
+ "erasure",
32
+ "right-to-be-forgotten",
33
+ "crypto-shred",
34
+ "receipt",
35
+ "compliance",
36
+ "audit",
37
+ "tamper-evident"
38
+ ],
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/SAIHM-Admin/saihm-erasure-receipt.git"
42
+ },
43
+ "homepage": "https://saihm.coti.global",
44
+ "publishConfig": {
45
+ "access": "public"
46
+ }
47
+ }
@@ -0,0 +1,61 @@
1
+ // Type definitions for @saihm/erasure-receipt
2
+
3
+ /** The receipt schema identifier embedded in every receipt. */
4
+ export const RECEIPT_SCHEMA: "saihm.erasure-receipt/v1";
5
+
6
+ /** The `forget()` result shape this module reads (from @saihm/client-pro). */
7
+ export interface ForgetResult {
8
+ /** Whether the erasure completed end to end. */
9
+ complete?: boolean;
10
+ /** Per-operation steps; the wrapped key is treated as destroyed only if every step succeeded. */
11
+ steps?: Array<{ success?: boolean }>;
12
+ /** SAIHM protocol epoch (HOURS since the unix epoch) of the erasure, as reported by the endpoint. */
13
+ epoch?: number | string | null;
14
+ }
15
+
16
+ export interface BuildErasureReceiptArgs {
17
+ /** Public id of the erased record. Required. */
18
+ cellId: string;
19
+ /** The record's public commitment (endpoint-reported; offline it equals the client-sealed sha256 of the ciphertext). */
20
+ commitmentHash?: string | null;
21
+ /** The `forget()` result. */
22
+ forget: ForgetResult;
23
+ /** Count of records with this id still readable after erasure — you verify this is 0. */
24
+ copiesRemaining: number;
25
+ /** 'local blind sandbox' or the hosted endpoint host. */
26
+ endpoint: string;
27
+ }
28
+
29
+ export interface ErasureReceipt {
30
+ schema: typeof RECEIPT_SCHEMA;
31
+ action: "cryptographic-erasure";
32
+ basis: string;
33
+ record: { cellId: string; commitmentHash: string | null };
34
+ result: {
35
+ keyDestroyed: boolean;
36
+ copiesRemaining: number;
37
+ irreversible: boolean;
38
+ };
39
+ erasedAt: string;
40
+ endpoint: string;
41
+ note: string;
42
+ /** SHA-256 over a canonical (key-sorted) serialization of the receipt body — tamper-evident. */
43
+ receiptHash: string;
44
+ }
45
+
46
+ export interface VerifyResult {
47
+ valid: boolean;
48
+ reasons: string[];
49
+ }
50
+
51
+ /**
52
+ * Build a tamper-evident erasure receipt from the protocol's seal + forget results.
53
+ * Throws if `cellId` is missing or `copiesRemaining` is not a non-negative integer.
54
+ */
55
+ export function buildErasureReceipt(args: BuildErasureReceiptArgs): ErasureReceipt;
56
+
57
+ /**
58
+ * Verify a receipt: its hash must match its body, and it must attest an irreversible erasure
59
+ * (wrapped key destroyed AND zero copies remaining).
60
+ */
61
+ export function verifyReceipt(receipt: unknown): VerifyResult;
@@ -0,0 +1,104 @@
1
+ // A public, tamper-evident erasure receipt for SAIHM.
2
+ //
3
+ // SAIHM erases a record by destroying the *wrapped key* that decrypts it: the stored
4
+ // ciphertext becomes unrecoverable noise, so the record is gone, not merely de-indexed.
5
+ // This module turns the protocol's own seal + forget results into a small, portable
6
+ // receipt that a compliance reviewer can read, re-verify, and archive.
7
+ //
8
+ // The receipt contains ONLY public material — the cell id and the record's public commitment (the
9
+ // endpoint-reported commitment for the record; offline it is the client-sealed sha256 of the
10
+ // ciphertext), plus the verifiable outcome. It carries no plaintext and no secret.
11
+ // Integrity is self-checking (`receiptHash`), and the core claim is *reproducible*: re-read
12
+ // the store after erasure and confirm zero copies survive.
13
+
14
+ import { createHash } from 'node:crypto';
15
+
16
+ export const RECEIPT_SCHEMA = 'saihm.erasure-receipt/v1';
17
+
18
+ // The protocol epoch is counted in hours; these bound what a receipt will accept as an erasure
19
+ // time. Anything outside the window falls back to the current time rather than being trusted.
20
+ const SECONDS_PER_EPOCH = 3600;
21
+ const EPOCH_FLOOR_SEC = Date.UTC(2020, 0, 1) / 1000;
22
+ const EPOCH_SKEW_SEC = 86400;
23
+
24
+ /**
25
+ * Build an erasure receipt from the protocol's seal + forget results.
26
+ *
27
+ * @param {object} a
28
+ * @param {string} a.cellId - public id of the erased record
29
+ * @param {string|null} [a.commitmentHash] - the record's public commitment (endpoint-reported; offline it equals the client-sealed sha256 of the ciphertext). Verify it via verifyEnvelope() if you must trust it on a hosted endpoint
30
+ * @param {object} a.forget - the `forget()` result ({ complete, steps:[{success}], epoch }); `epoch` is the SAIHM protocol epoch, in hours
31
+ * @param {number} a.copiesRemaining - records with this id still readable after erasure (verified by re-reading)
32
+ * @param {string} a.endpoint - 'local blind sandbox' or the hosted endpoint host
33
+ * @returns {object} the receipt, including a `receiptHash` that makes it tamper-evident
34
+ */
35
+ export function buildErasureReceipt({ cellId, commitmentHash = null, forget, copiesRemaining, endpoint }) {
36
+ if (!cellId) throw new Error('buildErasureReceipt: cellId is required');
37
+ if (!Number.isInteger(copiesRemaining) || copiesRemaining < 0) {
38
+ throw new Error('buildErasureReceipt: copiesRemaining must be a non-negative integer');
39
+ }
40
+ const steps = Array.isArray(forget?.steps) ? forget.steps : [];
41
+ const keyDestroyed = Boolean(forget?.complete) && steps.length > 0 && steps.every((s) => s?.success === true);
42
+ const nowSec = Math.floor(Date.now() / 1000);
43
+ // `forget.epoch` is the SAIHM protocol epoch: HOURS since the unix epoch. That is what the
44
+ // blind operator endpoint reports and what the runtime itself multiplies by an hour to get
45
+ // milliseconds. Reading it as seconds lands the receipt in 1970 while every other field still
46
+ // checks out -- a receipt that verifies true and misstates when the erasure happened, which is
47
+ // the one outcome this artifact must never produce.
48
+ const epochSec = Number(forget?.epoch) * SECONDS_PER_EPOCH;
49
+ // Fail closed to now unless the result is a plausible erasure time. The floor is what makes the
50
+ // 1970 case unreachable; the ceiling catches the opposite mistake, a unix-seconds value passed
51
+ // in by hand, which overshoots by orders of magnitude. Either unit error degrades to "now"
52
+ // rather than to a date that would misstate the erasure. null/""/0, negative, NaN and Infinity
53
+ // all fall outside the window too, so a malformed or hostile epoch never throws.
54
+ const safeEpoch =
55
+ Number.isFinite(epochSec) && epochSec >= EPOCH_FLOOR_SEC && epochSec <= nowSec + EPOCH_SKEW_SEC
56
+ ? epochSec
57
+ : nowSec;
58
+ const erasedAt = new Date(safeEpoch * 1000).toISOString();
59
+
60
+ const body = {
61
+ schema: RECEIPT_SCHEMA,
62
+ action: 'cryptographic-erasure', // key destruction, not de-indexing
63
+ basis: 'GDPR Art. 17 (right to erasure)',
64
+ record: { cellId, commitmentHash }, // public anchors for the erased record (endpoint-reported commitment)
65
+ result: {
66
+ keyDestroyed, // the wrapped key that decrypts this record was destroyed
67
+ copiesRemaining, // verified by re-reading the store after erasure
68
+ irreversible: keyDestroyed && copiesRemaining === 0,
69
+ },
70
+ erasedAt,
71
+ endpoint,
72
+ note: 'The endpoint named in this receipt holds ciphertext only and reports destroying the wrapped '
73
+ + 'key, which leaves the stored bytes as unrecoverable noise. This receipt is tamper-evident '
74
+ + '(receiptHash), and its zero-copies outcome is reproducible — re-read the store with this cellId '
75
+ + 'and confirm none survive.',
76
+ };
77
+ return { ...body, receiptHash: sha256Hex(canonical(body)) };
78
+ }
79
+
80
+ /**
81
+ * Verify a receipt: its hash must match its body, and it must attest an irreversible erasure
82
+ * (wrapped key destroyed AND zero copies remaining). Returns a structured result.
83
+ */
84
+ export function verifyReceipt(receipt) {
85
+ const reasons = [];
86
+ if (!receipt || typeof receipt !== 'object') return { valid: false, reasons: ['not an object'] };
87
+ if (receipt.schema !== RECEIPT_SCHEMA) reasons.push(`unexpected schema: ${receipt.schema}`);
88
+ const { receiptHash, ...body } = receipt;
89
+ if (typeof receiptHash !== 'string') reasons.push('missing receiptHash');
90
+ else if (receiptHash !== sha256Hex(canonical(body))) reasons.push('receiptHash does not match body (tampered)');
91
+ if (receipt.result?.keyDestroyed !== true) reasons.push('keyDestroyed is not true');
92
+ if (receipt.result?.copiesRemaining !== 0) reasons.push('copiesRemaining is not zero');
93
+ if (receipt.result?.irreversible !== true) reasons.push('not marked irreversible');
94
+ return { valid: reasons.length === 0, reasons };
95
+ }
96
+
97
+ // --- helpers: a canonical (key-sorted) JSON so the hash is stable across runs/parsers ---
98
+ function canonical(o) { return JSON.stringify(sortKeys(o)); }
99
+ function sortKeys(v) {
100
+ if (Array.isArray(v)) return v.map(sortKeys);
101
+ if (v && typeof v === 'object') return Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys(v[k])]));
102
+ return v;
103
+ }
104
+ function sha256Hex(s) { return createHash('sha256').update(s, 'utf8').digest('hex'); }