@t3foundry/tasra-sdk 0.3.1-next.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (255) hide show
  1. package/CHANGELOG.md +1067 -28
  2. package/README.md +15 -0
  3. package/dist/app/approvals.d.ts +66 -4
  4. package/dist/app/approvals.js +153 -16
  5. package/dist/app/authorization.d.ts +1 -1
  6. package/dist/app/authorization.js +1 -1
  7. package/dist/app/browser.d.ts +63 -0
  8. package/dist/app/browser.js +242 -0
  9. package/dist/app/client.d.ts +114 -13
  10. package/dist/app/client.js +302 -76
  11. package/dist/app/identity.js +21 -9
  12. package/dist/app/index.d.ts +28 -3
  13. package/dist/app/index.js +16 -1
  14. package/dist/app/memory-store.d.ts +7 -0
  15. package/dist/app/memory-store.js +55 -0
  16. package/dist/app/node.d.ts +34 -6
  17. package/dist/app/node.js +387 -64
  18. package/dist/app/paid-allowance.d.ts +325 -0
  19. package/dist/app/paid-allowance.js +1290 -0
  20. package/dist/app/paid-approval.d.ts +122 -0
  21. package/dist/app/paid-approval.js +379 -0
  22. package/dist/app/paid-journal.d.ts +51 -0
  23. package/dist/app/paid-journal.js +117 -0
  24. package/dist/app/paid-keys.d.ts +12 -0
  25. package/dist/app/paid-keys.js +20 -0
  26. package/dist/app/paid-operation.d.ts +821 -0
  27. package/dist/app/paid-operation.js +1720 -0
  28. package/dist/app/paid-reservation.d.ts +157 -0
  29. package/dist/app/paid-reservation.js +323 -0
  30. package/dist/app/paid-session.d.ts +147 -0
  31. package/dist/app/paid-session.js +578 -0
  32. package/dist/app/payer-queue.d.ts +11 -0
  33. package/dist/app/payer-queue.js +27 -0
  34. package/dist/app/policy-bootstrap.d.ts +342 -0
  35. package/dist/app/policy-bootstrap.js +365 -0
  36. package/dist/app/policy-operation.d.ts +47 -0
  37. package/dist/app/policy-operation.js +101 -0
  38. package/dist/app/ready-slot.d.ts +12 -0
  39. package/dist/app/ready-slot.js +5 -2
  40. package/dist/app/rotation-lock.d.ts +38 -0
  41. package/dist/app/rotation-lock.js +42 -0
  42. package/dist/app/session-decrypt.d.ts +135 -0
  43. package/dist/app/session-decrypt.js +335 -0
  44. package/dist/app/session-grants.d.ts +349 -0
  45. package/dist/app/session-grants.js +811 -0
  46. package/dist/app/signing-intents.d.ts +78 -0
  47. package/dist/app/signing-intents.js +95 -0
  48. package/dist/app/store-commit.d.ts +63 -0
  49. package/dist/app/store-commit.js +126 -0
  50. package/dist/app/store-errors.d.ts +8 -0
  51. package/dist/app/store-errors.js +11 -0
  52. package/dist/app/tasra-client.d.ts +2 -0
  53. package/dist/app/tasra-client.js +1 -1
  54. package/dist/app/wallet.js +4 -1
  55. package/dist/auth/holderProof.d.ts +3 -0
  56. package/dist/auth/holderProof.js +8 -7
  57. package/dist/auth/verifier.d.ts +4 -2
  58. package/dist/auth/verifier.js +5 -2
  59. package/dist/chain/abis/index.d.ts +6178 -4101
  60. package/dist/chain/abis/index.js +3 -0
  61. package/dist/chain/abis/keyRegistry.d.ts +256 -0
  62. package/dist/chain/abis/keyRegistry.js +333 -0
  63. package/dist/chain/abis/prepaidFaultOracle.d.ts +321 -0
  64. package/dist/chain/abis/prepaidFaultOracle.js +413 -0
  65. package/dist/chain/abis/settlement.d.ts +2203 -703
  66. package/dist/chain/abis/settlement.js +2685 -764
  67. package/dist/chain/allowance.d.ts +358 -0
  68. package/dist/chain/allowance.js +800 -0
  69. package/dist/chain/billing.d.ts +85 -0
  70. package/dist/chain/billing.js +197 -0
  71. package/dist/chain/chainId.d.ts +13 -0
  72. package/dist/chain/chainId.js +26 -0
  73. package/dist/chain/client.d.ts +15 -1
  74. package/dist/chain/client.js +57 -1
  75. package/dist/chain/commitmentRecovery.d.ts +51 -0
  76. package/dist/chain/commitmentRecovery.js +38 -0
  77. package/dist/chain/committeeClient.d.ts +17 -10
  78. package/dist/chain/committeeClient.js +64 -16
  79. package/dist/chain/committeeDraw.d.ts +12 -0
  80. package/dist/chain/committeeDraw.js +56 -0
  81. package/dist/chain/custodyHealth.d.ts +212 -0
  82. package/dist/chain/custodyHealth.js +365 -0
  83. package/dist/chain/deployments.js +2 -0
  84. package/dist/chain/events.js +2 -0
  85. package/dist/chain/headFollower.d.ts +77 -0
  86. package/dist/chain/headFollower.js +219 -0
  87. package/dist/chain/headPrefetch.d.ts +23 -0
  88. package/dist/chain/headPrefetch.js +67 -0
  89. package/dist/chain/index.d.ts +50 -8
  90. package/dist/chain/index.js +28 -3
  91. package/dist/chain/keeperExecution.d.ts +44 -0
  92. package/dist/chain/keeperExecution.js +127 -0
  93. package/dist/chain/keeperRecovery.d.ts +78 -0
  94. package/dist/chain/keeperRecovery.js +91 -0
  95. package/dist/chain/node.d.ts +24 -1
  96. package/dist/chain/node.js +88 -43
  97. package/dist/chain/offchain.d.ts +2 -0
  98. package/dist/chain/paidAgentTransport.d.ts +38 -0
  99. package/dist/chain/paidAgentTransport.js +1 -0
  100. package/dist/chain/paidEpoch.d.ts +66 -0
  101. package/dist/chain/paidEpoch.js +139 -0
  102. package/dist/chain/paidPacing.d.ts +81 -0
  103. package/dist/chain/paidPacing.js +136 -0
  104. package/dist/chain/pinnedReads.d.ts +49 -0
  105. package/dist/chain/pinnedReads.js +218 -0
  106. package/dist/chain/prepaid.d.ts +383 -0
  107. package/dist/chain/prepaid.js +1046 -0
  108. package/dist/chain/prepaidEscape.d.ts +274 -0
  109. package/dist/chain/prepaidEscape.js +432 -0
  110. package/dist/chain/prepaidFault.d.ts +94 -0
  111. package/dist/chain/prepaidFault.js +148 -0
  112. package/dist/chain/receipt.d.ts +24 -0
  113. package/dist/chain/receipt.js +82 -0
  114. package/dist/chain/registeredAgent.d.ts +68 -3
  115. package/dist/chain/registeredAgent.js +143 -42
  116. package/dist/chain/registeredOperation.d.ts +10 -1
  117. package/dist/chain/registeredOperation.js +18 -3
  118. package/dist/chain/registeredPaidAgent.d.ts +254 -0
  119. package/dist/chain/registeredPaidAgent.js +889 -0
  120. package/dist/chain/registeredRelay.d.ts +31 -1
  121. package/dist/chain/registeredRelay.js +164 -43
  122. package/dist/chain/relayVoucher.d.ts +64 -0
  123. package/dist/chain/relayVoucher.js +69 -0
  124. package/dist/chain/reservation.d.ts +239 -0
  125. package/dist/chain/reservation.js +746 -0
  126. package/dist/chain/reshareRoster.d.ts +64 -0
  127. package/dist/chain/reshareRoster.js +85 -0
  128. package/dist/chain/revertReason.d.ts +8 -0
  129. package/dist/chain/revertReason.js +2 -1
  130. package/dist/chain/rotationLock.d.ts +130 -0
  131. package/dist/chain/rotationLock.js +168 -0
  132. package/dist/chain/serviceRequestPolicy.d.ts +47 -0
  133. package/dist/chain/serviceRequestPolicy.js +86 -0
  134. package/dist/chain/services.d.ts +7 -0
  135. package/dist/chain/services.js +44 -4
  136. package/dist/chain/slotClient.js +11 -2
  137. package/dist/chain/slotHandoff.d.ts +81 -0
  138. package/dist/chain/slotHandoff.js +166 -0
  139. package/dist/chain/slotSeed.d.ts +47 -5
  140. package/dist/chain/slotSeed.js +173 -42
  141. package/dist/chain/verifierSnapshot.d.ts +36 -0
  142. package/dist/chain/verifierSnapshot.js +197 -0
  143. package/dist/chain/write.d.ts +111 -21
  144. package/dist/chain/write.js +378 -146
  145. package/dist/committee/blsSharing.d.ts +53 -0
  146. package/dist/committee/blsSharing.js +90 -0
  147. package/dist/committee/client.d.ts +62 -23
  148. package/dist/committee/client.js +288 -72
  149. package/dist/committee/dual-operation.d.ts +165 -0
  150. package/dist/committee/dual-operation.js +229 -0
  151. package/dist/committee/dual-sign.d.ts +26 -1
  152. package/dist/committee/dual-sign.js +85 -7
  153. package/dist/committee/ecdsa.d.ts +38 -0
  154. package/dist/committee/ecdsa.js +87 -15
  155. package/dist/committee/evidence.d.ts +30 -0
  156. package/dist/committee/evidence.js +65 -0
  157. package/dist/committee/execution.d.ts +414 -0
  158. package/dist/committee/execution.js +446 -0
  159. package/dist/committee/extraction.js +33 -26
  160. package/dist/committee/index.d.ts +30 -7
  161. package/dist/committee/index.js +18 -6
  162. package/dist/committee/keeperExecution.d.ts +37 -0
  163. package/dist/committee/keeperExecution.js +141 -0
  164. package/dist/committee/oauth.d.ts +14 -4
  165. package/dist/committee/oauth.js +17 -5
  166. package/dist/committee/payment.d.ts +369 -0
  167. package/dist/committee/payment.js +339 -0
  168. package/dist/committee/recovery.d.ts +136 -0
  169. package/dist/committee/recovery.js +204 -0
  170. package/dist/committee/recoveryJson.d.ts +2 -0
  171. package/dist/committee/recoveryJson.js +87 -0
  172. package/dist/committee/request.d.ts +63 -27
  173. package/dist/committee/request.js +77 -66
  174. package/dist/committee/session-grant.d.ts +320 -0
  175. package/dist/committee/session-grant.js +397 -0
  176. package/dist/committee/status-refresh.d.ts +257 -0
  177. package/dist/committee/status-refresh.js +619 -0
  178. package/dist/committee/token.d.ts +163 -15
  179. package/dist/committee/token.js +247 -10
  180. package/dist/crypto/bn254.d.ts +70 -0
  181. package/dist/crypto/bn254.js +222 -0
  182. package/dist/crypto/ibe.d.ts +32 -0
  183. package/dist/crypto/ibe.js +56 -8
  184. package/dist/crypto/index.d.ts +1 -1
  185. package/dist/crypto/index.js +1 -1
  186. package/dist/crypto/kem.d.ts +31 -0
  187. package/dist/crypto/kem.js +113 -7
  188. package/dist/crypto/recipient.d.ts +75 -0
  189. package/dist/crypto/recipient.js +107 -0
  190. package/dist/decryption/client.d.ts +10 -16
  191. package/dist/decryption/client.js +8 -76
  192. package/dist/decryption/index.d.ts +2 -0
  193. package/dist/decryption/index.js +2 -0
  194. package/dist/decryption/sealed.d.ts +72 -0
  195. package/dist/decryption/sealed.js +147 -0
  196. package/dist/decryption/session.d.ts +115 -0
  197. package/dist/decryption/session.js +358 -0
  198. package/dist/errors.d.ts +406 -1
  199. package/dist/errors.js +400 -5
  200. package/dist/index.d.ts +9 -2
  201. package/dist/index.js +6 -1
  202. package/dist/internal/bounded.d.ts +66 -0
  203. package/dist/internal/bounded.js +126 -0
  204. package/dist/internal/network.d.ts +4 -0
  205. package/dist/internal/network.js +40 -0
  206. package/dist/internal/retryAfter.d.ts +8 -0
  207. package/dist/internal/retryAfter.js +28 -0
  208. package/dist/internal/sleep.d.ts +6 -0
  209. package/dist/internal/sleep.js +15 -0
  210. package/dist/internal/typedData.d.ts +13 -0
  211. package/dist/internal/typedData.js +77 -0
  212. package/dist/internal/viemErrors.d.ts +26 -0
  213. package/dist/internal/viemErrors.js +49 -0
  214. package/dist/oid4vp/binding.d.ts +27 -1
  215. package/dist/oid4vp/binding.js +36 -1
  216. package/dist/oid4vp/jose.d.ts +4 -2
  217. package/dist/oid4vp/jose.js +39 -7
  218. package/dist/oid4vp/request-object.d.ts +61 -4
  219. package/dist/oid4vp/request-object.js +140 -5
  220. package/dist/oid4vp/verifier-agent.d.ts +18 -8
  221. package/dist/oid4vp/verifier-agent.js +48 -6
  222. package/dist/oid4vp/wallet.d.ts +2 -4
  223. package/dist/oid4vp/wallet.js +1 -0
  224. package/dist/retry.d.ts +78 -0
  225. package/dist/retry.js +137 -0
  226. package/dist/signing/frost.d.ts +1 -1
  227. package/dist/verifier-agent/index.d.ts +41 -5
  228. package/dist/verifier-agent/index.js +124 -9
  229. package/dist/verifier-agent/payment.d.ts +7 -0
  230. package/dist/verifier-agent/payment.js +17 -0
  231. package/docs/api.md +8 -2
  232. package/docs/application-api.md +25 -2
  233. package/docs/chain.md +155 -9
  234. package/docs/consumer-migrations.md +61 -0
  235. package/docs/encrypted-notes.md +3 -2
  236. package/docs/encryption.md +4 -2
  237. package/docs/errors.md +14 -1
  238. package/docs/flows.md +2 -2
  239. package/docs/funding.md +902 -0
  240. package/docs/native-approvals.md +63 -0
  241. package/docs/reference/README.md +9 -8
  242. package/docs/reference/app-browser.md +232 -0
  243. package/docs/reference/app-node.md +38 -8
  244. package/docs/reference/app.md +4621 -805
  245. package/docs/reference/chain-node.md +74 -16
  246. package/docs/reference/chain.md +6740 -1592
  247. package/docs/reference/committee.md +5630 -987
  248. package/docs/reference/main.md +1439 -140
  249. package/docs/reference/oid4vp.md +297 -144
  250. package/docs/reference/verifier-agent.md +77 -35
  251. package/docs/signing.md +6 -0
  252. package/examples/encrypted-notes.ts +21 -6
  253. package/examples/getting-started.ts +2 -7
  254. package/examples/live-config.ts +24 -17
  255. package/package.json +17 -5
@@ -0,0 +1,115 @@
1
+ import { type Ciphertext, type DecryptShare } from '../crypto/kem.js';
2
+ import { type ClientRecipient } from '../crypto/recipient.js';
3
+ import { type KeeperExecutionApprover } from '../committee/keeperExecution.js';
4
+ import type { PaymentIntentWire } from '../committee/payment.js';
5
+ import { type SessionGrantWire, type VerifiedSessionGrant } from '../committee/session-grant.js';
6
+ import type { SessionKeyHandle } from '../app/session-grants.js';
7
+ /** One ciphertext to decrypt under the grant. */
8
+ export interface SessionDecryptItem {
9
+ ciphertext: Ciphertext;
10
+ /** Exact identity (associated data) bytes the ciphertext was encrypted under. */
11
+ identity: Uint8Array;
12
+ /** Fresh client recipient the keepers seal to. */
13
+ recipient: ClientRecipient;
14
+ /** Canonical key epoch of the ciphertext. */
15
+ ciphertextEpoch: number;
16
+ /** This item's own payment ({@link paidSessionDecrypt}); every keeper requires one per item. */
17
+ payment: PaymentIntentWire;
18
+ /** Approves each keeper's contribution for exactly this item's payment. */
19
+ approveExecution: KeeperExecutionApprover;
20
+ /**
21
+ * Read a keeper's RETAINED partial for this item, after it answered that the item already ran
22
+ * (`409 recoverable`: executed, audit row missing; `409 already claimed`: the payment was used).
23
+ * Never re-sends work or pays again (`PaidSessionDecrypt.recoverPartial`). Returns the partial JSON.
24
+ */
25
+ recover?(nodeUrl: string, signal?: AbortSignal): Promise<unknown>;
26
+ }
27
+ /** A verifier witness on the wire, as for a compound-token request (`verifier_proofs`). */
28
+ export interface SessionVerifierProofWire {
29
+ verifier_index: number;
30
+ operator: string;
31
+ pubkey: string;
32
+ proof: string[];
33
+ }
34
+ /** Pluggable combine (e.g. a Web Worker); default runs combineDecryptShares in-process. */
35
+ export type SessionCombiner = (shares: DecryptShare[], ct: Ciphertext, identity: Uint8Array) => Uint8Array | Promise<Uint8Array>;
36
+ /** Request-wide settings. */
37
+ export interface SessionDecryptOptions {
38
+ /** Distinct assigned keeper endpoints. */
39
+ nodeUrls: string[];
40
+ chainId: number | bigint;
41
+ /** Slot the grant names. */
42
+ slotId: `0x${string}`;
43
+ /** Current grant (GrantedSession.current()). */
44
+ grant: SessionGrantWire;
45
+ /** The same grant verified for this slot (GrantedSession.verifiedFor). */
46
+ verified: VerifiedSessionGrant;
47
+ /** The session key the grant binds. */
48
+ key: SessionKeyHandle;
49
+ /** Keeper identifier → authenticated 144-byte G2 ‖ G1 verifying share. */
50
+ verifyingShares: ReadonlyMap<number, Uint8Array>;
51
+ /** Distinct verified contributions needed per item. */
52
+ threshold: number;
53
+ /**
54
+ * Anchored membership witnesses of the grant's draw at the grant's epoch. A keeper with a
55
+ * verifier-set registry (every production keeper) REQUIRES them; with them the request always
56
+ * uses the batch route (the single route's approved item body cannot carry them).
57
+ */
58
+ verifierProofs?: SessionVerifierProofWire[];
59
+ fetchImpl?: typeof fetch;
60
+ signal?: AbortSignal;
61
+ /** Clock override, Unix seconds (tests). */
62
+ clock?: () => number;
63
+ combine?: SessionCombiner;
64
+ }
65
+ /** One keeper's refusal of one item. */
66
+ export interface SessionItemRefusal {
67
+ nodeUrl: string;
68
+ status: number;
69
+ /** The keeper's stable code (`forbidden`, `session-stale`, ...), or `status N` from a keeper without one. */
70
+ code: string;
71
+ /** The keeper's public-safe message, truncated. */
72
+ message?: string;
73
+ /** `request`: the keeper refused the whole request before any item ran; `item`: this item alone. */
74
+ scope: 'request' | 'item';
75
+ }
76
+ /**
77
+ * One item's outcome: the plaintext, or why it failed (an item's refusal never fails the batch).
78
+ * `stale` (see {@link isStaleSessionRefusal}) is true only when the grant was refused as no longer
79
+ * current (its epoch left the beacon's window, or it passed its `exp`) and NO keeper ran this item:
80
+ * every keeper answered, none contributed, none said it already ran it, and every refusal is one
81
+ * that precedes execution. Only then may the caller refresh the grant and pay the message again,
82
+ * and only after confirming the staleness itself (a keeper's word is not proof): {@link decryptInSession}
83
+ * does, once, when a fresh chain read shows the grant two epochs behind. The unused debit stays in
84
+ * the cumulative voucher and is refunded (paid = 0) when it settles after the payment's expiry.
85
+ */
86
+ export type SessionDecryptResult = {
87
+ ok: true;
88
+ plaintext: Uint8Array;
89
+ } | {
90
+ ok: false;
91
+ error: string;
92
+ codes: string[];
93
+ refusals: SessionItemRefusal[];
94
+ stale: boolean;
95
+ };
96
+ /**
97
+ * Whether a keeper refusal says the session grant is no longer current: the stable code
98
+ * `session-stale`, or (older keepers, whose whole-request refusals carry no code) the fixed messages
99
+ * of the grant-freshness check and of the epoch-window seed pin. Both are judged before any item
100
+ * is admitted, so such a refusal never follows an execution.
101
+ */
102
+ export declare function isStaleSessionRefusal(r: Pick<SessionItemRefusal, 'status' | 'code' | 'message'>): boolean;
103
+ /**
104
+ * Decrypt 1..64 ciphertexts under a session grant: one request per keeper (the single route for
105
+ * one item without verifier proofs, the batch route otherwise), one fresh session-key proof per
106
+ * request, then per item the first `threshold` distinct contributions that open and batch-verify
107
+ * are combined locally. A keeper's `413 batch-too-large` splits the batch into requests of its
108
+ * `max_items` (nothing ran), a `429` is retried once after its `Retry-After` inside the deadline,
109
+ * and an item a keeper already ran (`409 recoverable` / `already claimed`) is re-served through
110
+ * `item.recover` when the threshold is still short; nothing is ever paid twice.
111
+ * Every opened contribution is cleared before returning.
112
+ * @param o - Grant, key, keepers, shares and threshold.
113
+ * @param items - Ciphertexts, each with its own recipient and payment.
114
+ */
115
+ export declare function decryptWithSessionGrant(o: SessionDecryptOptions, items: SessionDecryptItem[]): Promise<SessionDecryptResult[]>;
@@ -0,0 +1,358 @@
1
+ // ADR-0090 D7/D8 per-message KEM decrypts under a session grant. Each item carries its own payment
2
+ // (normally an allowance debit voucher) and its own sealed reply; one session-key proof covers the
3
+ // request: a single proof for one item, an ordered batch proof for `/v1/committee/decrypt/partials`.
4
+ //
5
+ // The wire is the keeper's (keykeeper-node `api/sealed_session.rs`):
6
+ // - an ITEM is today's sealed `/decrypt/partial` body without `committee_token` (and the evidence
7
+ // fields), plus the operation's own (REQUIRED) `payment` and its `key_slot_id`, plus its one
8
+ // contributor approval (kind `session-decrypt`, over the item body alone);
9
+ // - the batch body is `{session_grant, session_key, proof, items, verifier_proofs?}`; the single body
10
+ // is the item's fields beside `session_grant`, `session_key` and `proof`;
11
+ // - the batch reply is one `{status: 200, partial}` or `{status, code, error}` per item, in order;
12
+ // the single reply is the partial, or `{code, error}` with a non-2xx status (an older keeper
13
+ // sends `{error}` alone).
14
+ //
15
+ // Reply handling is the sealed path's (decryption/sealed.ts): same slot/epoch/verifying-share
16
+ // checks, same HPKE open bound to the request hash; shares are then verified IN BATCHES per item
17
+ // (kem.verifyDecryptSharesBatch, exactly the per-share verdicts) before the combine.
18
+ import { randomBytes } from '@noble/hashes/utils';
19
+ import { base64Decode, base64Encode } from '../crypto/envelope.js';
20
+ import { bytesToHex, hexToBytes } from '../crypto/hex.js';
21
+ import { combineDecryptShares, decodeKemU, verifyDecryptSharesBatch } from '../crypto/kem.js';
22
+ import { kemContentDigest, recipientPayloadDigest } from '../crypto/recipient.js';
23
+ import { requestHash } from '../oid4vp/binding.js';
24
+ import { withKeeperExecutionApprovals } from '../committee/keeperExecution.js';
25
+ import { MAX_BATCH_ITEMS, checkProofWindow, encodeSessionProof, sessionBatchProofHash, sessionKeyThumbprint, toBase64Url, sessionProofHash } from '../committee/session-grant.js';
26
+ import { withNetworkDeadline } from '../internal/network.js';
27
+ import { parseRetryAfter } from '../internal/retryAfter.js';
28
+ import { TasraError } from '../errors.js';
29
+ /**
30
+ * Whether a keeper refusal says the session grant is no longer current: the stable code
31
+ * `session-stale`, or (older keepers, whose whole-request refusals carry no code) the fixed messages
32
+ * of the grant-freshness check and of the epoch-window seed pin. Both are judged before any item
33
+ * is admitted, so such a refusal never follows an execution.
34
+ */
35
+ export function isStaleSessionRefusal(r) {
36
+ if (r.code === 'session-stale')
37
+ return true;
38
+ if (r.status !== 403 || !r.message)
39
+ return false;
40
+ if (/^session grant expired at \d+ \(now \d+\)/.test(r.message))
41
+ return true;
42
+ // The epoch-window message is stale only when the grant is BEHIND the keeper's window. A grant
43
+ // AHEAD of it (the keeper's beacon lags; C24 keepers answer that `forbidden` with the same text)
44
+ // is the keeper's problem: retry later or elsewhere, never refresh because of it.
45
+ const window = /\bepoch (\d+) is not current \(beacon latest (\d+)\)/.exec(r.message);
46
+ return window !== null && BigInt(window[1]) + 1n < BigInt(window[2]);
47
+ }
48
+ /** Statuses that a keeper answers only before an item runs (409 can mean "already ran"; 5xx is unknown). */
49
+ const PRE_EXECUTION = new Set([400, 401, 402, 403, 404, 410, 413, 429]);
50
+ const MAX_MESSAGE_CHARS = 240;
51
+ function freshJti() {
52
+ return toBase64Url(randomBytes(24));
53
+ }
54
+ function prepare(o, item) {
55
+ const content = kemContentDigest(item.ciphertext, item.identity);
56
+ const digest = recipientPayloadDigest(content, item.ciphertextEpoch, item.recipient.recipient);
57
+ const hash = requestHash(o.chainId, hexToBytes(o.slotId), 'decrypt', digest);
58
+ if (!item.payment)
59
+ throw new TasraError('Every session item carries its own payment');
60
+ if (item.payment.action !== 'decrypt' || item.payment.slot.toLowerCase() !== o.slotId.toLowerCase()
61
+ || item.payment.payload_digest.toLowerCase() !== bytesToHex(digest).toLowerCase())
62
+ throw new TasraError('Session item payment is not bound to this ciphertext and recipient');
63
+ const body = {
64
+ key_slot_id: o.slotId.slice(2).toLowerCase(),
65
+ identity: new TextDecoder('utf-8', { fatal: true }).decode(item.identity),
66
+ recipient: item.recipient.recipient, ciphertext_epoch: item.ciphertextEpoch,
67
+ ciphertext: { u: base64Encode(item.ciphertext.u), nonce: base64Encode(item.ciphertext.nonce), aead_ct: base64Encode(item.ciphertext.aeadCt) },
68
+ payment: structuredClone(item.payment),
69
+ };
70
+ return { item, requestHash: hash, body, U: decodeKemU(item.ciphertext.u) };
71
+ }
72
+ async function proofFor(o, hashes, batch) {
73
+ const iat = (o.clock ?? (() => Math.floor(Date.now() / 1000)))();
74
+ const jti = freshJti();
75
+ checkProofWindow(o.verified, o.key.jwk, { iat, jti }, iat);
76
+ const grantHash = o.verified.grantHash;
77
+ const hash = batch ? sessionBatchProofHash(grantHash, hashes, iat, jti) : sessionProofHash(grantHash, hashes[0], iat, jti);
78
+ return encodeSessionProof({ iat, jti, signature: await o.key.sign(hash) });
79
+ }
80
+ const messageOf = (error) => typeof error === 'string' && error ? error.slice(0, MAX_MESSAGE_CHARS) : undefined;
81
+ /** Codes of an item whose work already RAN at that keeper: re-serve it by recovery, never by paying again. */
82
+ const RAN = new Set(['recoverable', 'already-claimed']);
83
+ /**
84
+ * The item code a keeper refusal names. A batch item and (since the second security review) the
85
+ * single route both carry the keeper's stable `code` (`recoverable`, `conflict`, ...), which
86
+ * decides; only an older keeper's single route, answering `{error}` alone, is told apart by its
87
+ * fixed messages.
88
+ */
89
+ function itemCode(status, code, error) {
90
+ const text = typeof error === 'string' ? error : '';
91
+ const coded = typeof code === 'string' && /^[a-z0-9_-]{1,48}$/.test(code) ? code : undefined;
92
+ if (coded !== undefined) {
93
+ // `conflict` is the family of every 409 but `recoverable`; a claimed payment is the one the
94
+ // fan-out must not resend, named by the conflict's message.
95
+ if (status === 409 && coded === 'conflict' && text.includes('already claimed'))
96
+ return 'already-claimed';
97
+ return coded;
98
+ }
99
+ // Fallback for an older keeper without codes on the single route.
100
+ if (status === 409 && text.includes('recover its result through the paid-execution recovery route'))
101
+ return 'recoverable';
102
+ if (status === 409 && text.includes('already claimed'))
103
+ return 'already-claimed';
104
+ return `status ${status}`;
105
+ }
106
+ /** Largest keeper reply a session request reads, in bytes (64 sealed partials fit well below). */
107
+ const MAX_KEEPER_REPLY_BYTES = 4_194_304;
108
+ /**
109
+ * The reply body as text, refused the moment it passes `cap` BYTES while it streams (a declared
110
+ * `content-length` over the cap is refused before reading), so a hostile keeper cannot make the
111
+ * SDK buffer an unbounded body. A response without a body stream falls back to `text()`, capped.
112
+ */
113
+ async function readCappedText(res, cap, signal) {
114
+ const tooLarge = () => new TasraError('Session keeper reply exceeds its byte limit');
115
+ if (Number(res.headers.get('content-length')) > cap) {
116
+ void res.body?.cancel().catch(() => { });
117
+ throw tooLarge();
118
+ }
119
+ const reader = res.body?.getReader();
120
+ if (!reader) {
121
+ const text = await res.text();
122
+ if (new TextEncoder().encode(text).length > cap)
123
+ throw tooLarge();
124
+ return text;
125
+ }
126
+ const decoder = new TextDecoder();
127
+ let bytes = 0, text = '';
128
+ try {
129
+ for (;;) {
130
+ signal?.throwIfAborted();
131
+ const { done, value } = await reader.read();
132
+ if (done)
133
+ break;
134
+ bytes += value.length;
135
+ if (bytes > cap)
136
+ throw tooLarge();
137
+ text += decoder.decode(value, { stream: true });
138
+ }
139
+ return text + decoder.decode();
140
+ }
141
+ finally {
142
+ // Includes the cap refusal; never wait for a hostile body's cancel.
143
+ void reader.cancel().catch(() => { });
144
+ }
145
+ }
146
+ /**
147
+ * Decrypt 1..64 ciphertexts under a session grant: one request per keeper (the single route for
148
+ * one item without verifier proofs, the batch route otherwise), one fresh session-key proof per
149
+ * request, then per item the first `threshold` distinct contributions that open and batch-verify
150
+ * are combined locally. A keeper's `413 batch-too-large` splits the batch into requests of its
151
+ * `max_items` (nothing ran), a `429` is retried once after its `Retry-After` inside the deadline,
152
+ * and an item a keeper already ran (`409 recoverable` / `already claimed`) is re-served through
153
+ * `item.recover` when the threshold is still short; nothing is ever paid twice.
154
+ * Every opened contribution is cleared before returning.
155
+ * @param o - Grant, key, keepers, shares and threshold.
156
+ * @param items - Ciphertexts, each with its own recipient and payment.
157
+ */
158
+ export async function decryptWithSessionGrant(o, items) {
159
+ if (items.length === 0 || items.length > MAX_BATCH_ITEMS)
160
+ throw new TasraError(`A session request carries 1..${MAX_BATCH_ITEMS} items`);
161
+ if (!Number.isInteger(o.threshold) || o.threshold < 1 || o.threshold > o.nodeUrls.length || o.threshold > o.verifyingShares.size)
162
+ throw new TasraError('Invalid session decrypt threshold');
163
+ if (new Set(o.nodeUrls.map(u => u.replace(/\/$/, ''))).size !== o.nodeUrls.length)
164
+ throw new TasraError('Duplicate session keeper endpoint');
165
+ if (bytesToHex(o.verified.slotId).toLowerCase() !== o.slotId.toLowerCase())
166
+ throw new TasraError('Session grant was verified for another slot');
167
+ // A grant without its session key authorizes nothing: refuse before building or sending anything.
168
+ if (bytesToHex(sessionKeyThumbprint(o.key.jwk)) !== bytesToHex(o.verified.sessionKeyThumbprint))
169
+ throw new TasraError('Session key thumbprint does not match the grant');
170
+ if (o.verifierProofs !== undefined && (!Array.isArray(o.verifierProofs) || o.verifierProofs.length === 0))
171
+ throw new TasraError('Session verifier proofs, when given, are nonempty');
172
+ const prepared = items.map(item => prepare(o, item));
173
+ const state = { candidates: prepared.map(() => new Map()), codes: prepared.map(() => []),
174
+ ran: prepared.map(() => []), refusals: prepared.map(() => []), answered: prepared.map(() => 0), errors: [] };
175
+ try {
176
+ await withNetworkDeadline(signal => fanOut({ ...o, signal }, prepared, state), o.signal);
177
+ await recoverShort(o, prepared, state);
178
+ return await combineAll(o, prepared, state);
179
+ }
180
+ finally {
181
+ for (const c of state.candidates)
182
+ for (const v of c.values())
183
+ v.value.fill(0);
184
+ }
185
+ }
186
+ async function fanOut(o, prepared, state) {
187
+ const settled = await Promise.allSettled(o.nodeUrls.map(async (nodeUrl) => {
188
+ const base = nodeUrl.replace(/\/$/, '');
189
+ const approved = await Promise.all(prepared.map(p => withKeeperExecutionApprovals({ body: p.body, kind: 'session-decrypt', nodeUrl,
190
+ payment: p.item.payment, approveExecution: p.item.approveExecution, signal: o.signal })));
191
+ const replies = await send(o, base, prepared.map((p, i) => ({ index: i, hash: p.requestHash, body: approved[i] })));
192
+ await Promise.all(replies.map(async (reply, i) => {
193
+ state.answered[i]++;
194
+ if (reply.status !== 200) {
195
+ const r = reply;
196
+ state.codes[i].push(r.code);
197
+ state.refusals[i].push({ nodeUrl, status: r.status, code: r.code, ...r.message ? { message: r.message } : {}, scope: r.scope });
198
+ if (RAN.has(r.code))
199
+ state.ran[i].push(nodeUrl);
200
+ return;
201
+ }
202
+ await accept(o, prepared[i], state.candidates[i], state.codes[i], reply.partial);
203
+ }));
204
+ }));
205
+ for (const s of settled)
206
+ if (s.status === 'rejected')
207
+ state.errors.push(String(s.reason));
208
+ }
209
+ /** Open one partial and keep it as a candidate (one per keeper identifier). */
210
+ async function accept(o, p, candidates, codes, partial) {
211
+ const opened = await openPartial(o, p, partial);
212
+ if (!opened) {
213
+ codes.push('invalid-partial');
214
+ return;
215
+ }
216
+ if (candidates.has(opened.identifier))
217
+ opened.value.fill(0);
218
+ else
219
+ candidates.set(opened.identifier, opened);
220
+ }
221
+ /** Send `items` to one keeper and answer one reply per item, in order (splitting on 413, retrying a 429 once). */
222
+ async function send(o, base, items, split = false, retried = false) {
223
+ const batch = items.length > 1 || o.verifierProofs !== undefined || split;
224
+ const proof = await proofFor(o, items.map(i => i.hash), batch);
225
+ const session = { session_grant: o.grant, session_key: o.key.jwk, proof };
226
+ const body = batch ? { ...session, items: items.map(i => i.body), ...o.verifierProofs ? { verifier_proofs: o.verifierProofs } : {} } : { ...items[0].body, ...session };
227
+ const url = `${base}${batch ? '/v1/committee/decrypt/partials' : '/v1/committee/decrypt/partial'}`;
228
+ const res = await (o.fetchImpl ?? fetch)(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal: o.signal,
229
+ redirect: 'error', credentials: 'omit' });
230
+ const text = await readCappedText(res, MAX_KEEPER_REPLY_BYTES, o.signal);
231
+ let json;
232
+ try {
233
+ const v = text ? JSON.parse(text) : undefined;
234
+ json = v && typeof v === 'object' && !Array.isArray(v) ? v : undefined;
235
+ }
236
+ catch {
237
+ json = undefined;
238
+ }
239
+ // 413 batch-too-large: refused before anything ran; split into requests of the keeper's limit, each with its own proof.
240
+ if (res.status === 413 && json?.code === 'batch-too-large' && !split) {
241
+ const max = json.max_items;
242
+ if (typeof max !== 'number' || !Number.isSafeInteger(max) || max < 1 || max >= items.length)
243
+ throw new TasraError(`Session keeper refused the batch size without a usable max_items (${url})`);
244
+ const out = [];
245
+ for (let i = 0; i < items.length; i += max)
246
+ out.push(...await send(o, base, items.slice(i, i + max), true));
247
+ return out;
248
+ }
249
+ // 429: the keeper's per-IP item bucket (or the grant's jti budget) is short now; nothing ran. One retry with a fresh proof.
250
+ if (res.status === 429 && !retried) {
251
+ const wait = parseRetryAfter(res.headers.get('retry-after')) ?? 1_000;
252
+ if (wait <= 5_000) {
253
+ await new Promise((resolve, reject) => {
254
+ const t = setTimeout(resolve, wait);
255
+ o.signal?.addEventListener('abort', () => { clearTimeout(t); reject(o.signal.reason); }, { once: true });
256
+ });
257
+ return send(o, base, items, split, true);
258
+ }
259
+ }
260
+ if (!batch) {
261
+ if (res.ok)
262
+ return [{ status: 200, partial: json }];
263
+ return [{ status: res.status, code: itemCode(res.status, json?.code, json?.error), ...messageOf(json?.error) ? { message: messageOf(json?.error) } : {}, scope: 'item' }];
264
+ }
265
+ if (!res.ok) {
266
+ // A whole-request refusal answers every item the same way (none of them ran).
267
+ const code = itemCode(res.status, json?.code, json?.error), message = messageOf(json?.error);
268
+ return items.map(() => ({ status: res.status, code, ...message ? { message } : {}, scope: 'request' }));
269
+ }
270
+ const replies = json?.items;
271
+ if (!Array.isArray(replies) || replies.length !== items.length)
272
+ throw new TasraError('Session keeper reply does not answer every item exactly once');
273
+ return replies.map((reply) => {
274
+ const r = reply;
275
+ if (r?.status === 200)
276
+ return { status: 200, partial: r.partial };
277
+ const status = typeof r?.status === 'number' ? r.status : 0;
278
+ const message = messageOf(r?.error);
279
+ return { status, code: itemCode(status, r?.code, r?.error), ...message ? { message } : {}, scope: 'item' };
280
+ });
281
+ }
282
+ /** For each item still short of its threshold: read the retained partial of every keeper that said it already ran it. */
283
+ async function recoverShort(o, prepared, state) {
284
+ await Promise.all(prepared.map(async (p, i) => {
285
+ if (!p.item.recover)
286
+ return;
287
+ for (const nodeUrl of state.ran[i]) {
288
+ if (state.candidates[i].size >= o.threshold)
289
+ return;
290
+ o.signal?.throwIfAborted();
291
+ try {
292
+ await accept(o, p, state.candidates[i], state.codes[i], await p.item.recover(nodeUrl, o.signal));
293
+ }
294
+ catch (error) {
295
+ o.signal?.throwIfAborted();
296
+ state.codes[i].push('recovery-failed');
297
+ state.errors.push(`recovery from ${nodeUrl}: ${error instanceof Error ? error.message : String(error)}`);
298
+ }
299
+ }
300
+ }));
301
+ }
302
+ async function combineAll(o, prepared, state) {
303
+ const combine = o.combine ?? ((shares, ct, identity) => combineDecryptShares(shares, ct, identity, { verify: false }));
304
+ const results = [];
305
+ for (const [i, p] of prepared.entries()) {
306
+ const list = [...state.candidates[i].values()];
307
+ try {
308
+ const shares = list.map(c => ({ id: c.identifier, decryptionShare: c.value, verifyingShare: c.verifyingShare }));
309
+ const verdict = verifyDecryptSharesBatch(shares, p.U);
310
+ const valid = shares.filter((_, j) => verdict[j]).slice(0, o.threshold);
311
+ if (valid.length < o.threshold) {
312
+ const refusals = state.refusals[i];
313
+ const said = [...new Set(refusals.map(r => `${r.code}${r.message ? ' (' + r.message + ')' : ''}`))];
314
+ const detail = [...said, ...state.errors];
315
+ results.push({ ok: false, error: `session partial threshold not met (${valid.length}/${o.threshold})${detail.length ? ': ' + detail.join('; ') : ''}`,
316
+ codes: state.codes[i], refusals, stale: staleUnrun(o, state, i) });
317
+ continue;
318
+ }
319
+ results.push({ ok: true, plaintext: await combine(valid, p.item.ciphertext, p.item.identity) });
320
+ }
321
+ catch (error) {
322
+ results.push({ ok: false, error: String(error), codes: state.codes[i], refusals: state.refusals[i], stale: false });
323
+ }
324
+ }
325
+ return results;
326
+ }
327
+ /**
328
+ * True when item `i` is a staleness refusal that ran NOWHERE: every keeper answered it, none
329
+ * contributed or said it already ran it (nor did a recovery read), every refusal precedes execution,
330
+ * and at least one names a stale grant. A transport failure leaves "did it run?" open: never stale.
331
+ */
332
+ function staleUnrun(o, state, i) {
333
+ const refusals = state.refusals[i];
334
+ return state.answered[i] === o.nodeUrls.length && state.candidates[i].size === 0 && state.ran[i].length === 0
335
+ && refusals.length === o.nodeUrls.length && refusals.every(r => PRE_EXECUTION.has(r.status) && !RAN.has(r.code))
336
+ && refusals.some(isStaleSessionRefusal);
337
+ }
338
+ async function openPartial(o, p, partial) {
339
+ const d = partial;
340
+ if (!d || typeof d.identifier !== 'number' || d.epoch !== p.item.ciphertextEpoch || typeof d.key_slot_id !== 'string'
341
+ || d.key_slot_id.replace(/^0x/, '').toLowerCase() !== o.slotId.slice(2).toLowerCase() || typeof d.verifying_share !== 'string' || !d.sealed_share)
342
+ return undefined;
343
+ const vs = o.verifyingShares.get(d.identifier);
344
+ const supplied = base64Decode(d.verifying_share);
345
+ if (!vs || vs.length !== 144 || supplied.length !== 144 || !vs.every((b, i) => b === supplied[i]))
346
+ return undefined;
347
+ try {
348
+ const value = await p.item.recipient.open(d.sealed_share, p.requestHash, d.identifier, d.epoch, vs);
349
+ if (value.length !== 96) {
350
+ value.fill(0);
351
+ return undefined;
352
+ }
353
+ return { identifier: d.identifier, value, verifyingShare: vs };
354
+ }
355
+ catch {
356
+ return undefined;
357
+ }
358
+ }