@parmana/verifier 0.0.0-stage → 0.3.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/NOTICE ADDED
@@ -0,0 +1 @@
1
+ Copyright 2026 Parmana Systems Private Limited
package/README.md CHANGED
@@ -1,3 +1,159 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # Parmana Verifier
2
+
3
+ [![CI](https://github.com/pavancharak/parmana-verifier/actions/workflows/ci.yml/badge.svg)](https://github.com/pavancharak/parmana-verifier/actions/workflows/ci.yml) [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE) [![Node](https://img.shields.io/badge/node-%3E%3D24-brightgreen)](package.json)
4
+
5
+ Check whether an AI agent's action was approved and recorded as signed, using only a file and the keys you trust. No network access, no account, no dependencies.
6
+
7
+ Parmana signs an **Execution Trust Record** for every action an agent takes through it. The record says what was authorized, what ran, and what the outcome was, and it is signed with keys. This verifier checks that a record has not been changed and that it was signed by keys you chose to trust. It does not ask Parmana's servers anything, so you do not have to trust them to check a record.
8
+
9
+ The records come from [Parmana](https://github.com/pavancharak/parmana-core), which signs them. The verifier works without the rest of Parmana: it needs only a record and a trust file.
10
+
11
+ ## Who it is for
12
+
13
+ - **Auditors and reviewers** who need to confirm a record without relying on the system that produced it.
14
+ - **Operators** who want to check records in their own environment, with keys they pinned themselves.
15
+ - **Developers** who want a small, dependency-free reference implementation of the record checks.
16
+
17
+ ## Quick start
18
+
19
+ Requires Node.js 24 or later. Ed25519 works on any Node 24 build; post-quantum ML-DSA-65 signatures need OpenSSL 3.5 or later. From a clone of this repository:
20
+
21
+ ```sh
22
+ node bin/parmana-verify.mjs test/vectors/record-whole-record-v3.json test/vectors/trust-whole-record.json
23
+ ```
24
+
25
+ ```json
26
+ {"valid":true,"coverage":"full","errors":[],"checks":{"trustRecordHash":true,"signature":true,"hybridSignatures":true}}
27
+ ```
28
+
29
+ The exit code is `0`. A record that has been changed is rejected:
30
+
31
+ ```sh
32
+ node bin/parmana-verify.mjs test/vectors/record-tampered-amount.json test/vectors/trust.json
33
+ ```
34
+
35
+ The exit code is `1`, and the output lists the failed checks. The test vectors are labelled test material; see [test/vectors/README.md](test/vectors/README.md). For real records, pin the keys you trust (see [Pinning a key](#pinning-a-key)).
36
+
37
+ ## Installation and usage
38
+
39
+ The package is not published to npm. Run it from a clone of this repository.
40
+
41
+ ```sh
42
+ node bin/parmana-verify.mjs <proof.json> <trust.json>
43
+ node bin/parmana-verify.mjs key-fingerprint <public-key.pem>
44
+ ```
45
+
46
+ - `proof.json` is the Execution Trust Record.
47
+ - `trust.json` is the trust set. It lists each key you accept:
48
+
49
+ ```json
50
+ {
51
+ "keys": [
52
+ {
53
+ "keyId": "default",
54
+ "algorithm": "ed25519",
55
+ "publicKeyPem": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----\n",
56
+ "fingerprint": "sha256:<64 hex digits>",
57
+ "validFrom": "2026-01-01T00:00:00.000Z",
58
+ "validUntil": null,
59
+ "compromised": false
60
+ }
61
+ ]
62
+ }
63
+ ```
64
+
65
+ - `key-fingerprint` prints the `sha256:` value to pin for a PEM key. To pin a key safely, follow the steps in [Pinning a key](#pinning-a-key).
66
+
67
+ The verify command prints one line of JSON and exits with `0` (valid), `1` (invalid, with reasons), or `2` (usage, missing file, or invalid JSON). The full input and output rules are in [docs/FORMAT.md](docs/FORMAT.md).
68
+
69
+ On Windows PowerShell, use the same commands with Windows paths, for example `node bin\parmana-verify.mjs proof.json trust.json`.
70
+
71
+ ## Pinning a key
72
+
73
+ A signature proves only that a key made it. Before you trust a record, decide which keys you trust, and check that each key is the one its owner published.
74
+
75
+ 1. Get the operator's public key PEM and the `sha256:` fingerprint they published. Get the fingerprint from a source other than the one that gave you the key, such as a signed message or a call to a known number.
76
+ 2. Run `node bin/parmana-verify.mjs key-fingerprint public-key.pem` on the PEM you received.
77
+ 3. Compare the two fingerprints character by character. If they differ, do not use the key.
78
+ 4. Only then add the key to your trust file with that fingerprint.
79
+
80
+ ## Trust rules
81
+
82
+ A key is used only if all of these hold:
83
+
84
+ - its PEM hashes to the pinned fingerprint (SHA-256 of the SPKI DER encoding);
85
+ - the algorithm named by the signature matches the algorithm in the trust file;
86
+ - it is not marked `compromised`;
87
+ - the record's `createdAt` is at or after `validFrom` and before `validUntil` (if set).
88
+
89
+ A compromised key is rejected whatever the timestamp, so signatures it made stay void.
90
+
91
+ ## Examples
92
+
93
+ Run every example with:
94
+
95
+ ```sh
96
+ npm run examples
97
+ ```
98
+
99
+ The examples are in `examples/`, and each one prints what it checks:
100
+
101
+ - `01-verify-a-proof.mjs`: verify a record and explain each check.
102
+ - `02-tamper-detection.mjs`: change a signed field, then show that recomputing the hash does not help an attacker.
103
+ - `03-pinned-keys-and-windows.mjs`: how pinned fingerprints, validity windows and compromised keys decide what is accepted.
104
+ - `04-hybrid-envelope.mjs`: the Ed25519 and ML-DSA-65 entries of a hybrid record (needs Node 24).
105
+ - `05-build-and-verify-a-record.mjs`: build, hash, sign, pin and verify a record from scratch, with a runtime test key.
106
+ - `06-command-line.mjs`: the command-line exit codes, and fingerprinting a key for pinning.
107
+ - `07-whole-record-coverage.mjs`: what coverage `full` and `legacy` mean, and that a changed covered field is refused.
108
+ - `08-hybrid-cutover.mjs`: the `hybridRequiredFrom` cutover, and what it adds to a record created after it.
109
+ - `09-unsupported-schema-version.mjs`: a schema version other than 2 or 3 is refused, not guessed at.
110
+
111
+ Each example exits `0` when it behaves as described, so the set runs in CI.
112
+
113
+ ## Testing
114
+
115
+ ```sh
116
+ npm test
117
+ ```
118
+
119
+ Run the tests on Node 24. On Node 22 or any runtime without ML-DSA-65, the hybrid tests are skipped. Test keys are generated at run time, labelled "TEST KEY - NOT FOR PRODUCTION", and never written to disk.
120
+
121
+ The suite covers the legacy signature and hash, hybrid signatures, schema version 3 coverage, the trust rules, the test vectors, and the command-line exit codes. Each area has its own file under `test/`.
122
+
123
+ ## Limitations
124
+
125
+ - The verifier can only check that a record was signed by the key you pinned. It cannot prove that the key belongs to Parmana. That depends on how you obtained and compared the fingerprint.
126
+ - For records with `schemaVersion` 2, or with no `schemaVersion`, only the fields listed in [docs/FORMAT.md](docs/FORMAT.md) are protected. Any other field can be changed without the verifier noticing. Read decisions only from covered fields. See "Fields not covered by any signature" in that document.
127
+ - For records with `schemaVersion` 3, every field except the signature envelope, `verifications` and `receipts` is protected. Check that `coverage` is `full` when that matters.
128
+ - A record with `schemaVersion` 2 can be downgraded by someone who can write to storage, since `schemaVersion` is unsigned. Set `hybridRequiredFrom` in the trust file to reject downgraded records created after a cutover. Records before the cutover stay open to this.
129
+ - The validity window is checked against the record's `createdAt`, not against the signing time. A record that carries a false `createdAt` is checked against the window for that false time.
130
+ - Keys and fingerprints must be kept current. The verifier does not know about rotations or revocations that you have not written into the trust file.
131
+ - It does not verify the policy the record cites, the authorization decision logic, or the state of any connector or external system.
132
+ - It does not confirm that the action described by the record was executed.
133
+ - The records in `test/vectors/` were produced by the Parmana signing code and are test material only. They show that the checks agree with that code; they are not an independent specification.
134
+
135
+ ## Status
136
+
137
+ This is version 0.3.0. The record formats and the command-line interface may still change before 1.0; each change is listed in [CHANGELOG.md](CHANGELOG.md).
138
+
139
+ ## Repository layout
140
+
141
+ | Path | Contents |
142
+ | ------------ | ------------------------------------------------------------------------ |
143
+ | `bin/` | The `parmana-verify` command-line entry point |
144
+ | `src/` | The checks: canonical JSON, hashing, signatures, trust rules |
145
+ | `test/` | The test suite, and `test/vectors/`, the labelled test records |
146
+ | `examples/` | Nine runnable examples, run by `npm run examples` |
147
+ | `docs/` | `FORMAT.md` (the input and output rules) and `SECURITY-REVIEW.md` |
148
+
149
+ ## Security
150
+
151
+ Do not open a public issue for a security problem. Report it through GitHub's private vulnerability reporting: open the **Security** tab and choose **Report a vulnerability**. See [SECURITY.md](SECURITY.md). The scope for an external review is in [docs/SECURITY-REVIEW.md](docs/SECURITY-REVIEW.md).
152
+
153
+ ## Contributing
154
+
155
+ Read [CONTRIBUTING.md](CONTRIBUTING.md) before you open a pull request. Run `npm test` on Node 24 first. Every commit must carry a `Signed-off-by` line (`git commit -s`), certifying the [Developer Certificate of Origin](https://developercertificate.org). Everyone taking part follows the [Code of Conduct](CODE_OF_CONDUCT.md).
156
+
157
+ ## License
158
+
159
+ Licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env node
2
+ // Usage:
3
+ // parmana-verify <proof.json> <trust.json>
4
+ // parmana-verify key-fingerprint <public-key.pem>
5
+ //
6
+ // verify exits 0 = valid, 1 = invalid, 2 = usage or read error.
7
+ // key-fingerprint prints the "sha256:..." value to pin in a trust file.
8
+
9
+ import { readFileSync } from "node:fs";
10
+ import { verifyExecutionTrustRecord } from "../src/verify.mjs";
11
+ import { keyFingerprint, parseTrustPolicy } from "../src/trust.mjs";
12
+
13
+ const args = process.argv.slice(2);
14
+ const USAGE = "usage: parmana-verify <proof.json> <trust.json>\n parmana-verify key-fingerprint <public-key.pem>";
15
+
16
+ if (args[0] === "key-fingerprint") {
17
+ if (args.length !== 2) {
18
+ console.error(USAGE);
19
+ process.exit(2);
20
+ }
21
+
22
+ try {
23
+ console.log(keyFingerprint(readFileSync(args[1], "utf8")));
24
+ process.exit(0);
25
+ } catch (error) {
26
+ console.error(`key error: ${error.message}`);
27
+ process.exit(2);
28
+ }
29
+ }
30
+
31
+ const [proofPath, trustPath] = args;
32
+
33
+ if (!proofPath || !trustPath || args.length !== 2) {
34
+ console.error(USAGE);
35
+ process.exit(2);
36
+ }
37
+
38
+ let proof;
39
+ let policy;
40
+
41
+ try {
42
+ proof = JSON.parse(readFileSync(proofPath, "utf8"));
43
+ policy = parseTrustPolicy(JSON.parse(readFileSync(trustPath, "utf8")));
44
+ } catch (error) {
45
+ console.error(`read error: ${error.message}`);
46
+ process.exit(2);
47
+ }
48
+
49
+ const result = verifyExecutionTrustRecord(proof, policy.keys, { hybridRequiredFrom: policy.hybridRequiredFrom ?? undefined });
50
+
51
+ console.log(JSON.stringify(result));
52
+
53
+ process.exit(result.valid ? 0 : 1);
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
- {
2
- "name": "@parmana/verifier",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@parmana/verifier",
3
+ "version": "0.3.0",
4
+ "description": "Offline verifier for Parmana Execution Trust Records.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "bin": {
8
+ "parmana-verify": "bin/parmana-verify.mjs"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "src",
13
+ "LICENSE",
14
+ "NOTICE"
15
+ ],
16
+ "scripts": {
17
+ "test": "node --test test/verify.test.mjs test/hybrid.test.mjs test/trust.test.mjs test/vectors.test.mjs test/whole-record.test.mjs",
18
+ "examples": "node examples/run-all.mjs"
19
+ },
20
+ "engines": {
21
+ "node": ">=24"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/pavancharak/parmana-verifier.git"
26
+ },
27
+ "homepage": "https://github.com/pavancharak/parmana-verifier#readme",
28
+ "bugs": {
29
+ "url": "https://github.com/pavancharak/parmana-verifier/issues"
30
+ },
31
+ "keywords": [
32
+ "parmana",
33
+ "verifier",
34
+ "execution-trust-record",
35
+ "ed25519",
36
+ "ml-dsa",
37
+ "post-quantum",
38
+ "offline"
39
+ ]
40
+ }
@@ -0,0 +1,35 @@
1
+ // Canonical serialization for Parmana artifacts.
2
+ //
3
+ // Object keys are sorted in code-unit order, arrays keep their order, and the
4
+ // result is UTF-8 encoded JSON. Every hash and signature is computed over
5
+ // these bytes, so the verifier must produce exactly the same bytes as the
6
+ // signer.
7
+
8
+ export function canonicalBytes(value) {
9
+ return new TextEncoder().encode(JSON.stringify(normalize(value)));
10
+ }
11
+
12
+ function normalize(value) {
13
+ if (value === null || typeof value !== "object") {
14
+ return value;
15
+ }
16
+
17
+ if (Array.isArray(value)) {
18
+ return value.map(normalize);
19
+ }
20
+
21
+ const normalized = {};
22
+
23
+ for (const key of Object.keys(value).sort()) {
24
+ // defineProperty, not assignment: a key named "__proto__" must stay an
25
+ // own property so its content is covered by the hash and signature.
26
+ Object.defineProperty(normalized, key, {
27
+ value: normalize(value[key]),
28
+ enumerable: true,
29
+ writable: true,
30
+ configurable: true,
31
+ });
32
+ }
33
+
34
+ return normalized;
35
+ }
package/src/trust.mjs ADDED
@@ -0,0 +1,104 @@
1
+ // Trust set: the keys a verifier accepts, each pinned by fingerprint.
2
+ //
3
+ // A key is used only when all of these hold:
4
+ // - its PEM hashes to the pinned fingerprint (SHA-256 of the SPKI DER);
5
+ // - its algorithm matches the algorithm the signature names;
6
+ // - it is not marked compromised;
7
+ // - the record's createdAt falls within [validFrom, validUntil).
8
+ //
9
+ // The trust set is supplied by the caller. The verifier never fetches keys.
10
+
11
+ import { createHash, createPublicKey } from "node:crypto";
12
+
13
+ export const ALGORITHM_NAMES = ["ed25519", "dilithium3"];
14
+
15
+ export function keyFingerprint(publicKeyPem) {
16
+ return fingerprintOfKey(createPublicKey(publicKeyPem));
17
+ }
18
+
19
+ export function fingerprintOfKey(publicKey) {
20
+ const der = publicKey.export({ type: "spki", format: "der" });
21
+ return `sha256:${createHash("sha256").update(der).digest("hex")}`;
22
+ }
23
+
24
+ // Parses a trust-set document into a Map keyId -> entry. Throws an Error with
25
+ // a readable message when the document is malformed.
26
+ export function parseTrustSet(document) {
27
+ return parseTrustPolicy(document).keys;
28
+ }
29
+
30
+ // Parses a trust-set document into { keys, hybridRequiredFrom }. keys is the
31
+ // Map that parseTrustSet returns. hybridRequiredFrom is the optional cutover:
32
+ // a record created at or after it must carry a valid hybrid envelope. It is
33
+ // null when the document does not set one. It must be an ISO-8601 UTC
34
+ // timestamp ending in "Z", so that it means the same time everywhere.
35
+ export function parseTrustPolicy(document) {
36
+ if (document === null || typeof document !== "object" || !Array.isArray(document.keys)) {
37
+ throw new Error('trust set must be an object with a "keys" array');
38
+ }
39
+
40
+ let hybridRequiredFrom = null;
41
+
42
+ if (document.hybridRequiredFrom !== undefined && document.hybridRequiredFrom !== null) {
43
+ if (typeof document.hybridRequiredFrom !== "string" || !/Z$/.test(document.hybridRequiredFrom) || Number.isNaN(Date.parse(document.hybridRequiredFrom))) {
44
+ throw new Error('hybridRequiredFrom must be an ISO-8601 UTC timestamp ending in "Z"');
45
+ }
46
+
47
+ hybridRequiredFrom = document.hybridRequiredFrom;
48
+ }
49
+
50
+ const trustKeys = new Map();
51
+
52
+ for (const [index, entry] of document.keys.entries()) {
53
+ const at = `keys[${index}]`;
54
+
55
+ if (entry === null || typeof entry !== "object") {
56
+ throw new Error(`${at} must be an object`);
57
+ }
58
+
59
+ if (typeof entry.keyId !== "string" || entry.keyId === "") {
60
+ throw new Error(`${at}.keyId must be a non-empty string`);
61
+ }
62
+
63
+ if (trustKeys.has(entry.keyId)) {
64
+ throw new Error(`duplicate keyId "${entry.keyId}"`);
65
+ }
66
+
67
+ if (!ALGORITHM_NAMES.includes(entry.algorithm)) {
68
+ throw new Error(`${at}.algorithm must be one of ${ALGORITHM_NAMES.join(", ")}`);
69
+ }
70
+
71
+ if (typeof entry.publicKeyPem !== "string") {
72
+ throw new Error(`${at}.publicKeyPem must be a PEM string`);
73
+ }
74
+
75
+ if (typeof entry.fingerprint !== "string" || !/^sha256:[0-9a-f]{64}$/.test(entry.fingerprint)) {
76
+ throw new Error(`${at}.fingerprint must be "sha256:" followed by 64 lowercase hex digits`);
77
+ }
78
+
79
+ if (typeof entry.validFrom !== "string" || Number.isNaN(Date.parse(entry.validFrom))) {
80
+ throw new Error(`${at}.validFrom must be an ISO timestamp`);
81
+ }
82
+
83
+ if (entry.validUntil !== undefined && entry.validUntil !== null &&
84
+ (typeof entry.validUntil !== "string" || Number.isNaN(Date.parse(entry.validUntil)))) {
85
+ throw new Error(`${at}.validUntil must be an ISO timestamp or null`);
86
+ }
87
+
88
+ if (entry.compromised !== undefined && typeof entry.compromised !== "boolean") {
89
+ throw new Error(`${at}.compromised must be true or false`);
90
+ }
91
+
92
+ trustKeys.set(entry.keyId, {
93
+ keyId: entry.keyId,
94
+ algorithm: entry.algorithm,
95
+ publicKeyPem: entry.publicKeyPem,
96
+ fingerprint: entry.fingerprint,
97
+ validFrom: entry.validFrom,
98
+ validUntil: entry.validUntil ?? null,
99
+ compromised: entry.compromised ?? false,
100
+ });
101
+ }
102
+
103
+ return { keys: trustKeys, hybridRequiredFrom };
104
+ }
package/src/verify.mjs ADDED
@@ -0,0 +1,312 @@
1
+ // Offline verification of an Execution Trust Record.
2
+ //
3
+ // Checks run on the record alone:
4
+ // 1. trustRecordHash equals the SHA-256 (hex) of the canonical record fields.
5
+ // 2. signature is a valid signature over those canonical bytes, made by a
6
+ // trusted key named by signature.keyId (see trust.mjs for the trust rules).
7
+ // 3. If signatures is present, it is a hybrid envelope: at least two entries,
8
+ // no repeated algorithm, and every entry verifies over the message for
9
+ // its schemaVersion (default 2). Any failure makes the record invalid.
10
+ // A record with schemaVersion 3 must carry a hybrid envelope.
11
+ // 4. If a cutover is given (options.hybridRequiredFrom, from the trust
12
+ // file), a record created at or after it must pass check 3.
13
+ //
14
+ // Schema versions:
15
+ // 2 the message is the canonical fields plus schemaVersion.
16
+ // 3 the message is every top-level field except signature, signatures,
17
+ // schemaVersion, verifications and receipts, plus schemaVersion.
18
+ // Fields outside the version 2 message, such as updatedAt, are covered.
19
+ //
20
+ // The result's coverage is "full" when a version 3 envelope verifies, and
21
+ // "legacy" otherwise. Records with other schemaVersion values are invalid.
22
+ //
23
+ // Supported algorithms:
24
+ // ed25519 Ed25519 keys. Messages over 4096 bytes may be signed as a
25
+ // commitment: the prefix below followed by the SHA-512 digest of
26
+ // the canonical bytes. A raw signature over a large message is
27
+ // also accepted. A commitment over a small message is rejected.
28
+ // dilithium3 ML-DSA-65 keys (Node 24+ with OpenSSL 3.5+). Raw signatures
29
+ // only.
30
+ //
31
+ // The verifier reads no environment variables, no private keys, and makes no
32
+ // network calls.
33
+
34
+ import {
35
+ createHash,
36
+ createPublicKey,
37
+ generateKeyPairSync,
38
+ verify as verifySignature,
39
+ } from "node:crypto";
40
+ import { canonicalBytes } from "./canonical.mjs";
41
+ import { fingerprintOfKey } from "./trust.mjs";
42
+
43
+ const ALGORITHMS = {
44
+ ed25519: { keyType: "ed25519", commitment: true },
45
+ dilithium3: { keyType: "ml-dsa-65", commitment: false },
46
+ };
47
+
48
+ const RAW_MESSAGE_LIMIT_BYTES = 4096;
49
+ const COMMITMENT_PREFIX = Buffer.from("PARMANA-ED25519-LARGE-MESSAGE-V1\0", "utf8");
50
+ const DEFAULT_SCHEMA_VERSION = 2;
51
+ const WHOLE_RECORD_SCHEMA_VERSION = 3;
52
+ const SUPPORTED_SCHEMA_VERSIONS = [2, 3];
53
+
54
+ // Top-level fields that a version 3 message does not cover. verifications and
55
+ // receipts are attached after signing; receipts carry their own signature.
56
+ const WHOLE_RECORD_EXCLUDED_FIELDS = ["signature", "signatures", "schemaVersion", "verifications", "receipts"];
57
+
58
+ // The fields covered by trustRecordHash and the legacy signature.
59
+ export function canonicalTrustRecord(record) {
60
+ return {
61
+ trustRecordId: record.trustRecordId,
62
+ businessTransactionId: record.businessTransactionId,
63
+ transaction: record.transaction,
64
+ authorization: record.authorization,
65
+ overrides: record.overrides,
66
+ executions: record.executions,
67
+ createdAt: record.createdAt,
68
+ };
69
+ }
70
+
71
+ // The message a hybrid envelope of the given schema version signs.
72
+ export function hybridMessage(record, schemaVersion) {
73
+ if (schemaVersion === WHOLE_RECORD_SCHEMA_VERSION) {
74
+ const covered = Object.entries(record).filter(([key]) => !WHOLE_RECORD_EXCLUDED_FIELDS.includes(key));
75
+
76
+ return canonicalBytes({ ...Object.fromEntries(covered), schemaVersion });
77
+ }
78
+
79
+ return canonicalBytes({ ...canonicalTrustRecord(record), schemaVersion });
80
+ }
81
+
82
+ // trustKeys is a Map from keyId to a trust entry, as returned by parseTrustSet.
83
+ // options.hybridRequiredFrom is an ISO-8601 UTC timestamp from the trust file
84
+ // (see parseTrustPolicy); records created at or after it need a hybrid envelope.
85
+ export function verifyExecutionTrustRecord(record, trustKeys, options = {}) {
86
+ const errors = [];
87
+
88
+ if (!isObject(record)) {
89
+ return { valid: false, coverage: "legacy", errors: ["record must be a JSON object"], checks: {} };
90
+ }
91
+
92
+ const legacyMessage = canonicalBytes(canonicalTrustRecord(record));
93
+ const expectedHash = createHash("sha256").update(legacyMessage).digest("hex");
94
+ const hashValid = expectedHash === record.trustRecordHash;
95
+
96
+ if (!hashValid) {
97
+ errors.push(`trustRecordHash mismatch: expected ${expectedHash}.`);
98
+ }
99
+
100
+ const context = { trustKeys, createdAt: record.createdAt };
101
+
102
+ const signatureValid = verifyLegacySignature(record.signature, legacyMessage, context, errors);
103
+
104
+ const checks = { trustRecordHash: hashValid, signature: signatureValid };
105
+
106
+ const schemaVersion = record.schemaVersion ?? DEFAULT_SCHEMA_VERSION;
107
+ const hasEnvelope = record.signatures !== undefined && record.signatures !== null;
108
+
109
+ if (!SUPPORTED_SCHEMA_VERSIONS.includes(schemaVersion)) {
110
+ errors.push(`unsupported schemaVersion ${String(schemaVersion)}: expected 2 or 3.`);
111
+ checks.hybridSignatures = false;
112
+ } else if (hasEnvelope) {
113
+ checks.hybridSignatures = verifyHybridSignatures(record.signatures, hybridMessage(record, schemaVersion), context, errors);
114
+ } else if (schemaVersion === WHOLE_RECORD_SCHEMA_VERSION) {
115
+ errors.push("schemaVersion 3 record has no signatures array: a whole-record signature is required.");
116
+ checks.hybridSignatures = false;
117
+ }
118
+
119
+ const cutoverOk = !isAtOrAfterCutover(record.createdAt, options.hybridRequiredFrom) || checks.hybridSignatures === true;
120
+
121
+ if (!cutoverOk) {
122
+ errors.push(`record created at or after hybridRequiredFrom (${options.hybridRequiredFrom}) has no valid hybrid envelope.`);
123
+ }
124
+
125
+ const coverage = schemaVersion === WHOLE_RECORD_SCHEMA_VERSION && checks.hybridSignatures === true ? "full" : "legacy";
126
+
127
+ return {
128
+ valid: hashValid && signatureValid && (checks.hybridSignatures ?? true) && cutoverOk,
129
+ coverage,
130
+ errors,
131
+ checks,
132
+ };
133
+ }
134
+
135
+ function isAtOrAfterCutover(createdAt, hybridRequiredFrom) {
136
+ if (hybridRequiredFrom === undefined) {
137
+ return false;
138
+ }
139
+
140
+ const created = Date.parse(createdAt);
141
+
142
+ return !Number.isNaN(created) && created >= Date.parse(hybridRequiredFrom);
143
+ }
144
+
145
+ function verifyLegacySignature(signature, message, context, errors) {
146
+ if (!isSignatureEntry(signature)) {
147
+ errors.push("signature is missing or malformed.");
148
+ return false;
149
+ }
150
+
151
+ return verifyEntry(signature, message, context, errors);
152
+ }
153
+
154
+ function verifyHybridSignatures(entries, message, context, errors) {
155
+ if (!Array.isArray(entries) || !entries.every(isSignatureEntry)) {
156
+ errors.push("malformed signatures: expected an array of entries with string algorithm, keyId and signature.");
157
+ return false;
158
+ }
159
+
160
+ if (entries.length < 2) {
161
+ errors.push(`signatures array has ${entries.length} entr${entries.length === 1 ? "y" : "ies"}, need at least 2 for a hybrid record.`);
162
+ return false;
163
+ }
164
+
165
+ const seen = new Set();
166
+ let allValid = true;
167
+
168
+ for (const entry of entries) {
169
+ if (seen.has(entry.algorithm)) {
170
+ errors.push(`duplicate algorithm in signatures array: ${entry.algorithm}.`);
171
+ allValid = false;
172
+ continue;
173
+ }
174
+
175
+ seen.add(entry.algorithm);
176
+ allValid = verifyEntry(entry, message, context, errors) && allValid;
177
+ }
178
+
179
+ return allValid;
180
+ }
181
+
182
+ // Accepts { algorithm, keyId, signature } entries. The legacy `signature` field
183
+ // uses `value` for the same three parts, so that is accepted too.
184
+ function verifyEntry(entry, message, context, errors) {
185
+ const signatureText = entry.signature ?? entry.value;
186
+ const algorithm = ALGORITHMS[entry.algorithm];
187
+
188
+ if (!algorithm) {
189
+ errors.push(`unsupported algorithm: ${entry.algorithm}.`);
190
+ return false;
191
+ }
192
+
193
+ const trusted = context.trustKeys.get(entry.keyId);
194
+
195
+ if (!trusted) {
196
+ errors.push(`no trusted key for keyId "${entry.keyId}".`);
197
+ return false;
198
+ }
199
+
200
+ if (trusted.algorithm !== entry.algorithm) {
201
+ errors.push(`keyId "${entry.keyId}" is trusted for ${trusted.algorithm}, not ${entry.algorithm}.`);
202
+ return false;
203
+ }
204
+
205
+ if (trusted.compromised) {
206
+ errors.push(`keyId "${entry.keyId}" is marked compromised; its signatures are not accepted.`);
207
+ return false;
208
+ }
209
+
210
+ if (!withinValidityWindow(trusted, context.createdAt)) {
211
+ errors.push(`createdAt ${context.createdAt} is outside the validity window of keyId "${entry.keyId}".`);
212
+ return false;
213
+ }
214
+
215
+ if (entry.algorithm === "dilithium3" && !mlDsaSupported()) {
216
+ errors.push("algorithm dilithium3 needs Node 24 or later with OpenSSL 3.5 or later.");
217
+ return false;
218
+ }
219
+
220
+ let publicKey;
221
+
222
+ try {
223
+ publicKey = createPublicKey(trusted.publicKeyPem);
224
+ } catch {
225
+ errors.push(`public key for keyId "${entry.keyId}" is not a valid PEM key.`);
226
+ return false;
227
+ }
228
+
229
+ if (fingerprintOfKey(publicKey) !== trusted.fingerprint) {
230
+ errors.push(`public key for keyId "${entry.keyId}" does not match its pinned fingerprint.`);
231
+ return false;
232
+ }
233
+
234
+ if (publicKey.asymmetricKeyType !== algorithm.keyType) {
235
+ errors.push(`public key for keyId "${entry.keyId}" has type ${publicKey.asymmetricKeyType}, expected ${algorithm.keyType}.`);
236
+ return false;
237
+ }
238
+
239
+ const sigBytes = Buffer.from(signatureText, "base64");
240
+
241
+ const rawValid = safeVerify(message, sigBytes, publicKey);
242
+
243
+ const commitmentValid =
244
+ !rawValid &&
245
+ algorithm.commitment &&
246
+ message.length > RAW_MESSAGE_LIMIT_BYTES &&
247
+ safeVerify(commitment(message), sigBytes, publicKey);
248
+
249
+ if (!rawValid && !commitmentValid) {
250
+ errors.push(`signature verification failed for keyId "${entry.keyId}" (${entry.algorithm}).`);
251
+ return false;
252
+ }
253
+
254
+ return true;
255
+ }
256
+
257
+ function withinValidityWindow(trusted, createdAt) {
258
+ const at = Date.parse(createdAt);
259
+
260
+ if (Number.isNaN(at)) {
261
+ return false;
262
+ }
263
+
264
+ if (at < Date.parse(trusted.validFrom)) {
265
+ return false;
266
+ }
267
+
268
+ return trusted.validUntil === null || at < Date.parse(trusted.validUntil);
269
+ }
270
+
271
+ function commitment(message) {
272
+ return Buffer.concat([
273
+ COMMITMENT_PREFIX,
274
+ createHash("sha512").update(message).digest(),
275
+ ]);
276
+ }
277
+
278
+ function safeVerify(message, sigBytes, publicKey) {
279
+ try {
280
+ return verifySignature(null, Buffer.from(message), publicKey, sigBytes);
281
+ } catch {
282
+ return false;
283
+ }
284
+ }
285
+
286
+ let mlDsa;
287
+
288
+ function mlDsaSupported() {
289
+ if (mlDsa === undefined) {
290
+ try {
291
+ generateKeyPairSync("ml-dsa-65");
292
+ mlDsa = true;
293
+ } catch {
294
+ mlDsa = false;
295
+ }
296
+ }
297
+
298
+ return mlDsa;
299
+ }
300
+
301
+ function isSignatureEntry(value) {
302
+ return (
303
+ isObject(value) &&
304
+ typeof value.algorithm === "string" &&
305
+ typeof value.keyId === "string" &&
306
+ (typeof value.signature === "string" || typeof value.value === "string")
307
+ );
308
+ }
309
+
310
+ function isObject(value) {
311
+ return value !== null && typeof value === "object" && !Array.isArray(value);
312
+ }