@cello-protocol/cli 0.0.306 → 0.0.307

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 (234) hide show
  1. package/.claude-plugin/marketplace.json +15 -0
  2. package/README.md +107 -0
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +564 -0
  5. package/dist/daemon/account-page-assets.d.ts +4 -0
  6. package/dist/daemon/account-page-assets.js +160 -0
  7. package/dist/daemon/account-page.d.ts +14 -0
  8. package/dist/daemon/account-page.js +104 -0
  9. package/dist/daemon/address.d.ts +10 -0
  10. package/dist/daemon/address.js +34 -0
  11. package/dist/daemon/away.d.ts +31 -0
  12. package/dist/daemon/away.js +65 -0
  13. package/dist/daemon/channel-store.d.ts +112 -0
  14. package/dist/daemon/channel-store.js +284 -0
  15. package/dist/daemon/channels.d.ts +46 -0
  16. package/dist/daemon/channels.js +1049 -0
  17. package/dist/daemon/contacts.d.ts +26 -0
  18. package/dist/daemon/contacts.js +74 -0
  19. package/dist/daemon/engine.d.ts +80 -0
  20. package/dist/daemon/engine.js +2882 -0
  21. package/dist/daemon/errors.d.ts +5 -0
  22. package/dist/daemon/errors.js +16 -0
  23. package/dist/daemon/governance.d.ts +66 -0
  24. package/dist/daemon/governance.js +514 -0
  25. package/dist/daemon/guards.d.ts +36 -0
  26. package/dist/daemon/guards.js +140 -0
  27. package/dist/daemon/issuer-client.d.ts +56 -0
  28. package/dist/daemon/issuer-client.js +143 -0
  29. package/dist/daemon/link.d.ts +30 -0
  30. package/dist/daemon/link.js +191 -0
  31. package/dist/daemon/log.d.ts +1 -0
  32. package/dist/daemon/log.js +4 -0
  33. package/dist/daemon/main.d.ts +1 -0
  34. package/dist/daemon/main.js +511 -0
  35. package/dist/daemon/paths.d.ts +6 -0
  36. package/dist/daemon/paths.js +21 -0
  37. package/dist/daemon/pii.d.ts +24 -0
  38. package/dist/daemon/pii.js +146 -0
  39. package/dist/daemon/policy-cadence.d.ts +33 -0
  40. package/dist/daemon/policy-cadence.js +59 -0
  41. package/dist/daemon/policy-proposals.d.ts +41 -0
  42. package/dist/daemon/policy-proposals.js +83 -0
  43. package/dist/daemon/policy-store.d.ts +47 -0
  44. package/dist/daemon/policy-store.js +144 -0
  45. package/dist/daemon/presented.d.ts +36 -0
  46. package/dist/daemon/presented.js +94 -0
  47. package/dist/daemon/rate-limit.d.ts +17 -0
  48. package/dist/daemon/rate-limit.js +44 -0
  49. package/dist/daemon/reach.d.ts +63 -0
  50. package/dist/daemon/reach.js +207 -0
  51. package/dist/daemon/screening.d.ts +97 -0
  52. package/dist/daemon/screening.js +362 -0
  53. package/dist/daemon/settings.d.ts +125 -0
  54. package/dist/daemon/settings.js +73 -0
  55. package/dist/daemon/signal-rules.d.ts +55 -0
  56. package/dist/daemon/signal-rules.js +127 -0
  57. package/dist/daemon/signal-store.d.ts +53 -0
  58. package/dist/daemon/signal-store.js +114 -0
  59. package/dist/daemon/store.d.ts +188 -0
  60. package/dist/daemon/store.js +474 -0
  61. package/dist/daemon/tiers.d.ts +14 -0
  62. package/dist/daemon/tiers.js +9 -0
  63. package/dist/daemon/wallet.d.ts +73 -0
  64. package/dist/daemon/wallet.js +428 -0
  65. package/dist/daemon/who-label.d.ts +3 -0
  66. package/dist/daemon/who-label.js +11 -0
  67. package/dist/guidance.d.ts +39 -0
  68. package/dist/guidance.js +98 -0
  69. package/dist/hermes-bridge.d.ts +26 -0
  70. package/dist/hermes-bridge.js +180 -0
  71. package/dist/install-mcp.d.ts +6 -0
  72. package/dist/install-mcp.js +77 -0
  73. package/dist/ipc/client.d.ts +18 -0
  74. package/dist/ipc/client.js +107 -0
  75. package/dist/ipc/operations.d.ts +30 -0
  76. package/dist/ipc/operations.js +835 -0
  77. package/dist/ipc/protocol.d.ts +21 -0
  78. package/dist/ipc/protocol.js +1 -0
  79. package/dist/issuer-list-sign.d.ts +12 -0
  80. package/dist/issuer-list-sign.js +43 -0
  81. package/dist/local-operations.d.ts +2 -0
  82. package/dist/local-operations.js +73 -0
  83. package/dist/mcp-tools.d.ts +14 -0
  84. package/dist/mcp-tools.js +45 -0
  85. package/dist/mcp.d.ts +2 -0
  86. package/dist/mcp.js +155 -0
  87. package/dist/protocol/aead.d.ts +4 -0
  88. package/dist/protocol/aead.js +35 -0
  89. package/dist/protocol/cbor.d.ts +40 -0
  90. package/dist/protocol/cbor.js +106 -0
  91. package/dist/protocol/chain.d.ts +44 -0
  92. package/dist/protocol/chain.js +126 -0
  93. package/dist/protocol/channel.d.ts +153 -0
  94. package/dist/protocol/channel.js +298 -0
  95. package/dist/protocol/encode.d.ts +6 -0
  96. package/dist/protocol/encode.js +21 -0
  97. package/dist/protocol/identity.d.ts +27 -0
  98. package/dist/protocol/identity.js +94 -0
  99. package/dist/protocol/issuer-list.d.ts +56 -0
  100. package/dist/protocol/issuer-list.js +193 -0
  101. package/dist/protocol/issuer-roots.d.ts +6 -0
  102. package/dist/protocol/issuer-roots.js +10 -0
  103. package/dist/protocol/key-agreement.d.ts +20 -0
  104. package/dist/protocol/key-agreement.js +88 -0
  105. package/dist/protocol/merkle.d.ts +16 -0
  106. package/dist/protocol/merkle.js +166 -0
  107. package/dist/protocol/ml-dsa.d.ts +28 -0
  108. package/dist/protocol/ml-dsa.js +58 -0
  109. package/dist/protocol/ml-kem.d.ts +14 -0
  110. package/dist/protocol/ml-kem.js +57 -0
  111. package/dist/protocol/pq-errors.d.ts +9 -0
  112. package/dist/protocol/pq-errors.js +23 -0
  113. package/dist/protocol/pq-warnings.d.ts +1 -0
  114. package/dist/protocol/pq-warnings.js +18 -0
  115. package/dist/protocol/presented-signals.d.ts +17 -0
  116. package/dist/protocol/presented-signals.js +92 -0
  117. package/dist/protocol/salt.d.ts +5 -0
  118. package/dist/protocol/salt.js +47 -0
  119. package/dist/protocol/seal.d.ts +58 -0
  120. package/dist/protocol/seal.js +220 -0
  121. package/dist/protocol/signal.d.ts +54 -0
  122. package/dist/protocol/signal.js +266 -0
  123. package/dist/protocol/status.d.ts +41 -0
  124. package/dist/protocol/status.js +64 -0
  125. package/dist/protocol/structures.d.ts +359 -0
  126. package/dist/protocol/structures.js +296 -0
  127. package/dist/protocol/transcript.d.ts +61 -0
  128. package/dist/protocol/transcript.js +319 -0
  129. package/dist/protocol/wire.d.ts +212 -0
  130. package/dist/protocol/wire.js +161 -0
  131. package/dist/require-node.d.ts +1 -0
  132. package/dist/require-node.js +10 -0
  133. package/dist/screener/affordance.d.ts +1 -0
  134. package/dist/screener/affordance.js +2 -0
  135. package/dist/screener/classifier-selfcheck.d.ts +29 -0
  136. package/dist/screener/classifier-selfcheck.js +56 -0
  137. package/dist/screener/exfil.d.ts +11 -0
  138. package/dist/screener/exfil.js +45 -0
  139. package/dist/screener/gitleaks-rules.d.ts +9 -0
  140. package/dist/screener/gitleaks-rules.js +226 -0
  141. package/dist/screener/inbound.d.ts +25 -0
  142. package/dist/screener/inbound.js +102 -0
  143. package/dist/screener/injection-classifier-onnx.d.ts +20 -0
  144. package/dist/screener/injection-classifier-onnx.js +89 -0
  145. package/dist/screener/injection-classifier-wasm.d.ts +2 -0
  146. package/dist/screener/injection-classifier-wasm.js +97 -0
  147. package/dist/screener/injection-patterns.d.ts +8 -0
  148. package/dist/screener/injection-patterns.js +48 -0
  149. package/dist/screener/injection-windows.d.ts +9 -0
  150. package/dist/screener/injection-windows.js +37 -0
  151. package/dist/screener/language.d.ts +15 -0
  152. package/dist/screener/language.js +71 -0
  153. package/dist/screener/linear-regex.d.ts +8 -0
  154. package/dist/screener/linear-regex.js +27 -0
  155. package/dist/screener/model-installer.d.ts +14 -0
  156. package/dist/screener/model-installer.js +61 -0
  157. package/dist/screener/outbound.d.ts +19 -0
  158. package/dist/screener/outbound.js +62 -0
  159. package/dist/screener/sanitize.d.ts +44 -0
  160. package/dist/screener/sanitize.js +361 -0
  161. package/dist/screener/scan-variants.d.ts +5 -0
  162. package/dist/screener/scan-variants.js +146 -0
  163. package/dist/screener/screener-model-manifest.d.ts +16 -0
  164. package/dist/screener/screener-model-manifest.js +20 -0
  165. package/dist/screener/screener-state.d.ts +29 -0
  166. package/dist/screener/screener-state.js +119 -0
  167. package/dist/screener/secrets.d.ts +18 -0
  168. package/dist/screener/secrets.js +84 -0
  169. package/dist/screener/worker.d.ts +6 -0
  170. package/dist/screener/worker.js +83 -0
  171. package/dist/setup.d.ts +9 -0
  172. package/dist/setup.js +252 -0
  173. package/dist/shipped-issuer-list.d.ts +1 -0
  174. package/dist/shipped-issuer-list.js +3 -0
  175. package/dist/signals-text.d.ts +46 -0
  176. package/dist/signals-text.js +81 -0
  177. package/dist/verify-seal.d.ts +9 -0
  178. package/dist/verify-seal.js +30 -0
  179. package/hermes/plugin/__init__.py +1040 -0
  180. package/hermes/plugin/plugin.yaml +30 -0
  181. package/hermes/skills/cello-bridge-setup/SKILL.md +38 -0
  182. package/hermes/skills/cello-policy/SKILL.md +44 -0
  183. package/package.json +48 -16
  184. package/plugins/cello/.claude-plugin/plugin.json +19 -0
  185. package/plugins/cello/.mcp.json +7 -0
  186. package/plugins/cello/skills/cello/SKILL.md +117 -0
  187. package/dist/arg-parse.d.ts +0 -19
  188. package/dist/arg-parse.d.ts.map +0 -1
  189. package/dist/arg-parse.js +0 -29
  190. package/dist/arg-parse.js.map +0 -1
  191. package/dist/bin/cello.d.ts +0 -15
  192. package/dist/bin/cello.d.ts.map +0 -1
  193. package/dist/bin/cello.js +0 -110
  194. package/dist/bin/cello.js.map +0 -1
  195. package/dist/cli-args.d.ts +0 -62
  196. package/dist/cli-args.d.ts.map +0 -1
  197. package/dist/cli-args.js +0 -129
  198. package/dist/cli-args.js.map +0 -1
  199. package/dist/commands.d.ts +0 -196
  200. package/dist/commands.d.ts.map +0 -1
  201. package/dist/commands.js +0 -1544
  202. package/dist/commands.js.map +0 -1
  203. package/dist/hermes/assets.d.ts +0 -41
  204. package/dist/hermes/assets.d.ts.map +0 -1
  205. package/dist/hermes/assets.js +0 -2281
  206. package/dist/hermes/assets.js.map +0 -1
  207. package/dist/hermes/install-hermes.d.ts +0 -50
  208. package/dist/hermes/install-hermes.d.ts.map +0 -1
  209. package/dist/hermes/install-hermes.js +0 -232
  210. package/dist/hermes/install-hermes.js.map +0 -1
  211. package/dist/json-out.d.ts +0 -41
  212. package/dist/json-out.d.ts.map +0 -1
  213. package/dist/json-out.js +0 -59
  214. package/dist/json-out.js.map +0 -1
  215. package/dist/node-runtime-guard-init.d.ts +0 -6
  216. package/dist/node-runtime-guard-init.d.ts.map +0 -1
  217. package/dist/node-runtime-guard-init.js +0 -7
  218. package/dist/node-runtime-guard-init.js.map +0 -1
  219. package/dist/node-runtime-guard.d.ts +0 -48
  220. package/dist/node-runtime-guard.d.ts.map +0 -1
  221. package/dist/node-runtime-guard.js +0 -79
  222. package/dist/node-runtime-guard.js.map +0 -1
  223. package/dist/parity-commands.d.ts +0 -427
  224. package/dist/parity-commands.d.ts.map +0 -1
  225. package/dist/parity-commands.js +0 -953
  226. package/dist/parity-commands.js.map +0 -1
  227. package/dist/registry.d.ts +0 -120
  228. package/dist/registry.d.ts.map +0 -1
  229. package/dist/registry.js +0 -2169
  230. package/dist/registry.js.map +0 -1
  231. package/dist/screener-commands.d.ts +0 -85
  232. package/dist/screener-commands.d.ts.map +0 -1
  233. package/dist/screener-commands.js +0 -313
  234. package/dist/screener-commands.js.map +0 -1
@@ -0,0 +1,94 @@
1
+ // Identities and signatures. Everything is signed twice, Ed25519 and ML-DSA-44, and both must verify.
2
+ // An identity is the hash of both public keys, so post-quantum protection doesn't stop at an Ed25519 root.
3
+ import { ed25519 } from "@noble/curves/ed25519.js";
4
+ import { sha256 } from "@noble/hashes/sha2.js";
5
+ import { randomBytes, webcrypto } from "node:crypto";
6
+ import { ML_DSA_ALGORITHM, ML_DSA_PUBLIC_KEY_BYTES, ML_DSA_SEED_BYTES, ML_DSA_SIGNATURE_BYTES, mlDsaGenerateSeed, mlDsaProviderFromSeed, } from "./ml-dsa.js";
7
+ import { exact } from "./encode.js";
8
+ import { identityBytes } from "./structures.js";
9
+ export const ED25519_SEED_BYTES = 32;
10
+ export const ED25519_PUBLIC_KEY_BYTES = 32;
11
+ export const ED25519_SIGNATURE_BYTES = 64;
12
+ // Each signed artifact has its own context, so a signature can't be moved from one kind to another.
13
+ export const CONTEXTS = [
14
+ "cello-register",
15
+ "cello-agent-auth",
16
+ "cello-visit",
17
+ "cello-server-auth",
18
+ "cello-session-offer",
19
+ "cello-session-accept",
20
+ "cello-session-refuse",
21
+ "cello-agent-encryption-key",
22
+ "cello-session-greeting",
23
+ "cello-session-confirm",
24
+ "cello-session-assignment",
25
+ "cello-entry",
26
+ "cello-ack",
27
+ "cello-delivery-ack",
28
+ "cello-seal-request",
29
+ "cello-seal-certificate",
30
+ "cello-seal-log-head",
31
+ "cello-seal-key-binding",
32
+ "cello-agent-status",
33
+ "cello-agent-status-witness",
34
+ "cello-channel-record",
35
+ "cello-channel-info",
36
+ "cello-channel-post",
37
+ "cello-channel-post-ack",
38
+ "cello-channel-state",
39
+ "cello-channel-member-key",
40
+ "cello-channel-roster",
41
+ "cello-channel-key-entry",
42
+ "cello-signal",
43
+ "cello-issuer-list",
44
+ ];
45
+ export function frame(context, bytes) {
46
+ if (!CONTEXTS.includes(context))
47
+ throw new Error(`unknown signing context: ${String(context)}`);
48
+ const ctx = new TextEncoder().encode(context);
49
+ const framed = new Uint8Array(ctx.length + 1 + bytes.length);
50
+ framed.set(ctx, 0);
51
+ framed[ctx.length] = 0x00;
52
+ framed.set(bytes, ctx.length + 1);
53
+ return framed;
54
+ }
55
+ export function identityId(pub) {
56
+ exact("Ed25519 public key", pub.ed, ED25519_PUBLIC_KEY_BYTES);
57
+ exact("ML-DSA public key", pub.pq, ML_DSA_PUBLIC_KEY_BYTES);
58
+ return sha256(identityBytes(pub));
59
+ }
60
+ export function generateIdentitySeeds() {
61
+ return { ed: new Uint8Array(randomBytes(ED25519_SEED_BYTES)), pq: mlDsaGenerateSeed() };
62
+ }
63
+ export async function signerFromSeeds(seeds) {
64
+ exact("Ed25519 seed", seeds.ed, ED25519_SEED_BYTES);
65
+ exact("ML-DSA seed", seeds.pq, ML_DSA_SEED_BYTES);
66
+ const edSeed = seeds.ed.slice();
67
+ const pqProvider = await mlDsaProviderFromSeed(seeds.pq);
68
+ const publicIdentity = { ed: ed25519.getPublicKey(edSeed), pq: await pqProvider.getPublicKey() };
69
+ return {
70
+ publicIdentity,
71
+ id: identityId(publicIdentity),
72
+ async sign(context, bytes) {
73
+ const framed = frame(context, bytes);
74
+ return { ed: ed25519.sign(framed, edSeed), pq: await pqProvider.sign(framed) };
75
+ },
76
+ };
77
+ }
78
+ // Never throws: every bad input is a refusal, and the caller names its own reason.
79
+ export async function verifySignature(pub, context, bytes, signature) {
80
+ if (pub.ed?.length !== ED25519_PUBLIC_KEY_BYTES || pub.pq?.length !== ML_DSA_PUBLIC_KEY_BYTES)
81
+ return false;
82
+ if (signature.ed?.length !== ED25519_SIGNATURE_BYTES || signature.pq?.length !== ML_DSA_SIGNATURE_BYTES)
83
+ return false;
84
+ try {
85
+ const framed = frame(context, bytes);
86
+ if (!ed25519.verify(signature.ed, framed, pub.ed, { zip215: false }))
87
+ return false;
88
+ const key = await webcrypto.subtle.importKey("raw-public", new Uint8Array(pub.pq), ML_DSA_ALGORITHM, false, ["verify"]);
89
+ return await webcrypto.subtle.verify(ML_DSA_ALGORITHM, key, new Uint8Array(signature.pq), framed);
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ }
@@ -0,0 +1,56 @@
1
+ import { type PublicIdentity } from "./identity.ts";
2
+ export declare const ISSUER_ENTRY_DOMAIN = "cello-issuer-entry-v1";
3
+ export declare const ISSUER_LIST_DOMAIN = "cello-issuer-list-v1";
4
+ export declare const SIGNED_ISSUER_LIST_DOMAIN = "cello-signed-issuer-list-v1";
5
+ export declare const REQUIRED_ROOT_SIGNATURES = 2;
6
+ export declare const ROOT_NAMES: readonly ["enclave", "kms", "paper"];
7
+ export type RootName = (typeof ROOT_NAMES)[number];
8
+ export type RootAlgorithm = "p256" | "ed25519";
9
+ export interface RootKey {
10
+ name: RootName;
11
+ algorithm: RootAlgorithm;
12
+ publicKey: Uint8Array;
13
+ }
14
+ export declare class RootKeysNotConfigured extends Error {
15
+ readonly code = "root_keys_not_configured";
16
+ }
17
+ export declare function rootKeysFrom(config: Readonly<Record<RootName, Omit<RootKey, "name"> | null | undefined>>): readonly RootKey[];
18
+ export interface IssuerEntry {
19
+ name: string;
20
+ ed: Uint8Array;
21
+ pq: Uint8Array;
22
+ expires_at: number;
23
+ }
24
+ export interface IssuerList {
25
+ issued_at: number;
26
+ expires_at: number;
27
+ issuers: readonly IssuerEntry[];
28
+ }
29
+ export declare function encodeIssuerEntry(entry: IssuerEntry): Uint8Array;
30
+ export declare function encodeIssuerList(list: IssuerList): Uint8Array;
31
+ export declare function decodeIssuerList(bytes: Uint8Array): IssuerList;
32
+ export interface SignedIssuerList {
33
+ listBytes: Uint8Array;
34
+ signatures: Readonly<Record<RootName, Uint8Array | null>>;
35
+ }
36
+ export declare function encodeSignedIssuerList(signed: SignedIssuerList): Uint8Array;
37
+ export declare function readSignedIssuerList(file: Uint8Array): SignedIssuerList;
38
+ export declare const issuerListSigningMessage: (listBytes: Uint8Array) => Uint8Array;
39
+ export interface RootSigner {
40
+ root: RootName;
41
+ sign(message: Uint8Array): Promise<Uint8Array>;
42
+ }
43
+ export declare function addRootSignature(existing: SignedIssuerList | {
44
+ listBytes: Uint8Array;
45
+ }, signer: RootSigner, roots: readonly RootKey[]): Promise<SignedIssuerList>;
46
+ export type IssuerListFault = "malformed" | "unknown_format" | "not_enough_signatures" | "expired";
47
+ export type IssuerListCheck = {
48
+ ok: true;
49
+ list: IssuerList;
50
+ } | {
51
+ ok: false;
52
+ fault: IssuerListFault;
53
+ message: string;
54
+ };
55
+ export declare function verifyIssuerList(file: Uint8Array, roots: readonly RootKey[], now: number): Promise<IssuerListCheck>;
56
+ export declare function recognisedIssuer(list: IssuerList, issuer: PublicIdentity, issuerAddress: string, now: number): IssuerEntry | null;
@@ -0,0 +1,193 @@
1
+ // The signed list of recognised issuers. It decides trust, not DNS or certificates: any two of three root keys sign it.
2
+ // Roots sign one classical signature each, because a Secure Enclave key can only be P-256.
3
+ import { ed25519 } from "@noble/curves/ed25519.js";
4
+ import { webcrypto } from "node:crypto";
5
+ import { decodeCbor, encodeCbor } from "./cbor.js";
6
+ import { equalBytes, toHex } from "./encode.js";
7
+ import { ED25519_PUBLIC_KEY_BYTES, frame } from "./identity.js";
8
+ import { ML_DSA_PUBLIC_KEY_BYTES } from "./ml-dsa.js";
9
+ import { UnknownFormat, assertFlat } from "./structures.js";
10
+ export const ISSUER_ENTRY_DOMAIN = "cello-issuer-entry-v1";
11
+ export const ISSUER_LIST_DOMAIN = "cello-issuer-list-v1";
12
+ export const SIGNED_ISSUER_LIST_DOMAIN = "cello-signed-issuer-list-v1";
13
+ export const REQUIRED_ROOT_SIGNATURES = 2;
14
+ const MAX_ISSUER_LIST_BYTES = 1_048_576;
15
+ const MAX_ENTRY_BYTES = 4_096;
16
+ const P256_PUBLIC_KEY_BYTES = 65;
17
+ const ROOT_SIGNATURE_BYTES = 64;
18
+ const MAX_EPOCH_SECONDS = 100_000_000_000;
19
+ const ISSUER_DOMAIN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/;
20
+ // Slot order in the signed file, and in the configured keys.
21
+ export const ROOT_NAMES = ["enclave", "kms", "paper"];
22
+ export class RootKeysNotConfigured extends Error {
23
+ code = "root_keys_not_configured";
24
+ }
25
+ // Trusts nothing unless all three are present, distinct and the right shape. The algorithm comes from here, never from a signed file.
26
+ export function rootKeysFrom(config) {
27
+ const keys = ROOT_NAMES.map((name) => {
28
+ const key = config[name];
29
+ if (!key)
30
+ throw new RootKeysNotConfigured(`root key "${name}" isn't configured, so no issuer list can be trusted`);
31
+ if (name === "enclave" && key.algorithm !== "p256")
32
+ throw new RootKeysNotConfigured("the enclave root key must be P-256");
33
+ const width = key.algorithm === "p256" ? P256_PUBLIC_KEY_BYTES : key.algorithm === "ed25519" ? ED25519_PUBLIC_KEY_BYTES : null;
34
+ if (width === null || !(key.publicKey instanceof Uint8Array) || key.publicKey.length !== width)
35
+ throw new RootKeysNotConfigured(`root key "${name}" isn't a valid ${String(key.algorithm)} public key`);
36
+ return { name, algorithm: key.algorithm, publicKey: key.publicKey };
37
+ });
38
+ if (new Set(keys.map((key) => toHex(key.publicKey))).size !== keys.length)
39
+ throw new RootKeysNotConfigured("two root slots hold the same key, so one key could count twice");
40
+ return keys;
41
+ }
42
+ function seconds(name, value) {
43
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || value >= MAX_EPOCH_SECONDS)
44
+ throw new RangeError(`${name} must be whole epoch seconds, got ${String(value)}`);
45
+ return value > 0xffffffff ? BigInt(value) : value;
46
+ }
47
+ const readSeconds = (name, value) => {
48
+ const asNumber = typeof value === "bigint" ? Number(value) : value;
49
+ seconds(name, asNumber);
50
+ return asNumber;
51
+ };
52
+ export function encodeIssuerEntry(entry) {
53
+ if (typeof entry.name !== "string" || !ISSUER_DOMAIN.test(entry.name))
54
+ throw new RangeError("an issuer's name must be its domain, in lowercase");
55
+ if (!(entry.ed instanceof Uint8Array) || entry.ed.length !== ED25519_PUBLIC_KEY_BYTES)
56
+ throw new RangeError(`an issuer's Ed25519 key must be ${ED25519_PUBLIC_KEY_BYTES} bytes`);
57
+ if (!(entry.pq instanceof Uint8Array) || entry.pq.length !== ML_DSA_PUBLIC_KEY_BYTES)
58
+ throw new RangeError(`an issuer's ML-DSA key must be ${ML_DSA_PUBLIC_KEY_BYTES} bytes`);
59
+ return new Uint8Array(encodeCbor([ISSUER_ENTRY_DOMAIN, entry.name, entry.ed, entry.pq, seconds("expires_at", entry.expires_at)]));
60
+ }
61
+ function decodeIssuerEntry(bytes) {
62
+ if (bytes.length > MAX_ENTRY_BYTES)
63
+ throw new RangeError(`an issuer entry can't be over ${MAX_ENTRY_BYTES} bytes`);
64
+ assertFlat(bytes, 5);
65
+ const [domain, name, ed, pq, expiresAt] = decodeCbor(bytes);
66
+ if (domain !== ISSUER_ENTRY_DOMAIN)
67
+ throw new UnknownFormat(`${ISSUER_ENTRY_DOMAIN} was expected`);
68
+ if (!(ed instanceof Uint8Array) || !(pq instanceof Uint8Array))
69
+ throw new RangeError("an issuer entry needs both public keys");
70
+ const entry = { name: name, ed: new Uint8Array(ed), pq: new Uint8Array(pq), expires_at: readSeconds("expires_at", expiresAt) };
71
+ if (!equalBytes(encodeIssuerEntry(entry), bytes))
72
+ throw new RangeError("this issuer entry's bytes aren't canonical");
73
+ return entry;
74
+ }
75
+ // Each entry is bytes in a slot of a flat array, so nothing nested reaches the decoder.
76
+ export function encodeIssuerList(list) {
77
+ if (list.expires_at <= list.issued_at)
78
+ throw new RangeError("an issuer list must expire after it's issued");
79
+ const names = new Set();
80
+ const keys = new Set();
81
+ for (const entry of list.issuers) {
82
+ names.add(entry.name);
83
+ keys.add(toHex(entry.ed));
84
+ keys.add(toHex(entry.pq));
85
+ }
86
+ if (names.size !== list.issuers.length || keys.size !== list.issuers.length * 2)
87
+ throw new RangeError("an issuer list can't name an issuer or a key twice");
88
+ return new Uint8Array(encodeCbor([ISSUER_LIST_DOMAIN, seconds("issued_at", list.issued_at), seconds("expires_at", list.expires_at), ...list.issuers.map(encodeIssuerEntry)]));
89
+ }
90
+ export function decodeIssuerList(bytes) {
91
+ if (bytes.length > MAX_ISSUER_LIST_BYTES)
92
+ throw new RangeError(`an issuer list can't be over ${MAX_ISSUER_LIST_BYTES} bytes`);
93
+ assertFlat(bytes, null);
94
+ const items = decodeCbor(bytes);
95
+ if (items.length < 3)
96
+ throw new RangeError("an issuer list needs its dates");
97
+ if (items[0] !== ISSUER_LIST_DOMAIN)
98
+ throw new UnknownFormat(`${ISSUER_LIST_DOMAIN} was expected`);
99
+ const issuers = items.slice(3).map((item) => {
100
+ if (!(item instanceof Uint8Array))
101
+ throw new RangeError("each issuer must be its own bytes");
102
+ return decodeIssuerEntry(new Uint8Array(item));
103
+ });
104
+ const list = { issued_at: readSeconds("issued_at", items[1]), expires_at: readSeconds("expires_at", items[2]), issuers };
105
+ if (!equalBytes(encodeIssuerList(list), bytes))
106
+ throw new RangeError("this issuer list's bytes aren't canonical");
107
+ return list;
108
+ }
109
+ export function encodeSignedIssuerList(signed) {
110
+ return new Uint8Array(encodeCbor([SIGNED_ISSUER_LIST_DOMAIN, signed.listBytes, ...ROOT_NAMES.map((name) => signed.signatures[name])]));
111
+ }
112
+ export function readSignedIssuerList(file) {
113
+ if (file.length > MAX_ISSUER_LIST_BYTES + 512)
114
+ throw new RangeError("a signed issuer list is too long");
115
+ assertFlat(file, 2 + ROOT_NAMES.length);
116
+ const [domain, listBytes, ...slots] = decodeCbor(file);
117
+ if (domain !== SIGNED_ISSUER_LIST_DOMAIN)
118
+ throw new UnknownFormat(`${SIGNED_ISSUER_LIST_DOMAIN} was expected`);
119
+ if (!(listBytes instanceof Uint8Array))
120
+ throw new RangeError("a signed issuer list needs its list");
121
+ const slot = (i) => {
122
+ const value = slots[i];
123
+ if (value === null)
124
+ return null;
125
+ if (!(value instanceof Uint8Array) || value.length !== ROOT_SIGNATURE_BYTES)
126
+ throw new RangeError(`a root signature must be ${ROOT_SIGNATURE_BYTES} bytes, r then s`);
127
+ return new Uint8Array(value);
128
+ };
129
+ const signed = { listBytes: new Uint8Array(listBytes), signatures: { enclave: slot(0), kms: slot(1), paper: slot(2) } };
130
+ if (!equalBytes(encodeSignedIssuerList(signed), file))
131
+ throw new RangeError("this signed issuer list's bytes aren't canonical");
132
+ return signed;
133
+ }
134
+ export const issuerListSigningMessage = (listBytes) => frame("cello-issuer-list", listBytes);
135
+ async function rootSignatureVerifies(key, message, signature) {
136
+ try {
137
+ if (key.algorithm === "ed25519")
138
+ return ed25519.verify(signature, message, key.publicKey, { zip215: false });
139
+ const imported = await webcrypto.subtle.importKey("raw", new Uint8Array(key.publicKey), { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
140
+ return await webcrypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, imported, new Uint8Array(signature), new Uint8Array(message));
141
+ }
142
+ catch {
143
+ return false;
144
+ }
145
+ }
146
+ // Adds one root's signature to a new or partly signed file, and refuses one that doesn't verify against that root.
147
+ export async function addRootSignature(existing, signer, roots) {
148
+ const key = rootKeysFrom(asConfig(roots)).find((candidate) => candidate.name === signer.root);
149
+ if (!key)
150
+ throw new RootKeysNotConfigured(`no root is named ${String(signer.root)}`);
151
+ decodeIssuerList(existing.listBytes);
152
+ const signature = await signer.sign(issuerListSigningMessage(existing.listBytes));
153
+ if (!(signature instanceof Uint8Array) || signature.length !== ROOT_SIGNATURE_BYTES || !(await rootSignatureVerifies(key, issuerListSigningMessage(existing.listBytes), signature))) {
154
+ throw new Error(`that signature doesn't verify against the ${signer.root} root key. Nothing was written.`);
155
+ }
156
+ const before = "signatures" in existing ? existing.signatures : { enclave: null, kms: null, paper: null };
157
+ return { listBytes: existing.listBytes, signatures: { ...before, [signer.root]: signature } };
158
+ }
159
+ const asConfig = (roots) => ({
160
+ enclave: roots.find((root) => root.name === "enclave") ?? null,
161
+ kms: roots.find((root) => root.name === "kms") ?? null,
162
+ paper: roots.find((root) => root.name === "paper") ?? null,
163
+ });
164
+ // A bad root configuration throws: that's this installation's fault, never the file's, and it must not read as a bad list.
165
+ export async function verifyIssuerList(file, roots, now) {
166
+ const keys = rootKeysFrom(asConfig(roots));
167
+ let signed;
168
+ let list;
169
+ try {
170
+ signed = readSignedIssuerList(file);
171
+ list = decodeIssuerList(signed.listBytes);
172
+ }
173
+ catch (err) {
174
+ return { ok: false, fault: err instanceof UnknownFormat ? "unknown_format" : "malformed", message: err instanceof Error ? err.message : String(err) };
175
+ }
176
+ const message = issuerListSigningMessage(signed.listBytes);
177
+ let valid = 0;
178
+ for (const key of keys) {
179
+ const signature = signed.signatures[key.name];
180
+ if (signature && (await rootSignatureVerifies(key, message, signature)))
181
+ valid += 1;
182
+ }
183
+ if (valid < REQUIRED_ROOT_SIGNATURES)
184
+ return { ok: false, fault: "not_enough_signatures", message: `this list has ${valid} valid root signature${valid === 1 ? "" : "s"}, and it needs ${REQUIRED_ROOT_SIGNATURES}` };
185
+ if (list.expires_at <= now)
186
+ return { ok: false, fault: "expired", message: `this issuer list expired at ${list.expires_at}` };
187
+ return { ok: true, list };
188
+ }
189
+ // Matches both keys and the domain the signal states, exactly, so a listed issuer can't sign under another's name.
190
+ // Null means unknown, or expired from the list.
191
+ export function recognisedIssuer(list, issuer, issuerAddress, now) {
192
+ return list.issuers.find((entry) => entry.name === issuerAddress && equalBytes(entry.ed, issuer.ed) && equalBytes(entry.pq, issuer.pq) && entry.expires_at > now) ?? null;
193
+ }
@@ -0,0 +1,6 @@
1
+ import { type RootAlgorithm, type RootKey, type RootName } from "./issuer-list.ts";
2
+ export declare const PRODUCTION_ROOT_KEYS: Readonly<Record<RootName, {
3
+ algorithm: RootAlgorithm;
4
+ publicKey: Uint8Array;
5
+ } | null>>;
6
+ export declare const productionRootKeys: () => readonly RootKey[];
@@ -0,0 +1,10 @@
1
+ // The public halves of the three root keys, shipped in the client. Made on 6 November 2026: enclave on Andre's Mac,
2
+ // KMS in cello-infra (keyring cello-root, key issuer-list-root, version 1, HSM), paper sealed with Andre's passphrase.
3
+ import { rootKeysFrom } from "./issuer-list.js";
4
+ const hex = (value) => new Uint8Array(Buffer.from(value, "hex"));
5
+ export const PRODUCTION_ROOT_KEYS = {
6
+ enclave: { algorithm: "p256", publicKey: hex("04cc234a1b150da2ba91b6dde521a6fd1c54a0dfb64a6bcb471b2260934d8354e61d6a0fcc03a694c8c53bc88bc3da5b90280baee89072ab6f4c2371f466c5b81f") },
7
+ kms: { algorithm: "p256", publicKey: hex("0412ca53dc2d3087e3f369e0bbeb38e036558de41ffaf3df75405663f81b56b60582c76baeb575123ae9e5b1195311a43f4ad5dc5bbed5d4be60c175a54283e6a3") },
8
+ paper: { algorithm: "ed25519", publicKey: hex("7d05ff4e73879c4e1b7bb4a84f381c1aa4f7c550d6088004484c773efad3f5cc") },
9
+ };
10
+ export const productionRootKeys = () => rootKeysFrom(PRODUCTION_ROOT_KEYS);
@@ -0,0 +1,20 @@
1
+ export declare const SESSION_KEY_BYTES = 32;
2
+ export declare const SESSION_PQ_TRANSCRIPT_BYTES: number;
3
+ export interface SessionEphemeral {
4
+ secretKey: Uint8Array;
5
+ publicKey: Uint8Array;
6
+ mlKemSeed: Uint8Array;
7
+ mlKemPublic: Uint8Array;
8
+ }
9
+ export interface SessionSecrets {
10
+ contentKey: Uint8Array;
11
+ }
12
+ export declare function generateSessionEphemeral(): Promise<SessionEphemeral>;
13
+ export declare function destroySessionEphemeral(e: SessionEphemeral): void;
14
+ export declare function deriveSessionSecrets(opts: {
15
+ ownEphemeralSecret: Uint8Array;
16
+ peerEphemeralPublic: Uint8Array;
17
+ sessionId: Uint8Array;
18
+ extraSharedSecret: Uint8Array;
19
+ pqTranscript: Uint8Array;
20
+ }): SessionSecrets;
@@ -0,0 +1,88 @@
1
+ import { x25519 } from "@noble/curves/ed25519.js";
2
+ import { hkdf } from "@noble/hashes/hkdf.js";
3
+ import { sha256 } from "@noble/hashes/sha2.js";
4
+ import { mlKemGenerateSeed, mlKemKeypairFromSeed, ML_KEM_CIPHERTEXT_BYTES, ML_KEM_PUBLIC_KEY_BYTES, ML_KEM_SHARED_SECRET_BYTES, } from "./ml-kem.js";
5
+ const X25519_KEY_BYTES = 32;
6
+ export const SESSION_KEY_BYTES = 32;
7
+ export const SESSION_PQ_TRANSCRIPT_BYTES = ML_KEM_CIPHERTEXT_BYTES + ML_KEM_PUBLIC_KEY_BYTES;
8
+ const ENC = new TextEncoder();
9
+ const INFO_CONTENT_KEY = ENC.encode("cello-session-content-key");
10
+ export async function generateSessionEphemeral() {
11
+ const secretKey = x25519.utils.randomSecretKey();
12
+ const mlKemSeed = mlKemGenerateSeed();
13
+ const { publicKey: mlKemPublic } = await mlKemKeypairFromSeed(mlKemSeed);
14
+ return { secretKey, publicKey: x25519.getPublicKey(secretKey), mlKemSeed, mlKemPublic };
15
+ }
16
+ export function destroySessionEphemeral(e) {
17
+ e.secretKey.fill(0);
18
+ e.mlKemSeed.fill(0);
19
+ }
20
+ function isAllZero(b) {
21
+ let acc = 0;
22
+ for (const x of b)
23
+ acc |= x;
24
+ return acc === 0;
25
+ }
26
+ function lexLess(a, b) {
27
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
28
+ const x = a[i];
29
+ const y = b[i];
30
+ if (x !== y)
31
+ return x < y;
32
+ }
33
+ return a.length < b.length;
34
+ }
35
+ export function deriveSessionSecrets(opts) {
36
+ if (!(opts.extraSharedSecret instanceof Uint8Array) || opts.extraSharedSecret.length !== ML_KEM_SHARED_SECRET_BYTES) {
37
+ throw new Error(`key agreement: the ML-KEM shared secret must be ${ML_KEM_SHARED_SECRET_BYTES} bytes`);
38
+ }
39
+ if (!(opts.pqTranscript instanceof Uint8Array) || opts.pqTranscript.length !== SESSION_PQ_TRANSCRIPT_BYTES) {
40
+ throw new Error(`key agreement: the transcript must be ${SESSION_PQ_TRANSCRIPT_BYTES} bytes (ciphertext, then ML-KEM public key)`);
41
+ }
42
+ if (opts.peerEphemeralPublic.length !== X25519_KEY_BYTES) {
43
+ throw new Error(`key agreement: the peer X25519 public key must be ${X25519_KEY_BYTES} bytes`);
44
+ }
45
+ if (opts.ownEphemeralSecret.length !== X25519_KEY_BYTES) {
46
+ throw new Error(`key agreement: our X25519 secret must be ${X25519_KEY_BYTES} bytes`);
47
+ }
48
+ if (opts.peerEphemeralPublic[31] & 0x80) {
49
+ throw new Error("key agreement: the peer X25519 public key is non-canonical (bit 255 set, RFC 7748 section 5)");
50
+ }
51
+ if (opts.sessionId.length === 0) {
52
+ throw new Error("key agreement: the session id must not be empty");
53
+ }
54
+ let shared;
55
+ try {
56
+ shared = x25519.getSharedSecret(opts.ownEphemeralSecret, opts.peerEphemeralPublic);
57
+ }
58
+ catch (err) {
59
+ throw new Error("key agreement: the peer X25519 public key is invalid or a small-order point (RFC 7748 section 6.1)", { cause: err });
60
+ }
61
+ if (isAllZero(shared)) {
62
+ throw new Error("key agreement: the X25519 shared secret is all zeros (RFC 7748 section 6.1)");
63
+ }
64
+ const ownPublic = x25519.getPublicKey(opts.ownEphemeralSecret);
65
+ if (Buffer.compare(Buffer.from(ownPublic), Buffer.from(opts.peerEphemeralPublic)) === 0) {
66
+ throw new Error("key agreement: the peer sent back our own X25519 public key");
67
+ }
68
+ const [first, second] = lexLess(ownPublic, opts.peerEphemeralPublic)
69
+ ? [ownPublic, opts.peerEphemeralPublic]
70
+ : [opts.peerEphemeralPublic, ownPublic];
71
+ const extra = opts.extraSharedSecret;
72
+ const ikm = new Uint8Array(shared.length + extra.length);
73
+ ikm.set(shared, 0);
74
+ ikm.set(extra, shared.length);
75
+ const transcript = opts.pqTranscript;
76
+ const info = (label) => {
77
+ const out = new Uint8Array(label.length + first.length + second.length + transcript.length);
78
+ out.set(label, 0);
79
+ out.set(first, label.length);
80
+ out.set(second, label.length + first.length);
81
+ out.set(transcript, label.length + first.length + second.length);
82
+ return out;
83
+ };
84
+ const contentKey = hkdf(sha256, ikm, opts.sessionId, info(INFO_CONTENT_KEY), SESSION_KEY_BYTES);
85
+ ikm.fill(0);
86
+ shared.fill(0);
87
+ return { contentKey };
88
+ }
@@ -0,0 +1,16 @@
1
+ export declare const EMPTY_ROOT: Uint8Array;
2
+ export declare function leafHash(entryHash: Uint8Array): Uint8Array;
3
+ export declare function nodeHash(left: Uint8Array, right: Uint8Array): Uint8Array;
4
+ export declare class RunningMerkle {
5
+ #private;
6
+ constructor(size?: number, peaks?: Uint8Array[]);
7
+ static fromBytes(size: number, bytes: Uint8Array): RunningMerkle;
8
+ get size(): number;
9
+ toBytes(): Uint8Array;
10
+ nextLeafPath(): Uint8Array[];
11
+ append(entryHash: Uint8Array): Uint8Array;
12
+ root(): Uint8Array;
13
+ }
14
+ export declare function consistencyPath(entryHashes: readonly Uint8Array[], m: number): Uint8Array[];
15
+ export declare function verifyConsistency(m: number, n: number, rootM: Uint8Array, rootN: Uint8Array, path: readonly Uint8Array[]): boolean;
16
+ export declare function verifyInclusion(entryHash: Uint8Array, index: number, size: number, root: Uint8Array, path: readonly Uint8Array[]): boolean;
@@ -0,0 +1,166 @@
1
+ // A running Merkle root over a session's entries, with RFC 6962 hashing.
2
+ // It keeps only the tree's peaks, so a server can extend it without reading the whole log.
3
+ import { sha256 } from "@noble/hashes/sha2.js";
4
+ import { HASH_BYTES, equalBytes, exact } from "./encode.js";
5
+ export const EMPTY_ROOT = sha256(new Uint8Array(0));
6
+ export function leafHash(entryHash) {
7
+ exact("entry hash", entryHash, HASH_BYTES);
8
+ const buf = new Uint8Array(1 + HASH_BYTES);
9
+ buf[0] = 0x00;
10
+ buf.set(entryHash, 1);
11
+ return sha256(buf);
12
+ }
13
+ export function nodeHash(left, right) {
14
+ const buf = new Uint8Array(1 + HASH_BYTES * 2);
15
+ buf[0] = 0x01;
16
+ buf.set(left, 1);
17
+ buf.set(right, 1 + HASH_BYTES);
18
+ return sha256(buf);
19
+ }
20
+ export class RunningMerkle {
21
+ #size;
22
+ #peaks;
23
+ constructor(size = 0, peaks = []) {
24
+ let bits = 0;
25
+ for (let n = size; n > 0; n = Math.floor(n / 2))
26
+ bits += n % 2;
27
+ if (!Number.isSafeInteger(size) || size < 0 || peaks.length !== bits) {
28
+ throw new RangeError(`a tree of size ${size} has ${bits} peaks, got ${peaks.length}`);
29
+ }
30
+ this.#size = size;
31
+ this.#peaks = peaks.slice();
32
+ }
33
+ static fromBytes(size, bytes) {
34
+ if (bytes.length % HASH_BYTES !== 0)
35
+ throw new RangeError(`peaks must be multiples of ${HASH_BYTES} bytes`);
36
+ const peaks = [];
37
+ for (let at = 0; at < bytes.length; at += HASH_BYTES)
38
+ peaks.push(bytes.slice(at, at + HASH_BYTES));
39
+ return new RunningMerkle(size, peaks);
40
+ }
41
+ get size() {
42
+ return this.#size;
43
+ }
44
+ toBytes() {
45
+ const out = new Uint8Array(this.#peaks.length * HASH_BYTES);
46
+ this.#peaks.forEach((peak, i) => out.set(peak, i * HASH_BYTES));
47
+ return out;
48
+ }
49
+ // The proof that a leaf appended now sits in the tree: the peaks, smallest first.
50
+ nextLeafPath() {
51
+ return this.#peaks.slice().reverse();
52
+ }
53
+ append(entryHash) {
54
+ let hash = leafHash(entryHash);
55
+ for (let n = this.#size; n % 2 === 1; n = Math.floor(n / 2)) {
56
+ hash = nodeHash(this.#peaks.pop(), hash);
57
+ }
58
+ this.#peaks.push(hash);
59
+ this.#size += 1;
60
+ return this.root();
61
+ }
62
+ root() {
63
+ if (this.#peaks.length === 0)
64
+ return EMPTY_ROOT;
65
+ let root = this.#peaks[this.#peaks.length - 1];
66
+ for (let i = this.#peaks.length - 2; i >= 0; i--)
67
+ root = nodeHash(this.#peaks[i], root);
68
+ return root;
69
+ }
70
+ }
71
+ // A proof longer than this can't belong to any tree this code can count, so it's refused unread.
72
+ const MAX_PROOF_HASHES = 106;
73
+ function largestPowerOfTwoBelow(n) {
74
+ let k = 1;
75
+ while (k * 2 < n)
76
+ k *= 2;
77
+ return k;
78
+ }
79
+ function subtreeRoot(leaves) {
80
+ if (leaves.length === 1)
81
+ return leaves[0];
82
+ const k = largestPowerOfTwoBelow(leaves.length);
83
+ return nodeHash(subtreeRoot(leaves.slice(0, k)), subtreeRoot(leaves.slice(k)));
84
+ }
85
+ function subproof(m, leaves, whole) {
86
+ if (m === leaves.length)
87
+ return whole ? [] : [subtreeRoot(leaves)];
88
+ const k = largestPowerOfTwoBelow(leaves.length);
89
+ if (m <= k)
90
+ return [...subproof(m, leaves.slice(0, k), whole), subtreeRoot(leaves.slice(k))];
91
+ return [...subproof(m - k, leaves.slice(k), false), subtreeRoot(leaves.slice(0, k))];
92
+ }
93
+ // RFC 6962 2.1.2: shows the tree of the first m entries is a prefix of the tree of all of them.
94
+ export function consistencyPath(entryHashes, m) {
95
+ if (!Number.isSafeInteger(m) || m < 1 || m > entryHashes.length)
96
+ throw new RangeError(`no prefix of size ${m} in a tree of ${entryHashes.length}`);
97
+ return subproof(m, entryHashes.map(leafHash), true);
98
+ }
99
+ const isOdd = (n) => n % 2 === 1;
100
+ const half = (n) => Math.floor(n / 2);
101
+ // RFC 9162 2.1.4.2. Never throws: bad input just proves nothing.
102
+ export function verifyConsistency(m, n, rootM, rootN, path) {
103
+ if (!Number.isSafeInteger(m) || !Number.isSafeInteger(n) || m < 1 || m > n || path.length > MAX_PROOF_HASHES)
104
+ return false;
105
+ if (rootM.length !== HASH_BYTES || rootN.length !== HASH_BYTES || path.some((hash) => hash.length !== HASH_BYTES))
106
+ return false;
107
+ if (m === n)
108
+ return path.length === 0 && equalBytes(rootM, rootN);
109
+ let fn = m - 1;
110
+ let sn = n - 1;
111
+ while (isOdd(fn)) {
112
+ fn = half(fn);
113
+ sn = half(sn);
114
+ }
115
+ const hashes = fn === 0 ? [rootM, ...path] : [...path];
116
+ const first = hashes[0];
117
+ if (!first)
118
+ return false;
119
+ let fr = first;
120
+ let sr = first;
121
+ for (const c of hashes.slice(1)) {
122
+ if (sn === 0)
123
+ return false;
124
+ if (isOdd(fn) || fn === sn) {
125
+ fr = nodeHash(c, fr);
126
+ sr = nodeHash(c, sr);
127
+ while (!isOdd(fn) && fn !== 0) {
128
+ fn = half(fn);
129
+ sn = half(sn);
130
+ }
131
+ }
132
+ else {
133
+ sr = nodeHash(sr, c);
134
+ }
135
+ fn = half(fn);
136
+ sn = half(sn);
137
+ }
138
+ return sn === 0 && equalBytes(fr, rootM) && equalBytes(sr, rootN);
139
+ }
140
+ // RFC 9162 2.1.3.2: shows this entry sits at this index in a tree of this size. Never throws.
141
+ export function verifyInclusion(entryHash, index, size, root, path) {
142
+ if (!Number.isSafeInteger(index) || !Number.isSafeInteger(size) || index < 0 || index >= size || path.length > MAX_PROOF_HASHES)
143
+ return false;
144
+ if (entryHash.length !== HASH_BYTES || path.some((hash) => hash.length !== HASH_BYTES))
145
+ return false;
146
+ let fn = index;
147
+ let sn = size - 1;
148
+ let r = leafHash(entryHash);
149
+ for (const p of path) {
150
+ if (sn === 0)
151
+ return false;
152
+ if (isOdd(fn) || fn === sn) {
153
+ r = nodeHash(p, r);
154
+ while (!isOdd(fn) && fn !== 0) {
155
+ fn = half(fn);
156
+ sn = half(sn);
157
+ }
158
+ }
159
+ else {
160
+ r = nodeHash(r, p);
161
+ }
162
+ fn = half(fn);
163
+ sn = half(sn);
164
+ }
165
+ return sn === 0 && equalBytes(r, root);
166
+ }