@datumesh/verify 0.0.0-stage → 0.2.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.
Files changed (73) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +56 -2
  3. package/dist/cjs/ed25519.d.ts +2 -0
  4. package/dist/cjs/ed25519.js +82 -0
  5. package/dist/cjs/envelope.d.ts +38 -0
  6. package/dist/cjs/envelope.js +243 -0
  7. package/dist/cjs/errors.d.ts +14 -0
  8. package/dist/cjs/errors.js +65 -0
  9. package/dist/cjs/hash.d.ts +6 -0
  10. package/dist/cjs/hash.js +27 -0
  11. package/dist/cjs/index.d.ts +37 -0
  12. package/dist/cjs/index.js +101 -0
  13. package/dist/cjs/jcs.d.ts +5 -0
  14. package/dist/cjs/jcs.js +25 -0
  15. package/dist/cjs/json.d.ts +29 -0
  16. package/dist/cjs/json.js +325 -0
  17. package/dist/cjs/keys.d.ts +73 -0
  18. package/dist/cjs/keys.js +257 -0
  19. package/dist/cjs/lexical.d.ts +69 -0
  20. package/dist/cjs/lexical.js +231 -0
  21. package/dist/cjs/package.json +3 -0
  22. package/dist/cjs/unicode-data.d.ts +8 -0
  23. package/dist/cjs/unicode-data.js +14 -0
  24. package/dist/cjs/unicode.d.ts +12 -0
  25. package/dist/cjs/unicode.js +192 -0
  26. package/dist/cjs/units-data.d.ts +4 -0
  27. package/dist/cjs/units-data.js +11 -0
  28. package/dist/cjs/units.d.ts +24 -0
  29. package/dist/cjs/units.js +131 -0
  30. package/dist/cjs/uri.d.ts +43 -0
  31. package/dist/cjs/uri.js +209 -0
  32. package/dist/cjs/utf8.d.ts +10 -0
  33. package/dist/cjs/utf8.js +101 -0
  34. package/dist/cjs/validate.d.ts +25 -0
  35. package/dist/cjs/validate.js +408 -0
  36. package/dist/cjs/verify.d.ts +57 -0
  37. package/dist/cjs/verify.js +232 -0
  38. package/dist/esm/ed25519.d.ts +2 -0
  39. package/dist/esm/ed25519.js +79 -0
  40. package/dist/esm/envelope.d.ts +38 -0
  41. package/dist/esm/envelope.js +240 -0
  42. package/dist/esm/errors.d.ts +14 -0
  43. package/dist/esm/errors.js +60 -0
  44. package/dist/esm/hash.d.ts +6 -0
  45. package/dist/esm/hash.js +21 -0
  46. package/dist/esm/index.d.ts +37 -0
  47. package/dist/esm/index.js +79 -0
  48. package/dist/esm/jcs.d.ts +5 -0
  49. package/dist/esm/jcs.js +18 -0
  50. package/dist/esm/json.d.ts +29 -0
  51. package/dist/esm/json.js +313 -0
  52. package/dist/esm/keys.d.ts +73 -0
  53. package/dist/esm/keys.js +249 -0
  54. package/dist/esm/lexical.d.ts +69 -0
  55. package/dist/esm/lexical.js +209 -0
  56. package/dist/esm/package.json +3 -0
  57. package/dist/esm/unicode-data.d.ts +8 -0
  58. package/dist/esm/unicode-data.js +11 -0
  59. package/dist/esm/unicode.d.ts +12 -0
  60. package/dist/esm/unicode.js +184 -0
  61. package/dist/esm/units-data.d.ts +4 -0
  62. package/dist/esm/units-data.js +8 -0
  63. package/dist/esm/units.d.ts +24 -0
  64. package/dist/esm/units.js +123 -0
  65. package/dist/esm/uri.d.ts +43 -0
  66. package/dist/esm/uri.js +204 -0
  67. package/dist/esm/utf8.d.ts +10 -0
  68. package/dist/esm/utf8.js +96 -0
  69. package/dist/esm/validate.d.ts +25 -0
  70. package/dist/esm/validate.js +397 -0
  71. package/dist/esm/verify.d.ts +57 -0
  72. package/dist/esm/verify.js +227 -0
  73. package/package.json +54 -4
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 CHANGED
@@ -1,3 +1,57 @@
1
- # Temporary Holding Version
1
+ # @datumesh/verify
2
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.
3
+ Verify [Datumesh](https://datumesh.com) receipts in JavaScript: signed answers for addressable data cells, checked offline against strict RFC 8785 canonical JSON and Ed25519, following the [Datumesh specification](https://github.com/datumesh-com/datumesh-spec) revision `spec-0.2.0` and passing all of its test vectors.
4
+
5
+ ```sh
6
+ npm install @datumesh/verify
7
+ ```
8
+
9
+ ```js
10
+ import { readFileSync } from 'node:fs';
11
+ import { verify, keysFromResponse } from '@datumesh/verify';
12
+
13
+ // vectors/receipt/stored-number.json from https://github.com/datumesh-com/datumesh-spec
14
+ const vector = JSON.parse(readFileSync('stored-number.json', 'utf8'));
15
+ const keys = keysFromResponse('rates.example.org', 200, vector.keys['rates.example.org'].https.body);
16
+ const result = verify(vector.input, keys);
17
+ console.log(result.ok, result.code, result.level, result.hash);
18
+ // true OK signed 19a5fe3a744c5792f747fb4c286ce396ab44b95922de4f07937502fe595b6f81
19
+ ```
20
+
21
+ The same with CommonJS:
22
+
23
+ ```js
24
+ const { readFileSync } = require('node:fs');
25
+ const { verify, keysFromResponse } = require('@datumesh/verify');
26
+
27
+ const vector = JSON.parse(readFileSync('stored-number.json', 'utf8'));
28
+ const keys = keysFromResponse('rates.example.org', 200, vector.keys['rates.example.org'].https.body);
29
+ console.log(verify(vector.input, keys).code); // OK
30
+ ```
31
+
32
+ ## What it does
33
+
34
+ - `verify(receipt, keys, recompute?, blob?)` runs the verification procedure of SPEC.md 10.1 and returns `{ ok, code, level, hash, key, detail, path, blobChecked }`. It is synchronous, never touches the network and never throws for a bad receipt or bad key material; failures come back as the spec's error codes (`E_SIGNATURE`, `E_KEY_NOT_VALID`, ...). `level` is `"signed"`, or `"recomputed"` when you pass the descriptor, the input receipts and the value you obtained by evaluating the function (the library checks lineage and compares; it does not evaluate functions). For a receipt whose value is a `blob`, pass the content bytes as `blob` to check their length and SHA-256 (`E_BLOB_MISMATCH`; `blobChecked` is then true).
35
+ - `keys` is a key document, the result of `keysFromResponse` / `fetchKeys`, a `{ keyId: publicKeyHex }` map, or an array of these (one per host for lineage).
36
+ - `fetchKeys(host)` is the only function that uses the network: one `GET https://<host>/.well-known/datumesh.json`, no redirects, 10 s timeout, using the platform's `fetch` and TLS verification.
37
+ - `checkEnvelope(status, body, keys, request)` checks a mesh's response envelope (SPEC.md 5.5) against its HTTP status, verifies the embedded receipt through the signature, and checks that it answers your request (`request` is `{ cell_id, asof? }`: the id of the cell you asked for and the `asof` you asked with, if any), returning `{ ok, code, outcome, trust, receiptHash, detail, path }`. The envelope itself is unsigned: `stale`, `superseded_by` and `verified` remain the mesh's claims.
38
+ - `resolvedUnit(descriptor, cell)` gives the unit of a cell's value from its function's declared units (`"USD/EUR"`, `"degC"`, or `null` for a non-number), using the closed list of `units.md` shipped with the package. The library never converts or checks values against units.
39
+ - `canonicalize(obj, kind)`, `cellHash`, `receiptHash`, `functionHash`, `parseUri(uri, signature)`, `formatUri(ref)` and `keyId` expose canonical forms, hashes and cell URIs. These and `resolvedUnit` throw `DatumeshError` (with `.code` and `.path`).
40
+
41
+ SHA-256 and Ed25519 come from the `@noble` libraries (pure JavaScript), so blob checks work the same in Node 18.0 and in browsers. Strings are checked against Unicode 15.1 tables shipped with the package, so results do not depend on the JavaScript engine's Unicode version. Ed25519 verification is libsodium-strict, as the spec requires. ESM and CommonJS builds with TypeScript types, for Node 18+ and for browsers through a bundler (the core uses no Node built-ins). Where the specification left a question open, the choices made are listed in [DEFECTS.md](https://github.com/datumesh-com/datumesh-verify-js/blob/main/DEFECTS.md).
42
+
43
+ A valid signature means only that the holder of the key named in `computed_by` stated the value. Whom to trust is your policy.
44
+
45
+ ## Development
46
+
47
+ ```sh
48
+ git clone --recurse-submodules https://github.com/datumesh-com/datumesh-verify-js && cd datumesh-verify-js
49
+ npm ci && npm test # all tests; scripts/browser-test.sh and scripts/package-test.sh need Docker
50
+ ```
51
+
52
+ ## Links
53
+
54
+ - Datumesh: https://datumesh.com
55
+ - Specification and test vectors: https://github.com/datumesh-com/datumesh-spec
56
+
57
+ Licensed under the Apache License 2.0.
@@ -0,0 +1,2 @@
1
+ /** Strict Ed25519 verification of `sig` (64 bytes) over `msg` with public key `pub` (32 bytes). */
2
+ export declare function verifyEd25519Strict(sig: Uint8Array, msg: Uint8Array, pub: Uint8Array): boolean;
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.verifyEd25519Strict = verifyEd25519Strict;
4
+ // Ed25519 verification as SPEC.md 10.1 step 6 requires (libsodium-strict, RFC 8032 cofactorless):
5
+ // - S < L;
6
+ // - A and R canonically encoded (y < p; x = 0 with the sign bit set is rejected);
7
+ // - A and R not of small order;
8
+ // - [S]B - [k]A, encoded, equals R byte for byte, with k = SHA-512(R || A || M) mod L.
9
+ //
10
+ // @noble/curves supplies the group arithmetic. Its own verify() with zip215:false enforces
11
+ // S < L, canonical A and R, and rejects small-order A, but it accepts small-order R and checks
12
+ // the cofactored equation [8]([S]B - R - [k]A) = 0, which accepts some signatures the
13
+ // cofactorless rule rejects. So the checks are done here, and noble's verify() is additionally
14
+ // required to succeed (it is implied by the cofactorless check; it is a second opinion only).
15
+ const ed25519_1 = require("@noble/curves/ed25519");
16
+ const sha2_1 = require("@noble/hashes/sha2");
17
+ const Point = ed25519_1.ed25519.Point;
18
+ const L = 2n ** 252n + 27742317777372353535851937790883648493n;
19
+ const P = 2n ** 255n - 19n;
20
+ function le(b) {
21
+ let n = 0n;
22
+ for (let i = b.length - 1; i >= 0; i--)
23
+ n = (n << 8n) | BigInt(b[i]);
24
+ return n;
25
+ }
26
+ function decodeStrict(b) {
27
+ const y = le(b) & ((1n << 255n) - 1n);
28
+ if (y >= P)
29
+ return null; // non-canonical encoding
30
+ try {
31
+ return Point.fromBytes(b, false); // also rejects x = 0 with the sign bit set
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ function equalBytes(a, b) {
38
+ if (a.length !== b.length)
39
+ return false;
40
+ let d = 0;
41
+ for (let i = 0; i < a.length; i++)
42
+ d |= a[i] ^ b[i];
43
+ return d === 0;
44
+ }
45
+ /** Strict Ed25519 verification of `sig` (64 bytes) over `msg` with public key `pub` (32 bytes). */
46
+ function verifyEd25519Strict(sig, msg, pub) {
47
+ if (sig.length !== 64 || pub.length !== 32)
48
+ return false;
49
+ const rBytes = sig.subarray(0, 32);
50
+ const s = le(sig.subarray(32, 64));
51
+ if (s >= L)
52
+ return false;
53
+ const A = decodeStrict(pub);
54
+ const R = decodeStrict(rBytes);
55
+ if (!A || !R)
56
+ return false;
57
+ if (A.isSmallOrder() || R.isSmallOrder())
58
+ return false;
59
+ const h = (0, sha2_1.sha512)(concat(rBytes, pub, msg));
60
+ const k = le(h) % L;
61
+ // R' = [S]B - [k]A (multiplyUnsafe accepts 0; inputs are public, so variable time is fine).
62
+ const SB = s === 0n ? Point.ZERO : Point.BASE.multiplyUnsafe(s);
63
+ const kA = k === 0n ? Point.ZERO : A.multiplyUnsafe(k);
64
+ const rCheck = SB.subtract(kA).toBytes();
65
+ if (!equalBytes(rCheck, rBytes))
66
+ return false;
67
+ try {
68
+ return ed25519_1.ed25519.verify(sig, msg, pub, { zip215: false });
69
+ }
70
+ catch {
71
+ return false;
72
+ }
73
+ }
74
+ function concat(...parts) {
75
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
76
+ let o = 0;
77
+ for (const p of parts) {
78
+ out.set(p, o);
79
+ o += p.length;
80
+ }
81
+ return out;
82
+ }
@@ -0,0 +1,38 @@
1
+ import { type ErrorCode } from './errors.js';
2
+ export type Outcome = 'ok' | 'stale' | 'not_covered' | 'unlicensed' | 'payment_required' | 'rate_limited' | 'error' | 'bad_request';
3
+ /** What the client asked for (SPEC 5.5 step 5): the requested cell's id, and `asof` if the request had one. */
4
+ export interface EnvelopeRequest {
5
+ cell_id: string;
6
+ asof?: string;
7
+ }
8
+ export type Trust = 'primary' | 'verified' | 'unverified';
9
+ export interface EnvelopeResult {
10
+ /** True when the envelope is well formed, matches the status, and its receipt (if any) is signature-valid. */
11
+ ok: boolean;
12
+ /** "OK", E_ENVELOPE, a parse code, or the code of the embedded receipt's verification. */
13
+ code: 'OK' | ErrorCode;
14
+ /** The envelope's outcome when ok, else null. */
15
+ outcome: Outcome | null;
16
+ /** The trust label when ok and the envelope carries a receipt, else null. */
17
+ trust: Trust | null;
18
+ /** The embedded receipt's hash once it has been verified (SPEC 10.1 steps 1-6), else null. */
19
+ receiptHash: string | null;
20
+ /** Human-readable explanation. */
21
+ detail: string;
22
+ /** Where the failure was found (a JSON path such as `$.quote.amount`), or null. */
23
+ path: string | null;
24
+ }
25
+ /**
26
+ * Check a mesh response (SPEC 5.5): `status` is the HTTP status, `body` the response body as
27
+ * JSON text or bytes (a parsed object is accepted too, without duplicate-member detection), and
28
+ * `keys` any key source `verify` accepts, used to verify an embedded receipt through step 6.
29
+ * `request` is what the client asked for: `{cell_id, asof?}`, the id (SPEC 4.4) of the requested
30
+ * cell resolved to the fn_hash the client used, and the requested asof if there was one.
31
+ * Steps: strict parse; members (E_ENVELOPE); status against outcome (E_ENVELOPE); the receipt
32
+ * (its own codes); the receipt answers the request (E_ENVELOPE); then `trust` against the receipt
33
+ * and `superseded_by` against its hash (E_ENVELOPE).
34
+ *
35
+ * Never throws for an invalid body or bad key material; throws TypeError only when `status` is
36
+ * not an integer, `request` is malformed, or `keys` is not a key source at all.
37
+ */
38
+ export declare function checkEnvelope(status: number, body: unknown, keys: unknown, request: EnvelopeRequest): EnvelopeResult;
@@ -0,0 +1,243 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkEnvelope = checkEnvelope;
4
+ // Response envelopes (SPEC.md 5.5): the unsigned JSON body a mesh returns around a receipt.
5
+ // Synchronous, offline; the embedded receipt is verified through step 6 with the given keys.
6
+ const errors_js_1 = require("./errors.js");
7
+ const json_js_1 = require("./json.js");
8
+ const lexical_js_1 = require("./lexical.js");
9
+ const hash_js_1 = require("./hash.js");
10
+ const jcs_js_1 = require("./jcs.js");
11
+ const keys_js_1 = require("./keys.js");
12
+ const units_js_1 = require("./units.js");
13
+ const verify_js_1 = require("./verify.js");
14
+ /** SPEC 5.5: required and optional members per outcome (besides `outcome`). */
15
+ const MEMBERS = {
16
+ ok: { required: ['receipt', 'trust'], optional: ['superseded_by', 'reason'] },
17
+ stale: { required: ['receipt', 'trust', 'age_seconds'], optional: ['superseded_by', 'reason'] },
18
+ not_covered: { required: [], optional: [] },
19
+ unlicensed: { required: [], optional: [] },
20
+ payment_required: { required: ['quote'], optional: [] },
21
+ rate_limited: { required: ['retry_after_seconds'], optional: [] },
22
+ error: { required: ['error'], optional: [] },
23
+ bad_request: { required: ['error'], optional: [] },
24
+ };
25
+ const STATUS = {
26
+ ok: (s) => s === 200,
27
+ stale: (s) => s === 200,
28
+ not_covered: (s) => s === 404,
29
+ unlicensed: (s) => s === 403,
30
+ payment_required: (s) => s === 402,
31
+ rate_limited: (s) => s === 429,
32
+ error: (s) => s >= 500 && s <= 599,
33
+ bad_request: (s) => s === 400,
34
+ };
35
+ /** SPEC 5.5: the codes `parse` can raise (5.4), the only ones a bad_request carries. */
36
+ const PARSE_CODES = ['E_PARSE_URI', 'E_CANON_NAME', 'E_CANON_ARG_NAME', 'E_CANON_ARG_DUPLICATE', 'E_CANON_ARG_ORDER', 'E_CANON_PERCENT', 'E_CANON_TYPE', 'E_CANON_NUMBER', 'E_CANON_DATE', 'E_CANON_INSTANT', 'E_CANON_STRING', 'E_CANON_BLOB', 'E_CANON_LIMIT', 'E_ARG_UNKNOWN', 'E_ARG_MISSING'];
37
+ const TRUST = ['primary', 'verified', 'unverified'];
38
+ const MAX_SECONDS = 9007199254740991;
39
+ class Bad extends Error {
40
+ constructor(detail, path) {
41
+ super(detail);
42
+ this.detail = detail;
43
+ this.path = path;
44
+ }
45
+ }
46
+ function bad(detail, path) {
47
+ throw new Bad(detail, path);
48
+ }
49
+ /** A rule of 3.x checked inside an envelope: its own code becomes part of the E_ENVELOPE detail. */
50
+ function inner(f, path) {
51
+ try {
52
+ f();
53
+ }
54
+ catch (e) {
55
+ if (e instanceof errors_js_1.DatumeshError)
56
+ bad(`${e.code}: ${e.detail}`, path);
57
+ throw e;
58
+ }
59
+ }
60
+ /**
61
+ * SPEC 5.5 integer members: written 0 or [1-9][0-9]*, at most 2^53 - 1. The source text decides
62
+ * (`30.0`, `3e1` and `-0` are rejected); for an already-parsed body, whose text is gone, the
63
+ * value must be a non-negative safe integer other than -0.
64
+ */
65
+ function seconds(v, text, name, path) {
66
+ const why = `${name} is written 0 or [1-9][0-9]*, at most 2^53 - 1`;
67
+ if (typeof v !== 'number')
68
+ bad(why, path);
69
+ if (text !== undefined ? !/^(0|[1-9][0-9]*)$/.test(text) : !Number.isSafeInteger(v) || Object.is(v, -0))
70
+ bad(why, path);
71
+ if (v < 0 || v > MAX_SECONDS)
72
+ bad(why, path);
73
+ }
74
+ function quote(v, path) {
75
+ if (!(0, json_js_1.isObject)(v))
76
+ bad('quote is an object {amount, authorise, currency}', path);
77
+ for (const k of ['amount', 'authorise', 'currency'])
78
+ if (!(0, json_js_1.has)(v, k))
79
+ bad(`quote has no ${k}`, path);
80
+ for (const k of (0, json_js_1.sortedKeys)(v))
81
+ if (!['amount', 'authorise', 'currency'].includes(k))
82
+ bad(`quote has an unexpected member ${JSON.stringify(k)}`, path);
83
+ const amount = v.amount;
84
+ const ap = (0, json_js_1.memberPath)(path, 'amount');
85
+ if (typeof amount !== 'string')
86
+ bad('amount is a decimal string (SPEC 3.1)', ap);
87
+ inner(() => (0, lexical_js_1.checkNumber)(amount, ap), ap);
88
+ if (amount.startsWith('-') || amount === '0')
89
+ bad('amount is greater than zero', ap);
90
+ const url = v.authorise;
91
+ const up = (0, json_js_1.memberPath)(path, 'authorise');
92
+ if (typeof url !== 'string' || !lexical_js_1.URL_RE.test(url) || url.length > lexical_js_1.LIMITS.licence_url)
93
+ bad('authorise is an https:// URL in the form of a licence URL (SPEC 8.1)', up);
94
+ if (!(0, units_js_1.isCurrency)(v.currency))
95
+ bad('currency is a currency code from units.md', (0, json_js_1.memberPath)(path, 'currency'));
96
+ }
97
+ /** Step 2: members against the table and their rules. Returns the outcome. */
98
+ function members(o, numbers) {
99
+ if (!(0, json_js_1.isObject)(o) || typeof o.outcome !== 'string')
100
+ bad('an envelope is an object with a string outcome', '$');
101
+ const outcome = o.outcome;
102
+ if (!Object.prototype.hasOwnProperty.call(MEMBERS, outcome))
103
+ bad(`unknown outcome ${JSON.stringify(outcome)}`, '$.outcome');
104
+ const { required, optional } = MEMBERS[outcome];
105
+ for (const k of required)
106
+ if (!(0, json_js_1.has)(o, k))
107
+ bad(`outcome ${outcome} requires ${k}`, '$');
108
+ for (const k of (0, json_js_1.sortedKeys)(o))
109
+ if (k !== 'outcome' && !required.includes(k) && !optional.includes(k))
110
+ bad(`member ${JSON.stringify(k)} is not allowed with outcome ${outcome}`, (0, json_js_1.memberPath)('$', k));
111
+ if ((0, json_js_1.has)(o, 'reason') && !(0, json_js_1.has)(o, 'superseded_by'))
112
+ bad('reason is only present with superseded_by', '$.reason');
113
+ for (const k of (0, json_js_1.sortedKeys)(o)) {
114
+ const v = o[k];
115
+ const p = (0, json_js_1.memberPath)('$', k);
116
+ switch (k) {
117
+ case 'age_seconds':
118
+ case 'retry_after_seconds':
119
+ seconds(v, numbers.get(p), k, p);
120
+ break;
121
+ case 'error':
122
+ if (outcome === 'bad_request') {
123
+ if (typeof v !== 'string' || !PARSE_CODES.includes(v))
124
+ bad('a bad_request carries a code that parsing a cell URI raises (SPEC 5.4)', p);
125
+ }
126
+ else if (typeof v !== 'string' || v === 'E_ENVELOPE' || !errors_js_1.ERROR_CODES.includes(v)) {
127
+ bad('error is a code from SPEC.md 10.2 other than E_ENVELOPE', p);
128
+ }
129
+ break;
130
+ case 'quote':
131
+ quote(v, p);
132
+ break;
133
+ case 'reason':
134
+ if (typeof v !== 'string')
135
+ bad('reason is a string', p);
136
+ if (v === '')
137
+ bad('reason must not be empty', p);
138
+ inner(() => (0, lexical_js_1.checkString)(v, p, { limit: lexical_js_1.LIMITS.summary }), p);
139
+ break;
140
+ case 'receipt':
141
+ if (!(0, json_js_1.isObject)(v))
142
+ bad('receipt is a receipt object', p);
143
+ break;
144
+ case 'superseded_by':
145
+ if (typeof v !== 'string' || !(0, lexical_js_1.isHex)(v, 64))
146
+ bad('superseded_by is a receipt hash: 64 lowercase hex digits', p);
147
+ break;
148
+ case 'trust':
149
+ if (typeof v !== 'string' || !TRUST.includes(v))
150
+ bad('trust is one of primary, verified, unverified', p);
151
+ break;
152
+ }
153
+ }
154
+ return outcome;
155
+ }
156
+ function checkRequest(request) {
157
+ const ok = (0, json_js_1.isObject)(request) &&
158
+ typeof request.cell_id === 'string' &&
159
+ (0, lexical_js_1.isHex)(request.cell_id, 64) &&
160
+ Object.keys(request).every((k) => k === 'cell_id' || k === 'asof') &&
161
+ (!(0, json_js_1.has)(request, 'asof') || (typeof request.asof === 'string' && (0, lexical_js_1.isInstant)(request.asof)));
162
+ if (!ok)
163
+ throw new TypeError('request must be {cell_id: <64 lowercase hex>, asof?: <instant>}: the cell id of the requested cell (resolved to the fn_hash used) and its asof, if the request had one');
164
+ }
165
+ const hostOf = (s, sep) => {
166
+ const i = s.indexOf(sep);
167
+ return i < 0 ? s : s.slice(0, i);
168
+ };
169
+ /**
170
+ * Check a mesh response (SPEC 5.5): `status` is the HTTP status, `body` the response body as
171
+ * JSON text or bytes (a parsed object is accepted too, without duplicate-member detection), and
172
+ * `keys` any key source `verify` accepts, used to verify an embedded receipt through step 6.
173
+ * `request` is what the client asked for: `{cell_id, asof?}`, the id (SPEC 4.4) of the requested
174
+ * cell resolved to the fn_hash the client used, and the requested asof if there was one.
175
+ * Steps: strict parse; members (E_ENVELOPE); status against outcome (E_ENVELOPE); the receipt
176
+ * (its own codes); the receipt answers the request (E_ENVELOPE); then `trust` against the receipt
177
+ * and `superseded_by` against its hash (E_ENVELOPE).
178
+ *
179
+ * Never throws for an invalid body or bad key material; throws TypeError only when `status` is
180
+ * not an integer, `request` is malformed, or `keys` is not a key source at all.
181
+ */
182
+ function checkEnvelope(status, body, keys, request) {
183
+ if (typeof status !== 'number' || !Number.isInteger(status))
184
+ throw new TypeError('status must be the HTTP status as an integer');
185
+ checkRequest(request);
186
+ const sources = (0, keys_js_1.collectSources)(keys);
187
+ const fail = (code, detail, path, receiptHash = null) => ({ ok: false, code, outcome: null, trust: null, receiptHash, detail, path });
188
+ let o;
189
+ const numbers = new Map();
190
+ try {
191
+ o = (0, json_js_1.toJson)(body, numbers); // step 1
192
+ }
193
+ catch (e) {
194
+ if (e instanceof errors_js_1.DatumeshError)
195
+ return fail(e.code, e.detail, e.path);
196
+ throw e;
197
+ }
198
+ let outcome;
199
+ try {
200
+ outcome = members(o, numbers); // step 2
201
+ if (!STATUS[outcome](status))
202
+ bad(`status ${status} does not match outcome ${outcome}`, '$.outcome'); // step 3
203
+ }
204
+ catch (e) {
205
+ if (e instanceof Bad)
206
+ return fail('E_ENVELOPE', e.detail, e.path);
207
+ throw e;
208
+ }
209
+ const env = o;
210
+ if (!(0, json_js_1.has)(env, 'receipt'))
211
+ return { ok: true, code: 'OK', outcome, trust: null, receiptHash: null, detail: `outcome ${outcome}`, path: null };
212
+ // Step 4.
213
+ let r;
214
+ try {
215
+ r = (0, verify_js_1.verifyEmbedded)(env.receipt, sources);
216
+ }
217
+ catch (e) {
218
+ if (e instanceof verify_js_1.Stop)
219
+ return fail(e.code, `receipt: ${e.detail}`, e.path === null ? '$.receipt' : e.path.replace(/^\$/, '$.receipt'));
220
+ throw e;
221
+ }
222
+ // Step 5: the receipt answers the request.
223
+ const cellId = (0, hash_js_1.sha256Hex)((0, jcs_js_1.jcsBytes)(r.receipt.cell));
224
+ if (cellId !== request.cell_id)
225
+ return fail('E_ENVELOPE', `the receipt is for cell ${cellId}, not the requested ${request.cell_id}`, '$.receipt.cell', r.hash);
226
+ // With a requested asof: equal for ok; at or before it for stale (D31). Instants are fixed
227
+ // width, so string order is time order (SPEC 3.3).
228
+ const asof = r.receipt.asof;
229
+ if (request.asof !== undefined && (outcome === 'stale' ? !(asof <= request.asof) : asof !== request.asof)) {
230
+ const want = outcome === 'stale' ? `at or before the requested ${request.asof}` : `the requested ${request.asof}`;
231
+ return fail('E_ENVELOPE', `the receipt answers asof ${asof}, not ${want}`, '$.receipt.asof', r.hash);
232
+ }
233
+ // Step 6.
234
+ const trust = env.trust;
235
+ const cell = r.receipt.cell;
236
+ const primary = hostOf(r.receipt.computed_by, '#') === hostOf(cell.ns, '/') && r.receipt.inputs.length === 0;
237
+ if ((trust === 'primary') !== primary) {
238
+ return fail('E_ENVELOPE', primary ? 'the receipt is primary (signed by its namespace host, no inputs): trust must be primary' : 'trust primary needs a receipt signed by the host of cell.ns with no inputs', '$.trust', r.hash);
239
+ }
240
+ if (env.superseded_by === r.hash)
241
+ return fail('E_ENVELOPE', 'superseded_by is the receipt itself', '$.superseded_by', r.hash);
242
+ return { ok: true, code: 'OK', outcome, trust, receiptHash: r.hash, detail: `outcome ${outcome}, trust ${trust}, receipt signed by ${r.receipt.computed_by}`, path: null };
243
+ }
@@ -0,0 +1,14 @@
1
+ /** The spec revision this library conforms to. */
2
+ export declare const SPEC_VERSION = "spec-0.2.0";
3
+ /** Every error code defined by SPEC.md 10.2, in the order of that table. */
4
+ export declare const ERROR_CODES: readonly ["E_PARSE_JSON", "E_PARSE_DUPLICATE_KEY", "E_PARSE_URI", "E_SCHEMA", "E_CANON_NAME", "E_CANON_ARG_NAME", "E_CANON_ARG_DUPLICATE", "E_CANON_ARG_ORDER", "E_CANON_PERCENT", "E_CANON_TYPE", "E_CANON_NUMBER", "E_CANON_UNIT", "E_CANON_DATE", "E_CANON_INSTANT", "E_CANON_STRING", "E_CANON_BLOB", "E_CANON_HEX", "E_CANON_LICENCE", "E_CANON_SET", "E_CANON_LIMIT", "E_SLICE", "E_PUBLISHER_MISMATCH", "E_VALID_MISMATCH", "E_TIME_ORDER", "E_ARG_UNKNOWN", "E_ARG_MISSING", "E_KEY_UNAVAILABLE", "E_KEY_DOC", "E_KEY_UNKNOWN", "E_KEY_NOT_VALID", "E_SIGNATURE", "E_FN_UNAVAILABLE", "E_FN_HASH_MISMATCH", "E_ARG_TYPE", "E_RETURN_TYPE", "E_INPUT_UNAVAILABLE", "E_INPUT_INVALID", "E_INPUT_UNDECLARED", "E_VALUE_MISMATCH", "E_BLOB_MISMATCH", "E_ENVELOPE"];
5
+ export type ErrorCode = (typeof ERROR_CODES)[number];
6
+ /** A Datumesh rule was broken. `code` is a SPEC.md 10.2 code; `path` locates the failure. */
7
+ export declare class DatumeshError extends Error {
8
+ readonly code: ErrorCode;
9
+ readonly path: string | null;
10
+ readonly detail: string;
11
+ constructor(code: ErrorCode, detail: string, path?: string | null);
12
+ }
13
+ /** Shorthand used throughout: throw a DatumeshError. */
14
+ export declare function fail(code: ErrorCode, detail: string, path?: string | null): never;