@t3foundry/tasra-sdk 0.0.0-stage → 0.3.0-next.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 (322) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +94 -0
  4. package/README.md +137 -2
  5. package/SECURITY.md +115 -0
  6. package/dist/app/approvals.d.ts +50 -0
  7. package/dist/app/approvals.js +90 -0
  8. package/dist/app/authorization.d.ts +19 -0
  9. package/dist/app/authorization.js +20 -0
  10. package/dist/app/client.d.ts +231 -0
  11. package/dist/app/client.js +272 -0
  12. package/dist/app/creation.d.ts +73 -0
  13. package/dist/app/creation.js +77 -0
  14. package/dist/app/deployment.d.ts +36 -0
  15. package/dist/app/deployment.js +18 -0
  16. package/dist/app/identity.d.ts +211 -0
  17. package/dist/app/identity.js +287 -0
  18. package/dist/app/index.d.ts +22 -0
  19. package/dist/app/index.js +12 -0
  20. package/dist/app/manifest.d.ts +74 -0
  21. package/dist/app/manifest.js +120 -0
  22. package/dist/app/node.d.ts +30 -0
  23. package/dist/app/node.js +159 -0
  24. package/dist/app/ready-slot.d.ts +157 -0
  25. package/dist/app/ready-slot.js +199 -0
  26. package/dist/app/tasra-client.d.ts +125 -0
  27. package/dist/app/tasra-client.js +79 -0
  28. package/dist/app/viem.d.ts +10 -0
  29. package/dist/app/viem.js +32 -0
  30. package/dist/app/wallet.d.ts +126 -0
  31. package/dist/app/wallet.js +137 -0
  32. package/dist/auth/dpop.d.ts +86 -0
  33. package/dist/auth/dpop.js +142 -0
  34. package/dist/auth/holderProof.d.ts +102 -0
  35. package/dist/auth/holderProof.js +161 -0
  36. package/dist/auth/identityScope.d.ts +19 -0
  37. package/dist/auth/identityScope.js +82 -0
  38. package/dist/auth/index.d.ts +11 -0
  39. package/dist/auth/index.js +13 -0
  40. package/dist/auth/oid4vp.d.ts +230 -0
  41. package/dist/auth/oid4vp.js +780 -0
  42. package/dist/auth/rego/wasm/PINS.json +11 -0
  43. package/dist/auth/rego/wasm/keykeeper_rego_wasm.d.ts +76 -0
  44. package/dist/auth/rego/wasm/keykeeper_rego_wasm.js +379 -0
  45. package/dist/auth/rego/wasm/keykeeper_rego_wasm_bg.wasm +0 -0
  46. package/dist/auth/rego.d.ts +192 -0
  47. package/dist/auth/rego.js +492 -0
  48. package/dist/auth/verifier.d.ts +166 -0
  49. package/dist/auth/verifier.js +211 -0
  50. package/dist/chain/abis/accountantSetRegistry.d.ts +441 -0
  51. package/dist/chain/abis/accountantSetRegistry.js +574 -0
  52. package/dist/chain/abis/accountantSlashing.d.ts +2071 -0
  53. package/dist/chain/abis/accountantSlashing.js +2670 -0
  54. package/dist/chain/abis/bondingCurve.d.ts +398 -0
  55. package/dist/chain/abis/bondingCurve.js +521 -0
  56. package/dist/chain/abis/equivocationSlasher.d.ts +292 -0
  57. package/dist/chain/abis/equivocationSlasher.js +379 -0
  58. package/dist/chain/abis/fixedTasraPriceOracle.d.ts +52 -0
  59. package/dist/chain/abis/fixedTasraPriceOracle.js +72 -0
  60. package/dist/chain/abis/index.d.ts +12801 -0
  61. package/dist/chain/abis/index.js +64 -0
  62. package/dist/chain/abis/keeperShareRegistry.d.ts +519 -0
  63. package/dist/chain/abis/keeperShareRegistry.js +675 -0
  64. package/dist/chain/abis/keyRegistry.d.ts +2421 -0
  65. package/dist/chain/abis/keyRegistry.js +3114 -0
  66. package/dist/chain/abis/livenessRegistry.d.ts +402 -0
  67. package/dist/chain/abis/livenessRegistry.js +524 -0
  68. package/dist/chain/abis/mockEurc.d.ts +210 -0
  69. package/dist/chain/abis/mockEurc.js +276 -0
  70. package/dist/chain/abis/nodeRegistry.d.ts +1630 -0
  71. package/dist/chain/abis/nodeRegistry.js +2113 -0
  72. package/dist/chain/abis/platformExecutor.d.ts +328 -0
  73. package/dist/chain/abis/platformExecutor.js +429 -0
  74. package/dist/chain/abis/prevrandaoSaltBeacon.d.ts +16 -0
  75. package/dist/chain/abis/prevrandaoSaltBeacon.js +24 -0
  76. package/dist/chain/abis/serviceRegistry.d.ts +556 -0
  77. package/dist/chain/abis/serviceRegistry.js +719 -0
  78. package/dist/chain/abis/settlement.d.ts +1624 -0
  79. package/dist/chain/abis/settlement.js +2096 -0
  80. package/dist/chain/abis/tasraSwapRouter.d.ts +92 -0
  81. package/dist/chain/abis/tasraSwapRouter.js +122 -0
  82. package/dist/chain/abis/tasraToken.d.ts +455 -0
  83. package/dist/chain/abis/tasraToken.js +599 -0
  84. package/dist/chain/abis/tasraVestingVault.d.ts +165 -0
  85. package/dist/chain/abis/tasraVestingVault.js +215 -0
  86. package/dist/chain/abis/thresholdRandomBeacon.d.ts +378 -0
  87. package/dist/chain/abis/thresholdRandomBeacon.js +494 -0
  88. package/dist/chain/abis/treasury.d.ts +301 -0
  89. package/dist/chain/abis/treasury.js +390 -0
  90. package/dist/chain/abis/verifierSetRegistry.d.ts +445 -0
  91. package/dist/chain/abis/verifierSetRegistry.js +579 -0
  92. package/dist/chain/client.d.ts +212 -0
  93. package/dist/chain/client.js +576 -0
  94. package/dist/chain/commitmentRecovery.d.ts +21 -0
  95. package/dist/chain/commitmentRecovery.js +44 -0
  96. package/dist/chain/committeeClient.d.ts +102 -0
  97. package/dist/chain/committeeClient.js +137 -0
  98. package/dist/chain/deployments.d.ts +56 -0
  99. package/dist/chain/deployments.js +269 -0
  100. package/dist/chain/discovery.d.ts +49 -0
  101. package/dist/chain/discovery.js +107 -0
  102. package/dist/chain/events.d.ts +58 -0
  103. package/dist/chain/events.js +125 -0
  104. package/dist/chain/format.d.ts +25 -0
  105. package/dist/chain/format.js +51 -0
  106. package/dist/chain/index.d.ts +41 -0
  107. package/dist/chain/index.js +56 -0
  108. package/dist/chain/manifest.d.ts +165 -0
  109. package/dist/chain/manifest.js +132 -0
  110. package/dist/chain/network-profiles.json +75 -0
  111. package/dist/chain/networks.d.ts +73 -0
  112. package/dist/chain/networks.js +62 -0
  113. package/dist/chain/node.d.ts +44 -0
  114. package/dist/chain/node.js +176 -0
  115. package/dist/chain/offchain.d.ts +149 -0
  116. package/dist/chain/offchain.js +73 -0
  117. package/dist/chain/provisionRule.d.ts +164 -0
  118. package/dist/chain/provisionRule.js +212 -0
  119. package/dist/chain/registeredAgent.d.ts +64 -0
  120. package/dist/chain/registeredAgent.js +140 -0
  121. package/dist/chain/registeredOperation.d.ts +49 -0
  122. package/dist/chain/registeredOperation.js +136 -0
  123. package/dist/chain/registeredRelay.d.ts +206 -0
  124. package/dist/chain/registeredRelay.js +312 -0
  125. package/dist/chain/revertReason.d.ts +14 -0
  126. package/dist/chain/revertReason.js +62 -0
  127. package/dist/chain/ruleAmendment.d.ts +80 -0
  128. package/dist/chain/ruleAmendment.js +195 -0
  129. package/dist/chain/ruleAmendmentCore.d.ts +129 -0
  130. package/dist/chain/ruleAmendmentCore.js +152 -0
  131. package/dist/chain/ruleInput.d.ts +10 -0
  132. package/dist/chain/ruleInput.js +13 -0
  133. package/dist/chain/serviceIdentity.d.ts +176 -0
  134. package/dist/chain/serviceIdentity.js +237 -0
  135. package/dist/chain/serviceProfiles.d.ts +39 -0
  136. package/dist/chain/serviceProfiles.js +74 -0
  137. package/dist/chain/services.d.ts +141 -0
  138. package/dist/chain/services.js +79 -0
  139. package/dist/chain/slotClient.d.ts +55 -0
  140. package/dist/chain/slotClient.js +62 -0
  141. package/dist/chain/slotSeed.d.ts +31 -0
  142. package/dist/chain/slotSeed.js +98 -0
  143. package/dist/chain/write.d.ts +431 -0
  144. package/dist/chain/write.js +958 -0
  145. package/dist/client/client.d.ts +112 -0
  146. package/dist/client/client.js +111 -0
  147. package/dist/client/index.d.ts +3 -0
  148. package/dist/client/index.js +2 -0
  149. package/dist/client/session.d.ts +67 -0
  150. package/dist/client/session.js +238 -0
  151. package/dist/committee/client.d.ts +284 -0
  152. package/dist/committee/client.js +351 -0
  153. package/dist/committee/dual-sign.d.ts +110 -0
  154. package/dist/committee/dual-sign.js +202 -0
  155. package/dist/committee/ecdsa.d.ts +36 -0
  156. package/dist/committee/ecdsa.js +45 -0
  157. package/dist/committee/extraction.d.ts +82 -0
  158. package/dist/committee/extraction.js +96 -0
  159. package/dist/committee/index.d.ts +19 -0
  160. package/dist/committee/index.js +13 -0
  161. package/dist/committee/oauth.d.ts +51 -0
  162. package/dist/committee/oauth.js +90 -0
  163. package/dist/committee/receipts.d.ts +51 -0
  164. package/dist/committee/receipts.js +59 -0
  165. package/dist/committee/request.d.ts +264 -0
  166. package/dist/committee/request.js +305 -0
  167. package/dist/committee/token.d.ts +274 -0
  168. package/dist/committee/token.js +418 -0
  169. package/dist/crypto/constants.d.ts +10 -0
  170. package/dist/crypto/constants.js +32 -0
  171. package/dist/crypto/detect.d.ts +20 -0
  172. package/dist/crypto/detect.js +44 -0
  173. package/dist/crypto/envelope.d.ts +60 -0
  174. package/dist/crypto/envelope.js +243 -0
  175. package/dist/crypto/frost.d.ts +49 -0
  176. package/dist/crypto/frost.js +152 -0
  177. package/dist/crypto/hex.d.ts +7 -0
  178. package/dist/crypto/hex.js +24 -0
  179. package/dist/crypto/ibe-blob.d.ts +114 -0
  180. package/dist/crypto/ibe-blob.js +208 -0
  181. package/dist/crypto/ibe.d.ts +88 -0
  182. package/dist/crypto/ibe.js +262 -0
  183. package/dist/crypto/index.d.ts +12 -0
  184. package/dist/crypto/index.js +12 -0
  185. package/dist/crypto/kem.d.ts +55 -0
  186. package/dist/crypto/kem.js +241 -0
  187. package/dist/decryption/client.d.ts +64 -0
  188. package/dist/decryption/client.js +82 -0
  189. package/dist/decryption/index.d.ts +2 -0
  190. package/dist/decryption/index.js +2 -0
  191. package/dist/errors.d.ts +124 -0
  192. package/dist/errors.js +167 -0
  193. package/dist/index.d.ts +43 -0
  194. package/dist/index.js +98 -0
  195. package/dist/keys/index.d.ts +1 -0
  196. package/dist/keys/index.js +4 -0
  197. package/dist/keys/node-client.d.ts +27 -0
  198. package/dist/keys/node-client.js +97 -0
  199. package/dist/oid4vp/binding.d.ts +76 -0
  200. package/dist/oid4vp/binding.js +118 -0
  201. package/dist/oid4vp/did-web.d.ts +49 -0
  202. package/dist/oid4vp/did-web.js +57 -0
  203. package/dist/oid4vp/index.d.ts +9 -0
  204. package/dist/oid4vp/index.js +10 -0
  205. package/dist/oid4vp/jose.d.ts +166 -0
  206. package/dist/oid4vp/jose.js +242 -0
  207. package/dist/oid4vp/jwe.d.ts +30 -0
  208. package/dist/oid4vp/jwe.js +93 -0
  209. package/dist/oid4vp/oid4vci.d.ts +84 -0
  210. package/dist/oid4vp/oid4vci.js +85 -0
  211. package/dist/oid4vp/request-object.d.ts +109 -0
  212. package/dist/oid4vp/request-object.js +96 -0
  213. package/dist/oid4vp/sd-jwt.d.ts +177 -0
  214. package/dist/oid4vp/sd-jwt.js +208 -0
  215. package/dist/oid4vp/verifier-agent.d.ts +161 -0
  216. package/dist/oid4vp/verifier-agent.js +132 -0
  217. package/dist/oid4vp/wallet.d.ts +116 -0
  218. package/dist/oid4vp/wallet.js +108 -0
  219. package/dist/recipient/store.d.ts +67 -0
  220. package/dist/recipient/store.js +98 -0
  221. package/dist/signing/ecdsa.d.ts +49 -0
  222. package/dist/signing/ecdsa.js +79 -0
  223. package/dist/signing/frost.d.ts +88 -0
  224. package/dist/signing/frost.js +145 -0
  225. package/dist/signing/index.d.ts +4 -0
  226. package/dist/signing/index.js +3 -0
  227. package/dist/slots/faucet.d.ts +23 -0
  228. package/dist/slots/faucet.js +35 -0
  229. package/dist/slots/index.d.ts +2 -0
  230. package/dist/slots/index.js +4 -0
  231. package/dist/verifier-agent/index.d.ts +241 -0
  232. package/dist/verifier-agent/index.js +411 -0
  233. package/docs/DEVELOPER-EXPERIENCE.md +62 -0
  234. package/docs/README.md +33 -0
  235. package/docs/access-control.md +76 -0
  236. package/docs/ai-development.md +292 -0
  237. package/docs/api.md +338 -0
  238. package/docs/application-api.md +335 -0
  239. package/docs/architecture.md +65 -0
  240. package/docs/basics.md +48 -0
  241. package/docs/capabilities.md +86 -0
  242. package/docs/chain.md +153 -0
  243. package/docs/compatibility.md +36 -0
  244. package/docs/consumer-migrations.md +80 -0
  245. package/docs/create-slot.md +104 -0
  246. package/docs/document-signing.md +243 -0
  247. package/docs/encrypted-notes.md +129 -0
  248. package/docs/encryption.md +100 -0
  249. package/docs/errors.md +76 -0
  250. package/docs/flows.md +289 -0
  251. package/docs/fuji.md +127 -0
  252. package/docs/funding.md +126 -0
  253. package/docs/getting-started.md +94 -0
  254. package/docs/glossary.md +44 -0
  255. package/docs/installation.md +132 -0
  256. package/docs/manage-slot.md +95 -0
  257. package/docs/native-approvals.md +124 -0
  258. package/docs/prerequisites.md +137 -0
  259. package/docs/read-slot.md +41 -0
  260. package/docs/reference/README.md +30 -0
  261. package/docs/reference/app-node.md +102 -0
  262. package/docs/reference/app.md +1737 -0
  263. package/docs/reference/chain-node.md +159 -0
  264. package/docs/reference/chain.md +3609 -0
  265. package/docs/reference/committee.md +2176 -0
  266. package/docs/reference/main.md +4068 -0
  267. package/docs/reference/oid4vp.md +2547 -0
  268. package/docs/reference/verifier-agent.md +498 -0
  269. package/docs/shared-account.md +168 -0
  270. package/docs/signing-and-encryption.md +52 -0
  271. package/docs/signing.md +172 -0
  272. package/examples/committee-slot.ts +16 -0
  273. package/examples/connect-fuji.ts +41 -0
  274. package/examples/connect-network.ts +14 -0
  275. package/examples/credential-approvals.ts +46 -0
  276. package/examples/document-signing/README.md +59 -0
  277. package/examples/document-signing/backend.ts +132 -0
  278. package/examples/document-signing/build.mjs +19 -0
  279. package/examples/document-signing/config.ts +34 -0
  280. package/examples/document-signing/gitignore.template +9 -0
  281. package/examples/document-signing/model.ts +140 -0
  282. package/examples/document-signing/network.ts +58 -0
  283. package/examples/document-signing/package.json +25 -0
  284. package/examples/document-signing/public/index.html +27 -0
  285. package/examples/document-signing/public/sample.pdf +31 -0
  286. package/examples/document-signing/public/styles.css +531 -0
  287. package/examples/document-signing/server.ts +358 -0
  288. package/examples/document-signing/setup.ts +111 -0
  289. package/examples/document-signing/store.ts +105 -0
  290. package/examples/document-signing/tsconfig.json +24 -0
  291. package/examples/document-signing/verify.ts +24 -0
  292. package/examples/document-signing/web/app.ts +312 -0
  293. package/examples/document-signing/web/preview.ts +67 -0
  294. package/examples/document-signing/web/wallet.ts +146 -0
  295. package/examples/document-signing/workflow.test.ts +228 -0
  296. package/examples/document-signing/workflow.ts +241 -0
  297. package/examples/document-signing.ts +96 -0
  298. package/examples/encrypted-notes.ts +86 -0
  299. package/examples/ethers-signer.ts +204 -0
  300. package/examples/fund-slot.ts +73 -0
  301. package/examples/getting-started.ts +25 -0
  302. package/examples/learning-authorize.ts +23 -0
  303. package/examples/learning-cancel-slot.ts +11 -0
  304. package/examples/learning-context.ts +28 -0
  305. package/examples/learning-create-slot.ts +25 -0
  306. package/examples/learning-read-slot.ts +8 -0
  307. package/examples/learning-renew-slot.ts +12 -0
  308. package/examples/learning-sign.ts +8 -0
  309. package/examples/live-config.ts +71 -0
  310. package/examples/minimal.ts +6 -0
  311. package/examples/native-approvals.ts +57 -0
  312. package/examples/network.ts +58 -0
  313. package/examples/offline.ts +16 -0
  314. package/examples/personal-vault.ts +20 -0
  315. package/examples/provision-slot.ts +47 -0
  316. package/examples/shared-account.ts +46 -0
  317. package/examples/slot-address.ts +13 -0
  318. package/examples/slot-creation.ts +9 -0
  319. package/examples/tutorial-negative.ts +26 -0
  320. package/examples/tutorial-support.ts +76 -0
  321. package/examples/viem-account.ts +203 -0
  322. package/package.json +303 -4
@@ -0,0 +1,241 @@
1
+ // BLS12-381 threshold KEM - mirrors the reference KEM implementation.
2
+ //
3
+ // Protocol: ElGamal in G2 with a ChaCha20-Poly1305 envelope.
4
+ //
5
+ // Encrypt(mpk, identity, message):
6
+ // r ← Fr (random)
7
+ // U = r * G2 (ephemeral public key)
8
+ // S = r * mpk (shared secret)
9
+ // k = SHA256(KEM_DOMAIN || "key" || len(identity) || identity || compress(S))
10
+ // n = SHA256(KEM_DOMAIN || "nonce" || compress(U))[0..12]
11
+ // ct = ChaCha20Poly1305(k, n, aad=identity).encrypt(message)
12
+ // return { U, n, ct }
13
+ //
14
+ // Decrypt(msk, {U, n, ct}, identity):
15
+ // S = msk * U
16
+ // k = SHA256(KEM_DOMAIN || "key" || len(identity) || identity || compress(S))
17
+ // return ChaCha20Poly1305(k, n, aad=identity).decrypt(ct)
18
+ //
19
+ // AssembleKey([(id₁,sk₁), ..., (idₖ,skₖ)]):
20
+ // msk = Σ λᵢ * skᵢ (Lagrange interpolation at 0 over Fr)
21
+ import { chacha20poly1305 } from '@noble/ciphers/chacha';
22
+ import { bls12_381 } from '@noble/curves/bls12-381';
23
+ import { sha256 } from '@noble/hashes/sha256';
24
+ import { randomBytes } from '@noble/hashes/utils';
25
+ import { KEM_DOMAIN } from './constants.js';
26
+ const { Fr } = bls12_381.fields;
27
+ const G1 = bls12_381.G1;
28
+ const G2 = bls12_381.G2;
29
+ const Fp12 = bls12_381.fields.Fp12;
30
+ // Fr scalar helpers
31
+ // Convert 32-byte little-endian encoding (the reference scalar encoding)
32
+ // to bigint. Throws if the value is >= Fr.ORDER (non-canonical).
33
+ export function leToScalar(leBytes) {
34
+ if (leBytes.length !== 32) {
35
+ throw new Error(`leToScalar: expected 32 bytes, got ${leBytes.length}`);
36
+ }
37
+ let n = 0n;
38
+ for (let i = leBytes.length - 1; i >= 0; i--) {
39
+ n = (n << 8n) | BigInt(leBytes[i]);
40
+ }
41
+ if (n >= Fr.ORDER) {
42
+ throw new Error('leToScalar: non-canonical scalar (>= field order)');
43
+ }
44
+ return n;
45
+ }
46
+ // Convert Fr bigint to 32-byte little-endian (matching the reference scalar encoding).
47
+ export function scalarToLe(n) {
48
+ const canonical = ((n % Fr.ORDER) + Fr.ORDER) % Fr.ORDER;
49
+ const out = new Uint8Array(32);
50
+ let v = canonical;
51
+ for (let i = 0; i < 32; i++) {
52
+ out[i] = Number(v & 0xffn);
53
+ v >>= 8n;
54
+ }
55
+ return out;
56
+ }
57
+ // Sample a uniformly random non-zero Fr scalar.
58
+ function randomScalar() {
59
+ // Sample 64 bytes (2times field width) for uniformity, then reduce mod ORDER.
60
+ // Retry on the astronomically unlikely event of getting zero.
61
+ while (true) {
62
+ const bytes = randomBytes(64);
63
+ let n = 0n;
64
+ for (const b of bytes)
65
+ n = (n << 8n) | BigInt(b);
66
+ const r = n % Fr.ORDER;
67
+ if (r !== 0n)
68
+ return r;
69
+ }
70
+ }
71
+ // KDF
72
+ // Derive 32-byte ChaCha20-Poly1305 key from identity and shared G2 point.
73
+ // Mirrors the reference derive_key exactly:
74
+ // SHA256(KEM_DOMAIN || "key" || u64_le(identity.len) || identity || compress(shared))
75
+ function deriveKey(identity, sharedCompressed) {
76
+ const lenBuf = new Uint8Array(8);
77
+ new DataView(lenBuf.buffer).setBigUint64(0, BigInt(identity.length), true);
78
+ const h = sha256.create();
79
+ h.update(KEM_DOMAIN);
80
+ h.update(new TextEncoder().encode('key'));
81
+ h.update(lenBuf);
82
+ h.update(identity);
83
+ h.update(sharedCompressed);
84
+ return h.digest();
85
+ }
86
+ // Derive 12-byte AEAD nonce from the ephemeral G2 point U.
87
+ // Mirrors the reference derive_nonce exactly:
88
+ // SHA256(KEM_DOMAIN || "nonce" || u_bytes)[0..12]
89
+ function deriveNonce(uBytes) {
90
+ const h = sha256.create();
91
+ h.update(KEM_DOMAIN);
92
+ h.update(new TextEncoder().encode('nonce'));
93
+ h.update(uBytes);
94
+ return h.digest().slice(0, 12);
95
+ }
96
+ // Lagrange
97
+ // Lagrange basis polynomial evaluated at 0 for participant `id`
98
+ // over index set `xs`. Mirrors the reference lagrange_at_zero exactly.
99
+ function lagrangeAtZero(id, xs) {
100
+ const xi = id;
101
+ let num = 1n;
102
+ let den = 1n;
103
+ for (const xj of xs) {
104
+ if (xj === xi)
105
+ continue;
106
+ num = Fr.mul(num, Fr.neg(xj)); // num *= -xj
107
+ den = Fr.mul(den, Fr.sub(xi, xj)); // den *= (xi - xj)
108
+ }
109
+ return Fr.mul(num, Fr.inv(den));
110
+ }
111
+ // Core operations
112
+ // Assemble master secret key from k raw shard scalars via Lagrange interpolation.
113
+ // Mirrors the reference assemble_key. Returns 32-byte LE-encoded msk.
114
+ //
115
+ // Security note: the returned msk is the full threshold private key.
116
+ // Keep it in memory only for the session duration.
117
+ export function assembleKey(shards) {
118
+ if (shards.length === 0) {
119
+ throw new Error('assembleKey: no shards provided');
120
+ }
121
+ const ids = shards.map(s => s.id);
122
+ const sortedIds = [...ids].sort((a, b) => a - b);
123
+ for (let i = 0; i < sortedIds.length - 1; i++) {
124
+ if (sortedIds[i] === sortedIds[i + 1]) {
125
+ throw new Error(`assembleKey: duplicate identifier ${sortedIds[i]}`);
126
+ }
127
+ }
128
+ const xs = shards.map(s => BigInt(s.id));
129
+ let msk = 0n;
130
+ for (const shard of shards) {
131
+ const scalar = leToScalar(shard.bytes); // validates canonical range
132
+ const lambda = lagrangeAtZero(BigInt(shard.id), xs);
133
+ msk = Fr.add(msk, Fr.mul(scalar, lambda));
134
+ }
135
+ return scalarToLe(msk);
136
+ }
137
+ // Encrypt plaintext to a group's master public key.
138
+ //
139
+ // mpkBytes: 96-byte compressed G2 point (from GET /v1/keys/{slot}/public)
140
+ // identity: AEAD additional authenticated data - typically the room/slot
141
+ // identifier the receiver must replay on decryption
142
+ export function encrypt(mpkBytes, identity, plaintext) {
143
+ const mpk = G2.ProjectivePoint.fromHex(mpkBytes);
144
+ const r = randomScalar();
145
+ const uPoint = G2.ProjectivePoint.BASE.multiply(r);
146
+ const uBytes = uPoint.toRawBytes(true); // 96 bytes compressed
147
+ const shared = mpk.multiply(r);
148
+ const sharedBytes = shared.toRawBytes(true); // 96 bytes compressed
149
+ const aeadKey = deriveKey(identity, sharedBytes);
150
+ const nonce = deriveNonce(uBytes);
151
+ const aeadCt = chacha20poly1305(aeadKey, nonce, identity).encrypt(plaintext);
152
+ return { u: uBytes, nonce, aeadCt };
153
+ }
154
+ // Decrypt ciphertext using the assembled master secret key.
155
+ // mskBytes: 32-byte LE scalar (output of assembleKey).
156
+ // Throws on authentication failure or malformed input.
157
+ /**
158
+ * Decrypt with a reconstructed BLS master secret key and the original associated data. Reject malformed keys or failed authentication.
159
+ *
160
+ * @param mskBytes - 32-byte little-endian master secret scalar.
161
+ * @param ct - Group ciphertext to decrypt.
162
+ * @param identity - Original associated data supplied during encryption.
163
+ */
164
+ export function decryptWithMasterKey(mskBytes, ct, identity) {
165
+ const msk = leToScalar(mskBytes); // validates canonical range
166
+ const u = G2.ProjectivePoint.fromHex(ct.u);
167
+ const shared = u.multiply(msk);
168
+ const sharedBytes = shared.toRawBytes(true);
169
+ const aeadKey = deriveKey(identity, sharedBytes);
170
+ try {
171
+ return chacha20poly1305(aeadKey, ct.nonce, identity).decrypt(ct.aeadCt);
172
+ }
173
+ catch {
174
+ throw new Error('decryptWithMasterKey: AEAD authentication failed');
175
+ }
176
+ }
177
+ // Verify a partial decryption share via the pairing equation
178
+ // e(Y_i^{G1}, U) == e(g1, D_i), where Y_i^{G1} = sk_i*g1.
179
+ // Mirrors the reference verify_share. Returns false on malformed input.
180
+ /**
181
+ * Check a partial decryption against its supplied verifying share using a pairing. Return false for missing or malformed material.
182
+ *
183
+ * @param share - Partial decryption and its public verifying share.
184
+ * @param u - 96-byte compressed ephemeral G2 key from the ciphertext.
185
+ */
186
+ export function verifyDecryptShare(share, u) {
187
+ try {
188
+ if (!share.verifyingShare || share.verifyingShare.length !== 144)
189
+ return false;
190
+ const yiG1 = G1.ProjectivePoint.fromHex(share.verifyingShare.subarray(96, 144));
191
+ const U = G2.ProjectivePoint.fromHex(u);
192
+ const di = G2.ProjectivePoint.fromHex(share.decryptionShare);
193
+ return Fp12.eql(bls12_381.pairing(yiG1, U), bls12_381.pairing(G1.ProjectivePoint.BASE, di));
194
+ }
195
+ catch {
196
+ return false;
197
+ }
198
+ }
199
+ // Combine k partial decryption shares into the plaintext. With `verify`, each
200
+ // share is pairing-checked first (identifiable abort) and a bad share throws
201
+ // naming its id. Mirrors the reference combine_decrypt.
202
+ /**
203
+ * Interpolate distinct partial decryptions and authenticate the plaintext. Enable verify to check each share before combining; the caller supplies a sufficient threshold.
204
+ *
205
+ * @param shares - Distinct participant shares sufficient for the slot threshold.
206
+ * @param ct - Ciphertext associated with the partial decryptions.
207
+ * @param identity - Original encryption associated data.
208
+ * @param opts - Whether to verify each partial decryption before combining.
209
+ */
210
+ export function combineDecryptShares(shares, ct, identity, opts = {}) {
211
+ if (shares.length === 0)
212
+ throw new Error('combineDecryptShares: no shares provided');
213
+ const sortedIds = shares.map(s => s.id).sort((a, b) => a - b);
214
+ for (let i = 0; i < sortedIds.length - 1; i++) {
215
+ if (sortedIds[i] === sortedIds[i + 1]) {
216
+ throw new Error(`combineDecryptShares: duplicate identifier ${sortedIds[i]}`);
217
+ }
218
+ }
219
+ if (opts.verify) {
220
+ for (const s of shares) {
221
+ if (!verifyDecryptShare(s, ct.u)) {
222
+ throw new Error(`combineDecryptShares: invalid decryption share from identifier ${s.id}`);
223
+ }
224
+ }
225
+ }
226
+ const xs = shares.map(s => BigInt(s.id));
227
+ let dPoint = G2.ProjectivePoint.ZERO;
228
+ for (const s of shares) {
229
+ const di = G2.ProjectivePoint.fromHex(s.decryptionShare);
230
+ const lambda = lagrangeAtZero(BigInt(s.id), xs);
231
+ if (lambda !== 0n)
232
+ dPoint = dPoint.add(di.multiply(lambda));
233
+ }
234
+ const aeadKey = deriveKey(identity, dPoint.toRawBytes(true)); // compress(S)
235
+ try {
236
+ return chacha20poly1305(aeadKey, ct.nonce, identity).decrypt(ct.aeadCt);
237
+ }
238
+ catch {
239
+ throw new Error('combineDecryptShares: AEAD authentication failed');
240
+ }
241
+ }
@@ -0,0 +1,64 @@
1
+ import { type Ciphertext } from '../crypto/kem.js';
2
+ /** A node's BLS identifier + its libp2p PeerId, for the custody decrypting set. */
3
+ export interface BlsPeer {
4
+ /** BLS threshold participant identifier. */
5
+ id: number;
6
+ /** Network peer identifier for that participant. */
7
+ peerId: string;
8
+ }
9
+ /** JWT-authorized group decryption coordinated by one keeper, including participant selection. */
10
+ export interface DecryptCustodyOpts {
11
+ /** Keeper HTTP base URL. */
12
+ nodeUrl: string;
13
+ /** Compact bearer JWT authorizing the request. */
14
+ jwt: string;
15
+ /** 32-byte slot identifier. */
16
+ slotId: string;
17
+ /** Ciphertext to decrypt. */
18
+ ciphertext: Ciphertext;
19
+ /** AEAD additional-authenticated-data (the identity the envelope was bound to). */
20
+ identity: Uint8Array;
21
+ /** BLS identifiers (k..n, distinct) to run the ceremony with. */
22
+ decryptingSet: number[];
23
+ /** The libp2p peers for those identifiers. */
24
+ blsPeers: BlsPeer[];
25
+ /** 64-byte Ed25519 user signature, required iff the slot has an owner pubkey. */
26
+ userSignature?: Uint8Array;
27
+ /** Pin the ciphertext epoch; a rotated slot returns 410. */
28
+ ciphertextEpoch?: number;
29
+ /** Optional 20-byte operator address to pin the intended keeper. */
30
+ targetKeykeeper?: string;
31
+ /** Request identifier used to correlate or resume the operation. */
32
+ requestId?: string;
33
+ }
34
+ /**
35
+ * Decrypt via the custody path: the node runs the whole k-of-n ceremony and
36
+ * returns the plaintext (one HTTP round-trip).
37
+ *
38
+ * @param opts - Keeper endpoint, JWT, ciphertext, associated data and decryption participants.
39
+ */
40
+ export declare function decryptCustody(opts: DecryptCustodyOpts): Promise<Uint8Array>;
41
+ /** Keeper endpoints, JWT and ciphertext for combining partial decryptions in the caller. */
42
+ export interface ShardDecryptOpts {
43
+ /** Base URLs of at least k nodes to fetch partial decryptions from. */
44
+ nodeUrls: string[];
45
+ /** Compact bearer JWT authorizing the request. */
46
+ jwt: string;
47
+ /** 32-byte slot identifier. */
48
+ slotId: string;
49
+ /** Ciphertext to decrypt. */
50
+ ciphertext: Ciphertext;
51
+ /** Original encryption associated data. */
52
+ identity: Uint8Array;
53
+ /** Expected key epoch of the ciphertext; used to detect rotation. */
54
+ ciphertextEpoch?: number;
55
+ /** Pairing-verify each share before combining (identifiable abort). Default false. */
56
+ verifyShares?: boolean;
57
+ }
58
+ /**
59
+ * Decrypt via the shard-delivery path: fetch a partial decryption from each
60
+ * node and combine the shares locally (the master key is never assembled).
61
+ *
62
+ * @param opts - Keeper endpoints, JWT, ciphertext and optional per-share verification.
63
+ */
64
+ export declare function decryptWithShardDelivery(opts: ShardDecryptOpts): Promise<Uint8Array>;
@@ -0,0 +1,82 @@
1
+ // BLS threshold decryption - HTTP clients for the two node paths:
2
+ // - custody (POST /v1/decrypt) - node coordinates, returns plaintext
3
+ // - shard-delivery (POST /v1/shards/decrypt) - CLIENT fans out to k nodes and
4
+ // combines partial shares locally
5
+ //
6
+ // Ciphertext fields are base64 (standard, padded); key ids are bare hex; the
7
+ // `identity` AAD is sent as a UTF-8 string (the node uses its bytes as the AEAD
8
+ // AAD / audit key). Identity bytes that aren't valid UTF-8 are not supported on
9
+ // the wire.
10
+ import { combineDecryptShares } from '../crypto/kem.js';
11
+ import { base64Encode, base64Decode } from '../crypto/envelope.js';
12
+ import { bytesToHex as toHex } from '@noble/hashes/utils';
13
+ import { httpError } from '../errors.js';
14
+ const strip0x = (s) => (s.startsWith('0x') ? s.slice(2) : s);
15
+ const base = (u) => u.replace(/\/$/, '');
16
+ function ctToWire(ct) {
17
+ return { u: base64Encode(ct.u), nonce: base64Encode(ct.nonce), aead_ct: base64Encode(ct.aeadCt) };
18
+ }
19
+ async function nodePost(url, jwt, body, requestId) {
20
+ const headers = {
21
+ 'Content-Type': 'application/json',
22
+ Authorization: `Bearer ${jwt}`,
23
+ };
24
+ if (requestId)
25
+ headers['x-request-id'] = requestId;
26
+ const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify(body) });
27
+ if (!res.ok)
28
+ throw await httpError(res, url, `POST ${url}`);
29
+ return res.json();
30
+ }
31
+ /**
32
+ * Decrypt via the custody path: the node runs the whole k-of-n ceremony and
33
+ * returns the plaintext (one HTTP round-trip).
34
+ *
35
+ * @param opts - Keeper endpoint, JWT, ciphertext, associated data and decryption participants.
36
+ */
37
+ export async function decryptCustody(opts) {
38
+ const body = {
39
+ key_slot_id: strip0x(opts.slotId),
40
+ ciphertext: ctToWire(opts.ciphertext),
41
+ identity: new TextDecoder().decode(opts.identity),
42
+ decrypting_set: opts.decryptingSet,
43
+ bls_peers: opts.blsPeers.map(p => ({ id: p.id, peer_id: p.peerId })),
44
+ };
45
+ if (opts.userSignature)
46
+ body.user_signature = toHex(opts.userSignature);
47
+ if (opts.ciphertextEpoch !== undefined)
48
+ body.ciphertext_epoch = opts.ciphertextEpoch;
49
+ if (opts.targetKeykeeper)
50
+ body.target_keykeeper = strip0x(opts.targetKeykeeper);
51
+ const d = await nodePost(`${base(opts.nodeUrl)}/v1/decrypt`, opts.jwt, body, opts.requestId);
52
+ return base64Decode(d.plaintext);
53
+ }
54
+ async function partialDecrypt(nodeUrl, jwt, slotId, ct, identity, ciphertextEpoch) {
55
+ const body = {
56
+ key_slot_id: strip0x(slotId),
57
+ ciphertext: ctToWire(ct),
58
+ identity: new TextDecoder().decode(identity),
59
+ };
60
+ if (ciphertextEpoch !== undefined)
61
+ body.ciphertext_epoch = ciphertextEpoch;
62
+ const d = await nodePost(`${base(nodeUrl)}/v1/shards/decrypt`, jwt, body);
63
+ return {
64
+ id: Number(d.identifier),
65
+ decryptionShare: base64Decode(d.decryption_share),
66
+ verifyingShare: base64Decode(d.verifying_share),
67
+ };
68
+ }
69
+ /**
70
+ * Decrypt via the shard-delivery path: fetch a partial decryption from each
71
+ * node and combine the shares locally (the master key is never assembled).
72
+ *
73
+ * @param opts - Keeper endpoints, JWT, ciphertext and optional per-share verification.
74
+ */
75
+ export async function decryptWithShardDelivery(opts) {
76
+ if (opts.nodeUrls.length === 0)
77
+ throw new Error('decryptWithShardDelivery: no node URLs');
78
+ const shares = await Promise.all(opts.nodeUrls.map(u => partialDecrypt(u, opts.jwt, opts.slotId, opts.ciphertext, opts.identity, opts.ciphertextEpoch)));
79
+ return combineDecryptShares(shares, opts.ciphertext, opts.identity, {
80
+ verify: opts.verifyShares ?? false,
81
+ });
82
+ }
@@ -0,0 +1,2 @@
1
+ export { decryptCustody, decryptWithShardDelivery } from './client.js';
2
+ export type { DecryptCustodyOpts, ShardDecryptOpts, BlsPeer } from './client.js';
@@ -0,0 +1,2 @@
1
+ // BLS threshold decryption over the node fleet (custody + shard-delivery).
2
+ export { decryptCustody, decryptWithShardDelivery } from './client.js';
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Base class for typed SDK failures with a retryability hint.
3
+ * Some SDK errors extend plain Error, including relay and agent-session
4
+ * reconciliation errors. A retryable failure does not make a write safe to repeat.
5
+ */
6
+ export declare class TasraError extends Error {
7
+ /** `false` when retrying the identical request cannot succeed. */
8
+ readonly retryable: boolean;
9
+ constructor(message: string, opts?: {
10
+ retryable?: boolean;
11
+ cause?: unknown;
12
+ });
13
+ }
14
+ /**
15
+ * A node or verifier answered with a non-2xx status. `body` is the response body,
16
+ * truncated to 200 characters - enough to carry the service's own error text
17
+ * without dumping a page of HTML into a log line.
18
+ *
19
+ * 5xx and 429 are marked retryable; other 4xx are not.
20
+ */
21
+ export declare class TasraHttpError extends TasraError {
22
+ /** HTTP status code returned by the service. */
23
+ readonly status: number;
24
+ /** Service URL that failed. */
25
+ readonly url: string;
26
+ /** Response body retained as diagnostic information. */
27
+ readonly body: string;
28
+ constructor(args: {
29
+ status: number;
30
+ url: string;
31
+ body?: string;
32
+ message?: string;
33
+ retryable?: boolean;
34
+ });
35
+ }
36
+ /**
37
+ * The credential was rejected: 401 or 403. Never retryable - the same token will
38
+ * be refused again. Re-claim (redeem a fresh credential or renewal) instead.
39
+ */
40
+ export declare class AuthDeniedError extends TasraHttpError {
41
+ constructor(args: {
42
+ status: number;
43
+ url: string;
44
+ body?: string;
45
+ message?: string;
46
+ });
47
+ }
48
+ /**
49
+ * The request never got an HTTP answer - DNS failure, connection refused,
50
+ * timeout, CORS. Retryable: the service may simply not be up yet.
51
+ */
52
+ export declare class NodeUnreachableError extends TasraError {
53
+ /** Endpoint that could not be reached. */
54
+ readonly url: string;
55
+ constructor(args: {
56
+ url: string;
57
+ message?: string;
58
+ cause?: unknown;
59
+ });
60
+ }
61
+ /**
62
+ * Fewer than the required number of participants answered - too few shards to
63
+ * assemble a key, too few verifier signatures for a quorum, too few nodes for a
64
+ * signing set.
65
+ *
66
+ * `reasons` carries one entry per participant that failed, which is what makes
67
+ * this actionable: previously those were collected and then discarded, so a DNS
68
+ * failure and a cold DKG produced the same opaque message.
69
+ */
70
+ export declare class ThresholdNotMetError extends TasraError {
71
+ /** How many participants answered successfully. */
72
+ readonly got: number;
73
+ /** How many were needed. */
74
+ readonly need: number;
75
+ /** Why each failing participant failed, one string per participant. */
76
+ readonly reasons: readonly string[];
77
+ constructor(args: {
78
+ got: number;
79
+ need: number;
80
+ reasons?: readonly string[];
81
+ message?: string;
82
+ retryable?: boolean;
83
+ });
84
+ }
85
+ /**
86
+ * The slot was re-keyed (rotated) since the key in hand was assembled, so that
87
+ * key cannot read anything encrypted after the rotation. Retryable: re-assemble
88
+ * at the new epoch and try again - the managed {@link Session} does this for you.
89
+ */
90
+ export declare class SlotRotatedError extends TasraError {
91
+ /** The epoch the caller's key/envelope belongs to. */
92
+ readonly expected: number;
93
+ /** The slot's current on-chain/served epoch. */
94
+ readonly actual: number;
95
+ constructor(args: {
96
+ expected: number;
97
+ actual: number;
98
+ slotId?: string;
99
+ message?: string;
100
+ });
101
+ }
102
+ /**
103
+ * Build the right error for a non-2xx `Response`: {@link AuthDeniedError} for
104
+ * 401/403, otherwise {@link TasraHttpError}. Reads and truncates the body.
105
+ *
106
+ * `label` prefixes the message so it names the operation rather than just the
107
+ * URL (`'committee/sign'` to `committee/sign to HTTP 403: ...`).
108
+ */
109
+ export declare function httpError(res: Response, url: string, label?: string): Promise<TasraHttpError>;
110
+ /**
111
+ * True when `e` is an auth rejection - i.e. retrying is pointless, re-claim
112
+ * instead. Keyed on the HTTP status rather than the class, so it also catches
113
+ * subclasses that carry their own name (e.g. `CommitteeAuthorizeError`).
114
+ *
115
+ * @param e - Caught value to classify as an authorization rejection.
116
+ */
117
+ export declare function isAuthDenied(e: unknown): e is TasraHttpError;
118
+ /**
119
+ * True when a typed failure may be transient. Errors outside the TasraError
120
+ * hierarchy return false. This hint does not make a write safe to repeat.
121
+ *
122
+ * @param e - Caught value to inspect for a retryable Tasra error.
123
+ */
124
+ export declare function isRetryable(e: unknown): boolean;
package/dist/errors.js ADDED
@@ -0,0 +1,167 @@
1
+ // Error taxonomy.
2
+ //
3
+ // Before this existed the SDK threw bare `Error` from ~90 sites, so the only way
4
+ // to tell "the JWT was denied" from "the node is unreachable" from "not enough
5
+ // nodes answered" was to regex `err.message`. The SDK was doing that to itself in
6
+ // node-client.ts. Message-matching breaks on any wording change, and it cannot
7
+ // carry structure - a caller that wants the HTTP status, or the per-node reasons
8
+ // behind a failed assembly, had nowhere to read them from.
9
+ //
10
+ // Every class here extends `Error`, so existing `catch (e) { e.message }` code is
11
+ // unaffected; the messages keep their previous shape too. What's new is that you
12
+ // can branch on the type and read fields off it:
13
+ //
14
+ // try {
15
+ // await session.decrypt(envelope)
16
+ // } catch (e) {
17
+ // if (e instanceof AuthDeniedError) return reclaimCredential() // never retry
18
+ // if (e instanceof ThresholdNotMetError) {
19
+ // console.warn(`only ${e.got}/${e.need} nodes answered:`, e.reasons)
20
+ // return retryLater() // transient
21
+ // }
22
+ // throw e
23
+ // }
24
+ //
25
+ // `retryable` is the coarse signal for callers that don't want to enumerate
26
+ // types: false means the request will fail identically on retry (a denied or
27
+ // expired credential, a malformed rule), true means it might not.
28
+ /**
29
+ * Base class for typed SDK failures with a retryability hint.
30
+ * Some SDK errors extend plain Error, including relay and agent-session
31
+ * reconciliation errors. A retryable failure does not make a write safe to repeat.
32
+ */
33
+ export class TasraError extends Error {
34
+ /** `false` when retrying the identical request cannot succeed. */
35
+ retryable;
36
+ constructor(message, opts) {
37
+ super(message, opts?.cause !== undefined ? { cause: opts.cause } : undefined);
38
+ this.name = new.target.name;
39
+ this.retryable = opts?.retryable ?? false;
40
+ }
41
+ }
42
+ /**
43
+ * A node or verifier answered with a non-2xx status. `body` is the response body,
44
+ * truncated to 200 characters - enough to carry the service's own error text
45
+ * without dumping a page of HTML into a log line.
46
+ *
47
+ * 5xx and 429 are marked retryable; other 4xx are not.
48
+ */
49
+ export class TasraHttpError extends TasraError {
50
+ /** HTTP status code returned by the service. */
51
+ status;
52
+ /** Service URL that failed. */
53
+ url;
54
+ /** Response body retained as diagnostic information. */
55
+ body;
56
+ constructor(args) {
57
+ const body = args.body ?? '';
58
+ super(args.message ?? `${args.url} → HTTP ${args.status}${body ? `: ${body}` : ''}`, {
59
+ retryable: args.retryable ?? (args.status >= 500 || args.status === 429),
60
+ });
61
+ this.status = args.status;
62
+ this.url = args.url;
63
+ this.body = body;
64
+ }
65
+ }
66
+ /**
67
+ * The credential was rejected: 401 or 403. Never retryable - the same token will
68
+ * be refused again. Re-claim (redeem a fresh credential or renewal) instead.
69
+ */
70
+ export class AuthDeniedError extends TasraHttpError {
71
+ constructor(args) {
72
+ super({ ...args, retryable: false });
73
+ }
74
+ }
75
+ /**
76
+ * The request never got an HTTP answer - DNS failure, connection refused,
77
+ * timeout, CORS. Retryable: the service may simply not be up yet.
78
+ */
79
+ export class NodeUnreachableError extends TasraError {
80
+ /** Endpoint that could not be reached. */
81
+ url;
82
+ constructor(args) {
83
+ super(args.message ?? `${args.url} is unreachable`, { retryable: true, cause: args.cause });
84
+ this.url = args.url;
85
+ }
86
+ }
87
+ /**
88
+ * Fewer than the required number of participants answered - too few shards to
89
+ * assemble a key, too few verifier signatures for a quorum, too few nodes for a
90
+ * signing set.
91
+ *
92
+ * `reasons` carries one entry per participant that failed, which is what makes
93
+ * this actionable: previously those were collected and then discarded, so a DNS
94
+ * failure and a cold DKG produced the same opaque message.
95
+ */
96
+ export class ThresholdNotMetError extends TasraError {
97
+ /** How many participants answered successfully. */
98
+ got;
99
+ /** How many were needed. */
100
+ need;
101
+ /** Why each failing participant failed, one string per participant. */
102
+ reasons;
103
+ constructor(args) {
104
+ const reasons = args.reasons ?? [];
105
+ super(args.message ??
106
+ `threshold not met: ${args.got}/${args.need} participants answered` +
107
+ (reasons.length ? ` — ${reasons.join('; ')}` : ''),
108
+ // Transient by default: a cold DKG or a restarting node clears on its own.
109
+ // Callers that know better (all-auth failures) pass retryable: false.
110
+ { retryable: args.retryable ?? true });
111
+ this.got = args.got;
112
+ this.need = args.need;
113
+ this.reasons = reasons;
114
+ }
115
+ }
116
+ /**
117
+ * The slot was re-keyed (rotated) since the key in hand was assembled, so that
118
+ * key cannot read anything encrypted after the rotation. Retryable: re-assemble
119
+ * at the new epoch and try again - the managed {@link Session} does this for you.
120
+ */
121
+ export class SlotRotatedError extends TasraError {
122
+ /** The epoch the caller's key/envelope belongs to. */
123
+ expected;
124
+ /** The slot's current on-chain/served epoch. */
125
+ actual;
126
+ constructor(args) {
127
+ super(args.message ??
128
+ `slot${args.slotId ? ` ${args.slotId.slice(0, 10)}…` : ''} rotated: ` +
129
+ `key is epoch ${args.expected}, slot is now epoch ${args.actual}`, { retryable: true });
130
+ this.expected = args.expected;
131
+ this.actual = args.actual;
132
+ }
133
+ }
134
+ /**
135
+ * Build the right error for a non-2xx `Response`: {@link AuthDeniedError} for
136
+ * 401/403, otherwise {@link TasraHttpError}. Reads and truncates the body.
137
+ *
138
+ * `label` prefixes the message so it names the operation rather than just the
139
+ * URL (`'committee/sign'` to `committee/sign to HTTP 403: ...`).
140
+ */
141
+ export async function httpError(res, url, label) {
142
+ const body = (await res.text().catch(() => '')).slice(0, 200);
143
+ const message = `${label ?? url} → HTTP ${res.status}${body ? `: ${body}` : ''}`;
144
+ const args = { status: res.status, url, body, message };
145
+ return res.status === 401 || res.status === 403
146
+ ? new AuthDeniedError(args)
147
+ : new TasraHttpError(args);
148
+ }
149
+ /**
150
+ * True when `e` is an auth rejection - i.e. retrying is pointless, re-claim
151
+ * instead. Keyed on the HTTP status rather than the class, so it also catches
152
+ * subclasses that carry their own name (e.g. `CommitteeAuthorizeError`).
153
+ *
154
+ * @param e - Caught value to classify as an authorization rejection.
155
+ */
156
+ export function isAuthDenied(e) {
157
+ return e instanceof TasraHttpError && (e.status === 401 || e.status === 403);
158
+ }
159
+ /**
160
+ * True when a typed failure may be transient. Errors outside the TasraError
161
+ * hierarchy return false. This hint does not make a write safe to repeat.
162
+ *
163
+ * @param e - Caught value to inspect for a retryable Tasra error.
164
+ */
165
+ export function isRetryable(e) {
166
+ return e instanceof TasraError && e.retryable;
167
+ }