@t3foundry/tasra-sdk 0.3.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,42 @@
1
+ import { encodeFunctionData } from 'viem';
2
+ import { keyRegistryAbi } from '../chain/abis/index.js';
3
+ import { RotationLockError, readRotationLockOnChain } from '../chain/rotationLock.js';
4
+ import { protocolHex } from '../committee/receipts.js';
5
+ /**
6
+ * Lock a slot's key against every rotation, for good, with a durable named transaction from the
7
+ * slot creator's wallet (`KeyRegistry.lockKeyRotation`). Afterwards no creator, operator vote or
8
+ * revocation notice can rotate the key; resharing still works, because it keeps the key. Use it
9
+ * when the key is an identity that must never change, such as a custody address.
10
+ *
11
+ * The lock is SET-ONCE: a slot already locked resolves `already-locked` without sending. Every
12
+ * threshold-ECDSA slot is locked by its mode already, so it resolves that way too and never emits
13
+ * `KeyRotationLocked`. Refused before sending, as a `RotationLockError`: `no-slot`, `cancelled`,
14
+ * `unsupported` (a KeyRegistry without the lock) and `not-creator`; `not-confirmed` when the
15
+ * transaction confirmed but the chain does not show the lock. A transaction whose outcome was
16
+ * unknown is reconciled by calling this again with the same name (the wallet's journal).
17
+ * @param app Application client for the slot deployment.
18
+ * @param slotId Slot whose rotation is being locked.
19
+ * @param options Creator wallet and durable store for the named lock transaction.
20
+ */
21
+ export async function lockKeyRotation(app, slotId, options) {
22
+ protocolHex(slotId, 32, 'slot id');
23
+ const { wallet, store } = options, name = options.name ?? `rotation-lock-${slotId.slice(2)}`;
24
+ if (wallet.wallet.chain.id !== app.deployment.chainId)
25
+ throw new Error('Rotation lock wallet uses a different chain');
26
+ const registry = app.deployment.addresses.KeyRegistry, read = app.chain.client.readContract;
27
+ // Set-once: judge what is on chain before anything is signed or sent.
28
+ const before = await readRotationLockOnChain(read, registry, slotId);
29
+ if (before.cancelled)
30
+ throw new RotationLockError('cancelled', slotId, `slot ${slotId} is cancelled; a cancelled slot cannot be locked`);
31
+ if (before.locked)
32
+ return { phase: 'already-locked', slotId, lockedByCreator: before.lockedByCreator, lockedByMode: before.lockedByMode };
33
+ if (before.creator.toLowerCase() !== wallet.address.toLowerCase()) {
34
+ throw new RotationLockError('not-creator', slotId, `slot ${slotId} has creator ${before.creator}, but the wallet is ${wallet.address}`);
35
+ }
36
+ const data = encodeFunctionData({ abi: keyRegistryAbi, functionName: 'lockKeyRotation', args: [slotId] });
37
+ const transaction = await wallet.transfer(name, { to: registry, data }, store);
38
+ const after = await readRotationLockOnChain(read, registry, slotId);
39
+ if (!after.lockedByCreator)
40
+ throw new RotationLockError('not-confirmed', slotId, `slot ${slotId} shows lastRotatedAt ${after.lastRotatedAt}, not the lock`);
41
+ return transaction;
42
+ }
@@ -0,0 +1,135 @@
1
+ import type { Hex } from 'viem';
2
+ import { TasraError } from '../errors.js';
3
+ import type { DecryptionBindingWire } from '../crypto/recipient.js';
4
+ import { type DecryptShare } from '../crypto/kem.js';
5
+ import { type SessionDecryptItem, type SessionDecryptOptions, type SessionDecryptResult, type SessionVerifierProofWire } from '../decryption/session.js';
6
+ import { type PaidOperationConfig, type PaidSessionDecrypt } from './paid-operation.js';
7
+ import { SessionEndedError, type GrantedSession } from './session-grants.js';
8
+ /** One message to decrypt under a session. */
9
+ export interface SessionMessageRequest {
10
+ /** Paid operation configuration (the slot creator pays each message). */
11
+ config: PaidOperationConfig;
12
+ /** The accepted session ({@link GrantedSession}); call its `start()` so it follows the beacon. */
13
+ session: GrantedSession;
14
+ /**
15
+ * Open a NEW session when `session` ended before this message was served (`SessionEndedError`):
16
+ * ONE fresh presentation (a paid KEM decrypt in session mode) of exactly `message` (its
17
+ * `decryption` binding and recipient), accepted and started. Return the decrypt shares it opened
18
+ * and its payment's request id ({@link SessionReopened}); the message is served from them, never
19
+ * paid again. It may pay at most `budget.debits` (1 when the message already paid once); a
20
+ * reply naming more, or none, is refused. Called at most once per message, and once per ended
21
+ * session across concurrent messages (the others continue on its new session); without it the
22
+ * end is thrown.
23
+ */
24
+ reopen?(ended: SessionEndedError, message: SessionMessageRequest['message'], budget: {
25
+ debits: number;
26
+ }): Promise<SessionReopened>;
27
+ /** KEM slot the grant names. */
28
+ slot: Hex;
29
+ /** The keepers and their shares: everything {@link decryptWithSessionGrant} takes but the grant, key and proofs. */
30
+ keepers: Omit<SessionDecryptOptions, 'grant' | 'verified' | 'key' | 'slotId' | 'verifierProofs' | 'signal'>;
31
+ /** The anchored membership witnesses of the grant's draw at `epoch` (every production keeper requires them). */
32
+ verifierProofs?(slot: Hex, epoch: bigint): Promise<SessionVerifierProofWire[] | undefined>;
33
+ /** The ciphertext, its recipient and its binding ({@link decryptionBinding}). */
34
+ message: Omit<SessionDecryptItem, 'payment' | 'approveExecution' | 'recover'> & {
35
+ decryption: DecryptionBindingWire;
36
+ };
37
+ /**
38
+ * The beacon's latest epoch, read FRESH from the chain for each decision (default
39
+ * `readCurrentBeaconEpoch` on `config.chain.client` and `config.deployment`, at an RPC `latest`
40
+ * head of its own, never a followed tip that may lag the keepers' head). A keeper's refusal
41
+ * text never sets the session's beacon: it only triggers this read.
42
+ */
43
+ latestBeaconEpoch?(): Promise<bigint>;
44
+ /** Payment lifetime, seconds. */
45
+ ttlSecs?: number;
46
+ /** Aborts the payment and the keeper requests. */
47
+ signal?: AbortSignal;
48
+ /** Observers (timing, accounting); a throw from one is the caller's own. */
49
+ hooks?: {
50
+ onRequestId?(requestId: Hex): void | Promise<void>;
51
+ onPaid?(paid: PaidSessionDecrypt): void;
52
+ onApproval?(): void;
53
+ /**
54
+ * The message is paid and sent again on a refreshed grant (`reason`: `draw-moved`, `stale`,
55
+ * `reservation-stale` or `newer-verifier-epoch`).
56
+ */
57
+ onRetry?(reason: 'draw-moved' | 'stale' | 'reservation-stale' | 'newer-verifier-epoch'): void;
58
+ /** The session ended under this message and `reopen` is called (`code`: the end's). */
59
+ onReopen?(code: string): void;
60
+ };
61
+ }
62
+ /** A re-open: its presentation decrypted the message in flight. */
63
+ export interface SessionReopened {
64
+ /**
65
+ * The presentation's decrypt shares for THIS message (D_i = sk_i·U of `message.ciphertext`, as
66
+ * opened from the keepers' sealed partials, e.g. `collectSealedPartials`). Verified here against
67
+ * this ciphertext and `keepers.verifyingShares`, combined against this ciphertext and identity
68
+ * (AEAD), and zeroed after use: shares of any other message yield no plaintext.
69
+ */
70
+ shares: DecryptShare[];
71
+ /** The presentation's payment request ids (normally one): counted in {@link SessionMessageResult.requestIds}. */
72
+ requestIds: Hex[];
73
+ /** The new session, absent when the presentation opened no grant. */
74
+ session?: GrantedSession;
75
+ }
76
+ /** A message pays at most this many debits, a re-open's presentation included. */
77
+ export declare const MAX_MESSAGE_DEBITS = 2;
78
+ /** A decrypted message. */
79
+ export interface SessionMessageResult {
80
+ /** The decrypted message bytes. */
81
+ plaintext: Uint8Array;
82
+ /**
83
+ * Every payment request id this message made, in order, a re-open's presentation included. At most
84
+ * {@link MAX_MESSAGE_DEBITS} of them are debits: an allowance debit the accountant refused before
85
+ * the per-operation fallback names an id too, but debits nothing, as does a reservation refused
86
+ * before it was sent because the verifier epoch moved on (`NewerVerifierEpoch`).
87
+ */
88
+ requestIds: Hex[];
89
+ /** The epoch of the grant that served it (after a presenting re-open: the new grant's, 0 without one). */
90
+ grantEpoch: bigint;
91
+ /**
92
+ * The session for the next messages: `request.session`, or the one `reopen` returned; absent
93
+ * when the re-open's presentation served the message but opened no grant (open one again).
94
+ */
95
+ session?: GrantedSession;
96
+ /** The message was decrypted by the re-open's presentation, not under a grant. */
97
+ presented?: true;
98
+ }
99
+ /** A message the keepers refused (after the one retry a stale grant earns). */
100
+ export declare class SessionMessageError extends TasraError {
101
+ /** The keepers' refusal. */
102
+ readonly result: Extract<SessionDecryptResult, {
103
+ ok: false;
104
+ }>;
105
+ /** Every payment request id this message made, in order. */
106
+ readonly requestIds: Hex[];
107
+ constructor(
108
+ /** The keepers' refusal. */
109
+ result: Extract<SessionDecryptResult, {
110
+ ok: false;
111
+ }>,
112
+ /** Every payment request id this message made, in order. */
113
+ requestIds: Hex[]);
114
+ /** The first keeper code, for classification. */
115
+ get code(): string;
116
+ }
117
+ /**
118
+ * Decrypt one message under a session grant: pay it on the grant's draw ({@link paidSessionDecrypt}),
119
+ * send it to the keepers ({@link decryptWithSessionGrant}), combine. A beacon move the payment's
120
+ * discovery observes starts the grant's background refresh. A message whose grant the beacon has
121
+ * already left is re-paid ONCE on the refreshed grant before anything is signed
122
+ * (`PaidDrawMovedError`), or, refused by the keepers as stale with no keeper having run it
123
+ * (`SessionDecryptResult.stale`), re-paid and re-sent ONCE, and only when a fresh chain read
124
+ * ({@link SessionMessageRequest.latestBeaconEpoch}) confirms it: the beacon's latest epoch is past
125
+ * the grant's epoch + 1 (so the draw moved and no keeper may admit it). When the chain still says
126
+ * the grant is admissible, or cannot be read, the keepers' "stale" is unconfirmed and the refusal
127
+ * is thrown: nothing is paid again. A grant-expiry claim is never confirmed this way (the session
128
+ * checks `exp` itself before sending). Residual bound: at most two debits per message, the first
129
+ * refunded unexecuted at settlement unless a keeper lied about not running it (module comment).
130
+ * Every other refusal throws {@link SessionMessageError}; a session that cannot continue throws
131
+ * `SessionEndedError` (present again). A session that ended is re-opened through `reopen`
132
+ * (module comment): its presentation serves this message, single-flight per ended session.
133
+ * @param request - Message, session, slot and payment configuration.
134
+ */
135
+ export declare function decryptInSession(request: SessionMessageRequest): Promise<SessionMessageResult>;
@@ -0,0 +1,335 @@
1
+ // ADR-0090 D7–D9 one message under a session grant, end to end: pay on the grant's draw, decrypt
2
+ // through the keepers, and survive a beacon-epoch boundary.
3
+ //
4
+ // Keepers admit a grant only while its epoch is the beacon's latest or previous, and the agent
5
+ // continues a session exactly ONE epoch per refresh. So a grant must follow the beacon: the
6
+ // session refreshes in the background as soon as a CHAIN observation (this payment's discovery,
7
+ // the beacon poll, a fresh read a keeper refusal triggers) shows the beacon past the grant's
8
+ // epoch; a keeper's own claim about the beacon is never taken as one. The held grant
9
+ // stays admissible for the whole next epoch. A message that still crosses the boundary (its grant
10
+ // two epochs behind by the time the keepers judge it) is refused by every keeper BEFORE any item
11
+ // runs; then, and only when a fresh chain read confirms the grant really left the window, this
12
+ // helper waits for the refreshed grant, pays the message again on its draw and sends it once more.
13
+ //
14
+ // What the first payment costs: its debit stays in the cumulative allowance voucher (it uses
15
+ // allowance headroom until settled) and, unexecuted, is refunded (paid = 0, prepaidRefunded =
16
+ // cost) when the settlement worker settles it after the payment's expiry; that close is blocked
17
+ // while an operator named on that debit is unreachable. The residual risk is bounded: a keeper can
18
+ // compute its partial yet answer "stale" (and later report the execution it approved), so a
19
+ // message may pay at most TWO debits, and only when every other keeper also refused before
20
+ // execution AND the chain independently shows the grant two epochs behind, i.e. the retry was due.
21
+ //
22
+ // A session that ENDS under a message (a definite refusal such as `session_context_changed`, the
23
+ // beacon two epochs past the grant, idle/absolute expiry) is re-opened ONCE for that message when
24
+ // the caller supplies `reopen` (a fresh presentation is the caller's: only it holds the wallet).
25
+ // The re-open never resends a paid write. Its presentation IS a paid KEM decrypt, so it must
26
+ // decrypt THIS message: it returns the decrypt shares it opened, and this helper verifies them
27
+ // against this message's ciphertext and the keepers' authenticated verifying shares and combines
28
+ // them itself (the AEAD open under this message's identity), so a plaintext of any other message
29
+ // can never be returned for this one. The message is then served; nothing more is paid. Its
30
+ // payment counts among the message's debits (and its ids in `requestIds`): an end before the message paid costs
31
+ // that one debit; an end after a confirmed-stale refusal is that refusal's one retry. The bound is
32
+ // enforced: no payment and no re-open is started once the message holds MAX_MESSAGE_DEBITS (2).
33
+ //
34
+ // Concurrent messages of one ended session share ONE re-open: the first calls `reopen` (serving
35
+ // its own message), the others wait for it and continue on its new session, each paying its own
36
+ // message there as usual; when that presentation opened no grant they re-open in turn.
37
+ import { TasraError } from '../errors.js';
38
+ import { PaidDrawMovedError, readCurrentBeaconEpoch } from '../chain/prepaid.js';
39
+ import { PaidReservationStaleEpochError } from '../chain/reservation.js';
40
+ import { combineDecryptShares, decodeKemU, verifyDecryptSharesBatch } from '../crypto/kem.js';
41
+ import { decryptWithSessionGrant } from '../decryption/session.js';
42
+ import { NewerVerifierEpoch, paidSessionDecrypt } from './paid-operation.js';
43
+ import { SessionEndedError } from './session-grants.js';
44
+ /** A message pays at most this many debits, a re-open's presentation included. */
45
+ export const MAX_MESSAGE_DEBITS = 2;
46
+ const HEX32 = /^0x[0-9a-fA-F]{64}$/;
47
+ /** The running re-open of an ended session, shared by every message that finds it ended. */
48
+ const reopening = new WeakMap();
49
+ /** An ended session's re-opened successor: later messages of the ended session continue there. */
50
+ const successors = new WeakMap();
51
+ /** A message the keepers refused (after the one retry a stale grant earns). */
52
+ export class SessionMessageError extends TasraError {
53
+ result;
54
+ requestIds;
55
+ constructor(
56
+ /** The keepers' refusal. */
57
+ result,
58
+ /** Every payment request id this message made, in order. */
59
+ requestIds) {
60
+ super(`session item refused: ${result.error}`);
61
+ this.result = result;
62
+ this.requestIds = requestIds;
63
+ this.name = 'SessionMessageError';
64
+ }
65
+ /** The first keeper code, for classification. */
66
+ get code() { return this.result.codes[0] ?? 'session-item'; }
67
+ }
68
+ /** The epoch of a re-opened session's grant (0 when there is none, or it already ended). */
69
+ function openedEpoch(session) {
70
+ try {
71
+ return session ? BigInt(session.current().epoch) : 0n;
72
+ }
73
+ catch {
74
+ return 0n;
75
+ }
76
+ }
77
+ /**
78
+ * The plaintext of THIS message from a re-open's decrypt shares: each share's verifying share is the
79
+ * keeper's authenticated one, each share verifies against this ciphertext's U, and the first
80
+ * `threshold` valid ones are combined against this ciphertext and identity (the AEAD open). The
81
+ * shares are zeroed whatever the outcome.
82
+ */
83
+ async function combineReopened(request, shares) {
84
+ const { ciphertext, identity } = request.message, { threshold, verifyingShares } = request.keepers;
85
+ try {
86
+ if (!Array.isArray(shares))
87
+ throw new TasraError('Session re-open answered no decrypt shares');
88
+ const seen = new Set();
89
+ const candidates = [];
90
+ for (const share of shares) {
91
+ const vs = share && verifyingShares.get(share.id);
92
+ // One share per authenticated keeper; the supplied verifying share is never trusted.
93
+ if (!vs || seen.has(share.id) || !(share.decryptionShare instanceof Uint8Array))
94
+ continue;
95
+ seen.add(share.id);
96
+ candidates.push({ id: share.id, decryptionShare: share.decryptionShare, verifyingShare: vs });
97
+ }
98
+ const verdict = verifyDecryptSharesBatch(candidates, decodeKemU(ciphertext.u));
99
+ const valid = candidates.filter((_, i) => verdict[i]).slice(0, threshold);
100
+ if (valid.length < threshold)
101
+ throw new TasraError(`Session re-open shares do not decrypt this message (${valid.length}/${threshold} valid)`);
102
+ const combine = request.keepers.combine ?? ((s, ct, id) => combineDecryptShares(s, ct, id, { verify: false }));
103
+ try {
104
+ return await combine(valid, ciphertext, identity);
105
+ }
106
+ catch (cause) {
107
+ throw new TasraError('Session re-open shares do not decrypt this message (AEAD)', { cause });
108
+ }
109
+ }
110
+ finally {
111
+ if (Array.isArray(shares))
112
+ for (const share of shares)
113
+ if (share?.decryptionShare instanceof Uint8Array)
114
+ share.decryptionShare.fill(0);
115
+ }
116
+ }
117
+ /** The chain's beacon epoch now, or undefined when the read fails (never cached across decisions). */
118
+ async function chainBeacon(request) {
119
+ try {
120
+ const epoch = await (request.latestBeaconEpoch ? request.latestBeaconEpoch() : readCurrentBeaconEpoch(request.config.chain.client, { ...request.config.deployment }, { fresh: true }));
121
+ return typeof epoch === 'bigint' && epoch >= 0n ? epoch : undefined;
122
+ }
123
+ catch {
124
+ return undefined;
125
+ }
126
+ }
127
+ /**
128
+ * Wait for a refresh only when the held grant cannot serve (two epochs behind the observed beacon).
129
+ * A grant one epoch behind is still admissible for the whole epoch: the message uses it at once
130
+ * and the follow runs in the background (re-kicked here, honoring its backoff); it never waits for
131
+ * a refresh that may take a whole anchoring delay.
132
+ */
133
+ async function settle(session) {
134
+ const beacon = session.beaconEpoch;
135
+ if (beacon === undefined)
136
+ return;
137
+ const at = BigInt(session.current().epoch);
138
+ if (at >= beacon)
139
+ return;
140
+ if (at + 1n >= beacon) {
141
+ session.observeBeacon(beacon);
142
+ return;
143
+ }
144
+ try {
145
+ await session.followBeacon();
146
+ }
147
+ catch (error) {
148
+ // The follow moved the grant into the window before it gave up: use it; a later observation retries.
149
+ if (!(error instanceof SessionEndedError) && BigInt(session.current().epoch) + 1n >= (session.beaconEpoch ?? beacon))
150
+ return;
151
+ throw error;
152
+ }
153
+ }
154
+ /**
155
+ * Decrypt one message under a session grant: pay it on the grant's draw ({@link paidSessionDecrypt}),
156
+ * send it to the keepers ({@link decryptWithSessionGrant}), combine. A beacon move the payment's
157
+ * discovery observes starts the grant's background refresh. A message whose grant the beacon has
158
+ * already left is re-paid ONCE on the refreshed grant before anything is signed
159
+ * (`PaidDrawMovedError`), or, refused by the keepers as stale with no keeper having run it
160
+ * (`SessionDecryptResult.stale`), re-paid and re-sent ONCE, and only when a fresh chain read
161
+ * ({@link SessionMessageRequest.latestBeaconEpoch}) confirms it: the beacon's latest epoch is past
162
+ * the grant's epoch + 1 (so the draw moved and no keeper may admit it). When the chain still says
163
+ * the grant is admissible, or cannot be read, the keepers' "stale" is unconfirmed and the refusal
164
+ * is thrown: nothing is paid again. A grant-expiry claim is never confirmed this way (the session
165
+ * checks `exp` itself before sending). Residual bound: at most two debits per message, the first
166
+ * refunded unexecuted at settlement unless a keeper lied about not running it (module comment).
167
+ * Every other refusal throws {@link SessionMessageError}; a session that cannot continue throws
168
+ * `SessionEndedError` (present again). A session that ended is re-opened through `reopen`
169
+ * (module comment): its presentation serves this message, single-flight per ended session.
170
+ * @param request - Message, session, slot and payment configuration.
171
+ */
172
+ export async function decryptInSession(request) {
173
+ const { slot, hooks } = request;
174
+ let session = request.session;
175
+ const requestIds = [];
176
+ let retried = false;
177
+ /** A reservation refused before it was sent (`NewerVerifierEpoch`) was already paid again once. */
178
+ let epochRetried = false;
179
+ /** Debits this message started: each payment, a stale-refused reservation (its intent may land), the re-open's presentation. */
180
+ let debits = 0;
181
+ for (;;) {
182
+ let grant, verified;
183
+ try {
184
+ await settle(session);
185
+ grant = session.current();
186
+ verified = await session.verifiedFor(slot);
187
+ }
188
+ catch (error) {
189
+ // The session ended (nothing of this attempt is paid yet).
190
+ if (!(error instanceof SessionEndedError))
191
+ throw error;
192
+ // Another message already re-opened it: continue on its session, paying as usual.
193
+ const after = successors.get(session);
194
+ if (after) {
195
+ session = after;
196
+ continue;
197
+ }
198
+ // Another message is re-opening it now: wait for its session (one presentation per end).
199
+ const running = reopening.get(session);
200
+ if (running) {
201
+ try {
202
+ await running;
203
+ }
204
+ catch {
205
+ throw error;
206
+ }
207
+ const opened = successors.get(session);
208
+ if (opened) {
209
+ session = opened;
210
+ continue;
211
+ }
212
+ // That presentation opened no grant: this message re-opens in turn (below).
213
+ }
214
+ // At most once per message: the re-open below always serves the message (or throws).
215
+ if (!request.reopen || debits >= MAX_MESSAGE_DEBITS)
216
+ throw error;
217
+ hooks?.onReopen?.(error.code);
218
+ const ended = session, budget = MAX_MESSAGE_DEBITS - debits;
219
+ const flight = request.reopen(error, request.message, { debits: budget }).then(next => {
220
+ if (next?.session)
221
+ successors.set(ended, next.session);
222
+ return next;
223
+ });
224
+ reopening.set(ended, flight);
225
+ let next;
226
+ try {
227
+ next = await flight;
228
+ }
229
+ finally {
230
+ if (reopening.get(ended) === flight)
231
+ reopening.delete(ended);
232
+ }
233
+ const ids = next?.requestIds;
234
+ if (!Array.isArray(ids) || ids.length < 1 || ids.length > budget || ids.some(id => typeof id !== 'string' || !HEX32.test(id))) {
235
+ if (Array.isArray(next?.shares))
236
+ for (const share of next.shares)
237
+ share?.decryptionShare?.fill?.(0);
238
+ throw new TasraError(`Session re-open must name its presentation's payment (1..${budget} request ids)`);
239
+ }
240
+ requestIds.push(...ids);
241
+ // The opening presentation decrypted this message: served from its shares; nothing more is paid.
242
+ const plaintext = await combineReopened(request, next.shares);
243
+ return { plaintext, requestIds, grantEpoch: openedEpoch(next.session), ...next.session ? { session: next.session } : {}, presented: true };
244
+ }
245
+ const proofs = request.verifierProofs ? await request.verifierProofs(slot, BigInt(grant.epoch)) : undefined;
246
+ // The two-debit bound, enforced (a re-open's presentation counts).
247
+ if (debits >= MAX_MESSAGE_DEBITS)
248
+ throw new TasraError(`Session message already started ${debits} debits; not paying again`);
249
+ let paid;
250
+ try {
251
+ paid = await paidSessionDecrypt(request.config, { slot, decryption: request.message.decryption, grant: { epoch: grant.epoch, seed: grant.seed },
252
+ ...request.ttlSecs !== undefined ? { ttlSecs: request.ttlSecs } : {}, ...request.signal ? { signal: request.signal } : {},
253
+ onBeaconEpoch: epoch => session.observeBeacon(epoch),
254
+ onRequestId: async (id) => { requestIds.push(id); await hooks?.onRequestId?.(id); } });
255
+ debits++;
256
+ }
257
+ catch (error) {
258
+ // The grant left the window before anything was signed or paid: refresh and pay once more.
259
+ if (error instanceof PaidDrawMovedError && !retried) {
260
+ session.observeBeacon(error.beaconEpoch);
261
+ retried = true;
262
+ hooks?.onRetry?.('draw-moved');
263
+ continue;
264
+ }
265
+ // The reservation waited for its payer until the grant's epoch was two behind the beacon and
266
+ // was refused BEFORE anything was sent: no reservation was prepared, persisted or broadcast,
267
+ // and its journal is `failed` (never resumed). It debited nothing, so it does not count as a
268
+ // debit; it is paid again once, on the refreshed grant (the epoch it carries is this
269
+ // process's own chain read, which starts the follow), and only while the message is under
270
+ // its debit bound. A second one is thrown.
271
+ if (error instanceof NewerVerifierEpoch && error.code === 'newer-verifier-epoch' && !epochRetried && debits < MAX_MESSAGE_DEBITS) {
272
+ session.observeBeacon(error.beaconEpoch);
273
+ epochRetried = true;
274
+ hooks?.onRetry?.('newer-verifier-epoch');
275
+ continue;
276
+ }
277
+ // The accountant refused the reservation's draw as no longer current or previous (it waited
278
+ // past an epoch tick; nothing was sent). That intent may still land, permissionlessly, until
279
+ // it expires: it stays journaled and is never re-sent. It cannot execute (keepers execute a
280
+ // session item only with the payment this helper sends them), so if it lands it is refunded
281
+ // unexecuted at settlement, like a stale-refused first debit. Pay once more only when a fresh
282
+ // chain read confirms the grant left the window (which also ends the session, so the retry
283
+ // runs on a re-opened one): the same two-debit bound.
284
+ const refused = error;
285
+ if (refused?.code === 'reservation-refused' && refused.cause instanceof PaidReservationStaleEpochError && !retried) {
286
+ debits++;
287
+ const latest = await chainBeacon(request);
288
+ if (latest !== undefined)
289
+ session.observeBeacon(latest);
290
+ if (latest !== undefined && latest > BigInt(grant.epoch) + 1n) {
291
+ retried = true;
292
+ hooks?.onRetry?.('reservation-stale');
293
+ continue;
294
+ }
295
+ }
296
+ throw error;
297
+ }
298
+ try {
299
+ hooks?.onPaid?.(paid);
300
+ const approveExecution = async (approval) => {
301
+ const approved = await paid.approveExecution(approval);
302
+ hooks?.onApproval?.();
303
+ return approved;
304
+ };
305
+ const { decryption: _binding, ...message } = request.message;
306
+ const [result] = await decryptWithSessionGrant({ ...request.keepers, slotId: slot, grant, verified, key: session.key,
307
+ ...proofs ? { verifierProofs: proofs } : {}, ...request.signal ? { signal: request.signal } : {} }, [{ ...message, payment: paid.payment, approveExecution }]);
308
+ if (!result)
309
+ throw new TasraError('Session keepers answered no item');
310
+ if (result.ok)
311
+ return { plaintext: result.plaintext, requestIds, grantEpoch: BigInt(grant.epoch), session };
312
+ if (result.stale && !retried) {
313
+ // Every keeper refused the grant as no longer current before running anything. Their text
314
+ // (any "beacon latest N") is the keepers' claim, never fed into the session: it only
315
+ // triggers a fresh chain read, and the chain's epoch is what the session follows.
316
+ // Pay again only when the chain CONFIRMS staleness: a keeper that computed its partial and
317
+ // answered "stale" anyway must not earn a second debit while the grant is still admissible.
318
+ // An unreadable chain confirms nothing.
319
+ const latest = await chainBeacon(request);
320
+ // The chain's epoch is a fair observation either way (a move past the grant starts its follow).
321
+ if (latest !== undefined)
322
+ session.observeBeacon(latest);
323
+ if (latest !== undefined && latest > BigInt(grant.epoch) + 1n) {
324
+ retried = true;
325
+ hooks?.onRetry?.('stale');
326
+ continue;
327
+ }
328
+ }
329
+ throw new SessionMessageError(result, requestIds);
330
+ }
331
+ finally {
332
+ paid.dispose();
333
+ }
334
+ }
335
+ }