@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
@@ -1,5 +1,13 @@
1
+ import { p256 } from '@noble/curves/p256';
2
+ import { evidenceBody } from './evidence.js';
3
+ import { equalBytes } from '@noble/curves/utils.js';
1
4
  import { hexToBytes, bytesToHex } from '../crypto/hex.js';
2
5
  import { httpError } from '../errors.js';
6
+ import { withKeeperExecutionApprovals } from './keeperExecution.js';
7
+ import { withNetworkDeadline } from '../internal/network.js';
8
+ import { sha256 } from '@noble/hashes/sha256';
9
+ import { requireDualOperationProof } from './dual-operation.js';
10
+ import { protocolHex } from './receipts.js';
3
11
  /**
4
12
  * Sign an Ethereum digest using credential-based committee authorization.
5
13
  * Open the verifier-agent session with action `sign` and message equal to `digest`.
@@ -8,38 +16,102 @@ import { httpError } from '../errors.js';
8
16
  * @returns Ethereum signature components and the secp256k1 group public key.
9
17
  * @throws On malformed input/response, network failure, or keeper rejection.
10
18
  * HTTP 401/403 is an authorization denial; do not retry it as a network failure.
19
+ * Approvals, HTTP and response decoding have one 15-second deadline. A timeout
20
+ * requires reconciliation of the original operation, not a new paid attempt.
11
21
  *
12
22
  * @param opts - Compound authorization, keeper endpoint and 32-byte ECDSA digest.
13
23
  */
14
24
  export async function committeeSignEoaDigest(opts) {
25
+ return withNetworkDeadline(signal => signWithinDeadline({ ...opts, signal }), opts.signal);
26
+ }
27
+ /**
28
+ * Sign a 32-byte digest with a threshold P-256 (`tecdsa-p256`) slot through the same keeper route
29
+ * and authorization as {@link committeeSignEoaDigest}. The reply must name mode `tecdsa-p256`,
30
+ * carry the expected group key and verify as a P-256 signature over the digest (no prehash);
31
+ * anything else is refused.
32
+ * @param opts - Compound authorization, keeper endpoint, 32-byte digest and the slot's group key.
33
+ * @returns r, s and the group key.
34
+ * @throws On malformed input/response, a signature that does not verify, network failure or keeper rejection.
35
+ */
36
+ export async function committeeSignP256Digest(opts) {
37
+ if (opts.digest.length !== 32)
38
+ throw new Error('committeeSignP256Digest: digest must be 32 bytes');
39
+ let expected;
40
+ try {
41
+ expected = p256.ProjectivePoint.fromHex(opts.groupPublicKey).toRawBytes(true);
42
+ }
43
+ catch {
44
+ throw new Error('committeeSignP256Digest: invalid expected P-256 group public key');
45
+ }
46
+ const digest = opts.digest.slice();
47
+ const data = await withNetworkDeadline(signal => requestWithinDeadline({ ...opts, signal }, 'p256-sign'), opts.signal);
48
+ const scalar = (value) => typeof value === 'string' && /^(?:0x)?[a-fA-F0-9]{64}$/.test(value);
49
+ if (!data || data.mode !== 'tecdsa-p256' || !scalar(data.signature_r) || !scalar(data.signature_s)
50
+ || typeof data.group_public_key !== 'string' || !/^(?:0x)?(?:0[23][a-fA-F0-9]{64}|04[a-fA-F0-9]{128})$/.test(data.group_public_key)) {
51
+ throw new Error('committeeSignP256Digest: invalid P-256 signature response');
52
+ }
53
+ const groupPublicKey = hexToBytes(data.group_public_key), r = hexToBytes(data.signature_r), s = hexToBytes(data.signature_s);
54
+ let returned;
55
+ try {
56
+ returned = p256.ProjectivePoint.fromHex(groupPublicKey).toRawBytes(true);
57
+ }
58
+ catch {
59
+ throw new Error('committeeSignP256Digest: invalid P-256 group public key');
60
+ }
61
+ if (!equalBytes(returned, expected))
62
+ throw new Error('committeeSignP256Digest: group public key differs from the slot key');
63
+ const signature = new Uint8Array(64);
64
+ signature.set(r, 0);
65
+ signature.set(s, 32);
66
+ if (!p256.verify(signature, digest, expected, { prehash: false, lowS: false }))
67
+ throw new Error('committeeSignP256Digest: signature does not verify under the slot key');
68
+ return { groupPublicKey, r, s };
69
+ }
70
+ async function signWithinDeadline(opts) {
71
+ const data = await requestWithinDeadline(opts, 'secp256k1-sign');
72
+ const scalar = (value) => typeof value === 'string' && /^(?:0x)?[a-fA-F0-9]{64}$/.test(value);
73
+ if (!data || data.mode !== 'tecdsa' || (data.signature_v !== 0 && data.signature_v !== 1) ||
74
+ !scalar(data.signature_r) || !scalar(data.signature_s) ||
75
+ typeof data.group_public_key !== 'string' || !/^(?:0x)?0[23][a-fA-F0-9]{64}$/.test(data.group_public_key)) {
76
+ throw new Error('committeeSignEoaDigest: invalid secp256k1 signature response');
77
+ }
78
+ return { groupPublicKey: hexToBytes(data.group_public_key), r: hexToBytes(data.signature_r),
79
+ s: hexToBytes(data.signature_s), yParity: data.signature_v };
80
+ }
81
+ /** The shared keeper request of both digest clients: approvals, POST and the decoded JSON reply. */
82
+ async function requestWithinDeadline(opts, operation) {
83
+ opts = { ...opts, committeeToken: structuredClone(opts.committeeToken) };
15
84
  if (opts.digest.length !== 32)
16
85
  throw new Error('committeeSignEoaDigest: digest must be 32 bytes');
17
86
  if (opts.userSignature && opts.userSignature.length !== 64)
18
87
  throw new Error('userSignature must be 64 bytes');
19
88
  const bare = (hex) => hex.replace(/^0x/, '');
20
- const body = {
89
+ if (opts.dualControl) {
90
+ const payment = opts.committeeToken.payment;
91
+ if (!payment)
92
+ throw new Error('dual-control approvals require a paid authorization');
93
+ requireDualOperationProof(opts.dualControl, { operation, slot: protocolHex(opts.committeeToken.slot_id, 32, 'token slot'), payloadDigest: sha256(opts.digest), payment });
94
+ }
95
+ const unsignedBody = {
21
96
  committee_token: opts.committeeToken,
97
+ ...evidenceBody(opts.committeeToken, opts.evidenceCt),
22
98
  digest: bare(bytesToHex(opts.digest)),
23
- verifier_proofs: opts.verifierProofs?.map(p => ({
24
- verifier_index: p.verifierIndex, operator: bare(p.operator), pubkey: bare(p.pubkey), proof: p.proof.map(bare),
25
- })),
26
- target_keykeeper: opts.targetKeykeeper && bare(opts.targetKeykeeper),
27
- user_signature: opts.userSignature && bare(bytesToHex(opts.userSignature)),
99
+ ...(opts.verifierProofs ? { verifier_proofs: opts.verifierProofs.map(p => ({
100
+ verifier_index: p.verifierIndex, operator: bare(p.operator), pubkey: bare(p.pubkey), proof: p.proof.map(bare),
101
+ })) } : {}),
102
+ ...(opts.targetKeykeeper ? { target_keykeeper: bare(opts.targetKeykeeper) } : {}),
103
+ ...(opts.userSignature ? { user_signature: bare(bytesToHex(opts.userSignature)) } : {}),
104
+ ...(opts.dualControl ? { dual_control: structuredClone(opts.dualControl) } : {}),
28
105
  };
106
+ const body = await withKeeperExecutionApprovals({ body: unsignedBody, kind: 'committee-eoa-digest', nodeUrl: opts.nodeUrl,
107
+ payment: opts.committeeToken.payment, approveExecution: opts.approveExecution, signal: opts.signal });
29
108
  const url = `${opts.nodeUrl.replace(/\/$/, '')}/v1/committee/sign/eoa-digest`;
30
109
  const response = await (opts.fetchImpl ?? fetch)(url, {
31
110
  method: 'POST', headers: { 'Content-Type': 'application/json', ...(opts.requestId ? { 'x-request-id': opts.requestId } : {}) },
32
111
  body: JSON.stringify(body), signal: opts.signal,
112
+ ...(opts.committeeToken.payment ? { redirect: 'error', credentials: 'omit' } : {}),
33
113
  });
34
114
  if (!response.ok)
35
115
  throw await httpError(response, url, 'committee/sign/eoa-digest');
36
- const data = await response.json();
37
- const scalar = (value) => typeof value === 'string' && /^(?:0x)?[a-fA-F0-9]{64}$/.test(value);
38
- if (!data || data.mode !== 'tecdsa' || (data.signature_v !== 0 && data.signature_v !== 1) ||
39
- !scalar(data.signature_r) || !scalar(data.signature_s) ||
40
- typeof data.group_public_key !== 'string' || !/^(?:0x)?0[23][a-fA-F0-9]{64}$/.test(data.group_public_key)) {
41
- throw new Error('committeeSignEoaDigest: invalid secp256k1 signature response');
42
- }
43
- return { groupPublicKey: hexToBytes(data.group_public_key), r: hexToBytes(data.signature_r),
44
- s: hexToBytes(data.signature_s), yParity: data.signature_v };
116
+ return await response.json();
45
117
  }
@@ -0,0 +1,30 @@
1
+ import { evidenceBindingMessage } from './token.js';
2
+ /** Sealed presentation bindings signed beside the unchanged compound-token hash. */
3
+ export interface EvidenceBindingWire {
4
+ /** Keccak-256 of the encoded ciphertext bytes. */
5
+ evidence_hash?: string;
6
+ /** Certified accountant evidence-key identifier. */
7
+ evidence_key_id?: string;
8
+ /** Verifier signatures binding the token, ciphertext hash and evidence key. */
9
+ evidence_signatures?: {
10
+ verifier_index: number;
11
+ signature: string;
12
+ }[];
13
+ }
14
+ /** Validate all-or-none metadata without changing any signed token bytes. */
15
+ export declare function assertEvidenceBinding(token: EvidenceBindingWire & {
16
+ verifier_indexes: number[];
17
+ }): boolean;
18
+ /** Bind the exact canonical base64url ciphertext before keeper approval or submission. */
19
+ export declare function evidenceBody(token: EvidenceBindingWire & {
20
+ verifier_indexes: number[];
21
+ }, evidenceCt?: string): {
22
+ evidence_ct?: string;
23
+ };
24
+ /** Domain-separated message signed beside the original compound token. ONE implementation:
25
+ * the public `evidenceBindingMessage` in `./token.ts` (byte-identical to the Rust one). */
26
+ export { evidenceBindingMessage };
27
+ /** Authenticate sealed evidence under the independently anchored verifier committee keys. */
28
+ export declare function verifyEvidenceBinding(token: EvidenceBindingWire & {
29
+ verifier_indexes: number[];
30
+ }, evidenceCt: string | undefined, tokenHash: Uint8Array, keys: Map<number, Uint8Array>, quorum: number): void;
@@ -0,0 +1,65 @@
1
+ import { keccak_256 } from '@noble/hashes/sha3';
2
+ import { ed25519 } from '@noble/curves/ed25519';
3
+ import { bytesToHex } from '@noble/hashes/utils';
4
+ import { base64Decode, base64Encode } from '../crypto/envelope.js';
5
+ import { hexToBytes } from '../crypto/hex.js';
6
+ import { evidenceBindingMessage } from './token.js';
7
+ const hash32 = /^(?:0x)?[a-f0-9]{64}$/i;
8
+ const sig64 = /^(?:0x)?[a-f0-9]{128}$/i;
9
+ /** Validate all-or-none metadata without changing any signed token bytes. */
10
+ export function assertEvidenceBinding(token) {
11
+ const present = token.evidence_hash != null || token.evidence_key_id != null || (token.evidence_signatures?.length ?? 0) > 0;
12
+ if (!present) {
13
+ if (token.evidence_signatures != null && !Array.isArray(token.evidence_signatures))
14
+ throw new Error('Invalid sealed evidence signatures');
15
+ return false;
16
+ }
17
+ if (typeof token.evidence_hash !== 'string' || !hash32.test(token.evidence_hash)
18
+ || typeof token.evidence_key_id !== 'string' || !hash32.test(token.evidence_key_id)
19
+ || !Array.isArray(token.evidence_signatures) || token.evidence_signatures.length === 0
20
+ || token.evidence_signatures.length > token.verifier_indexes.length)
21
+ throw new Error('Incomplete sealed evidence binding');
22
+ const seen = new Set();
23
+ for (const entry of token.evidence_signatures) {
24
+ if (!entry || !Number.isSafeInteger(entry.verifier_index) || !token.verifier_indexes.includes(entry.verifier_index)
25
+ || seen.has(entry.verifier_index) || typeof entry.signature !== 'string' || !sig64.test(entry.signature))
26
+ throw new Error('Invalid sealed evidence signature');
27
+ seen.add(entry.verifier_index);
28
+ }
29
+ return true;
30
+ }
31
+ /** Bind the exact canonical base64url ciphertext before keeper approval or submission. */
32
+ export function evidenceBody(token, evidenceCt) {
33
+ const bound = assertEvidenceBinding(token);
34
+ if (!bound && evidenceCt === undefined)
35
+ return {};
36
+ if (!bound || typeof evidenceCt !== 'string' || evidenceCt.length === 0 || evidenceCt.length > 21846
37
+ || !/^[A-Za-z0-9_-]+$/.test(evidenceCt))
38
+ throw new Error('Missing or invalid sealed evidence ciphertext');
39
+ const bytes = base64Decode(evidenceCt.replace(/-/g, '+').replace(/_/g, '/'));
40
+ if (bytes.length > 16384 || base64Encode(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') !== evidenceCt
41
+ || bytesToHex(keccak_256(bytes)) !== token.evidence_hash.replace(/^0x/, '').toLowerCase())
42
+ throw new Error('Sealed evidence ciphertext does not match its binding');
43
+ return { evidence_ct: evidenceCt };
44
+ }
45
+ /** Domain-separated message signed beside the original compound token. ONE implementation:
46
+ * the public `evidenceBindingMessage` in `./token.ts` (byte-identical to the Rust one). */
47
+ export { evidenceBindingMessage };
48
+ /** Authenticate sealed evidence under the independently anchored verifier committee keys. */
49
+ export function verifyEvidenceBinding(token, evidenceCt, tokenHash, keys, quorum) {
50
+ evidenceBody(token, evidenceCt);
51
+ if (!assertEvidenceBinding(token))
52
+ return;
53
+ if (!Number.isSafeInteger(quorum) || quorum < 1 || quorum > token.verifier_indexes.length)
54
+ throw new Error('Invalid evidence quorum');
55
+ const message = evidenceBindingMessage(tokenHash, hexToBytes(token.evidence_hash), hexToBytes(token.evidence_key_id));
56
+ let count = 0;
57
+ for (const entry of token.evidence_signatures) {
58
+ const key = keys.get(entry.verifier_index);
59
+ if (!key || !ed25519.verify(hexToBytes(entry.signature), message, key, { zip215: false }))
60
+ throw new Error('Sealed evidence signature does not verify');
61
+ count++;
62
+ }
63
+ if (count < quorum)
64
+ throw new Error('Sealed evidence quorum not met');
65
+ }
@@ -0,0 +1,414 @@
1
+ import { type Address, type Hex } from 'viem';
2
+ import { type PaymentIntentWire } from './payment.js';
3
+ /** Separate creator-consent domain; original payment commitments remain unchanged. */
4
+ export declare const EXECUTION_CERTIFICATE_DOMAIN = "Keykeeper Client Execution Certificate";
5
+ /** Client stage approvals bind complete request bodies and assigned operator keys. */
6
+ export declare const EXECUTION_APPROVAL_DOMAIN = "Keykeeper Client Stage Approval";
7
+ /** Client consent to one exact session and independently approved registered agent. */
8
+ export declare const EXECUTION_INITIALIZATION_DOMAIN = "Keykeeper Client Session Initialization";
9
+ /** Maximum complete unsigned request size shared with the Rust verifier. */
10
+ export declare const MAX_EXECUTION_BODY_BYTES: number;
11
+ /** Stable stage names and ordinals from the shared execution report protocol. */
12
+ export type ExecutionStage = 'coordinator' | 'contributor' | 'presentation_sign' | 'presentation_attest' | 'credential';
13
+ /** Creator certificate for one payment and a client-owned Ed25519 public key. */
14
+ export interface ExecutionCertificate {
15
+ /** Public key; never deliver its private seed to the verifier agent. */
16
+ execution_key: Hex;
17
+ /** Unix expiry no later than the original creator payment. */
18
+ expires: number;
19
+ /** Creator EIP-712 signature over the certificate. */
20
+ creator_signature: Hex;
21
+ }
22
+ /** Client signature authorizing one exact body, stage and assigned operator. */
23
+ export interface ExecutionAuthorization {
24
+ /** Creator-certified public execution key and bounded consent. */
25
+ certificate: ExecutionCertificate;
26
+ /** Paid stage being authorized. */
27
+ stage: ExecutionStage;
28
+ /** Independently authenticated operator's Ed25519 public key. */
29
+ operator_key: Hex;
30
+ /** Locally recomputed complete unsigned body hash. */
31
+ body_hash: Hex;
32
+ /** Unix expiry no later than the certificate. */
33
+ expires: number;
34
+ /** Client Ed25519 signature over the structured stage approval hash. */
35
+ signature: Hex;
36
+ }
37
+ /** Public proof of the original client-approved work, without its private request body. */
38
+ export interface ExecutionConsent {
39
+ /** Creator certificate and original client signature for this stage. */
40
+ authorization: ExecutionAuthorization;
41
+ /** Worker commitment to its exact accepted inputs; this is not a computation proof. */
42
+ inputs_commitment: number[];
43
+ /** Original admission time, checked against canonical historical backing by the reader. */
44
+ verified_at: number;
45
+ }
46
+ /** Client authorization to create a session; this is not a paid operator stage. */
47
+ export interface SessionInitialization {
48
+ /** Public execution key certified by the slot creator. */
49
+ certificate: ExecutionCertificate;
50
+ /** Hash of the independently approved registered agent profile. */
51
+ profile_hash: Hex;
52
+ /** Hash of the complete unsigned create body, including the client owner bearer. */
53
+ body_hash: Hex;
54
+ /** Unix expiry bounded by the certificate. */
55
+ expires: number;
56
+ /** Client Ed25519 signature in a separate initialization domain. */
57
+ signature: Hex;
58
+ }
59
+ /** Independent client intent for a registered agent session. */
60
+ export interface ExpectedInitialization {
61
+ /** Previously authenticated and approved agent profile; never copied from its response. */
62
+ serviceProfile: Record<string, unknown>;
63
+ /** Client-built complete create body, excluding execution_initialization. */
64
+ body: Record<string, unknown>;
65
+ }
66
+ /** Independently selected deployment, creator and exact reserved payment. */
67
+ export interface ExecutionConsentPolicy {
68
+ /** Approved chain ID. */
69
+ chainId: number;
70
+ /** Approved Settlement proxy. */
71
+ settlement: Address;
72
+ /** Approved KeyRegistry proxy. */
73
+ keyRegistry: Address;
74
+ /** Creator read independently from the intended slot. */
75
+ creator: Address;
76
+ /** Exact locally retained payment commitment, never copied from a proposal. */
77
+ paymentHash: Hex;
78
+ /** Nonzero fee from the canonical quote or mined reservation, in TASRA base units. */
79
+ cost: bigint;
80
+ /** Fresh clock supplied at the approval boundary; no stale policy cache. */
81
+ nowSecs: number;
82
+ }
83
+ /** Client-built complete unsigned body and independently selected destination. */
84
+ export interface ExpectedExecution {
85
+ /** Stage the application intends to authorize. */
86
+ stage: ExecutionStage;
87
+ /** Key from authenticated slot assignment or verifier snapshot/draw. */
88
+ operatorKey: Hex;
89
+ /** Complete body reconstructed by the application, including optional field shape. */
90
+ body: Record<string, unknown>;
91
+ }
92
+ /** Untrusted agent proposal. An opaque body hash is deliberately not accepted. */
93
+ export interface ExecutionProposal {
94
+ /** Requested stage; compared with the application's own selection. */
95
+ stage: ExecutionStage;
96
+ /** Requested key; compared with an independently authenticated key. */
97
+ operator_key: Hex;
98
+ /** Complete unsigned JSON body, with no execution_authorization envelope. */
99
+ unsigned_body: Record<string, unknown>;
100
+ /** Requested bounded Unix expiry. */
101
+ expires: number;
102
+ }
103
+ /** Local Ed25519 signing capability; implementations must keep their key on the client. */
104
+ export interface ClientExecutionSigner {
105
+ /** Public key used by the creator certificate. */
106
+ publicKey: Uint8Array;
107
+ /** Sign the SDK-reconstructed structured hash; never a hash supplied by an agent. */
108
+ sign(message: Uint8Array): Promise<Uint8Array>;
109
+ }
110
+ /** Disposable local signer whose private seed never leaves its closure. */
111
+ export interface LocalExecutionSigner extends ClientExecutionSigner {
112
+ /** Erase the retained private seed and permanently disable further signatures. */
113
+ dispose(): void;
114
+ }
115
+ /**
116
+ * Reconstruct the creator certificate typed data from the original payment.
117
+ * @param payment Locally retained payment; signing this data does not reserve or spend funds.
118
+ * @param certificate Public execution key and expiry to certify.
119
+ */
120
+ export declare function executionCertificateTypedData(payment: PaymentIntentWire, certificate: Pick<ExecutionCertificate, 'execution_key' | 'expires'>): {
121
+ domain: {
122
+ name: string;
123
+ version: string;
124
+ chainId: number;
125
+ verifyingContract: `0x${string}`;
126
+ };
127
+ primaryType: "ClientExecutionCertificate";
128
+ types: {
129
+ readonly ClientExecutionCertificate: readonly [{
130
+ readonly name: "chainId";
131
+ readonly type: "uint256";
132
+ }, {
133
+ readonly name: "settlement";
134
+ readonly type: "address";
135
+ }, {
136
+ readonly name: "keyRegistry";
137
+ readonly type: "address";
138
+ }, {
139
+ readonly name: "slotId";
140
+ readonly type: "bytes32";
141
+ }, {
142
+ readonly name: "paymentHash";
143
+ readonly type: "bytes32";
144
+ }, {
145
+ readonly name: "requestId";
146
+ readonly type: "bytes32";
147
+ }, {
148
+ readonly name: "sessionCommitment";
149
+ readonly type: "bytes32";
150
+ }, {
151
+ readonly name: "executionKey";
152
+ readonly type: "bytes32";
153
+ }, {
154
+ readonly name: "expires";
155
+ readonly type: "uint64";
156
+ }];
157
+ };
158
+ message: {
159
+ executionKey: `0x${string}`;
160
+ expires: bigint;
161
+ chainId: bigint;
162
+ settlement: `0x${string}`;
163
+ keyRegistry: `0x${string}`;
164
+ slotId: `0x${string}`;
165
+ paymentHash: `0x${string}`;
166
+ requestId: `0x${string}`;
167
+ sessionCommitment: `0x${string}`;
168
+ };
169
+ };
170
+ /** Creator wallet capable of signing the separate execution certificate. */
171
+ export interface ExecutionCreatorSigner {
172
+ /** Must equal the independently read slot creator. Delegation is not spending authority. */
173
+ address: Address;
174
+ /** Sign the SDK-reconstructed creator certificate typed data. */
175
+ signTypedData(args: ReturnType<typeof executionCertificateTypedData>): Promise<Hex>;
176
+ }
177
+ /**
178
+ * Reconstruct the complete stage typed data; callers never sign an agent's opaque hash.
179
+ * @param payment Original independently retained payment.
180
+ * @param approval Stage, target and locally recomputed body commitment.
181
+ */
182
+ export declare function executionApprovalTypedData(payment: PaymentIntentWire, approval: Omit<ExecutionAuthorization, 'signature'>): {
183
+ domain: {
184
+ name: string;
185
+ version: string;
186
+ chainId: number;
187
+ verifyingContract: `0x${string}`;
188
+ };
189
+ primaryType: "ClientStageApproval";
190
+ types: {
191
+ readonly ClientStageApproval: readonly [{
192
+ readonly name: "chainId";
193
+ readonly type: "uint256";
194
+ }, {
195
+ readonly name: "settlement";
196
+ readonly type: "address";
197
+ }, {
198
+ readonly name: "keyRegistry";
199
+ readonly type: "address";
200
+ }, {
201
+ readonly name: "slotId";
202
+ readonly type: "bytes32";
203
+ }, {
204
+ readonly name: "paymentHash";
205
+ readonly type: "bytes32";
206
+ }, {
207
+ readonly name: "requestId";
208
+ readonly type: "bytes32";
209
+ }, {
210
+ readonly name: "sessionCommitment";
211
+ readonly type: "bytes32";
212
+ }, {
213
+ readonly name: "certificateHash";
214
+ readonly type: "bytes32";
215
+ }, {
216
+ readonly name: "stage";
217
+ readonly type: "uint8";
218
+ }, {
219
+ readonly name: "operatorKey";
220
+ readonly type: "bytes32";
221
+ }, {
222
+ readonly name: "action";
223
+ readonly type: "uint8";
224
+ }, {
225
+ readonly name: "payloadDigest";
226
+ readonly type: "bytes32";
227
+ }, {
228
+ readonly name: "bodyHash";
229
+ readonly type: "bytes32";
230
+ }, {
231
+ readonly name: "expires";
232
+ readonly type: "uint64";
233
+ }];
234
+ };
235
+ message: {
236
+ certificateHash: `0x${string}`;
237
+ stage: number;
238
+ operatorKey: `0x${string}`;
239
+ action: 0 | 1 | 2 | 3 | 6;
240
+ payloadDigest: `0x${string}`;
241
+ bodyHash: `0x${string}`;
242
+ expires: bigint;
243
+ chainId: bigint;
244
+ settlement: `0x${string}`;
245
+ keyRegistry: `0x${string}`;
246
+ slotId: `0x${string}`;
247
+ paymentHash: `0x${string}`;
248
+ requestId: `0x${string}`;
249
+ sessionCommitment: `0x${string}`;
250
+ };
251
+ };
252
+ /**
253
+ * Hash the complete unsigned body with the existing RFC8785 encoder and Rust bounds.
254
+ * Explicit null and absent fields remain distinct; no operation field is dropped.
255
+ * @param body Complete unsigned JSON object, excluding only its approval envelope.
256
+ */
257
+ export declare function executionBodyHash(body: Record<string, unknown>): Hex;
258
+ /**
259
+ * Sign and verify a creator certificate without handing a private execution key to the agent.
260
+ * @param options Independent consent policy, original payment, public execution key and creator wallet.
261
+ */
262
+ export declare function createExecutionCertificate(options: {
263
+ payment: PaymentIntentWire;
264
+ policy: ExecutionConsentPolicy;
265
+ publicKey: Uint8Array;
266
+ expires: number;
267
+ creator: ExecutionCreatorSigner;
268
+ }): Promise<ExecutionCertificate>;
269
+ /**
270
+ * Verify creator consent, stage/operator/body binding and the strict local client signature.
271
+ * The caller must independently authenticate the operator assignment and fresh payment backing.
272
+ * @param options Original payment, independently selected policy/target and untrusted proof.
273
+ */
274
+ export declare function verifyExecutionAuthorization(options: {
275
+ payment: PaymentIntentWire;
276
+ policy: ExecutionConsentPolicy;
277
+ expected: ExpectedExecution;
278
+ authorization: ExecutionAuthorization;
279
+ }): Promise<void>;
280
+ /**
281
+ * Reconstruct the durable binding shared with the worker and accountant journals.
282
+ * This is a commitment helper, not permission to execute or evidence of correct computation.
283
+ * @param payment Original locally retained payment.
284
+ * @param consent Public original consent; never includes the private request preimage.
285
+ * @param reservationBlock Canonical block hash at the worker's original admission.
286
+ */
287
+ export declare function executionConsentBinding(payment: PaymentIntentWire, consent: ExecutionConsent, reservationBlock: Hex): Hex;
288
+ /**
289
+ * Verify public financial consent at its original admission time. The caller must first
290
+ * authenticate the historical creator, reserved cost, canonical block and operator assignment.
291
+ * Work admission must continue to use verifyExecutionAuthorization with the complete body.
292
+ * @param options Independently established history and worker binding, plus untrusted consent.
293
+ */
294
+ export declare function verifyExecutionConsent(options: {
295
+ payment: PaymentIntentWire;
296
+ policy: ExecutionConsentPolicy;
297
+ consent: ExecutionConsent;
298
+ expected: {
299
+ stage: ExecutionStage;
300
+ operatorKey: Hex;
301
+ reservationBlock: Hex;
302
+ executionBinding: Hex;
303
+ };
304
+ }): Promise<void>;
305
+ /**
306
+ * Approve a complete proposal ONLY after comparing it with a separately client-built body.
307
+ * Applications must construct expected.body from their own intent and validated presentation,
308
+ * never echo an agent's proposal into that field. This helper performs no automatic HTTP dispatch.
309
+ * @param options Original consent, certified local signer, independent expected body and untrusted proposal.
310
+ */
311
+ export declare function approveExecutionRequest(options: {
312
+ payment: PaymentIntentWire;
313
+ certificate: ExecutionCertificate;
314
+ signer: ClientExecutionSigner;
315
+ policy: ExecutionConsentPolicy;
316
+ expected: ExpectedExecution;
317
+ proposal: ExecutionProposal;
318
+ }): Promise<ExecutionAuthorization>;
319
+ /**
320
+ * Reconstruct session initialization typed data from the original payment and client-built commitments.
321
+ * @param payment Original locally retained creator payment.
322
+ * @param initialization Certificate, approved profile hash, complete create-body hash and expiry.
323
+ */
324
+ export declare function executionInitializationTypedData(payment: PaymentIntentWire, initialization: Omit<SessionInitialization, 'signature'>): {
325
+ domain: {
326
+ name: string;
327
+ version: string;
328
+ chainId: number;
329
+ verifyingContract: `0x${string}`;
330
+ };
331
+ primaryType: "ClientSessionInitialization";
332
+ types: {
333
+ readonly ClientSessionInitialization: readonly [{
334
+ readonly name: "chainId";
335
+ readonly type: "uint256";
336
+ }, {
337
+ readonly name: "settlement";
338
+ readonly type: "address";
339
+ }, {
340
+ readonly name: "keyRegistry";
341
+ readonly type: "address";
342
+ }, {
343
+ readonly name: "slotId";
344
+ readonly type: "bytes32";
345
+ }, {
346
+ readonly name: "paymentHash";
347
+ readonly type: "bytes32";
348
+ }, {
349
+ readonly name: "requestId";
350
+ readonly type: "bytes32";
351
+ }, {
352
+ readonly name: "sessionCommitment";
353
+ readonly type: "bytes32";
354
+ }, {
355
+ readonly name: "certificateHash";
356
+ readonly type: "bytes32";
357
+ }, {
358
+ readonly name: "profileHash";
359
+ readonly type: "bytes32";
360
+ }, {
361
+ readonly name: "bodyHash";
362
+ readonly type: "bytes32";
363
+ }, {
364
+ readonly name: "expires";
365
+ readonly type: "uint64";
366
+ }];
367
+ };
368
+ message: {
369
+ certificateHash: `0x${string}`;
370
+ profileHash: `0x${string}`;
371
+ bodyHash: `0x${string}`;
372
+ expires: bigint;
373
+ chainId: bigint;
374
+ settlement: `0x${string}`;
375
+ keyRegistry: `0x${string}`;
376
+ slotId: `0x${string}`;
377
+ paymentHash: `0x${string}`;
378
+ requestId: `0x${string}`;
379
+ sessionCommitment: `0x${string}`;
380
+ };
381
+ };
382
+ /**
383
+ * Verify fresh client consent before creating or retrying a registered agent session.
384
+ * @param options Independently selected profile/body/policy, original payment and untrusted proof.
385
+ */
386
+ export declare function verifySessionInitialization(options: {
387
+ payment: PaymentIntentWire;
388
+ policy: ExecutionConsentPolicy;
389
+ expected: ExpectedInitialization;
390
+ initialization: SessionInitialization;
391
+ }): Promise<void>;
392
+ /**
393
+ * Authorize one client-built creation body, including a locally generated owner bearer.
394
+ * Retain the body, proof and signer privately until expiry: retrying the identical POST uses
395
+ * the hash of these typed data as its session ID and cannot replace the original ECDH key.
396
+ * This function neither reserves funds nor starts or pays an operator.
397
+ * @param options Original payment, certified client signer and independently approved create intent.
398
+ */
399
+ export declare function initializeExecutionSession(options: {
400
+ payment: PaymentIntentWire;
401
+ certificate: ExecutionCertificate;
402
+ signer: ClientExecutionSigner;
403
+ policy: ExecutionConsentPolicy;
404
+ expected: ExpectedInitialization;
405
+ expires: number;
406
+ }): Promise<SessionInitialization>;
407
+ /**
408
+ * Create a disposable client-only Ed25519 execution signer. The seed is copied or generated
409
+ * with Web Crypto, retained only locally and erased by dispose; caller copies remain its responsibility.
410
+ * The copy never shares memory with the caller's bytes (a Node `Buffer` or any view of a larger
411
+ * buffer included), so the caller may wipe its seed at once and dispose never touches it.
412
+ * @param seed Optional local 32-byte seed, for private persistence or deterministic tests.
413
+ */
414
+ export declare function createLocalExecutionSigner(seed?: Uint8Array): LocalExecutionSigner;