ust-protocol 1.0.0-rc.1

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 (4) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +93 -0
  3. package/index.mjs +320 -0
  4. package/package.json +40 -0
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,93 @@
1
+ # ust-protocol
2
+
3
+ **Verify machine-readable state without trusting whoever handed it to you.**
4
+
5
+ UST (Universal State Transcript) is trust infrastructure for data: a signed, canonical, tamper-evident record of
6
+ *state* — some data about the world at a moment — that verifies the same no matter how it reached you (a cache, a
7
+ mirror, another agent, a file on disk). TLS secures the pipe; **UST secures the payload**, and the guarantee
8
+ travels *with* the data.
9
+
10
+ `ust-protocol` is the stateless reference base: canonical hashing (JCS), Ed25519 signing, three-tier
11
+ verification, privacy commitments, chains, and anchoring. Zero-dependency (`node:crypto`; a WebCrypto/`@noble`
12
+ adapter for browsers and Workers — same rules, same results).
13
+
14
+ > **Release candidate — `1.0.0-rc.1`.** The specification has been extensively red-teamed; an independent
15
+ > external cryptographic audit is pending. Suitable for evaluation and integration testing. Pin exact versions.
16
+
17
+ ## Install
18
+
19
+ ```
20
+ npm i ust-protocol
21
+ ```
22
+
23
+ ## Verify a document
24
+
25
+ ```js
26
+ import { verify } from 'ust-protocol';
27
+
28
+ const r = verify(doc);
29
+ // { result: 'VALID' | 'INVALID' | 'INDETERMINATE', identity, time, publisher, content_hash, ... }
30
+ ```
31
+
32
+ - **`VALID`** — well-formed, hashes match the data, signature checks out: the document **is** what the publisher
33
+ committed to, unchanged.
34
+ - **`INVALID`** — a check failed (tampering, bad signature, malformed) — with an `error` code.
35
+ - **`INDETERMINATE`** — something needed for a higher tier was *unavailable* (not a failure; retry).
36
+
37
+ ## What it proves — and what it doesn't
38
+
39
+ UST proves **fixation, not truth**: *this publisher committed to this data, at this time, unchanged.* It does
40
+ **not** prove the data is *correct* — a publisher can sign a wrong reading. You learn **whom to hold accountable**
41
+ and **that nothing was tampered** — a real, bounded guarantee, not an oracle of truth.
42
+
43
+ ## Trust tiers — same document, more trust as you bring more
44
+
45
+ | Tier | You also supply | You learn |
46
+ |------|-----------------|-----------|
47
+ | **LIGHT** | nothing (the document alone) | integrity + a *claimed* publisher (`self-asserted`) |
48
+ | **HIGH** | the publisher's genesis + key-log | the key is *provably bound* to the publisher's name (`authoritative`) |
49
+ | **TOP** | an anchor proof | the document provably existed by a point in time; a stream is provably complete |
50
+
51
+ ```js
52
+ // HIGH — resolve name authority
53
+ verify(doc, { genesis, keylog, noForkConfirmed: true, requireAuthoritative: true });
54
+
55
+ // TOP — verify a time-anchor's inclusion proof (substrate confirmation is delegated to the caller)
56
+ import { verifyAnchor } from 'ust-protocol';
57
+ verifyAnchor(content_hash, proof);
58
+ ```
59
+
60
+ ## Create
61
+
62
+ ```js
63
+ import { buildState, seal } from 'ust-protocol';
64
+
65
+ const state = buildState(
66
+ { domain_shard: 'example.com', ust_id: 'ust:20260705.15', key_id, class: 'observation' },
67
+ { generated_at, valid_from, valid_to },
68
+ { reading: { kind: 'captured', value: { temp_c: '21.4' } } } // string-only leaves, verbatim
69
+ );
70
+ const doc = seal(state, privateKey, publicKeyB64url);
71
+ ```
72
+
73
+ Also: `buildAttestation` (Merkle root over constituents), `buildDerivation` (based-on + seed), `buildGenesis`,
74
+ `buildKeyLogEntry`, `buildCheckpoint`, `blindPartition` (privacy commitments). `resolveAuthority` and
75
+ `verifyStream` cover HIGH name-authority and TOP completeness.
76
+
77
+ ## Design in one paragraph
78
+
79
+ Every value is a **string** (numbers stay verbatim — no float drift). Documents are **canonicalized** (JCS,
80
+ tightened) before hashing, so the same state always yields the same bytes. Hashing is **domain-separated**; the
81
+ `content_hash` is a unique descriptor of the whole document. Signatures use **strict** Ed25519 (non-canonical `S`
82
+ rejected). Verification is **fail-closed** and returns one of three honest outcomes — availability is never
83
+ confused with failure.
84
+
85
+ ## Spec & conformance
86
+
87
+ - Specification and a client-side verifier: **https://github.com/thelabmd/UST/blob/main/spec/UST-1.0.md**
88
+ - This library is validated against a suite of deterministic conformance vectors (the same vectors any
89
+ independent implementation should pass).
90
+
91
+ ## License
92
+
93
+ Apache-2.0 · © 2026 THE LAB
package/index.mjs ADDED
@@ -0,0 +1,320 @@
1
+ // ust-protocol — reference implementation of UST 1.0 (the official STATELESS base; the public verification lib) (REV 24), LIGHT floor first.
2
+ // Written FROM THE SPEC (§ references inline), NOT copied from the vector generator — so running it against
3
+ // the vectors is a cross-check between two independently-written artifacts. Zero-dependency: node:crypto
4
+ // (Ed25519 + SHA-256). Portable note: WebCrypto (SubtleCrypto Ed25519) or @noble/{ed25519,hashes} for
5
+ // browsers/Workers; same rules.
6
+ import { createHash, sign as edSign, verify as edVerify, createPublicKey, createPrivateKey, createDecipheriv } from 'node:crypto';
7
+
8
+ // ─── §6 Canonicalization (JCS tightened) ────────────────────────────────────────────────────────────
9
+ // keys sorted by UTF-16 code unit, no whitespace, string-only leaves (reject number/bool/null), NFC,
10
+ // unique member names. Throws {code:'E-CANON'} on violation.
11
+ export function canon(v) {
12
+ if (v === null || typeof v === 'number' || typeof v === 'boolean') throw err('E-CANON', 'non-string leaf');
13
+ if (typeof v === 'string') { if (v.normalize('NFC') !== v) throw err('E-CANON', 'non-NFC string'); return JSON.stringify(v); }
14
+ if (Array.isArray(v)) return '[' + v.map(canon).join(',') + ']'; // §6.3 order significant
15
+ if (typeof v === 'object') {
16
+ const k = Object.keys(v);
17
+ if (new Set(k).size !== k.length) throw err('E-CANON', 'duplicate key'); // §6.1
18
+ return '{' + k.slice().sort().map(x => JSON.stringify(x) + ':' + canon(v[x])).join(',') + '}';
19
+ }
20
+ throw err('E-CANON', 'unsupported');
21
+ }
22
+
23
+ // ─── §7 Domain-separated hash: H_t(x) = "sha256:" || hex(SHA256(ascii(t) || 0x00 || x)) ──────────────
24
+ function sha(buf) { return 'sha256:' + createHash('sha256').update(buf).digest('hex'); }
25
+ export const H = (tag, strInput) => sha(Buffer.concat([Buffer.from(tag, 'ascii'), Buffer.from([0]), Buffer.from(strInput, 'utf8')])); // x = utf8 string
26
+ export const Hbytes = (tag, rawBuf) => sha(Buffer.concat([Buffer.from(tag, 'ascii'), Buffer.from([0]), rawBuf])); // x = raw bytes
27
+
28
+ // ─── §12.2/§17 key_id = H("ust:keylog", raw_pub_bytes) — raw = base64url-decode(pub), NOT plain SHA256(pub)
29
+ export const keyId = (pubB64url) => Hbytes('ust:keylog', Buffer.from(pubB64url, 'base64url'));
30
+
31
+ // ─── §4.4 per-partition hash. captured binds domain_shard; computed omits it (cross-engine); private = over commit
32
+ export function partitionHash({ domain_shard, ust_id, name, value, kind, commit }) {
33
+ if (commit !== undefined) return Hbytes('ust:shard', Buffer.from(commit, 'utf8')); // §4.4 private: hash over its commit
34
+ const scope = kind === 'computed' ? { ust_id, [name]: value } : { domain_shard, ust_id, [name]: value };
35
+ return H('ust:shard', canon(scope));
36
+ }
37
+
38
+ // ─── §7 content_hash = H("ust:state", canon({ust, state})) — the unique document descriptor ─────────────
39
+ export const signedContent = (doc) => canon({ ust: doc.ust, state: doc.state });
40
+ export const contentHash = (doc) => H('ust:state', signedContent(doc));
41
+
42
+ // ─── §9.4 seed / §9.2 Merkle root ───────────────────────────────────────────────────────────────────
43
+ export const seed = (contentHashes) => H('ust:seed', canon(contentHashes)); // pinned signed order
44
+ export function merkleRoot(contentHashes) { // byte-ascending sort, ust:leaf/ust:node
45
+ let lvl = contentHashes.slice().sort().map(h => Hbytes('ust:leaf', Buffer.from(h, 'utf8')));
46
+ while (lvl.length > 1) {
47
+ const nx = [];
48
+ for (let i = 0; i < lvl.length; i += 2)
49
+ nx.push(i + 1 < lvl.length ? Hbytes('ust:node', Buffer.from(lvl[i] + lvl[i + 1], 'utf8')) : lvl[i]);
50
+ lvl = nx;
51
+ }
52
+ return lvl[0];
53
+ }
54
+
55
+ // ─── §10 PRIVACY — blinded commitment (frame-bound, G23; nonce MUST be fresh & unique per commit, Z2) ────
56
+ // commit = H_shard(canon({domain_shard, ust_id, nonce, <name>: value})) — verifier reproduces from a disclosure.
57
+ export const blindedCommit = ({ domain_shard, ust_id, name, value, nonce }) =>
58
+ H('ust:shard', canon({ domain_shard, ust_id, nonce, [name]: value }));
59
+ // producer helper: build a blinded PRIVATE partition envelope + its hashes entry (§4.4 private hash = H over commit).
60
+ export function blindPartition(name, value, { domain_shard, ust_id, nonce, kind = 'captured' }) {
61
+ const commit = blindedCommit({ domain_shard, ust_id, name, value, nonce });
62
+ return { partition: { kind, privacy: 'blinded', commit }, hash: partitionHash({ commit }) };
63
+ }
64
+ // §10 encrypted: AEAD-decrypt to recover the committed plaintext canon({nonce,<name>:value}). AES-256-GCM here
65
+ // (node:crypto); XChaCha20-Poly1305 needs @noble/ciphers (browsers/Workers). enc.ct = b64url(iv12 || ct || tag16).
66
+ function aeadDecrypt(enc, keyRawB64url) {
67
+ try {
68
+ if (enc.alg !== 'AES-256-GCM') return null; // XChaCha20-Poly1305: use @noble/ciphers
69
+ const raw = Buffer.from(enc.ct, 'base64url'), key = Buffer.from(keyRawB64url, 'base64url');
70
+ const iv = raw.subarray(0, 12), tag = raw.subarray(raw.length - 16), body = raw.subarray(12, raw.length - 16);
71
+ const d = createDecipheriv('aes-256-gcm', key, iv); d.setAuthTag(tag);
72
+ return Buffer.concat([d.update(body), d.final()]).toString('utf8'); // the committed plaintext (utf8 canon)
73
+ } catch { return null; } // auth-tag failure ⇒ null ⇒ E-COMMIT
74
+ }
75
+
76
+ // ─── crypto helpers (strict Ed25519 via node:crypto/OpenSSL) ─────────────────────────────────────────
77
+ const pubKeyObj = (b64url) => createPublicKey({ key: Buffer.concat([Buffer.from('302a300506032b6570032100', 'hex'), Buffer.from(b64url, 'base64url')]), format: 'der', type: 'spki' });
78
+ export function edVerifyStrict(pubB64url, msgUtf8, sigB64url) {
79
+ try { return edVerify(null, Buffer.from(msgUtf8, 'utf8'), pubKeyObj(pubB64url), Buffer.from(sigB64url, 'base64url')); }
80
+ catch { return false; }
81
+ }
82
+
83
+ // ─── producer: §7 seal — sign canon({ust,state}) with an Ed25519 private key ─────────────────────────
84
+ export function seal(state, privKeyObj, pubB64url) {
85
+ const doc = { ust: '1.0', state };
86
+ const sig = edSign(null, Buffer.from(signedContent(doc), 'utf8'), privKeyObj).toString('base64url');
87
+ return { ust: '1.0', state, sig: { alg: 'Ed25519', key_id: state.id.key_id, pub: pubB64url, sig } };
88
+ }
89
+
90
+ // ─── producer helpers: assemble a State with the per-partition `hashes` auto-computed (§4.4). `seal` signs it.
91
+ // `id` = {domain_shard, ust_id, key_id[, parent_ust]}. `data` = {name: {kind,value} | {kind,privacy,commit,enc?}}.
92
+ export function buildState(id, time, data, provenance) {
93
+ const hashes = {};
94
+ for (const [name, part] of Object.entries(data))
95
+ hashes[name] = part.commit !== undefined ? partitionHash({ commit: part.commit })
96
+ : partitionHash({ domain_shard: id.domain_shard, ust_id: id.ust_id, name, value: part.value, kind: part.kind });
97
+ const state = { id, time, data, hashes };
98
+ if (provenance) state.provenance = provenance;
99
+ return state;
100
+ }
101
+ export const buildAttestation = (id, time, data, constituents, prev) => // §9.2 constituents + Merkle root
102
+ buildState({ ...id, class: 'attestation' }, time, data, { constituents, root: merkleRoot(constituents), ...(prev !== undefined ? { prev } : {}) });
103
+ export const buildDerivation = (id, time, data, basedOn, prev) => // §9.3/§9.4 based_on + seed
104
+ buildState({ ...id, class: 'derivation' }, time, data, { based_on: basedOn, seed: seed(basedOn.map(b => b.hash)), ...(prev !== undefined ? { prev } : {}) });
105
+ export const buildGenesis = (id, time, pub) => // §12.1 self-signed name-binding root
106
+ buildState({ ...id, class: 'genesis' }, time, { genesis: { kind: 'captured', value: { pub, role: 'name-binding-root' } } });
107
+ export const buildKeyLogEntry = (id, time, keyOp, prev) => // §12.2 add|rotate|revoke
108
+ buildState({ ...id, class: 'key' }, time, { key_op: { kind: 'captured', value: keyOp } }, { prev });
109
+ export const buildCheckpoint = (id, time, head, frameCount, prev) => // §11.3 M5
110
+ buildState({ ...id, class: 'attestation' }, time, { checkpoint: { kind: 'computed', value: { head, frame_count: String(frameCount) } } }, { prev });
111
+
112
+ // ─── reserved-key sets (§3/§4.2/§17) ─────────────────────────────────────────────────────────────────
113
+ const RESERVED = { transcript: ['ust','state','sig','proof'], state: ['id','time','data','hashes','provenance'],
114
+ id: ['domain_shard','ust_id','key_id','class','parent_ust'], envelope: ['kind','value','privacy','commit','enc'] };
115
+ const CLASSES = ['observation','attestation','derivation','genesis','key'];
116
+ const TS = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/; // §6 pinned RFC3339 UTC-Z
117
+ const USTID = /^ust:\d{8}\.\d{2}(\d{2}(\d{2})?)?$/; // §8
118
+
119
+ // ─── §13 structural bounds — hard ceilings; exceed ⇒ E-BOUNDS ─────────────────────────────────────────
120
+ const BOUNDS = { depth: 8, array: 4096, partitions: 64, breadth: 64, sizeBytes: 1048576 };
121
+ export function checkBounds(doc) {
122
+ if (Buffer.byteLength(JSON.stringify(doc), 'utf8') > BOUNDS.sizeBytes) return 'size > 1 MiB';
123
+ if (doc.state?.data && Object.keys(doc.state.data).length > BOUNDS.partitions) return 'partitions > 64';
124
+ let bad = null;
125
+ (function walk(v, d) {
126
+ if (bad) return;
127
+ if (d > BOUNDS.depth) { bad = 'depth > 8'; return; }
128
+ if (Array.isArray(v)) { if (v.length > BOUNDS.array) { bad = 'array > 4096'; return; } for (const x of v) walk(x, d + 1); }
129
+ else if (v && typeof v === 'object') for (const k of Object.keys(v)) walk(v[k], d + 1);
130
+ })(doc.state ?? doc, 0);
131
+ const pr = doc.state?.provenance;
132
+ if (!bad && pr) for (const f of ['based_on', 'constituents']) if (Array.isArray(pr[f]) && pr[f].length > BOUNDS.breadth) bad = f + ' breadth > 64';
133
+ return bad;
134
+ }
135
+
136
+ // ─── §14 Verification (LIGHT floor: steps 1,2,4,5,8 + §13 bounds). Returns the three-outcome result. ──
137
+ // opts: { requireVersion:'1.0', context:'data'|'key' } ; HIGH/TOP (steps 3,6,7) are separate, later.
138
+ export function verify(doc, opts = {}) {
139
+ try {
140
+ // step 1 — structural admission (§14.1)
141
+ if (typeof doc !== 'object' || doc === null) return bad('E-MALFORMED', 'not an object');
142
+ if (doc.ust === undefined || doc.state === undefined || doc.sig === undefined) return bad('E-MALFORMED', 'missing ust/state/sig');
143
+ if (doc.ust !== '1.0') return bad('E-MALFORMED', 'unknown version ' + doc.ust); // §19 (this verifier is 1.0)
144
+ const bnd = checkBounds(doc); if (bnd) return bad('E-BOUNDS', bnd); // §13 bounds
145
+ const st = doc.state;
146
+ for (const k of Object.keys(st)) if (!RESERVED.state.includes(k)) return bad('E-MALFORMED', 'reserved-key: state.' + k);
147
+ if (!st.id || !st.time || !st.data || !st.hashes) return bad('E-MALFORMED', 'state missing id/time/data/hashes');
148
+ for (const k of Object.keys(st.id)) if (!RESERVED.id.includes(k)) return bad('E-MALFORMED', 'reserved-key: id.' + k);
149
+ // §I3 partition names must be non-reserved-envelope, non-collide
150
+ for (const name of Object.keys(st.data)) {
151
+ const part = st.data[name];
152
+ for (const k of Object.keys(part)) if (!RESERVED.envelope.includes(k)) return bad('E-MALFORMED', 'reserved-key: data.' + name + '.' + k);
153
+ }
154
+ // step 2 — canonical, content_hash, bijection, per-partition hashes (§14.2, G19, §4.4)
155
+ let S; try { S = signedContent(doc); } catch (e) { return bad('E-CANON', e.detail || 'canon'); }
156
+ const ch = H('ust:state', S);
157
+ const dk = Object.keys(st.data).sort(), hk = Object.keys(st.hashes).sort();
158
+ if (dk.length !== hk.length || dk.some((k, i) => k !== hk[i])) return bad('E-MALFORMED', 'hashes⇄data not a bijection (G19)');
159
+ for (const name of dk) {
160
+ const part = st.data[name];
161
+ let recomputed;
162
+ try {
163
+ recomputed = part.commit !== undefined
164
+ ? partitionHash({ commit: part.commit })
165
+ : partitionHash({ domain_shard: st.id.domain_shard, ust_id: st.id.ust_id, name, value: part.value, kind: part.kind });
166
+ } catch (e) { return bad('E-CANON', 'partition canon: ' + name); }
167
+ if (recomputed !== st.hashes[name]) return bad('E-CANON', 'partition hash mismatch: ' + name);
168
+ }
169
+ // step 5 — well-formed shape (§14.5)
170
+ if (!USTID.test(st.id.ust_id)) return bad('E-MALFORMED', 'ust_id shape');
171
+ if (!TS.test(st.time.generated_at) || !TS.test(st.time.valid_from) || !TS.test(st.time.valid_to)) return bad('E-MALFORMED', 'timestamp not pinned RFC3339-Z');
172
+ if (st.time.valid_from > st.time.valid_to) return bad('E-MALFORMED', 'valid_from > valid_to');
173
+ if (!CLASSES.includes(st.id.class)) return bad('E-MALFORMED', 'unknown class ' + st.id.class);
174
+ if (dk.length < 1) return bad('E-MALFORMED', 'no partition');
175
+ for (const name of dk) { // private partitions carry a commit
176
+ const part = st.data[name];
177
+ if (part.privacy !== undefined && part.commit === undefined) return bad('E-MALFORMED', 'private partition without commit: ' + name);
178
+ if (part.privacy === undefined && part.value === undefined) return bad('E-MALFORMED', 'public partition without value: ' + name);
179
+ }
180
+ // W3 class-context: a data verify must not accept a key-log/genesis transcript as data
181
+ if (opts.context === 'data' && (st.id.class === 'key' || st.id.class === 'genesis')) return bad('E-MALFORMED', 'class ' + st.id.class + ' not valid in data context (W3)');
182
+ // step 4 — authenticity (§14.4): key_id consistency + strict Ed25519 over S
183
+ if (doc.sig.key_id !== st.id.key_id) return bad('E-SIG', 'sig.key_id != state.id.key_id');
184
+ if (doc.sig.pub === undefined) return bad('E-KEY', 'no carried pub (LIGHT)');
185
+ if (keyId(doc.sig.pub) !== st.id.key_id) return bad('E-SIG', 'key_id != H(ust:keylog, pub)');
186
+ if (!edVerifyStrict(doc.sig.pub, S, doc.sig.sig)) return bad('E-SIG', 'Ed25519 verify failed');
187
+ // step 3 — name authority (HIGH, §12/§14.3): resolved ONLY if the caller supplies genesis+keylog.
188
+ const identity = opts.genesis ? resolveAuthority(doc, opts) : { strength: 'self-asserted', status: 'verified' };
189
+ if (identity.error) return bad(identity.error, identity.detail); // forked genesis / broken key-log
190
+ if (opts.requireAuthoritative && !(identity.strength === 'authoritative' && identity.status === 'verified'))
191
+ return identity.status === 'unavailable'
192
+ ? { result: 'INDETERMINATE', reason: 'unavailable', identity, detail: identity.detail } // W1: retry, NOT failure
193
+ : bad('E-GENESIS', 'authoritative required but ' + identity.strength + '/' + identity.status);
194
+ // step 8 — privacy (§14.8/§10): if the caller discloses {nonce,value}, REPRODUCE the commit; for
195
+ // `encrypted`, AEAD-decrypt must reproduce the SAME committed plaintext (E-COMMIT on mismatch). Never brute-force.
196
+ const disclosed = [];
197
+ for (const name of dk) {
198
+ const part = st.data[name];
199
+ if (part.privacy === undefined) continue;
200
+ const disc = opts.disclosures?.[name];
201
+ if (!disc) continue; // not authorized — commit stands, opaque
202
+ const reproduced = blindedCommit({ domain_shard: st.id.domain_shard, ust_id: st.id.ust_id, name, value: disc.value, nonce: disc.nonce });
203
+ if (reproduced !== part.commit) return bad('E-COMMIT', 'blinded commit mismatch: ' + name);
204
+ if (part.privacy === 'encrypted' && part.enc && opts.decKeys?.[part.enc.key_id]) {
205
+ const pt = aeadDecrypt(part.enc, opts.decKeys[part.enc.key_id]); // → canon({nonce,<p>:value}) plaintext
206
+ if (pt === null || pt !== canon({ nonce: disc.nonce, [name]: disc.value })) return bad('E-COMMIT', 'AEAD↔commit mismatch: ' + name);
207
+ }
208
+ disclosed.push(name);
209
+ }
210
+ // step 9 — provenance (§14.9): bound source identity (§9.1, I8). A source with a verifiable `src_sig`
211
+ // (the source's own signature over its `addr`) is AUTHENTICATED; without one it is an operator LABEL —
212
+ // marked `unauthenticated`, and a consumer MUST NOT surface it as source attribution.
213
+ const sources = {};
214
+ if (st.provenance?.sources) for (const [sid, s] of Object.entries(st.provenance.sources)) {
215
+ const key = opts.sourceKeys?.[sid];
216
+ sources[sid] = (key && s.src_sig && edVerifyStrict(key, s.addr, s.src_sig)) ? 'authenticated' : 'unauthenticated';
217
+ }
218
+ // §14.9 attestation: recompute the Merkle root from constituents (⇒ E-ROOT on mismatch).
219
+ if (st.id.class === 'attestation' && st.provenance?.constituents && st.provenance?.root !== undefined)
220
+ if (merkleRoot(st.provenance.constituents) !== st.provenance.root) return bad('E-ROOT', 'attestation root mismatch');
221
+ return { result: 'VALID', identity, disclosed, sources,
222
+ publisher: st.id.domain_shard, ust_id: st.id.ust_id, class: st.id.class, content_hash: ch,
223
+ time: { strength: 'unproven', status: doc.proof ? 'present' : 'none' } };
224
+ } catch (e) {
225
+ return bad(e.code || 'E-MALFORMED', e.detail || String(e)); // fail-closed (§14/I10)
226
+ }
227
+ }
228
+
229
+ // ─── §12 HIGH name-authority resolution. STATELESS: the caller (ustate/engine) supplies the genesis +
230
+ // key-log transcripts (retrieval is the stateful layer's job) and asserts no-fork from the witness (W1).
231
+ export function resolveAuthority(doc, { genesis, keylog = [], noForkConfirmed = false, anchorTime } = {}) {
232
+ if (!genesis) return { strength: 'self-asserted', status: 'verified' }; // LIGHT — nothing to resolve
233
+ const gv = verify(genesis); // genesis is itself a UST transcript
234
+ if (gv.result !== 'VALID') return { error: 'E-GENESIS', detail: 'genesis invalid: ' + gv.error };
235
+ if (genesis.state.id.class !== 'genesis') return { error: 'E-GENESIS', detail: 'not class:genesis' };
236
+ if (genesis.sig.key_id !== genesis.state.id.key_id) return { error: 'E-GENESIS', detail: 'genesis not self-signed' };
237
+ if (genesis.state.id.domain_shard !== doc.state.id.domain_shard) return { error: 'E-GENESIS', detail: 'genesis domain mismatch' };
238
+ if (keylog.length > 256) return { error: 'E-BOUNDS', detail: 'key-log > 256 (§13)' };
239
+ let prevHash = contentHash(genesis);
240
+ const validPubs = new Set([genesis.sig.pub]); // genesis key signs the first entry
241
+ const addedKeyIds = new Set([genesis.state.id.key_id]);
242
+ const revoked = new Map(); // §12.2 X1: key_id → {reason, compromised_since, at}
243
+ for (const [i, e] of keylog.entries()) { // §12.2 walk: prev-chained, self-signed
244
+ const ev = verify(e, { context: 'key' });
245
+ if (ev.result !== 'VALID') return { error: 'E-KEY', detail: 'key-log entry ' + i + ' invalid: ' + ev.error };
246
+ if (e.state.id.class !== 'key') return { error: 'E-KEY', detail: 'entry ' + i + ' not class:key' };
247
+ if (e.state.provenance?.prev !== prevHash) return { error: 'E-PREV', detail: 'entry ' + i + ' prev not chained' };
248
+ if (!validPubs.has(e.sig.pub)) return { error: 'E-KEY', detail: 'entry ' + i + ' not signed by a current valid key' };
249
+ const op = e.state.data.key_op.value;
250
+ if (op.op === 'add' || op.op === 'rotate') { validPubs.add(op.pub); addedKeyIds.add(op.new_key_id); }
251
+ else if (op.op === 'revoke') revoked.set(keyId(op.pub), { reason: op.reason, compromised_since: op.compromised_since, at: e.state.time.generated_at });
252
+ prevHash = contentHash(e);
253
+ }
254
+ if (!addedKeyIds.has(doc.state.id.key_id))
255
+ return { strength: 'self-asserted', status: 'verified', detail: 'doc key not in this key-log' };
256
+ // §12.2 X1 — revocation window, decided against the anchor UPPER BOUND (U = anchorTime, from §11.2).
257
+ const rev = revoked.get(doc.state.id.key_id);
258
+ let suspect = false;
259
+ if (rev) {
260
+ const U = anchorTime; // proven "not later than"
261
+ if (rev.reason === 'compromised') {
262
+ if (!U) return { strength: 'self-asserted', status: 'revoked-untrusted', detail: 'compromised key + UNANCHORED doc → untrusted (X1)' };
263
+ if (U >= rev.compromised_since) return { error: 'E-KEY', detail: 'signature not provably before compromise (U ≥ compromised_since, X1)' };
264
+ suspect = true; // provably pre-compromise, but C is a publisher estimate
265
+ } else if (rev.reason === 'retired' && U && U > rev.at)
266
+ return { strength: 'self-asserted', status: 'expired', detail: 'signed after hygienic retirement (X1)' };
267
+ }
268
+ // W1 — authoritative REQUIRES a positive no-fork confirmation (the witness), the caller/ustate's job.
269
+ if (!noForkConfirmed) return { strength: 'authoritative', status: 'unavailable',
270
+ detail: 'no-fork not confirmed (W1: witness check is the caller job) → authoritative DENIED, retry' };
271
+ return { strength: 'authoritative', status: suspect ? 'suspect' : 'verified' };
272
+ }
273
+
274
+ // ─── TOP §11.2 anchor-proof: recompute the Merkle inclusion path content_hash→root (RFC 6962, domain-sep
275
+ // ust:leaf/ust:node). The SUBSTRATE check (e.g. bitcoin-ots) is DELEGATED to opts.substrateVerify (needs
276
+ // external Bitcoin access — the caller/ustate's job). Returns { inclusion, time, status, anchorTime? }.
277
+ export function verifyAnchor(contentHash, proof, opts = {}) {
278
+ let node = Hbytes('ust:leaf', Buffer.from(contentHash, 'utf8'));
279
+ for (const s of proof.path) node = Hbytes('ust:node', Buffer.from(s.dir === 'L' ? s.hash + node : node + s.hash, 'utf8'));
280
+ const inclusion = node === proof.root;
281
+ if (!inclusion) return { inclusion: false, time: 'unproven', status: 'verified', detail: 'inclusion path does not reach root' };
282
+ if (!opts.substrateVerify) return { inclusion: true, time: 'unproven', status: 'unavailable', detail: 'inclusion OK; substrate not verified (caller job)' };
283
+ const sub = opts.substrateVerify(proof.anchor, proof.root); // → { final, time }
284
+ if (!sub) return { inclusion: true, time: 'unproven', status: 'unavailable', detail: 'substrate unreachable' };
285
+ if (!sub.final) return { inclusion: true, time: 'unproven', status: 'verified', detail: 'substrate not final (e.g. <6 conf)' };
286
+ return { inclusion: true, time: 'anchored', status: 'verified', anchorTime: sub.time };
287
+ }
288
+
289
+ // ─── TOP §11.3 completeness: a sequenced stream is prev-chained; first frame's prev = genesis content_hash
290
+ // (M4); per-frame validity is verified too (X2 — completeness ≠ validity); duplicate ust_id / shared prev
291
+ // = a fork ⇒ E-PREV (Y1). 'proven' needs a covering checkpoint (M5); else the open tail is 'provisional'.
292
+ export function verifyStream(frames, { genesis, checkpoint, requirePerFrameValid = true } = {}) {
293
+ if (!Array.isArray(frames) || !frames.length) return { complete: 'none' };
294
+ let prevHash = genesis ? contentHash(genesis) : null;
295
+ const seenUstId = new Set(), seenPrev = new Set();
296
+ for (const [i, f] of frames.entries()) {
297
+ if (requirePerFrameValid) { const v = verify(f, { context: 'data' }); if (v.result !== 'VALID') return { error: 'E-SIG', detail: 'frame ' + i + ' invalid: ' + v.error }; } // X2
298
+ if (seenUstId.has(f.state.id.ust_id)) return { error: 'E-PREV', detail: 'duplicate ust_id (fork, Y1): ' + f.state.id.ust_id };
299
+ seenUstId.add(f.state.id.ust_id);
300
+ const p = f.state.provenance?.prev;
301
+ if (i === 0) { if (genesis && p !== prevHash) return { error: 'E-PREV', detail: 'first frame prev != genesis content_hash (M4)' }; }
302
+ else if (p !== prevHash) return { error: 'E-PREV', detail: 'frame ' + i + ' prev dangling (broken chain)' };
303
+ if (p && seenPrev.has(p)) return { error: 'E-PREV', detail: 'two frames share a prev (fork, Y1)' };
304
+ if (p) seenPrev.add(p);
305
+ prevHash = contentHash(f);
306
+ }
307
+ // M5 — a COVERING checkpoint (class:attestation asserting head + frame_count) closes the interval → 'proven'.
308
+ if (checkpoint) {
309
+ const cv = verify(checkpoint, { context: 'data' });
310
+ if (cv.result !== 'VALID' || checkpoint.state.id.class !== 'attestation') return { error: 'E-PREV', detail: 'invalid checkpoint' };
311
+ const a = checkpoint.state.data.checkpoint?.value;
312
+ if (!a || a.head !== prevHash || String(a.frame_count) !== String(frames.length))
313
+ return { error: 'E-PREV', detail: 'checkpoint contradicts observed set (M5)' };
314
+ return { complete: 'proven', head: prevHash };
315
+ }
316
+ return { complete: 'provisional', head: prevHash }; // no checkpoint → open tail (P5)
317
+ }
318
+
319
+ function err(code, detail) { const e = new Error(code); e.code = code; e.detail = detail; return e; }
320
+ function bad(code, detail) { return { result: 'INVALID', error: code, detail }; }
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "ust-protocol",
3
+ "version": "1.0.0-rc.1",
4
+ "description": "Universal State Transcript (UST) — the stateless reference base: canonical hashing (JCS), Ed25519 signing, three-tier verification (LIGHT/HIGH/TOP), privacy commitments, chains, and anchoring. Trust infrastructure for machine-readable state.",
5
+ "author": "THE LAB (https://thelab.md)",
6
+ "type": "module",
7
+ "main": "./index.mjs",
8
+ "exports": {
9
+ ".": "./index.mjs"
10
+ },
11
+ "files": [
12
+ "index.mjs",
13
+ "LICENSE",
14
+ "README.md"
15
+ ],
16
+ "keywords": [
17
+ "ust",
18
+ "trust-infrastructure",
19
+ "verification",
20
+ "ed25519",
21
+ "canonical",
22
+ "jcs",
23
+ "merkle",
24
+ "provenance",
25
+ "attestation",
26
+ "notarization"
27
+ ],
28
+ "license": "Apache-2.0",
29
+ "engines": {
30
+ "node": ">=18"
31
+ },
32
+ "sideEffects": false,
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/thelabmd/UST.git",
36
+ "directory": "packages/ust-protocol"
37
+ },
38
+ "homepage": "https://github.com/thelabmd/UST/tree/main/packages/ust-protocol#readme",
39
+ "bugs": "https://github.com/thelabmd/UST/issues"
40
+ }