@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,237 @@
1
+ import { hashTypedData, recoverAddress } from 'viem';
2
+ import { hashServiceManifest, readApprovedServiceRecord } from './services.js';
3
+ /**
4
+ * HTTPS path where a registered service publishes its canonical manifest.
5
+ */
6
+ export const SERVICE_MANIFEST_PATH = '/.well-known/keykeeper-service.json';
7
+ /**
8
+ * HTTPS endpoint that signs a registered-service identity challenge.
9
+ */
10
+ export const SERVICE_IDENTITY_PATH = '/v1/service/identity';
11
+ /**
12
+ * Maximum accepted service manifest size in bytes.
13
+ */
14
+ export const SERVICE_MANIFEST_MAX_BYTES = 16_384;
15
+ /**
16
+ * Maximum accepted identity challenge response size in bytes.
17
+ */
18
+ export const SERVICE_IDENTITY_MAX_BYTES = 2_048;
19
+ /**
20
+ * Maximum accepted identity challenge validity window in seconds.
21
+ */
22
+ export const SERVICE_CHALLENGE_SECONDS = 30;
23
+ // Leave five seconds inside the responder acceptance window for ordinary clock differences.
24
+ /**
25
+ * Challenge lifetime in seconds, leaving room for clock differences.
26
+ */
27
+ export const SERVICE_CHALLENGE_LIFETIME_SECONDS = 25;
28
+ /**
29
+ * Protocol identifier required in registered-service manifests.
30
+ */
31
+ export const SERVICE_IDENTITY_PROTOCOL = 'keykeeper-service-identity-v1';
32
+ function requireHex(value, bytes) {
33
+ if (typeof value !== 'string' || !new RegExp(`^0x[0-9a-f]{${bytes * 2}}$`).test(value)) {
34
+ throw new Error('Service identity requires lowercase fixed-width hex');
35
+ }
36
+ }
37
+ function safeInteger(value) { return Number.isSafeInteger(value) && value > 0; }
38
+ /**
39
+ * Reject aliases instead of signing a URL which another implementation normalizes differently.
40
+ * @param endpoint Canonical HTTPS base URL without credentials, query or fragment.
41
+ */
42
+ export function validateServiceEndpoint(endpoint) {
43
+ if (endpoint.length > 512 || !/^https:\/\/[\x21-\x7e]+$/.test(endpoint) || /[%\\?#@]/.test(endpoint)) {
44
+ throw new Error('Service endpoint must be canonical HTTPS without escapes, userinfo, query or fragment');
45
+ }
46
+ const url = new URL(endpoint);
47
+ const canonical = url.origin + (url.pathname === '/' ? '' : url.pathname);
48
+ if (canonical !== endpoint || url.pathname.endsWith('/') && url.pathname !== '/' || url.pathname.includes('//') || url.hostname.endsWith('.')) {
49
+ throw new Error('Service endpoint is not canonical');
50
+ }
51
+ return url;
52
+ }
53
+ /**
54
+ * Canonical v1 bytes: fixed field order, compact ASCII JSON, one LF. No optional/unknown fields.
55
+ * @param manifest Versioned service metadata to validate and encode canonically.
56
+ */
57
+ export function encodeServiceManifest(manifest) {
58
+ if (manifest.schemaVersion !== 1 || !safeInteger(manifest.chainId) || ![0, 1, 2].includes(manifest.serviceType) || manifest.protocol !== SERVICE_IDENTITY_PROTOCOL) {
59
+ throw new Error('Unsupported service manifest');
60
+ }
61
+ requireHex(manifest.registry, 20);
62
+ requireHex(manifest.serviceId, 32);
63
+ validateServiceEndpoint(manifest.endpoint);
64
+ if (!Array.isArray(manifest.capabilities) || manifest.capabilities.length > 16 || new Set(manifest.capabilities).size !== manifest.capabilities.length || manifest.capabilities.some(c => typeof c !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(c))) {
65
+ throw new Error('Invalid service capabilities');
66
+ }
67
+ const bytes = new TextEncoder().encode(JSON.stringify({
68
+ schemaVersion: manifest.schemaVersion, chainId: manifest.chainId, registry: manifest.registry,
69
+ serviceId: manifest.serviceId, serviceType: manifest.serviceType, endpoint: manifest.endpoint,
70
+ protocol: manifest.protocol, capabilities: manifest.capabilities,
71
+ }) + '\n');
72
+ if (bytes.length > SERVICE_MANIFEST_MAX_BYTES)
73
+ throw new Error('Service manifest too large');
74
+ return bytes;
75
+ }
76
+ /**
77
+ * Verify exact manifest bytes against the approved hash, canonical encoding and registry record.
78
+ * @param bytes Exact downloaded service manifest bytes.
79
+ * @param approval Application-approved service identity and pinned manifest hash.
80
+ * @param record Registry record whose endpoint and hash must match the manifest.
81
+ */
82
+ export function verifyServiceManifest(bytes, approval, record) {
83
+ if (bytes.length > SERVICE_MANIFEST_MAX_BYTES || hashServiceManifest(bytes).toLowerCase() !== approval.manifestHash.toLowerCase() || record.manifestHash.toLowerCase() !== approval.manifestHash.toLowerCase()) {
84
+ throw new Error('Service manifest hash mismatch or size exceeded');
85
+ }
86
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
87
+ const manifest = JSON.parse(text);
88
+ const canonical = encodeServiceManifest(manifest);
89
+ if (canonical.length !== bytes.length || canonical.some((byte, i) => bytes[i] !== byte))
90
+ throw new Error('Noncanonical service manifest');
91
+ if (manifest.chainId !== approval.chainId || manifest.registry !== approval.registry.toLowerCase() || manifest.serviceId !== approval.serviceId.toLowerCase() || manifest.serviceType !== approval.serviceType || manifest.endpoint !== record.endpoint) {
92
+ throw new Error('Service manifest profile mismatch');
93
+ }
94
+ return manifest;
95
+ }
96
+ /**
97
+ * Build validated EIP-712 data binding a challenge to the approved service revision and endpoint.
98
+ * @param challenge Challenge binding the service revision, endpoint, nonce and expiry.
99
+ */
100
+ export function serviceChallengeTypedData(challenge) {
101
+ requireHex(challenge.registry, 20);
102
+ requireHex(challenge.serviceId, 32);
103
+ requireHex(challenge.manifestHash, 32);
104
+ requireHex(challenge.nonce, 32);
105
+ validateServiceEndpoint(challenge.endpoint);
106
+ if (challenge.version !== 1 || !safeInteger(challenge.chainId) || !safeInteger(challenge.expiresAt) || typeof challenge.revision !== 'string' || !/^[1-9][0-9]{0,19}$/.test(challenge.revision) || BigInt(challenge.revision) > (1n << 64n) - 1n) {
107
+ throw new Error('Invalid service challenge');
108
+ }
109
+ return {
110
+ domain: { name: 'Keykeeper Service Identity', version: '1', chainId: challenge.chainId, verifyingContract: challenge.registry },
111
+ primaryType: 'ServiceIdentity',
112
+ types: { ServiceIdentity: [
113
+ { name: 'serviceId', type: 'bytes32' }, { name: 'revision', type: 'uint64' },
114
+ { name: 'endpoint', type: 'string' }, { name: 'manifestHash', type: 'bytes32' },
115
+ { name: 'nonce', type: 'bytes32' }, { name: 'expiresAt', type: 'uint64' },
116
+ ] },
117
+ message: { serviceId: challenge.serviceId, revision: BigInt(challenge.revision), endpoint: challenge.endpoint,
118
+ manifestHash: challenge.manifestHash, nonce: challenge.nonce, expiresAt: BigInt(challenge.expiresAt) },
119
+ };
120
+ }
121
+ /**
122
+ * Canonical wire encoding accepted by both responder implementations.
123
+ * @param challenge Validated challenge to encode in the protocol wire format.
124
+ */
125
+ export function encodeServiceChallenge(challenge) {
126
+ serviceChallengeTypedData(challenge);
127
+ const bytes = new TextEncoder().encode(JSON.stringify({
128
+ version: challenge.version, chainId: challenge.chainId, registry: challenge.registry,
129
+ serviceId: challenge.serviceId, revision: challenge.revision, endpoint: challenge.endpoint,
130
+ manifestHash: challenge.manifestHash, nonce: challenge.nonce, expiresAt: challenge.expiresAt,
131
+ }));
132
+ if (bytes.length > SERVICE_IDENTITY_MAX_BYTES)
133
+ throw new Error('Service challenge too large');
134
+ return bytes;
135
+ }
136
+ /**
137
+ * Call only after enforcing the same limit while receiving the HTTP body.
138
+ * @param bytes UTF-8 challenge JSON bytes to decode and validate.
139
+ */
140
+ export function parseServiceChallenge(bytes) {
141
+ if (bytes.length > SERVICE_IDENTITY_MAX_BYTES)
142
+ throw new Error('Service challenge too large');
143
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
144
+ const challenge = JSON.parse(text);
145
+ const canonical = encodeServiceChallenge(challenge);
146
+ if (canonical.length !== bytes.length || canonical.some((byte, i) => bytes[i] !== byte))
147
+ throw new Error('Noncanonical service challenge');
148
+ return challenge;
149
+ }
150
+ /**
151
+ * Responder must validate against its own configured profile before asking its dedicated key to sign.
152
+ * @param challenge Parsed challenge received from the client.
153
+ * @param approval Approved service identity and revision.
154
+ * @param endpoint Expected canonical service endpoint.
155
+ * @param now Current Unix time in seconds used to validate the expiry.
156
+ */
157
+ export function validateServiceChallenge(challenge, approval, endpoint, now) {
158
+ serviceChallengeTypedData(challenge);
159
+ if (!Number.isSafeInteger(now) || now < 0 || challenge.expiresAt <= now || challenge.expiresAt - now > SERVICE_CHALLENGE_SECONDS)
160
+ throw new Error('Service challenge expired or too far ahead');
161
+ if (challenge.chainId !== approval.chainId || challenge.registry !== approval.registry.toLowerCase() || challenge.serviceId !== approval.serviceId.toLowerCase() || challenge.revision !== approval.revision.toString() || challenge.manifestHash !== approval.manifestHash.toLowerCase() || challenge.endpoint !== endpoint) {
162
+ throw new Error('Service challenge profile mismatch');
163
+ }
164
+ }
165
+ /**
166
+ * Verify the challenge response against the registry authentication key and expected request digest.
167
+ * @param challenge Expected challenge whose digest must be signed.
168
+ * @param signature Hex-encoded EIP-712 signature returned by the service.
169
+ * @param authKey Authentication address pinned by the registry record.
170
+ * @param now Current Unix time in seconds used to validate the expiry.
171
+ */
172
+ export async function verifyServiceIdentity(challenge, signature, authKey, now) {
173
+ serviceChallengeTypedData(challenge);
174
+ if (!Number.isSafeInteger(now) || now < 0 || challenge.expiresAt <= now || challenge.expiresAt - now > SERVICE_CHALLENGE_SECONDS)
175
+ throw new Error('Service challenge expired or too far ahead');
176
+ requireHex(signature, 65);
177
+ // One canonical Ethereum signature encoding: low-s and v=27/28, shared with the reference implementation.
178
+ const s = BigInt(`0x${signature.slice(66, 130)}`);
179
+ if (s === 0n || s > 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0n || !['1b', '1c'].includes(signature.slice(130)))
180
+ throw new Error('Noncanonical service signature');
181
+ if ((await recoverAddress({ hash: hashTypedData(serviceChallengeTypedData(challenge)), signature })).toLowerCase() !== authKey.toLowerCase())
182
+ throw new Error('Service endpoint key mismatch');
183
+ }
184
+ /**
185
+ * Uncached, bounded discovery only. A result is a short-lived observation, not verifier-agent or gas authorization.
186
+ * @param chain Trusted chain reader for the service registry.
187
+ * @param approved Application-approved service identity, revision and manifest hash.
188
+ * @param transport Guarded HTTPS transport for manifest and identity requests.
189
+ */
190
+ export async function authenticateApprovedService(chain, approved, transport) {
191
+ const approval = Object.freeze({ ...approved });
192
+ const controller = new AbortController();
193
+ const timer = setTimeout(() => controller.abort(new Error('Service discovery timed out')), SERVICE_CHALLENGE_SECONDS * 1000);
194
+ const expiresAt = Math.floor(Date.now() / 1000) + SERVICE_CHALLENGE_LIFETIME_SECONDS;
195
+ // RPC calls do not accept our abort signal. Race them, and stop the workflow after each await.
196
+ const bounded = async (work) => {
197
+ controller.signal.throwIfAborted();
198
+ let onAbort = () => { };
199
+ try {
200
+ return await Promise.race([work, new Promise((_, reject) => {
201
+ onAbort = () => reject(controller.signal.reason);
202
+ controller.signal.addEventListener('abort', onAbort, { once: true });
203
+ })]);
204
+ }
205
+ finally {
206
+ controller.signal.removeEventListener('abort', onAbort);
207
+ }
208
+ };
209
+ try {
210
+ const first = await bounded(readApprovedServiceRecord(chain, approval));
211
+ validateServiceEndpoint(first.record.endpoint);
212
+ const bytes = await bounded(transport.request(first.record.endpoint + SERVICE_MANIFEST_PATH, { maxBytes: SERVICE_MANIFEST_MAX_BYTES, signal: controller.signal }));
213
+ const manifest = verifyServiceManifest(bytes, approval, first.record);
214
+ const nonce = `0x${Array.from(globalThis.crypto.getRandomValues(new Uint8Array(32)), b => b.toString(16).padStart(2, '0')).join('')}`;
215
+ const challenge = { version: 1, chainId: approval.chainId, registry: approval.registry.toLowerCase(),
216
+ serviceId: approval.serviceId.toLowerCase(), revision: approval.revision.toString(), endpoint: first.record.endpoint,
217
+ manifestHash: approval.manifestHash.toLowerCase(), nonce, expiresAt };
218
+ validateServiceChallenge(challenge, approval, first.record.endpoint, Math.floor(Date.now() / 1000));
219
+ const reply = await bounded(transport.request(first.record.endpoint + SERVICE_IDENTITY_PATH, { body: encodeServiceChallenge(challenge), maxBytes: SERVICE_IDENTITY_MAX_BYTES, signal: controller.signal }));
220
+ if (reply.length > SERVICE_IDENTITY_MAX_BYTES)
221
+ throw new Error('Service identity reply too large');
222
+ const parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(reply));
223
+ if (!parsed || Object.keys(parsed).length !== 1 || !('signature' in parsed))
224
+ throw new Error('Invalid service identity reply');
225
+ await bounded(verifyServiceIdentity(challenge, parsed.signature, first.record.authKey, Math.floor(Date.now() / 1000)));
226
+ const last = await bounded(readApprovedServiceRecord(chain, approval));
227
+ if (last.blockNumber < first.blockNumber || Object.keys(first.record).some(k => first.record[k] !== last.record[k]))
228
+ throw new Error('Service changed during authentication');
229
+ controller.signal.throwIfAborted();
230
+ validateServiceChallenge(challenge, approval, first.record.endpoint, Math.floor(Date.now() / 1000));
231
+ return { approval, record: last.record, manifest, blockNumber: last.blockNumber, expiresAt };
232
+ }
233
+ finally {
234
+ clearTimeout(timer);
235
+ controller.abort();
236
+ }
237
+ }
@@ -0,0 +1,39 @@
1
+ import type { Address } from 'viem';
2
+ import type { ServiceApproval } from './services.js';
3
+ import type { ApprovedAgentProfile } from './registeredAgent.js';
4
+ /**
5
+ * Application-approved service identity and its expected endpoint.
6
+ */
7
+ export interface ApprovedServiceProfile {
8
+ /**
9
+ * Independently reviewed registry identity and metadata pins.
10
+ */
11
+ approval: ServiceApproval;
12
+ /**
13
+ * Expected canonical service endpoint.
14
+ */
15
+ endpoint: string;
16
+ }
17
+ /** Reviewed application configuration, never a list downloaded from a service registry. */
18
+ export interface ApplicationServiceProfiles {
19
+ /** Chain shared by all approved service profiles. */
20
+ chainId: number;
21
+ /** ServiceRegistry contract shared by the approved profiles. */
22
+ registry: Address;
23
+ /** Independently approved relay providers in application preference order. */
24
+ relayers: ApprovedServiceProfile[];
25
+ /** Independently approved verifier agents and their pinned audiences. */
26
+ verifierAgents: ApprovedAgentProfile[];
27
+ /** Independently approved vault-service identities and endpoints. */
28
+ vaultServices: ApprovedServiceProfile[];
29
+ }
30
+ /**
31
+ * Parse the public, JSON-safe deployment approval file. Decimal revisions preserve uint64.
32
+ * @param value Parsed approval object or its JSON text.
33
+ */
34
+ export declare function parseApplicationServiceProfiles(value: unknown): ApplicationServiceProfiles;
35
+ /**
36
+ * Publish only public approvals, with no runtime transport or private key material.
37
+ * @param profiles Application-approved service profiles to serialize without private runtime data.
38
+ */
39
+ export declare function applicationServiceProfilesDocument(profiles: ApplicationServiceProfiles): Record<string, unknown>;
@@ -0,0 +1,74 @@
1
+ import { validateServiceEndpoint } from './serviceIdentity.js';
2
+ function object(value, fields) {
3
+ if (!value || typeof value !== 'object' || Array.isArray(value))
4
+ throw new Error('Invalid service profile object');
5
+ const o = value;
6
+ if (Object.keys(o).length !== fields.length || fields.some(k => !Object.hasOwn(o, k)))
7
+ throw new Error('Unexpected or missing service profile fields');
8
+ return o;
9
+ }
10
+ function hex(value, bytes) {
11
+ if (typeof value !== 'string' || !new RegExp(`^0x[0-9a-fA-F]{${bytes * 2}}$`).test(value) || /^0x0+$/.test(value))
12
+ throw new Error('Invalid service profile address or hash');
13
+ return value.toLowerCase();
14
+ }
15
+ /**
16
+ * Parse the public, JSON-safe deployment approval file. Decimal revisions preserve uint64.
17
+ * @param value Parsed approval object or its JSON text.
18
+ */
19
+ export function parseApplicationServiceProfiles(value) {
20
+ if (typeof value === 'string') {
21
+ if (new TextEncoder().encode(value).length > 65_536)
22
+ throw new Error('Service profile file too large');
23
+ value = JSON.parse(value);
24
+ }
25
+ const o = object(value, ['schemaVersion', 'chainId', 'registry', 'relayers', 'verifierAgents', 'vaultServices']);
26
+ if (o.schemaVersion !== 1 || !Number.isSafeInteger(o.chainId) || Number(o.chainId) < 1)
27
+ throw new Error('Invalid service profile version or chain');
28
+ const chainId = Number(o.chainId), registry = hex(o.registry, 20);
29
+ const ids = new Set();
30
+ function profiles(input, serviceType) {
31
+ if (!Array.isArray(input) || input.length > 16)
32
+ throw new Error('At most 16 profiles per service type are allowed');
33
+ return input.map(item => {
34
+ const p = object(item, ['serviceId', 'owner', 'revision', 'manifestHash', 'endpoint', ...(serviceType === 1 ? ['clientId'] : [])]);
35
+ const serviceId = hex(p.serviceId, 32), owner = hex(p.owner, 20), manifestHash = hex(p.manifestHash, 32);
36
+ if (ids.has(serviceId))
37
+ throw new Error('Duplicate approved service ID');
38
+ ids.add(serviceId);
39
+ if (typeof p.revision !== 'string' || !/^[1-9][0-9]{0,19}$/.test(p.revision) || BigInt(p.revision) > (1n << 64n) - 1n)
40
+ throw new Error('Invalid service revision');
41
+ if (typeof p.endpoint !== 'string')
42
+ throw new Error('Service endpoint is required');
43
+ validateServiceEndpoint(p.endpoint);
44
+ const approval = { chainId, registry, serviceId, serviceType, owner, revision: BigInt(p.revision), manifestHash };
45
+ if (serviceType === 1) {
46
+ if (typeof p.clientId !== 'string' || !/^decentralized_identifier:did:web:[a-z0-9.-]+(?:(?:%3A)[0-9]+)?$/.test(p.clientId))
47
+ throw new Error('Invalid verifier-agent audience');
48
+ return { approval, endpoint: p.endpoint, clientId: p.clientId };
49
+ }
50
+ return { approval, endpoint: p.endpoint };
51
+ });
52
+ }
53
+ const relayers = profiles(o.relayers, 0), verifierAgents = profiles(o.verifierAgents, 1), vaultServices = profiles(o.vaultServices, 2);
54
+ if (new Set(verifierAgents.map(p => new URL(p.endpoint).origin)).size !== verifierAgents.length || new Set(verifierAgents.map(p => p.clientId)).size !== verifierAgents.length)
55
+ throw new Error('Independent verifier-agents require distinct origins and audiences');
56
+ return { chainId, registry, relayers, verifierAgents, vaultServices };
57
+ }
58
+ /**
59
+ * Publish only public approvals, with no runtime transport or private key material.
60
+ * @param profiles Application-approved service profiles to serialize without private runtime data.
61
+ */
62
+ export function applicationServiceProfilesDocument(profiles) {
63
+ function entries(values, serviceType) {
64
+ return values.map(({ approval: a, endpoint, clientId }) => {
65
+ if (a.serviceType !== serviceType || a.chainId !== profiles.chainId || a.registry.toLowerCase() !== profiles.registry.toLowerCase())
66
+ throw new Error('Service profile deployment mismatch');
67
+ return { serviceId: a.serviceId, owner: a.owner, revision: a.revision.toString(), manifestHash: a.manifestHash, endpoint, ...(clientId !== undefined ? { clientId } : {}) };
68
+ });
69
+ }
70
+ const document = { schemaVersion: 1, chainId: profiles.chainId, registry: profiles.registry,
71
+ relayers: entries(profiles.relayers, 0), verifierAgents: entries(profiles.verifierAgents, 1), vaultServices: entries(profiles.vaultServices, 2) };
72
+ parseApplicationServiceProfiles(document);
73
+ return document;
74
+ }
@@ -0,0 +1,141 @@
1
+ import { type Address, type Hex, type PublicClient, type ReadContractReturnType } from 'viem';
2
+ import { serviceRegistryAbi } from './abis/serviceRegistry.js';
3
+ import { type AddressBook } from './deployments.js';
4
+ /** Permanent ServiceRegistry ABI ordinals. Registration grants no operator privileges. */
5
+ export declare const SERVICE_TYPES: {
6
+ readonly gasRelayer: 0;
7
+ readonly verifierAgent: 1;
8
+ readonly vaultService: 2;
9
+ };
10
+ /**
11
+ * Registry lifecycle ordinals for active, draining and retired services.
12
+ */
13
+ export declare const SERVICE_STATUSES: {
14
+ readonly active: 0;
15
+ readonly draining: 1;
16
+ readonly retired: 2;
17
+ };
18
+ /**
19
+ * Registry ordinal identifying a gas relay, verifier agent or vault service.
20
+ */
21
+ export type ServiceType = (typeof SERVICE_TYPES)[keyof typeof SERVICE_TYPES];
22
+ /**
23
+ * Registry lifecycle status indicating whether a service accepts new work.
24
+ */
25
+ export type ServiceStatus = (typeof SERVICE_STATUSES)[keyof typeof SERVICE_STATUSES];
26
+ /** Provider claims, not authenticated endpoints or platform endorsements. */
27
+ export interface ServiceRecord {
28
+ /**
29
+ * Current provider account controlling the registration.
30
+ */
31
+ owner: Address;
32
+ /**
33
+ * Account nominated for ownership transfer; zero when none is pending.
34
+ */
35
+ pendingOwner: Address;
36
+ /**
37
+ * Address whose key must sign endpoint identity challenges.
38
+ */
39
+ authKey: Address;
40
+ /**
41
+ * Registered capability family.
42
+ */
43
+ serviceType: ServiceType;
44
+ /**
45
+ * Provider lifecycle state.
46
+ */
47
+ status: ServiceStatus;
48
+ /**
49
+ * Registry revision used to detect changed provider metadata.
50
+ */
51
+ revision: bigint;
52
+ /**
53
+ * Keccak-256 digest of the exact published manifest bytes.
54
+ */
55
+ manifestHash: Hex;
56
+ /**
57
+ * Registered canonical HTTPS service base URL.
58
+ */
59
+ endpoint: string;
60
+ }
61
+ /** Pin the approved revision so an endpoint, key or provider change requires a new decision. */
62
+ export interface ServiceApproval {
63
+ /**
64
+ * Approved EVM chain ID.
65
+ */
66
+ chainId: number;
67
+ /**
68
+ * Approved ServiceRegistry address.
69
+ */
70
+ registry: Address;
71
+ /**
72
+ * Stable identifier of the approved service.
73
+ */
74
+ serviceId: Hex;
75
+ /**
76
+ * Expected service capability family.
77
+ */
78
+ serviceType: ServiceType;
79
+ /**
80
+ * Approved provider owner address.
81
+ */
82
+ owner: Address;
83
+ /**
84
+ * Exact approved registry revision.
85
+ */
86
+ revision: bigint;
87
+ /**
88
+ * Approved hash of the canonical service manifest.
89
+ */
90
+ manifestHash: Hex;
91
+ }
92
+ /**
93
+ * Matches serviceIdFor on the proxy. Provider transfer does not change this ID.
94
+ * @param chainId EVM chain ID used in the registry identifier domain.
95
+ * @param registry Deployed ServiceRegistry address.
96
+ * @param creator Original provider address that registered the service.
97
+ * @param salt Provider-chosen 32-byte registration salt.
98
+ */
99
+ export declare function deriveServiceId(chainId: bigint, registry: Address, creator: Address, salt: Hex): Hex;
100
+ /**
101
+ * Minimal chain reader required to validate service approvals without contacting the service.
102
+ */
103
+ export interface ServiceRegistryChainReader {
104
+ readonly addresses: AddressBook;
105
+ readonly client: PublicClient;
106
+ readonly readers: {
107
+ readonly serviceRegistry: {
108
+ getService(serviceId: Hex, blockNumber?: bigint): Promise<ReadContractReturnType<typeof serviceRegistryAbi, 'getService'>>;
109
+ };
110
+ };
111
+ }
112
+ /**
113
+ * Hash the exact downloaded/published bytes; never parse and re-serialize before checking.
114
+ * @param bytes Exact canonical manifest bytes; do not parse and reserialize before hashing.
115
+ */
116
+ export declare function hashServiceManifest(bytes: Uint8Array): Hex;
117
+ /**
118
+ * Contract readers for service records and paginated service IDs. Supply one block number for a consistent snapshot.
119
+ */
120
+ export interface ServiceRegistryReaders {
121
+ getService(serviceId: Hex, blockNumber?: bigint): Promise<ReadContractReturnType<typeof serviceRegistryAbi, 'getService'>>;
122
+ serviceCount(blockNumber?: bigint): Promise<ReadContractReturnType<typeof serviceRegistryAbi, 'serviceCount'>>;
123
+ serviceIds(offset: bigint, limit: bigint, blockNumber?: bigint): Promise<ReadContractReturnType<typeof serviceRegistryAbi, 'serviceIds'>>;
124
+ }
125
+ /**
126
+ * Create paginated contract readers for service records and IDs.
127
+ * @param client Viem public client for contract reads.
128
+ * @param address Callback returning the deployed ServiceRegistry address.
129
+ */
130
+ export declare function createServiceRegistryReaders(client: PublicClient, address: () => Address): ServiceRegistryReaders;
131
+ /**
132
+ * Read metadata only after matching an explicit application approval. Never contacts the service.
133
+ * This does not authenticate its endpoint, verify its manifest or authorize a verifier-agent
134
+ * origin. Those checks must precede sending any credentials, session secrets or transactions.
135
+ * @param chain Trusted chain reader with ServiceRegistry access.
136
+ * @param approval Independently approved identity, owner, revision and manifest hash.
137
+ */
138
+ export declare function readApprovedServiceRecord(chain: ServiceRegistryChainReader, approval: ServiceApproval): Promise<{
139
+ record: ServiceRecord;
140
+ blockNumber: bigint;
141
+ }>;
@@ -0,0 +1,79 @@
1
+ import { encodeAbiParameters, keccak256 } from 'viem';
2
+ import { serviceRegistryAbi } from './abis/serviceRegistry.js';
3
+ import { requireAddress } from './deployments.js';
4
+ /** Permanent ServiceRegistry ABI ordinals. Registration grants no operator privileges. */
5
+ export const SERVICE_TYPES = { gasRelayer: 0, verifierAgent: 1, vaultService: 2 };
6
+ /**
7
+ * Registry lifecycle ordinals for active, draining and retired services.
8
+ */
9
+ export const SERVICE_STATUSES = { active: 0, draining: 1, retired: 2 };
10
+ /**
11
+ * Matches serviceIdFor on the proxy. Provider transfer does not change this ID.
12
+ * @param chainId EVM chain ID used in the registry identifier domain.
13
+ * @param registry Deployed ServiceRegistry address.
14
+ * @param creator Original provider address that registered the service.
15
+ * @param salt Provider-chosen 32-byte registration salt.
16
+ */
17
+ export function deriveServiceId(chainId, registry, creator, salt) {
18
+ return keccak256(encodeAbiParameters([{ type: 'uint256' }, { type: 'address' }, { type: 'address' }, { type: 'bytes32' }], [chainId, registry, creator, salt]));
19
+ }
20
+ /**
21
+ * Hash the exact downloaded/published bytes; never parse and re-serialize before checking.
22
+ * @param bytes Exact canonical manifest bytes; do not parse and reserialize before hashing.
23
+ */
24
+ export function hashServiceManifest(bytes) {
25
+ return keccak256(bytes);
26
+ }
27
+ /**
28
+ * Create paginated contract readers for service records and IDs.
29
+ * @param client Viem public client for contract reads.
30
+ * @param address Callback returning the deployed ServiceRegistry address.
31
+ */
32
+ export function createServiceRegistryReaders(client, address) {
33
+ return {
34
+ getService: (serviceId, blockNumber) => client.readContract({
35
+ address: address(), abi: serviceRegistryAbi, functionName: 'getService', args: [serviceId], blockNumber,
36
+ }),
37
+ serviceCount: (blockNumber) => client.readContract({
38
+ address: address(), abi: serviceRegistryAbi, functionName: 'serviceCount', blockNumber,
39
+ }),
40
+ serviceIds: (offset, limit, blockNumber) => {
41
+ if (offset < 0n || limit < 1n || limit > 100n)
42
+ throw new Error('Invalid ServiceRegistry page');
43
+ return client.readContract({
44
+ address: address(), abi: serviceRegistryAbi, functionName: 'serviceIds', args: [offset, limit], blockNumber,
45
+ });
46
+ },
47
+ };
48
+ }
49
+ /**
50
+ * Read metadata only after matching an explicit application approval. Never contacts the service.
51
+ * This does not authenticate its endpoint, verify its manifest or authorize a verifier-agent
52
+ * origin. Those checks must precede sending any credentials, session secrets or transactions.
53
+ * @param chain Trusted chain reader with ServiceRegistry access.
54
+ * @param approval Independently approved identity, owner, revision and manifest hash.
55
+ */
56
+ export async function readApprovedServiceRecord(chain, approval) {
57
+ const registry = requireAddress(chain.addresses, 'ServiceRegistry');
58
+ if (registry.toLowerCase() !== approval.registry.toLowerCase())
59
+ throw new Error('Service registry approval mismatch');
60
+ const chainId = await chain.client.getChainId();
61
+ if (chainId !== approval.chainId || (chain.client.chain && chain.client.chain.id !== chainId)) {
62
+ throw new Error('Service chain approval mismatch');
63
+ }
64
+ const blockNumber = await chain.client.getBlockNumber({ cacheTime: 0 });
65
+ const record = await chain.readers.serviceRegistry.getService(approval.serviceId, blockNumber);
66
+ if (record.status !== SERVICE_STATUSES.active)
67
+ throw new Error('Service is not accepting new work');
68
+ if (record.serviceType !== approval.serviceType || !Object.values(SERVICE_TYPES).includes(record.serviceType)) {
69
+ throw new Error('Service type approval mismatch');
70
+ }
71
+ if (record.owner.toLowerCase() !== approval.owner.toLowerCase())
72
+ throw new Error('Service owner approval mismatch');
73
+ if (record.revision !== approval.revision || record.revision < 1n)
74
+ throw new Error('Service revision approval mismatch');
75
+ if (record.manifestHash.toLowerCase() !== approval.manifestHash.toLowerCase()) {
76
+ throw new Error('Service manifest approval mismatch');
77
+ }
78
+ return { record: { ...record, serviceType: approval.serviceType, status: SERVICE_STATUSES.active }, blockNumber };
79
+ }
@@ -0,0 +1,55 @@
1
+ import type { TasraChainClient } from './client.js';
2
+ import { type SessionAuth, type OpenSessionOpts, type Session } from '../client/index.js';
3
+ import type { CommitteeVerifier } from '../committee/request.js';
4
+ /** How the session's endpoints were resolved from chain - surfaced so callers can see
5
+ * which verifier was chosen and which keeper committee the slot is bound to. */
6
+ export interface ResolvedEndpoints {
7
+ /** Slot identifier used to resolve the assigned service endpoints. */
8
+ slotId: string;
9
+ /** The slot's on-chain assigned keeper node URLs. */
10
+ nodes: string[];
11
+ /** The verifier chosen (at random) from the on-chain set - it issued the JWT. */
12
+ verifier: string;
13
+ /** Size of the on-chain verifier set the choice was drawn from. */
14
+ verifierCount: number;
15
+ }
16
+ /**
17
+ * Chain discovery and authorization options for a managed JWT slot session.
18
+ */
19
+ export interface TasraSlotClientConfig {
20
+ /** Read client for the deployment (RPC + address book). */
21
+ chain: TasraChainClient;
22
+ /** This holder's DID (recipient_did / holder for the JWT). */
23
+ identity?: string;
24
+ /**
25
+ * Explicit routing from registered service URLs to reachable URLs. Omission uses registry URLs unchanged.
26
+ */
27
+ rewriteUrl?: (url: string) => string;
28
+ /** Observe the per-session resolution (chosen verifier + discovered nodes). */
29
+ onResolve?: (r: ResolvedEndpoints) => void;
30
+ /** JWT refresh skew (ms), forwarded to the session. */
31
+ skewMs?: number;
32
+ }
33
+ /**
34
+ * Managed slot-session factory that resolves keeper and verifier endpoints from the registry.
35
+ */
36
+ export interface TasraSlotClient {
37
+ /** Discover the slot's nodes + choose a verifier from chain, mint the JWT via that
38
+ * verifier, and return a managed session (encrypt / decrypt / sign). */
39
+ openSession(slotId: string, auth: SessionAuth, opts?: OpenSessionOpts): Promise<Session>;
40
+ /** Resolve the endpoints for a slot WITHOUT opening a session (which verifier would be
41
+ * chosen + the slot's keeper committee). Handy for inspection. */
42
+ resolveEndpoints(slotId: string): Promise<ResolvedEndpoints>;
43
+ /** The discovered active verifier directory (cached). */
44
+ verifierDirectory(): Promise<CommitteeVerifier[]>;
45
+ /** Return currently open managed sessions. */
46
+ sessions(): readonly Session[];
47
+ /** Close all managed sessions and clear their reconstructed key material. */
48
+ closeAll(): Promise<void>;
49
+ }
50
+ /**
51
+ * Create managed JWT sessions using keeper endpoints and a randomly selected verifier discovered from the chain. The verifier authenticates the holder and issues the session token. Session key operations may reconstruct private key material in the client; use threshold committee operations when that custody model is unsuitable.
52
+ * @param cfg Chain reader, holder identity and optional endpoint routing or discovery callback.
53
+ * @returns Client that opens and tracks managed slot sessions.
54
+ */
55
+ export declare function createTasraSlotClient(cfg: TasraSlotClientConfig): TasraSlotClient;