@t3foundry/tasra-sdk 0.0.0-stage → 0.3.1-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (322) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +94 -0
  4. package/README.md +137 -2
  5. package/SECURITY.md +115 -0
  6. package/dist/app/approvals.d.ts +50 -0
  7. package/dist/app/approvals.js +90 -0
  8. package/dist/app/authorization.d.ts +19 -0
  9. package/dist/app/authorization.js +20 -0
  10. package/dist/app/client.d.ts +231 -0
  11. package/dist/app/client.js +272 -0
  12. package/dist/app/creation.d.ts +73 -0
  13. package/dist/app/creation.js +77 -0
  14. package/dist/app/deployment.d.ts +36 -0
  15. package/dist/app/deployment.js +18 -0
  16. package/dist/app/identity.d.ts +211 -0
  17. package/dist/app/identity.js +287 -0
  18. package/dist/app/index.d.ts +22 -0
  19. package/dist/app/index.js +12 -0
  20. package/dist/app/manifest.d.ts +74 -0
  21. package/dist/app/manifest.js +120 -0
  22. package/dist/app/node.d.ts +30 -0
  23. package/dist/app/node.js +159 -0
  24. package/dist/app/ready-slot.d.ts +157 -0
  25. package/dist/app/ready-slot.js +199 -0
  26. package/dist/app/tasra-client.d.ts +125 -0
  27. package/dist/app/tasra-client.js +79 -0
  28. package/dist/app/viem.d.ts +10 -0
  29. package/dist/app/viem.js +32 -0
  30. package/dist/app/wallet.d.ts +126 -0
  31. package/dist/app/wallet.js +137 -0
  32. package/dist/auth/dpop.d.ts +86 -0
  33. package/dist/auth/dpop.js +142 -0
  34. package/dist/auth/holderProof.d.ts +102 -0
  35. package/dist/auth/holderProof.js +161 -0
  36. package/dist/auth/identityScope.d.ts +19 -0
  37. package/dist/auth/identityScope.js +82 -0
  38. package/dist/auth/index.d.ts +11 -0
  39. package/dist/auth/index.js +13 -0
  40. package/dist/auth/oid4vp.d.ts +230 -0
  41. package/dist/auth/oid4vp.js +780 -0
  42. package/dist/auth/rego/wasm/PINS.json +11 -0
  43. package/dist/auth/rego/wasm/keykeeper_rego_wasm.d.ts +76 -0
  44. package/dist/auth/rego/wasm/keykeeper_rego_wasm.js +379 -0
  45. package/dist/auth/rego/wasm/keykeeper_rego_wasm_bg.wasm +0 -0
  46. package/dist/auth/rego.d.ts +192 -0
  47. package/dist/auth/rego.js +492 -0
  48. package/dist/auth/verifier.d.ts +166 -0
  49. package/dist/auth/verifier.js +211 -0
  50. package/dist/chain/abis/accountantSetRegistry.d.ts +441 -0
  51. package/dist/chain/abis/accountantSetRegistry.js +574 -0
  52. package/dist/chain/abis/accountantSlashing.d.ts +2071 -0
  53. package/dist/chain/abis/accountantSlashing.js +2670 -0
  54. package/dist/chain/abis/bondingCurve.d.ts +398 -0
  55. package/dist/chain/abis/bondingCurve.js +521 -0
  56. package/dist/chain/abis/equivocationSlasher.d.ts +292 -0
  57. package/dist/chain/abis/equivocationSlasher.js +379 -0
  58. package/dist/chain/abis/fixedTasraPriceOracle.d.ts +52 -0
  59. package/dist/chain/abis/fixedTasraPriceOracle.js +72 -0
  60. package/dist/chain/abis/index.d.ts +12801 -0
  61. package/dist/chain/abis/index.js +64 -0
  62. package/dist/chain/abis/keeperShareRegistry.d.ts +519 -0
  63. package/dist/chain/abis/keeperShareRegistry.js +675 -0
  64. package/dist/chain/abis/keyRegistry.d.ts +2421 -0
  65. package/dist/chain/abis/keyRegistry.js +3114 -0
  66. package/dist/chain/abis/livenessRegistry.d.ts +402 -0
  67. package/dist/chain/abis/livenessRegistry.js +524 -0
  68. package/dist/chain/abis/mockEurc.d.ts +210 -0
  69. package/dist/chain/abis/mockEurc.js +276 -0
  70. package/dist/chain/abis/nodeRegistry.d.ts +1630 -0
  71. package/dist/chain/abis/nodeRegistry.js +2113 -0
  72. package/dist/chain/abis/platformExecutor.d.ts +328 -0
  73. package/dist/chain/abis/platformExecutor.js +429 -0
  74. package/dist/chain/abis/prevrandaoSaltBeacon.d.ts +16 -0
  75. package/dist/chain/abis/prevrandaoSaltBeacon.js +24 -0
  76. package/dist/chain/abis/serviceRegistry.d.ts +556 -0
  77. package/dist/chain/abis/serviceRegistry.js +719 -0
  78. package/dist/chain/abis/settlement.d.ts +1624 -0
  79. package/dist/chain/abis/settlement.js +2096 -0
  80. package/dist/chain/abis/tasraSwapRouter.d.ts +92 -0
  81. package/dist/chain/abis/tasraSwapRouter.js +122 -0
  82. package/dist/chain/abis/tasraToken.d.ts +455 -0
  83. package/dist/chain/abis/tasraToken.js +599 -0
  84. package/dist/chain/abis/tasraVestingVault.d.ts +165 -0
  85. package/dist/chain/abis/tasraVestingVault.js +215 -0
  86. package/dist/chain/abis/thresholdRandomBeacon.d.ts +378 -0
  87. package/dist/chain/abis/thresholdRandomBeacon.js +494 -0
  88. package/dist/chain/abis/treasury.d.ts +301 -0
  89. package/dist/chain/abis/treasury.js +390 -0
  90. package/dist/chain/abis/verifierSetRegistry.d.ts +445 -0
  91. package/dist/chain/abis/verifierSetRegistry.js +579 -0
  92. package/dist/chain/client.d.ts +212 -0
  93. package/dist/chain/client.js +576 -0
  94. package/dist/chain/commitmentRecovery.d.ts +21 -0
  95. package/dist/chain/commitmentRecovery.js +44 -0
  96. package/dist/chain/committeeClient.d.ts +102 -0
  97. package/dist/chain/committeeClient.js +137 -0
  98. package/dist/chain/deployments.d.ts +56 -0
  99. package/dist/chain/deployments.js +269 -0
  100. package/dist/chain/discovery.d.ts +49 -0
  101. package/dist/chain/discovery.js +107 -0
  102. package/dist/chain/events.d.ts +58 -0
  103. package/dist/chain/events.js +125 -0
  104. package/dist/chain/format.d.ts +25 -0
  105. package/dist/chain/format.js +51 -0
  106. package/dist/chain/index.d.ts +41 -0
  107. package/dist/chain/index.js +56 -0
  108. package/dist/chain/manifest.d.ts +165 -0
  109. package/dist/chain/manifest.js +132 -0
  110. package/dist/chain/network-profiles.json +75 -0
  111. package/dist/chain/networks.d.ts +73 -0
  112. package/dist/chain/networks.js +62 -0
  113. package/dist/chain/node.d.ts +44 -0
  114. package/dist/chain/node.js +176 -0
  115. package/dist/chain/offchain.d.ts +149 -0
  116. package/dist/chain/offchain.js +73 -0
  117. package/dist/chain/provisionRule.d.ts +164 -0
  118. package/dist/chain/provisionRule.js +212 -0
  119. package/dist/chain/registeredAgent.d.ts +64 -0
  120. package/dist/chain/registeredAgent.js +140 -0
  121. package/dist/chain/registeredOperation.d.ts +49 -0
  122. package/dist/chain/registeredOperation.js +136 -0
  123. package/dist/chain/registeredRelay.d.ts +206 -0
  124. package/dist/chain/registeredRelay.js +312 -0
  125. package/dist/chain/revertReason.d.ts +14 -0
  126. package/dist/chain/revertReason.js +62 -0
  127. package/dist/chain/ruleAmendment.d.ts +80 -0
  128. package/dist/chain/ruleAmendment.js +195 -0
  129. package/dist/chain/ruleAmendmentCore.d.ts +129 -0
  130. package/dist/chain/ruleAmendmentCore.js +152 -0
  131. package/dist/chain/ruleInput.d.ts +10 -0
  132. package/dist/chain/ruleInput.js +13 -0
  133. package/dist/chain/serviceIdentity.d.ts +176 -0
  134. package/dist/chain/serviceIdentity.js +237 -0
  135. package/dist/chain/serviceProfiles.d.ts +39 -0
  136. package/dist/chain/serviceProfiles.js +74 -0
  137. package/dist/chain/services.d.ts +141 -0
  138. package/dist/chain/services.js +79 -0
  139. package/dist/chain/slotClient.d.ts +55 -0
  140. package/dist/chain/slotClient.js +62 -0
  141. package/dist/chain/slotSeed.d.ts +31 -0
  142. package/dist/chain/slotSeed.js +98 -0
  143. package/dist/chain/write.d.ts +431 -0
  144. package/dist/chain/write.js +958 -0
  145. package/dist/client/client.d.ts +112 -0
  146. package/dist/client/client.js +111 -0
  147. package/dist/client/index.d.ts +3 -0
  148. package/dist/client/index.js +2 -0
  149. package/dist/client/session.d.ts +67 -0
  150. package/dist/client/session.js +238 -0
  151. package/dist/committee/client.d.ts +284 -0
  152. package/dist/committee/client.js +351 -0
  153. package/dist/committee/dual-sign.d.ts +110 -0
  154. package/dist/committee/dual-sign.js +202 -0
  155. package/dist/committee/ecdsa.d.ts +36 -0
  156. package/dist/committee/ecdsa.js +45 -0
  157. package/dist/committee/extraction.d.ts +82 -0
  158. package/dist/committee/extraction.js +96 -0
  159. package/dist/committee/index.d.ts +19 -0
  160. package/dist/committee/index.js +13 -0
  161. package/dist/committee/oauth.d.ts +51 -0
  162. package/dist/committee/oauth.js +90 -0
  163. package/dist/committee/receipts.d.ts +51 -0
  164. package/dist/committee/receipts.js +59 -0
  165. package/dist/committee/request.d.ts +264 -0
  166. package/dist/committee/request.js +305 -0
  167. package/dist/committee/token.d.ts +274 -0
  168. package/dist/committee/token.js +418 -0
  169. package/dist/crypto/constants.d.ts +10 -0
  170. package/dist/crypto/constants.js +32 -0
  171. package/dist/crypto/detect.d.ts +20 -0
  172. package/dist/crypto/detect.js +44 -0
  173. package/dist/crypto/envelope.d.ts +60 -0
  174. package/dist/crypto/envelope.js +243 -0
  175. package/dist/crypto/frost.d.ts +49 -0
  176. package/dist/crypto/frost.js +152 -0
  177. package/dist/crypto/hex.d.ts +7 -0
  178. package/dist/crypto/hex.js +24 -0
  179. package/dist/crypto/ibe-blob.d.ts +114 -0
  180. package/dist/crypto/ibe-blob.js +208 -0
  181. package/dist/crypto/ibe.d.ts +88 -0
  182. package/dist/crypto/ibe.js +262 -0
  183. package/dist/crypto/index.d.ts +12 -0
  184. package/dist/crypto/index.js +12 -0
  185. package/dist/crypto/kem.d.ts +55 -0
  186. package/dist/crypto/kem.js +241 -0
  187. package/dist/decryption/client.d.ts +64 -0
  188. package/dist/decryption/client.js +82 -0
  189. package/dist/decryption/index.d.ts +2 -0
  190. package/dist/decryption/index.js +2 -0
  191. package/dist/errors.d.ts +124 -0
  192. package/dist/errors.js +167 -0
  193. package/dist/index.d.ts +43 -0
  194. package/dist/index.js +98 -0
  195. package/dist/keys/index.d.ts +1 -0
  196. package/dist/keys/index.js +4 -0
  197. package/dist/keys/node-client.d.ts +27 -0
  198. package/dist/keys/node-client.js +97 -0
  199. package/dist/oid4vp/binding.d.ts +76 -0
  200. package/dist/oid4vp/binding.js +118 -0
  201. package/dist/oid4vp/did-web.d.ts +49 -0
  202. package/dist/oid4vp/did-web.js +57 -0
  203. package/dist/oid4vp/index.d.ts +9 -0
  204. package/dist/oid4vp/index.js +10 -0
  205. package/dist/oid4vp/jose.d.ts +166 -0
  206. package/dist/oid4vp/jose.js +242 -0
  207. package/dist/oid4vp/jwe.d.ts +30 -0
  208. package/dist/oid4vp/jwe.js +93 -0
  209. package/dist/oid4vp/oid4vci.d.ts +84 -0
  210. package/dist/oid4vp/oid4vci.js +85 -0
  211. package/dist/oid4vp/request-object.d.ts +109 -0
  212. package/dist/oid4vp/request-object.js +96 -0
  213. package/dist/oid4vp/sd-jwt.d.ts +177 -0
  214. package/dist/oid4vp/sd-jwt.js +208 -0
  215. package/dist/oid4vp/verifier-agent.d.ts +161 -0
  216. package/dist/oid4vp/verifier-agent.js +132 -0
  217. package/dist/oid4vp/wallet.d.ts +116 -0
  218. package/dist/oid4vp/wallet.js +108 -0
  219. package/dist/recipient/store.d.ts +67 -0
  220. package/dist/recipient/store.js +98 -0
  221. package/dist/signing/ecdsa.d.ts +49 -0
  222. package/dist/signing/ecdsa.js +79 -0
  223. package/dist/signing/frost.d.ts +88 -0
  224. package/dist/signing/frost.js +145 -0
  225. package/dist/signing/index.d.ts +4 -0
  226. package/dist/signing/index.js +3 -0
  227. package/dist/slots/faucet.d.ts +23 -0
  228. package/dist/slots/faucet.js +35 -0
  229. package/dist/slots/index.d.ts +2 -0
  230. package/dist/slots/index.js +4 -0
  231. package/dist/verifier-agent/index.d.ts +241 -0
  232. package/dist/verifier-agent/index.js +411 -0
  233. package/docs/DEVELOPER-EXPERIENCE.md +62 -0
  234. package/docs/README.md +33 -0
  235. package/docs/access-control.md +76 -0
  236. package/docs/ai-development.md +292 -0
  237. package/docs/api.md +338 -0
  238. package/docs/application-api.md +335 -0
  239. package/docs/architecture.md +65 -0
  240. package/docs/basics.md +48 -0
  241. package/docs/capabilities.md +86 -0
  242. package/docs/chain.md +153 -0
  243. package/docs/compatibility.md +36 -0
  244. package/docs/consumer-migrations.md +80 -0
  245. package/docs/create-slot.md +104 -0
  246. package/docs/document-signing.md +243 -0
  247. package/docs/encrypted-notes.md +129 -0
  248. package/docs/encryption.md +100 -0
  249. package/docs/errors.md +76 -0
  250. package/docs/flows.md +289 -0
  251. package/docs/fuji.md +127 -0
  252. package/docs/funding.md +126 -0
  253. package/docs/getting-started.md +94 -0
  254. package/docs/glossary.md +44 -0
  255. package/docs/installation.md +132 -0
  256. package/docs/manage-slot.md +95 -0
  257. package/docs/native-approvals.md +124 -0
  258. package/docs/prerequisites.md +137 -0
  259. package/docs/read-slot.md +41 -0
  260. package/docs/reference/README.md +30 -0
  261. package/docs/reference/app-node.md +102 -0
  262. package/docs/reference/app.md +1737 -0
  263. package/docs/reference/chain-node.md +159 -0
  264. package/docs/reference/chain.md +3609 -0
  265. package/docs/reference/committee.md +2176 -0
  266. package/docs/reference/main.md +4068 -0
  267. package/docs/reference/oid4vp.md +2547 -0
  268. package/docs/reference/verifier-agent.md +498 -0
  269. package/docs/shared-account.md +168 -0
  270. package/docs/signing-and-encryption.md +52 -0
  271. package/docs/signing.md +172 -0
  272. package/examples/committee-slot.ts +16 -0
  273. package/examples/connect-fuji.ts +41 -0
  274. package/examples/connect-network.ts +14 -0
  275. package/examples/credential-approvals.ts +46 -0
  276. package/examples/document-signing/README.md +59 -0
  277. package/examples/document-signing/backend.ts +132 -0
  278. package/examples/document-signing/build.mjs +19 -0
  279. package/examples/document-signing/config.ts +34 -0
  280. package/examples/document-signing/gitignore.template +9 -0
  281. package/examples/document-signing/model.ts +140 -0
  282. package/examples/document-signing/network.ts +58 -0
  283. package/examples/document-signing/package.json +25 -0
  284. package/examples/document-signing/public/index.html +27 -0
  285. package/examples/document-signing/public/sample.pdf +31 -0
  286. package/examples/document-signing/public/styles.css +531 -0
  287. package/examples/document-signing/server.ts +358 -0
  288. package/examples/document-signing/setup.ts +111 -0
  289. package/examples/document-signing/store.ts +105 -0
  290. package/examples/document-signing/tsconfig.json +24 -0
  291. package/examples/document-signing/verify.ts +24 -0
  292. package/examples/document-signing/web/app.ts +312 -0
  293. package/examples/document-signing/web/preview.ts +67 -0
  294. package/examples/document-signing/web/wallet.ts +146 -0
  295. package/examples/document-signing/workflow.test.ts +228 -0
  296. package/examples/document-signing/workflow.ts +241 -0
  297. package/examples/document-signing.ts +96 -0
  298. package/examples/encrypted-notes.ts +86 -0
  299. package/examples/ethers-signer.ts +204 -0
  300. package/examples/fund-slot.ts +73 -0
  301. package/examples/getting-started.ts +25 -0
  302. package/examples/learning-authorize.ts +23 -0
  303. package/examples/learning-cancel-slot.ts +11 -0
  304. package/examples/learning-context.ts +28 -0
  305. package/examples/learning-create-slot.ts +25 -0
  306. package/examples/learning-read-slot.ts +8 -0
  307. package/examples/learning-renew-slot.ts +12 -0
  308. package/examples/learning-sign.ts +8 -0
  309. package/examples/live-config.ts +71 -0
  310. package/examples/minimal.ts +6 -0
  311. package/examples/native-approvals.ts +57 -0
  312. package/examples/network.ts +58 -0
  313. package/examples/offline.ts +16 -0
  314. package/examples/personal-vault.ts +20 -0
  315. package/examples/provision-slot.ts +47 -0
  316. package/examples/shared-account.ts +46 -0
  317. package/examples/slot-address.ts +13 -0
  318. package/examples/slot-creation.ts +9 -0
  319. package/examples/tutorial-negative.ts +26 -0
  320. package/examples/tutorial-support.ts +76 -0
  321. package/examples/viem-account.ts +203 -0
  322. package/package.json +303 -4
@@ -0,0 +1,140 @@
1
+ import { authenticateApprovedService, validateServiceEndpoint } from './serviceIdentity.js';
2
+ import { parseVerifierAgentSessionStatus } from '../verifier-agent/index.js';
3
+ /**
4
+ * Session creation may have reached the provider, so automatic retry is unsafe.
5
+ */
6
+ export class AgentSessionCreationUnknownError extends Error {
7
+ profile;
8
+ constructor(/** Approved verifier-agent profile whose session creation outcome is unknown. */ profile) {
9
+ super('Agent session creation has an uncertain result; explicitly open a fresh wallet session to retry. No session secret or presentation is transferred.');
10
+ this.profile = profile;
11
+ this.name = 'AgentSessionCreationUnknownError';
12
+ }
13
+ }
14
+ function decode(bytes, limit) {
15
+ if (bytes.length > limit)
16
+ throw new Error('Agent response too large');
17
+ const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
18
+ if (!value || typeof value !== 'object' || Array.isArray(value))
19
+ throw new Error('Invalid agent reply');
20
+ return value;
21
+ }
22
+ async function bounded(signal, work) {
23
+ const controller = new AbortController();
24
+ const combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
25
+ const timer = setTimeout(() => controller.abort(new Error('Agent request timed out')), 60_000);
26
+ let abort = () => { };
27
+ try {
28
+ combined.throwIfAborted();
29
+ return await Promise.race([work(combined), new Promise((_, reject) => {
30
+ abort = () => reject(combined.reason);
31
+ combined.addEventListener('abort', abort, { once: true });
32
+ })]);
33
+ }
34
+ finally {
35
+ clearTimeout(timer);
36
+ combined.removeEventListener('abort', abort);
37
+ controller.abort();
38
+ }
39
+ }
40
+ function pin(profile, record) {
41
+ const a = profile.approval;
42
+ return { chainId: a.chainId, registry: a.registry.toLowerCase(), serviceId: a.serviceId.toLowerCase(), serviceType: 1,
43
+ owner: a.owner.toLowerCase(), revision: a.revision.toString(), manifestHash: a.manifestHash.toLowerCase(),
44
+ authKey: record.authKey.toLowerCase(), endpoint: profile.endpoint, clientId: profile.clientId };
45
+ }
46
+ function equalPin(actual, expected) {
47
+ if (!actual || typeof actual !== 'object')
48
+ return false;
49
+ return Object.entries(expected).every(([key, value]) => actual[key] === value);
50
+ }
51
+ /**
52
+ * Selection authenticates public metadata first. Once POSTed, never silently switch providers.
53
+ * @param chain Reader for the approved service registry.
54
+ * @param config Independently approved provider profiles and guarded HTTP transport.
55
+ */
56
+ export function createRegisteredAgentClient(chain, config) {
57
+ if (!Array.isArray(config.profiles) || !config.profiles.length || config.profiles.length > 16 || typeof config.transport?.agentRequest !== 'function' || typeof config.transport.request !== 'function')
58
+ throw new Error('Approved agent profiles and a guarded transport are required');
59
+ const profiles = config.profiles.map(p => {
60
+ validateServiceEndpoint(p.endpoint);
61
+ if (p.approval.serviceType !== 1 || !/^decentralized_identifier:did:web:[a-z0-9.-]+(?:(?:%3A)[0-9]+)?$/.test(p.clientId))
62
+ throw new Error('Invalid verifier-agent profile');
63
+ return Object.freeze({ ...p, approval: Object.freeze({ ...p.approval }) });
64
+ });
65
+ const transport = config.transport;
66
+ return {
67
+ /** At most three discovery candidates; optional index explicitly starts a new independent session. */
68
+ async createSession(params, options = {}) {
69
+ const start = options.profileIndex ?? 0;
70
+ if (!Number.isInteger(start) || start < 0 || start >= profiles.length)
71
+ throw new Error('Invalid agent profile index');
72
+ return bounded(options.signal, async (signal) => {
73
+ for (const profile of profiles.slice(start, start + 3)) {
74
+ let record;
75
+ try {
76
+ const result = await authenticateApprovedService(chain, profile.approval, {
77
+ request: (url, opts) => transport.request(url, { ...opts, signal: AbortSignal.any([signal, opts.signal]) }),
78
+ });
79
+ signal.throwIfAborted();
80
+ if (result.record.endpoint !== profile.endpoint || !result.manifest.capabilities.includes('oid4vp'))
81
+ throw new Error('Agent endpoint/capability approval mismatch');
82
+ record = result.record;
83
+ }
84
+ catch {
85
+ signal.throwIfAborted();
86
+ continue;
87
+ }
88
+ if (params.operation.chain_id !== profile.approval.chainId)
89
+ throw new Error('Agent operation chain mismatch');
90
+ const body = new TextEncoder().encode(JSON.stringify({ operation: params.operation, operation_sig: params.operationSig, delegation: params.delegation, message_hex: params.messageHex }));
91
+ if (body.length > 65_536)
92
+ throw new Error('Agent session request too large');
93
+ signal.throwIfAborted();
94
+ let data;
95
+ try {
96
+ data = decode(await transport.agentRequest(profile.endpoint + '/v1/sessions', { body, maxBytes: 32_768, signal }), 32_768);
97
+ }
98
+ catch {
99
+ throw new AgentSessionCreationUnknownError(profile);
100
+ }
101
+ const expected = pin(profile, record);
102
+ if (!equalPin(data.service_profile, expected) || typeof data.session_id !== 'string' || !/^[0-9a-f]{64}$/.test(data.session_id)
103
+ || typeof data.poll_secret !== 'string' || !/^[0-9a-f]{64}$/.test(data.poll_secret))
104
+ throw new Error('Agent session profile or identifiers mismatch');
105
+ const sessionId = data.session_id, pollSecret = data.poll_secret;
106
+ const requestUri = `${profile.endpoint}/v1/request/${sessionId}`;
107
+ if (data.request_uri !== requestUri || typeof data.qr_payload !== 'string' || !data.qr_payload.startsWith('openid4vp://?'))
108
+ throw new Error('Agent wallet request destination mismatch');
109
+ const qr = new URL(data.qr_payload);
110
+ if (qr.searchParams.get('client_id') !== profile.clientId || qr.searchParams.get('request_uri') !== requestUri || [...qr.searchParams.keys()].length !== 2)
111
+ throw new Error('Agent wallet audience or request URI mismatch');
112
+ // Closure-owned routing and secret prevent a caller's mutable session object from
113
+ // redirecting a bearer. Replicas sit behind this one approved base endpoint.
114
+ return Object.freeze({ sessionId, pollSecret, requestUri, qrPayload: data.qr_payload, profile,
115
+ poll: (pollSignal) => bounded(pollSignal, async (activeSignal) => {
116
+ const a = profile.approval;
117
+ if (chain.addresses.ServiceRegistry?.toLowerCase() !== a.registry.toLowerCase() || await chain.client.getChainId() !== a.chainId)
118
+ throw new Error('Agent session chain/registry changed');
119
+ activeSignal.throwIfAborted();
120
+ const block = await chain.client.getBlockNumber({ cacheTime: 0 });
121
+ activeSignal.throwIfAborted();
122
+ const current = await chain.readers.serviceRegistry.getService(a.serviceId, block);
123
+ activeSignal.throwIfAborted();
124
+ if (current.status > 1 || current.revision < a.revision || current.serviceType !== 1
125
+ || current.owner.toLowerCase() !== record.owner.toLowerCase() || current.authKey.toLowerCase() !== record.authKey.toLowerCase()
126
+ || current.pendingOwner.toLowerCase() !== record.pendingOwner.toLowerCase() || current.manifestHash.toLowerCase() !== a.manifestHash.toLowerCase()
127
+ || current.endpoint !== profile.endpoint)
128
+ throw new Error('Agent session profile changed; open a fresh wallet session');
129
+ const reply = decode(await transport.agentRequest(`${profile.endpoint}/v1/sessions/${sessionId}`, { bearer: pollSecret, maxBytes: 1_048_576, signal: activeSignal }), 1_048_576);
130
+ if (!(reply.status === 'failed' && reply.binding_preimage == null && reply.compound_token == null) && !equalPin(reply.binding_preimage?.service_profile, expected))
131
+ throw new Error('Agent result belongs to another session profile');
132
+ return parseVerifierAgentSessionStatus(reply, sessionId);
133
+ }),
134
+ });
135
+ }
136
+ throw new Error('No approved verifier-agent authenticated');
137
+ });
138
+ },
139
+ };
140
+ }
@@ -0,0 +1,49 @@
1
+ import { type OperationInput, type TypedDataSigner, type VerifierAgentResult } from '../oid4vp/verifier-agent.js';
2
+ import type { VerifiedRequestObject } from '../oid4vp/request-object.js';
3
+ import type { SessionStatusResult } from '../verifier-agent/index.js';
4
+ import { type PresentationDelegation, type PresentationOperation, type WaitOpts } from '../verifier-agent/index.js';
5
+ import { type RegisteredAgentSession, type createRegisteredAgentClient } from './registeredAgent.js';
6
+ /**
7
+ * Authenticated provider session bound to one signed operation and request hash.
8
+ */
9
+ export interface RegisteredVerifierAgentSession extends RegisteredAgentSession {
10
+ /**
11
+ * Creator-signed operation associated with this session.
12
+ */
13
+ readonly operation: PresentationOperation;
14
+ /**
15
+ * Defensive copy of the operation request hash.
16
+ */
17
+ readonly requestHash: Uint8Array;
18
+ /**
19
+ * Authenticated provider endpoint retained for this session.
20
+ */
21
+ readonly verifierAgentUrl: string;
22
+ }
23
+ /**
24
+ * Sign once, authenticate an explicitly approved provider, and retain its pinned poll closure.
25
+ * @param client Registered agent client with independently approved providers.
26
+ * @param opts Exact operation, authorizing signer and optional delegation or cancellation.
27
+ */
28
+ export declare function openRegisteredVerifierAgentSession(client: ReturnType<typeof createRegisteredAgentClient>, opts: OperationInput & {
29
+ signer: TypedDataSigner;
30
+ delegation?: PresentationDelegation;
31
+ profileIndex?: number;
32
+ signal?: AbortSignal;
33
+ }): Promise<RegisteredVerifierAgentSession>;
34
+ /**
35
+ * Poll the original authenticated session only; no URL reconstruction or provider failover.
36
+ * @param session Previously opened authenticated session.
37
+ * @param opts Polling cadence, deadline, cancellation and phase notifications.
38
+ */
39
+ export declare function awaitRegisteredVerifierAgentResult(session: RegisteredVerifierAgentSession, opts?: {
40
+ intervalMs?: number;
41
+ timeoutMs?: number;
42
+ } & WaitOpts): Promise<VerifierAgentResult>;
43
+ /**
44
+ * Bind the wallet's signed request to the operation and authenticated session before disclosure.
45
+ * @param session Authenticated session bound to the creator-authorized operation.
46
+ * @param ro Verified wallet request object whose claims will be presented.
47
+ * @param status Session status carrying the operation binding preimage.
48
+ */
49
+ export declare function assertRegisteredWalletRequest(session: RegisteredVerifierAgentSession, ro: VerifiedRequestObject, status: SessionStatusResult): void;
@@ -0,0 +1,136 @@
1
+ import { hexToBytes } from '../crypto/hex.js';
2
+ import { presentationOperationTypedData, verifierAgentResult } from '../oid4vp/verifier-agent.js';
3
+ import { decodeJson } from '../oid4vp/jose.js';
4
+ import { derivedNonce, requestHash } from '../oid4vp/binding.js';
5
+ import { VerifierAgentSessionError, nextPollDelay } from '../verifier-agent/index.js';
6
+ /**
7
+ * Sign once, authenticate an explicitly approved provider, and retain its pinned poll closure.
8
+ * @param client Registered agent client with independently approved providers.
9
+ * @param opts Exact operation, authorizing signer and optional delegation or cancellation.
10
+ */
11
+ export async function openRegisteredVerifierAgentSession(client, opts) {
12
+ opts.signal?.throwIfAborted();
13
+ const { typedData, operation, messageHex, payloadDigest } = presentationOperationTypedData(opts);
14
+ const operationSig = await opts.signer.signTypedData(typedData);
15
+ opts.signal?.throwIfAborted();
16
+ const session = await client.createSession({ operation, operationSig, messageHex, delegation: opts.delegation }, { profileIndex: opts.profileIndex, signal: opts.signal });
17
+ const slot = typeof opts.slotId === 'string' ? hexToBytes(opts.slotId) : opts.slotId;
18
+ const expectedHash = requestHash(opts.chainId, slot, opts.action, payloadDigest);
19
+ return Object.freeze({ ...session, operation: Object.freeze(operation), verifierAgentUrl: session.profile.endpoint,
20
+ get requestHash() { return expectedHash.slice(); },
21
+ });
22
+ }
23
+ /**
24
+ * Poll the original authenticated session only; no URL reconstruction or provider failover.
25
+ * @param session Previously opened authenticated session.
26
+ * @param opts Polling cadence, deadline, cancellation and phase notifications.
27
+ */
28
+ export async function awaitRegisteredVerifierAgentResult(session, opts = {}) {
29
+ const interval = opts.intervalMs ?? 2000, timeout = opts.timeoutMs ?? 300_000;
30
+ const max = opts.maxIntervalMs ?? interval * 4;
31
+ if (![interval, timeout, max].every(n => Number.isSafeInteger(n) && n > 0 && n <= 2_147_483_647) || max < interval)
32
+ throw new Error('Invalid polling interval or timeout');
33
+ const controller = new AbortController();
34
+ const cancelled = () => controller.abort(new VerifierAgentSessionError('cancelled', session.sessionId, 'polling cancelled'));
35
+ opts.signal?.addEventListener('abort', cancelled, { once: true });
36
+ if (opts.signal?.aborted)
37
+ cancelled();
38
+ const timer = setTimeout(() => controller.abort(new VerifierAgentSessionError('timeout', session.sessionId, `still pending after ${timeout} ms`)), timeout);
39
+ let delay = 0;
40
+ let onAbort = () => { };
41
+ const aborted = new Promise((_, reject) => {
42
+ onAbort = () => reject(controller.signal.reason);
43
+ controller.signal.addEventListener('abort', onAbort, { once: true });
44
+ });
45
+ try {
46
+ controller.signal.throwIfAborted();
47
+ return await Promise.race([(async () => {
48
+ for (;;) {
49
+ controller.signal.throwIfAborted();
50
+ // Identity and policy failures propagate immediately; never disclose a bearer to another provider.
51
+ const result = await session.poll(controller.signal);
52
+ controller.signal.throwIfAborted();
53
+ opts.onPhase?.(result.phase);
54
+ if (result.status !== 'pending')
55
+ return verifierAgentResult(session, result);
56
+ delay = nextPollDelay(delay, interval, max, opts.random);
57
+ await new Promise(resolve => {
58
+ const done = () => { clearTimeout(wait); controller.signal.removeEventListener('abort', done); resolve(); };
59
+ const wait = setTimeout(done, delay);
60
+ controller.signal.addEventListener('abort', done, { once: true });
61
+ if (controller.signal.aborted)
62
+ done();
63
+ });
64
+ }
65
+ })(), aborted]);
66
+ }
67
+ finally {
68
+ clearTimeout(timer);
69
+ controller.signal.removeEventListener('abort', onAbort);
70
+ opts.signal?.removeEventListener('abort', cancelled);
71
+ controller.abort();
72
+ }
73
+ }
74
+ /**
75
+ * Bind the wallet's signed request to the operation and authenticated session before disclosure.
76
+ * @param session Authenticated session bound to the creator-authorized operation.
77
+ * @param ro Verified wallet request object whose claims will be presented.
78
+ * @param status Session status carrying the operation binding preimage.
79
+ */
80
+ export function assertRegisteredWalletRequest(session, ro, status) {
81
+ const claims = ro.claims, op = session.operation, binding = status.bindingPreimage;
82
+ if (status.status === 'failed')
83
+ throw new VerifierAgentSessionError('refused', session.sessionId, status.error ?? 'Session failed');
84
+ if (!binding || claims.client_id !== session.profile.clientId || claims.response_uri !== session.profile.endpoint + '/v1/response?session=' + session.sessionId ||
85
+ claims.response_mode !== 'direct_post.jwt' || ro.signerDid !== session.profile.clientId.replace(/^decentralized_identifier:/, ''))
86
+ throw new Error('Wallet request is outside the approved session');
87
+ const signedOperation = binding.operation;
88
+ if (!signedOperation || Object.entries(op).some(([k, v]) => signedOperation[k] !== v))
89
+ throw new Error('Wallet operation differs from the creator authorization');
90
+ const integer = (key) => {
91
+ const value = binding[key];
92
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
93
+ throw new Error('Invalid wallet nonce context');
94
+ return value;
95
+ };
96
+ const hex = (key) => {
97
+ const value = binding[key];
98
+ if (typeof value !== 'string' || !/^0x[0-9a-f]{64}$/i.test(value))
99
+ throw new Error('Invalid wallet nonce hash');
100
+ return hexToBytes(value);
101
+ };
102
+ const expected = derivedNonce(session.requestHash, hex('random'), { epoch: integer('epoch'), snapshotRoot: hex('snapshot_root'),
103
+ registrySize: integer('registry_size'), committee: integer('committee_count'), quorum: integer('quorum'), operationExp: op.exp });
104
+ if (claims.nonce !== expected || binding.nonce !== expected)
105
+ throw new Error('Wallet nonce does not bind the opened operation');
106
+ if (!Number.isSafeInteger(claims.exp) || Number(claims.exp) > op.exp || Number(claims.exp) < Math.floor(Date.now() / 1000))
107
+ throw new Error('Wallet request expiry exceeds its authorization');
108
+ // VERIFY WHEN PRESENT - DO not REQUIRE. Requiring it made this wallet the only one that
109
+ // could complete a presentation: a JAR carrying `transaction_data` is silently dropped by
110
+ // Hovi (it fetches the Request Object, shows it, and never POSTs a response), so a
111
+ // deployment had to choose one wallet. The verifier already takes this position -
112
+ // `[committee] require_transaction_data` defaults to false and is deliberately not forced
113
+ // by production posture - and the network configuration composes JARs without it.
114
+ //
115
+ // What the operation is still bound by when the entry is absent: `request_hash` is
116
+ // keccak256(domain || chain_id || slot_id || action || payload_digest), and the nonce check
117
+ // above proves this JAR was composed for exactly that request hash and `op.exp`. So four
118
+ // of the five fields compared below are already bound, twice over - the equality check
119
+ // against `binding.operation` near the top of this function is the other.
120
+ //
121
+ // What is not bound without it: `description`, the human-readable string the holder is
122
+ // shown. Nothing else. A deployment that needs the holder's displayed text to be
123
+ // cryptographically tied to the creator's authorization must set
124
+ // `[committee] transaction_data = true` AND accept that only wallets which understand
125
+ // the entry can be used.
126
+ //
127
+ // When the entry IS present the checks below are unchanged and still strict: exactly one
128
+ // entry, the right type, and every field equal to the authorized operation.
129
+ if (claims.transaction_data !== undefined) {
130
+ if (!Array.isArray(claims.transaction_data) || claims.transaction_data.length !== 1)
131
+ throw new Error('Wallet request has no unique transaction data');
132
+ const td = decodeJson(claims.transaction_data[0]);
133
+ if (td.type !== 'keykeeper-op/v1' || ['chain_id', 'slot_id', 'action', 'payload_digest', 'description'].some(k => td[k] !== op[k]))
134
+ throw new Error('Wallet transaction data differs from the creator authorization');
135
+ }
136
+ }
@@ -0,0 +1,206 @@
1
+ import { type Account, type Address, type Chain, type Hex, type Transport, type WalletClient } from 'viem';
2
+ import type { TasraChainClient } from './client.js';
3
+ import { type ServiceDiscoveryTransport } from './serviceIdentity.js';
4
+ import { type ServiceApproval } from './services.js';
5
+ /**
6
+ * Guarded discovery and transaction relay transport with bounded response bodies.
7
+ */
8
+ export interface RelayTransport extends ServiceDiscoveryTransport {
9
+ /** Guard the socket just like discovery. Accept bounded JSON status bodies for 200/202/422. */
10
+ relayRequest(url: string, options: {
11
+ body?: Uint8Array;
12
+ maxBytes: number;
13
+ signal: AbortSignal;
14
+ }): Promise<Uint8Array>;
15
+ }
16
+ /**
17
+ * Chain, forwarder, signer and exact calldata identifying a relay operation.
18
+ */
19
+ export interface RelayIntent {
20
+ /** Chain on which the forwarded call is intended to execute. */
21
+ chainId: number;
22
+ /** Independently pinned forwarding contract. */
23
+ forwarder: Address;
24
+ /** Account authorizing the forwarded operation. */
25
+ from: Address;
26
+ /** Target contract of the forwarded operation. */
27
+ to: Address;
28
+ /** Exact encoded calldata to execute. */
29
+ data: Hex;
30
+ /** Application label used to locate the operation recovery record. */
31
+ label: string;
32
+ }
33
+ /**
34
+ * Approved relay providers, pinned forwarder and durable recovery callbacks.
35
+ */
36
+ export interface RegisteredRelayConfig {
37
+ /** Application approvals, in preference order. Registry membership alone never selects a service. */
38
+ approvals: readonly ServiceApproval[];
39
+ /** Guarded HTTP transport for service authentication and relay submission. */
40
+ transport: RelayTransport;
41
+ /** Independently pinned deployment forwarder; never supplied by a relayer manifest. */
42
+ forwarder: Address;
43
+ /** Default operation label used when persisting or resuming relay attempts. */
44
+ label?: string;
45
+ /** Persist the signed reconciliation handle before its first POST. */
46
+ persistAttempt?: (attempt: RelayAttempt) => Promise<void>;
47
+ /** Load this durable operation's previous attempt before signing, including after a restart. */
48
+ resumeAttempt?: (intent: RelayIntent) => Promise<RelayAttempt | undefined>;
49
+ /** Relay status polling interval in milliseconds; defaults to 1500. */
50
+ pollMs?: number;
51
+ /** Deadline in milliseconds after a submission leaves the serialization queue; defaults to 120000 and cannot exceed it. */
52
+ timeoutMs?: number;
53
+ /** At most three authenticated providers receive the identical signed request. */
54
+ maxAttempts?: number;
55
+ /** Status polling budget per provider in milliseconds; defaults to 10000 and cannot exceed 30000. */
56
+ attemptMs?: number;
57
+ }
58
+ /**
59
+ * Verified forwarded transaction result with optional gas and native-token cost.
60
+ */
61
+ export interface RelayReceipt {
62
+ /**
63
+ * Signed relay-request identifier.
64
+ */
65
+ id: string;
66
+ /**
67
+ * Verified forwarded transaction hash.
68
+ */
69
+ txHash: Hex;
70
+ /**
71
+ * Gas consumed by the forwarded transaction, when reported.
72
+ */
73
+ gasUsed?: number;
74
+ /**
75
+ * Native-token transaction cost in base units, encoded as decimal text.
76
+ */
77
+ costWei?: string;
78
+ }
79
+ /**
80
+ * Forwarder ABI used to submit requests, read nonces and verify execution events.
81
+ */
82
+ export declare const relayForwarderAbi: readonly [{
83
+ readonly name: "nonces";
84
+ readonly type: "function";
85
+ readonly stateMutability: "view";
86
+ readonly inputs: readonly [{
87
+ readonly type: "address";
88
+ readonly name: "owner";
89
+ }];
90
+ readonly outputs: readonly [{
91
+ readonly type: "uint256";
92
+ }];
93
+ }, {
94
+ readonly name: "execute";
95
+ readonly type: "function";
96
+ readonly stateMutability: "payable";
97
+ readonly inputs: readonly [{
98
+ readonly type: "tuple";
99
+ readonly components: readonly [{
100
+ readonly type: "address";
101
+ readonly name: "from";
102
+ }, {
103
+ readonly type: "address";
104
+ readonly name: "to";
105
+ }, {
106
+ readonly type: "uint256";
107
+ readonly name: "value";
108
+ }, {
109
+ readonly type: "uint256";
110
+ readonly name: "gas";
111
+ }, {
112
+ readonly type: "uint48";
113
+ readonly name: "deadline";
114
+ }, {
115
+ readonly type: "bytes";
116
+ readonly name: "data";
117
+ }, {
118
+ readonly type: "bytes";
119
+ readonly name: "signature";
120
+ }];
121
+ readonly name: "request";
122
+ }];
123
+ readonly outputs: readonly [];
124
+ }, {
125
+ readonly name: "ExecutedForwardRequest";
126
+ readonly type: "event";
127
+ readonly inputs: readonly [{
128
+ readonly type: "address";
129
+ readonly name: "signer";
130
+ readonly indexed: true;
131
+ }, {
132
+ readonly type: "uint256";
133
+ readonly name: "nonce";
134
+ }, {
135
+ readonly type: "bool";
136
+ readonly name: "success";
137
+ }];
138
+ }];
139
+ /** JSON-safe reconciliation handle. Persist before POST to resume safely after a client restart. */
140
+ export interface RelayAttempt {
141
+ /** Chain bound into the signed forward request. */
142
+ chainId: number;
143
+ /** Pinned forwarder contract expected to execute the request. */
144
+ forwarder: Address;
145
+ /** Decimal block number from which reconciliation scans execution logs. */
146
+ fromBlock: string;
147
+ /** EIP-712 hash identifying the exact signed forward request. */
148
+ id: Hex;
149
+ /** Signed sender, target, calldata, gas, nonce and deadline used for submission and reconciliation. */
150
+ request: {
151
+ from: Address;
152
+ to: Address;
153
+ value: '0';
154
+ gas: number;
155
+ nonce: number;
156
+ deadline: number;
157
+ data: Hex;
158
+ signature: Hex;
159
+ label: string;
160
+ };
161
+ }
162
+ /**
163
+ * A relay request has no verified terminal result and must be reconciled before replacement.
164
+ */
165
+ export declare class RelayOutcomeUnknownError extends Error {
166
+ readonly attempt: RelayAttempt;
167
+ constructor(/** Persisted signed relay attempt whose execution outcome remains unknown. */ attempt: RelayAttempt, reason?: string);
168
+ }
169
+ /**
170
+ * Reconciled relay outcome. A receipt proves execution. Expired means the deadline passed with the nonce unused. Unresolvable means the nonce was consumed beyond the available log window; execution remains unknown and must not be retried as a new operation.
171
+ */
172
+ export interface RelayReconciliation {
173
+ /**
174
+ * Verified successful execution receipt, when found.
175
+ */
176
+ receipt?: RelayReceipt;
177
+ /**
178
+ * Whether the deadline passed while the request nonce remained unused.
179
+ */
180
+ expired: boolean;
181
+ /**
182
+ * Whether the consumed nonce predates the available log scan, leaving execution unknown.
183
+ */
184
+ unresolvable?: boolean;
185
+ }
186
+ /**
187
+ * Recover from a lost HTTP response or process restart using the trusted RPC, without broadcasting.
188
+ * @param chain Trusted reader for the chain on which the forward request may have executed.
189
+ * @param attempt Persisted signed request and original log-scan start block.
190
+ * @param timeoutMs Maximum reconciliation duration in milliseconds; defaults to 30000.
191
+ */
192
+ export declare function reconcileRelayAttempt(chain: TasraChainClient, attempt: RelayAttempt, timeoutMs?: number): Promise<RelayReconciliation>;
193
+ /**
194
+ * One signer per instance. Serializes nonces and blocks new signatures after an uncertain result.
195
+ * @param chain Trusted chain reader used for nonce and receipt verification.
196
+ * @param config Approved relay providers, pinned forwarder and recovery controls.
197
+ * @param wallet Account-bound and chain-bound wallet that signs forward requests.
198
+ * @param options Optional durable callback invoked before submitting a signed request.
199
+ */
200
+ export declare function createRegisteredRelaySubmitter(chain: TasraChainClient, config: RegisteredRelayConfig, wallet: WalletClient<Transport, Chain, Account>, options?: {
201
+ persistAttempt?: (attempt: RelayAttempt) => Promise<void>;
202
+ }): {
203
+ submit: (to: Address, data: Hex, label?: string) => Promise<RelayReceipt>;
204
+ pendingAttempt: () => RelayAttempt | undefined;
205
+ reconcile(): Promise<RelayReconciliation | undefined>;
206
+ };