@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,132 @@
1
+ import { sha256 } from '@noble/hashes/sha256';
2
+ import { bytesToHex } from '@noble/hashes/utils';
3
+ import { createPublicClient, getCreate2Address, http, keccak256 } from 'viem';
4
+ import { NETWORKS } from './networks.js';
5
+ const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
6
+ const HASH = /^0x[0-9a-fA-F]{64}$/;
7
+ const DECIMAL = /^(0|[1-9][0-9]*)$/;
8
+ function object(value) {
9
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
10
+ }
11
+ function requireValue(condition, message) {
12
+ if (!condition)
13
+ throw new Error(`Invalid network manifest: ${message}`);
14
+ }
15
+ function address(value) {
16
+ return typeof value === 'string' && ADDRESS.test(value) && !/^0x0{40}$/.test(value);
17
+ }
18
+ function hash(value) { return typeof value === 'string' && HASH.test(value); }
19
+ function decimal(value) { return typeof value === 'string' && DECIMAL.test(value); }
20
+ /**
21
+ * Validate data only. Authenticity requires a trusted digest or signature separately.
22
+ * @param value Untrusted parsed JSON to validate against the supported manifest schema.
23
+ */
24
+ export function parseNetworkManifest(value) {
25
+ requireValue(object(value) && value.schemaVersion === 1, 'unsupported schema');
26
+ requireValue(typeof value.network === 'string' && Object.hasOwn(NETWORKS, value.network), 'unknown network');
27
+ requireValue(value.chainId === NETWORKS[value.network].chainId, 'chain/network mismatch');
28
+ requireValue(typeof value.deploymentId === 'string' && /^[a-z0-9][a-z0-9.-]{0,95}$/.test(value.deploymentId), 'deployment ID');
29
+ requireValue(Number.isSafeInteger(value.revision) && Number(value.revision) > 0, 'revision');
30
+ requireValue(['planned', 'active', 'retired'].includes(String(value.status)), 'status');
31
+ requireValue(typeof value.protocolVersion === 'string' && /^\d+\.\d+\.\d+$/.test(value.protocolVersion), 'protocol version');
32
+ requireValue(value.verifiedAt === null || (object(value.verifiedAt) && decimal(value.verifiedAt.blockNumber) &&
33
+ hash(value.verifiedAt.blockHash) && typeof value.verifiedAt.timestamp === 'string' &&
34
+ Number.isFinite(Date.parse(value.verifiedAt.timestamp))), 'verification block');
35
+ requireValue(Array.isArray(value.contracts) && value.contracts.length <= 256, 'contracts');
36
+ const names = new Set();
37
+ for (const c of value.contracts) {
38
+ requireValue(object(c) && typeof c.name === 'string' && /^[A-Za-z][A-Za-z0-9_]*$/.test(c.name), 'contract name');
39
+ requireValue(!names.has(c.name), 'duplicate contract name');
40
+ names.add(c.name);
41
+ requireValue(address(c.address), `address for ${c.name}`);
42
+ requireValue(typeof c.abi === 'string' && /^contracts\/abi\/[a-zA-Z0-9/_.-]+\.json$/.test(c.abi) && !c.abi.includes('..'), 'ABI path');
43
+ requireValue(c.runtimeCodeHash === null || hash(c.runtimeCodeHash), 'runtime hash');
44
+ requireValue(c.deployment === null || (object(c.deployment) && hash(c.deployment.transactionHash) && decimal(c.deployment.blockNumber)), 'deployment receipt');
45
+ requireValue(c.create2 === null || (object(c.create2) && address(c.create2.factory) && hash(c.create2.salt) && hash(c.create2.initCodeHash)), 'CREATE2 inputs');
46
+ if (object(c.create2)) {
47
+ const predicted = getCreate2Address({ from: c.create2.factory, salt: c.create2.salt, bytecodeHash: c.create2.initCodeHash });
48
+ requireValue(predicted.toLowerCase() === c.address.toLowerCase(), `CREATE2 address for ${c.name}`);
49
+ }
50
+ requireValue(c.proxy === null || (object(c.proxy) && address(c.proxy.implementation) && hash(c.proxy.runtimeCodeHash) &&
51
+ (c.proxy.upgradeAuthority === null || address(c.proxy.upgradeAuthority))), 'proxy');
52
+ if (value.status === 'active')
53
+ requireValue(c.runtimeCodeHash && c.deployment, 'active contract needs code and receipt evidence');
54
+ }
55
+ if (value.status === 'active')
56
+ requireValue(value.verifiedAt && names.has('NodeRegistry') && names.has('KeyRegistry'), 'active network needs verified registries');
57
+ requireValue(Array.isArray(value.services) && value.services.length <= 256, 'services');
58
+ for (const service of value.services) {
59
+ requireValue(object(service) && typeof service.kind === 'string' && typeof service.url === 'string', 'service');
60
+ const url = new URL(service.url);
61
+ requireValue(!url.username && !url.password && !url.hash && (url.protocol === 'https:' || (value.network === 'local' && url.protocol === 'http:')), 'public service URL');
62
+ }
63
+ return value;
64
+ }
65
+ /**
66
+ * The digest must come from a verified release checksum file or application pin.
67
+ * @param text Exact UTF-8 manifest text downloaded from tasra-releases.
68
+ * @param expectedSha256 Independently trusted lowercase SHA-256 digest of that text.
69
+ */
70
+ export function parsePinnedNetworkManifest(text, expectedSha256) {
71
+ if (!/^[a-f0-9]{64}$/.test(expectedSha256) || bytesToHex(sha256(new TextEncoder().encode(text))) !== expectedSha256) {
72
+ throw new Error('Network manifest SHA-256 mismatch');
73
+ }
74
+ return parseNetworkManifest(JSON.parse(text));
75
+ }
76
+ /**
77
+ * Planned and retired records can be displayed, but cannot configure a live client.
78
+ * @param manifest Network manifest whose lifecycle status must be active.
79
+ */
80
+ export function addressBookFromManifest(manifest) {
81
+ const checked = parseNetworkManifest(manifest);
82
+ if (checked.status !== 'active')
83
+ throw new Error(`Deployment ${checked.deploymentId} is ${checked.status}`);
84
+ return Object.fromEntries(checked.contracts.map(c => [c.name, c.address]));
85
+ }
86
+ /**
87
+ * EIP-1967 storage slot containing a proxy implementation address.
88
+ */
89
+ export const IMPLEMENTATION_SLOT = '0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc';
90
+ /**
91
+ * Observe a single finalized block. This verifies code identity, not business wiring or audit quality.
92
+ * @param manifest Manifest containing expected deployment addresses and code hashes.
93
+ * @param rpcUrl RPC endpoint for the same chain as the manifest.
94
+ */
95
+ export async function observeNetworkManifest(manifest, rpcUrl) {
96
+ const checked = parseNetworkManifest(manifest);
97
+ const client = createPublicClient({ transport: http(rpcUrl, { timeout: 15_000, retryCount: 1 }) });
98
+ if (await client.getChainId() !== checked.chainId)
99
+ throw new Error('RPC chain does not match manifest');
100
+ const block = await client.getBlock({ blockTag: 'finalized' });
101
+ if (block.number === null || block.hash === null)
102
+ throw new Error('RPC returned an unfinalized block');
103
+ if (checked.verifiedAt) {
104
+ if (BigInt(checked.verifiedAt.blockNumber) > block.number)
105
+ throw new Error('Manifest verification is ahead of finalized chain');
106
+ const original = await client.getBlock({ blockNumber: BigInt(checked.verifiedAt.blockNumber) });
107
+ if (original.hash !== checked.verifiedAt.blockHash)
108
+ throw new Error('Manifest verification block is not canonical');
109
+ }
110
+ const contracts = [];
111
+ for (const c of checked.contracts) {
112
+ const code = await client.getBytecode({ address: c.address, blockNumber: block.number });
113
+ const observedCodeHash = code && code !== '0x' ? keccak256(code) : null;
114
+ let implementation = null;
115
+ let implementationCodeHash = null;
116
+ if (c.proxy) {
117
+ const word = await client.getStorageAt({ address: c.address, slot: IMPLEMENTATION_SLOT, blockNumber: block.number });
118
+ if (word && !/^0x0+$/.test(word)) {
119
+ implementation = `0x${word.slice(-40)}`;
120
+ const implCode = await client.getBytecode({ address: implementation, blockNumber: block.number });
121
+ implementationCodeHash = implCode && implCode !== '0x' ? keccak256(implCode) : null;
122
+ }
123
+ }
124
+ contracts.push({ name: c.name, address: c.address, expectedCodeHash: c.runtimeCodeHash, observedCodeHash,
125
+ implementation, implementationCodeHash,
126
+ matches: observedCodeHash !== null && observedCodeHash === c.runtimeCodeHash && (!c.proxy ||
127
+ (implementation?.toLowerCase() === c.proxy.implementation.toLowerCase() && implementationCodeHash === c.proxy.runtimeCodeHash)) });
128
+ }
129
+ return { chainId: checked.chainId, blockNumber: block.number.toString(), blockHash: block.hash,
130
+ observedAt: new Date().toISOString(), contracts,
131
+ matches: checked.status === 'active' && contracts.length > 0 && contracts.every(c => c.matches) };
132
+ }
@@ -0,0 +1,75 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "profiles": {
4
+ "local": {
5
+ "chainId": 43112,
6
+ "rpcUrl": "http://127.0.0.1:9650/ext/bc/C/rpc",
7
+ "nativeCurrency": {
8
+ "name": "Avalanche",
9
+ "symbol": "AVAX",
10
+ "decimals": 18
11
+ },
12
+ "eurc": {
13
+ "kind": "mock",
14
+ "address": null,
15
+ "name": "Tasra Mock Euro (test only)",
16
+ "symbol": "KKEUR",
17
+ "decimals": 6,
18
+ "faucet": true
19
+ },
20
+ "governance": {
21
+ "delaySecs": 120,
22
+ "floorSecs": 120
23
+ },
24
+ "productionPosture": true
25
+ },
26
+ "testnet": {
27
+ "chainId": 43113,
28
+ "rpcUrl": "https://api.avax-test.network/ext/bc/C/rpc",
29
+ "nativeCurrency": {
30
+ "name": "Avalanche",
31
+ "symbol": "AVAX",
32
+ "decimals": 18
33
+ },
34
+ "eurc": {
35
+ "kind": "mock",
36
+ "address": null,
37
+ "name": "Tasra Mock Euro (test only)",
38
+ "symbol": "KKEUR",
39
+ "decimals": 6,
40
+ "faucet": true
41
+ },
42
+ "governance": {
43
+ "delaySecs": 120,
44
+ "floorSecs": 120
45
+ },
46
+ "productionPosture": true
47
+ },
48
+ "mainnet": {
49
+ "chainId": 43114,
50
+ "rpcUrl": "https://api.avax.network/ext/bc/C/rpc",
51
+ "nativeCurrency": {
52
+ "name": "Avalanche",
53
+ "symbol": "AVAX",
54
+ "decimals": 18
55
+ },
56
+ "eurc": {
57
+ "kind": "circle",
58
+ "address": "0xc891eb4cbdeff6e073e859e987815ed1505c2acd",
59
+ "name": "Euro Coin",
60
+ "symbol": "EURC",
61
+ "decimals": 6,
62
+ "faucet": false
63
+ },
64
+ "governance": {
65
+ "delaySecs": 172800,
66
+ "floorSecs": 172800
67
+ },
68
+ "productionPosture": true
69
+ }
70
+ },
71
+ "sources": {
72
+ "eurc": "https://developers.circle.com/stablecoins/eurc-contract-addresses",
73
+ "verifiedAt": "2026-09-13"
74
+ }
75
+ }
@@ -0,0 +1,73 @@
1
+ import type { Address } from './deployments.js';
2
+ /**
3
+ * Supported network profile identifier.
4
+ */
5
+ export type NetworkName = 'local' | 'testnet' | 'mainnet';
6
+ /**
7
+ * Default network currency, RPC, governance and token configuration.
8
+ */
9
+ export interface NetworkPreset {
10
+ /** Default EVM chain identifier for this network profile. */
11
+ readonly chainId: number;
12
+ /** Default JSON-RPC endpoint; deployed configuration may supply an explicit override. */
13
+ readonly rpcUrl: string;
14
+ /** Native gas-token name, symbol and decimal precision. */
15
+ readonly nativeCurrency: Readonly<{
16
+ name: string;
17
+ symbol: string;
18
+ decimals: number;
19
+ }>;
20
+ /** EURC token policy, metadata and faucet eligibility; address may require deployment resolution. */
21
+ readonly eurc: Readonly<{
22
+ kind: 'mock' | 'circle';
23
+ address: string | null;
24
+ name: string;
25
+ symbol: string;
26
+ decimals: number;
27
+ faucet: boolean;
28
+ }>;
29
+ /** Configured governance delay and minimum delay, both in seconds. */
30
+ readonly governance: Readonly<{
31
+ delaySecs: number;
32
+ floorSecs: number;
33
+ }>;
34
+ /** Deployment-policy flag carried by the profile; the SDK does not use it to establish network readiness. */
35
+ readonly productionPosture: boolean;
36
+ }
37
+ /**
38
+ * Validated network profile with a concrete EURC contract address.
39
+ */
40
+ export interface ResolvedNetworkProfile extends NetworkPreset {
41
+ /** Network profile selected when validating the chain and token address. */
42
+ readonly environment: NetworkName;
43
+ /** Validated EURC policy with a concrete nonzero token contract address. */
44
+ readonly eurc: NetworkPreset['eurc'] & {
45
+ readonly address: Address;
46
+ };
47
+ }
48
+ /**
49
+ * Built-in network defaults; use a tasra-releases manifest for deployed contract addresses.
50
+ */
51
+ export declare const NETWORKS: Readonly<Record<NetworkName, NetworkPreset>>;
52
+ /**
53
+ * Map a supported EVM chain ID to its network profile; reject unknown chains.
54
+ * @param chainId EVM chain ID to resolve to a supported profile.
55
+ */
56
+ export declare function networkNameForChain(chainId: number): NetworkName;
57
+ /**
58
+ * Validate network overrides and resolve the required EURC token address.
59
+ * @param environment Supported network profile identifier.
60
+ * @param options Explicit chain, RPC and EURC address overrides from approved configuration.
61
+ */
62
+ export declare function resolveNetworkProfile(environment: NetworkName, options?: {
63
+ chainId?: number;
64
+ rpcUrl?: string;
65
+ eurcAddress?: string;
66
+ }): ResolvedNetworkProfile;
67
+ /**
68
+ * Recheck the actual RPC chain immediately before any faucet transaction.
69
+ * @param profile Approved network profile and its mock-token faucet policy.
70
+ * @param actualChainId Chain ID read from the RPC immediately before the transaction.
71
+ * @param actualEurcAddress EURC contract address targeted by the mint transaction.
72
+ */
73
+ export declare function assertEurcFaucetAllowed(profile: ResolvedNetworkProfile, actualChainId: number, actualEurcAddress: string): void;
@@ -0,0 +1,62 @@
1
+ import document from './network-profiles.json' with { type: 'json' };
2
+ // Vendored deployment policy; refresh manually from the network configuration.
3
+ /**
4
+ * Built-in network defaults; use a tasra-releases manifest for deployed contract addresses.
5
+ */
6
+ export const NETWORKS = Object.freeze(Object.fromEntries(Object.entries(document.profiles).map(([name, p]) => [name, Object.freeze({
7
+ ...p, eurc: Object.freeze(p.eurc), nativeCurrency: Object.freeze(p.nativeCurrency), governance: Object.freeze(p.governance),
8
+ })])));
9
+ /**
10
+ * Map a supported EVM chain ID to its network profile; reject unknown chains.
11
+ * @param chainId EVM chain ID to resolve to a supported profile.
12
+ */
13
+ export function networkNameForChain(chainId) {
14
+ if ([43112, 1337, 31337].includes(chainId))
15
+ return 'local';
16
+ if (chainId === 43113)
17
+ return 'testnet';
18
+ if (chainId === 43114)
19
+ return 'mainnet';
20
+ throw new Error(`Unsupported network chain ID: ${chainId}`);
21
+ }
22
+ /**
23
+ * Validate network overrides and resolve the required EURC token address.
24
+ * @param environment Supported network profile identifier.
25
+ * @param options Explicit chain, RPC and EURC address overrides from approved configuration.
26
+ */
27
+ export function resolveNetworkProfile(environment, options = {}) {
28
+ if (!Object.hasOwn(NETWORKS, environment))
29
+ throw new Error(`Unknown network profile: ${environment}`);
30
+ const preset = NETWORKS[environment];
31
+ const chainId = options.chainId ?? preset.chainId;
32
+ if (networkNameForChain(chainId) !== environment)
33
+ throw new Error('Network profile does not match chain ID');
34
+ const rpcUrl = options.rpcUrl ?? preset.rpcUrl;
35
+ const rpc = new URL(rpcUrl);
36
+ if (!['http:', 'https:'].includes(rpc.protocol) || rpc.username || rpc.password || rpc.hash ||
37
+ (environment !== 'local' && rpc.protocol !== 'https:'))
38
+ throw new Error('Invalid RPC URL for network profile');
39
+ const address = (options.eurcAddress ?? preset.eurc.address)?.toLowerCase();
40
+ if (!address || !/^0x[0-9a-f]{40}$/.test(address) || /^0x0{40}$/.test(address)) {
41
+ throw new Error('Network profile requires the deployed EURC token address');
42
+ }
43
+ if (environment === 'mainnet' && address !== preset.eurc.address)
44
+ throw new Error('Mainnet requires official Circle EURC');
45
+ if (environment !== 'mainnet' && [NETWORKS.mainnet.eurc.address, '0x5e44db7996c682e92a960b65ac713a54ad815c6b'].includes(address)) {
46
+ throw new Error('Local and testnet require our own Mock EURC, not a Circle token');
47
+ }
48
+ return Object.freeze({ ...preset, environment, chainId, rpcUrl, eurc: Object.freeze({ ...preset.eurc, address: address }) });
49
+ }
50
+ /**
51
+ * Recheck the actual RPC chain immediately before any faucet transaction.
52
+ * @param profile Approved network profile and its mock-token faucet policy.
53
+ * @param actualChainId Chain ID read from the RPC immediately before the transaction.
54
+ * @param actualEurcAddress EURC contract address targeted by the mint transaction.
55
+ */
56
+ export function assertEurcFaucetAllowed(profile, actualChainId, actualEurcAddress) {
57
+ const validated = resolveNetworkProfile(profile.environment, { chainId: actualChainId, eurcAddress: actualEurcAddress });
58
+ if (!validated.eurc.faucet || !profile.eurc.faucet || profile.eurc.kind !== 'mock' ||
59
+ profile.chainId !== actualChainId || profile.eurc.address.toLowerCase() !== actualEurcAddress.toLowerCase()) {
60
+ throw new Error('EURC faucet is disabled for this network or token');
61
+ }
62
+ }
@@ -0,0 +1,44 @@
1
+ import type { RegisteredAgentSession } from './registeredAgent.js';
2
+ import type { AgentTransport } from './registeredAgent.js';
3
+ import type { RelayTransport } from './registeredRelay.js';
4
+ import { type ServiceDiscoveryTransport } from './serviceIdentity.js';
5
+ /**
6
+ * Conservative globally routable destinations; special-purpose exceptions require explicit policy.
7
+ * @param address IPv4 or IPv6 address resolved for the service destination.
8
+ */
9
+ export declare function isPublicServiceAddress(address: string): boolean;
10
+ /**
11
+ * Caller-approved destination and certificate policy for Node.js service transports.
12
+ */
13
+ export interface ServiceTransportPolicy {
14
+ /** Exact, canonical hostnames/IPs only. Application configuration, never downloaded metadata. */
15
+ allowedPrivateHosts?: readonly string[];
16
+ /** Additional deployment CA roots. Certificate and hostname verification remain mandatory. */
17
+ ca?: string | Buffer | (string | Buffer)[];
18
+ }
19
+ /**
20
+ * Create a bounded HTTPS transport that validates destinations at socket connection time.
21
+ * @param policy Explicit private-host exceptions and additional trusted certificate roots.
22
+ */
23
+ export declare function createNodeServiceDiscoveryTransport(policy?: ServiceTransportPolicy): ServiceDiscoveryTransport;
24
+ /**
25
+ * Public readiness and relay-policy observations, with the same socket/TLS policy.
26
+ * @param policy Explicit private-host exceptions and additional trusted certificate roots.
27
+ */
28
+ export declare function createNodeServiceStatusTransport(policy?: ServiceTransportPolicy): ServiceDiscoveryTransport;
29
+ /**
30
+ * Discovery and relay traffic use the same socket-bound destination and TLS policy.
31
+ * @param policy Explicit private-host exceptions and additional trusted certificate roots.
32
+ */
33
+ export declare function createNodeRelayTransport(policy?: ServiceTransportPolicy): RelayTransport;
34
+ /**
35
+ * Session secrets use this same guarded connection and can only travel to a session GET.
36
+ * @param policy Explicit private-host exceptions and additional trusted certificate roots.
37
+ */
38
+ export declare function createNodeAgentTransport(policy?: ServiceTransportPolicy): AgentTransport;
39
+ /**
40
+ * Wallet protocol requests restricted to the selected session and approved DID, with socket checks.
41
+ * @param session Authenticated session whose request, response and DID URLs are allowed.
42
+ * @param policy Explicit private-host exceptions and additional trusted certificate roots.
43
+ */
44
+ export declare function createNodeAgentWalletFetch(session: Pick<RegisteredAgentSession, 'profile' | 'requestUri' | 'sessionId'>, policy?: ServiceTransportPolicy): typeof fetch;
@@ -0,0 +1,176 @@
1
+ /** Node-only service discovery transport; never imported by the browser-safe chain barrel. */
2
+ import { didWebUrl } from '../oid4vp/did-web.js';
3
+ import { lookup } from 'node:dns';
4
+ import { request } from 'node:https';
5
+ import { rootCertificates } from 'node:tls';
6
+ import { BlockList, isIP } from 'node:net';
7
+ import { SERVICE_MANIFEST_PATH, SERVICE_IDENTITY_PATH, validateServiceEndpoint } from './serviceIdentity.js';
8
+ const denied = new BlockList();
9
+ for (const [address, prefix] of [
10
+ ['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8],
11
+ ['169.254.0.0', 16], ['172.16.0.0', 12], ['192.0.0.0', 24], ['192.0.2.0', 24],
12
+ ['192.88.99.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15], ['198.51.100.0', 24],
13
+ ['203.0.113.0', 24], ['224.0.0.0', 3],
14
+ ])
15
+ denied.addSubnet(address, prefix, 'ipv4');
16
+ for (const [address, prefix] of [['2001::', 23], ['2001:db8::', 32], ['2002::', 16], ['3fff::', 20]])
17
+ denied.addSubnet(address, prefix, 'ipv6');
18
+ const globalV6 = new BlockList();
19
+ globalV6.addSubnet('2000::', 3, 'ipv6');
20
+ /**
21
+ * Conservative globally routable destinations; special-purpose exceptions require explicit policy.
22
+ * @param address IPv4 or IPv6 address resolved for the service destination.
23
+ */
24
+ export function isPublicServiceAddress(address) {
25
+ const family = isIP(address);
26
+ return family === 4 ? !denied.check(address, 'ipv4')
27
+ : family === 6 && globalV6.check(address, 'ipv6') && !denied.check(address, 'ipv6');
28
+ }
29
+ /**
30
+ * Create a bounded HTTPS transport that validates destinations at socket connection time.
31
+ * @param policy Explicit private-host exceptions and additional trusted certificate roots.
32
+ */
33
+ export function createNodeServiceDiscoveryTransport(policy = {}) {
34
+ return guardedTransport(policy, 'discovery');
35
+ }
36
+ /**
37
+ * Public readiness and relay-policy observations, with the same socket/TLS policy.
38
+ * @param policy Explicit private-host exceptions and additional trusted certificate roots.
39
+ */
40
+ export function createNodeServiceStatusTransport(policy = {}) {
41
+ return guardedTransport(policy, 'status');
42
+ }
43
+ /**
44
+ * Discovery and relay traffic use the same socket-bound destination and TLS policy.
45
+ * @param policy Explicit private-host exceptions and additional trusted certificate roots.
46
+ */
47
+ export function createNodeRelayTransport(policy = {}) {
48
+ const discovery = guardedTransport(policy, 'discovery');
49
+ const relay = guardedTransport(policy, 'relay');
50
+ return { ...discovery, relayRequest: relay.request };
51
+ }
52
+ /**
53
+ * Session secrets use this same guarded connection and can only travel to a session GET.
54
+ * @param policy Explicit private-host exceptions and additional trusted certificate roots.
55
+ */
56
+ export function createNodeAgentTransport(policy = {}) {
57
+ const discovery = guardedTransport(policy, 'discovery');
58
+ const agent = guardedTransport(policy, 'agent');
59
+ return { ...discovery, agentRequest: agent.request };
60
+ }
61
+ /**
62
+ * Wallet protocol requests restricted to the selected session and approved DID, with socket checks.
63
+ * @param session Authenticated session whose request, response and DID URLs are allowed.
64
+ * @param policy Explicit private-host exceptions and additional trusted certificate roots.
65
+ */
66
+ export function createNodeAgentWalletFetch(session, policy = {}) {
67
+ const did = session.profile.clientId.replace(/^decentralized_identifier:/, '');
68
+ if (!/^[0-9a-f]{64}$/.test(session.sessionId))
69
+ throw new Error('Invalid wallet session ID');
70
+ const didUrl = didWebUrl(did), responseUrl = session.profile.endpoint + '/v1/response?session=' + session.sessionId;
71
+ const requestUri = session.requestUri;
72
+ const transport = guardedTransport(policy, 'wallet');
73
+ return async (input, init) => {
74
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
75
+ const method = init?.method ?? 'GET';
76
+ const post = method === 'POST' && url === responseUrl;
77
+ if (!(method === 'GET' && (url === requestUri || url === didUrl)) && !post)
78
+ throw new Error('Wallet request is outside the approved session');
79
+ if (post && typeof init?.body !== 'string' || !post && init?.body != null)
80
+ throw new Error('Invalid wallet request body');
81
+ const signal = init?.signal ?? AbortSignal.timeout(30_000);
82
+ const bytes = await transport.request(url, { body: post ? new TextEncoder().encode(init.body) : undefined, maxBytes: post ? 16_384 : 65_536, signal });
83
+ return new Response(new TextDecoder('utf-8', { fatal: true }).decode(bytes), { status: 200, headers: { 'content-type': url === requestUri ? 'application/oauth-authz-req+jwt' : 'application/json' } });
84
+ };
85
+ }
86
+ function guardedTransport(policy, mode) {
87
+ const relay = mode === 'relay', agent = mode === 'agent', wallet = mode === 'wallet', status = mode === 'status';
88
+ const allowed = new Set(policy.allowedPrivateHosts ?? []);
89
+ // Snapshot mutable caller configuration before the first asynchronous request.
90
+ const ca = Array.isArray(policy.ca) ? policy.ca.map(c => typeof c === 'string' ? c : Buffer.from(c))
91
+ : typeof policy.ca === 'string' || policy.ca === undefined ? policy.ca : Buffer.from(policy.ca);
92
+ return {
93
+ request(url, { body, maxBytes, signal, bearer }) {
94
+ signal.throwIfAborted();
95
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > (agent || wallet ? 1_048_576 : relay ? 4_096 : 16_384) || body && body.length > (wallet ? 1_048_576 : agent || relay ? 65_536 : 2_048))
96
+ throw new Error('Invalid service HTTP bounds');
97
+ // The registry's 512-byte limit applies to the base, excluding appended protocol paths.
98
+ const relaySuffix = url.match(/\/v1\/relay\/(forward|0x[0-9a-f]{64})$/)?.[0];
99
+ if (relay && (!relaySuffix || Boolean(body) !== relaySuffix.endsWith('/forward')))
100
+ throw new Error('Invalid relay path or method');
101
+ const agentSuffix = url.match(/\/v1\/sessions(?:\/[0-9a-f]{64})?$/)?.[0];
102
+ if (agent && (!agentSuffix || (body ? agentSuffix !== '/v1/sessions' || bearer !== undefined : agentSuffix === '/v1/sessions' || !/^[0-9a-f]{64}$/.test(bearer ?? ''))))
103
+ throw new Error('Invalid agent path, method or poll secret');
104
+ if (!agent && bearer !== undefined)
105
+ throw new Error('Bearer is only allowed for agent polling');
106
+ const walletSuffix = url.match(/(?:\/\.well-known\/did\.json|\/v1\/request\/[0-9a-f]{64}|\/v1\/response\?session=[0-9a-f]{64})$/)?.[0];
107
+ if (wallet && (!walletSuffix || Boolean(body) !== walletSuffix.startsWith('/v1/response?session=')))
108
+ throw new Error('Invalid wallet path or method');
109
+ const statusSuffix = url.match(/(?:\/readyz|\/v1\/relay\/policy)$/)?.[0];
110
+ if (status && (!statusSuffix || body !== undefined))
111
+ throw new Error('Invalid service status path or method');
112
+ const contentType = status && statusSuffix === '/readyz' ? 'text/plain' : wallet && !body && !url.endsWith('/did.json') ? 'application/oauth-authz-req+jwt' : 'application/json';
113
+ const responseTypes = wallet && walletSuffix === '/.well-known/did.json'
114
+ ? ['application/json', 'application/did+json', 'application/did+ld+json'] : [contentType];
115
+ const suffix = status ? statusSuffix : wallet ? walletSuffix : agent ? agentSuffix : relay ? relaySuffix : [SERVICE_MANIFEST_PATH, SERVICE_IDENTITY_PATH].find(path => url.endsWith(path));
116
+ validateServiceEndpoint(suffix ? url.slice(0, -suffix.length) : url);
117
+ const parsed = new URL(url);
118
+ const host = parsed.hostname.replace(/^\[|\]$/g, '');
119
+ const permits = (address) => allowed.has(host) || isPublicServiceAddress(address);
120
+ if (isIP(host) && !permits(host))
121
+ throw new Error('Service destination policy refuses address');
122
+ const checkedLookup = (hostname, options, callback) => {
123
+ lookup(hostname, { all: true, verbatim: true }, (error, addresses) => {
124
+ if (error) {
125
+ callback(error, '', 4);
126
+ return;
127
+ }
128
+ if (!addresses.length || addresses.some(a => !permits(a.address))) {
129
+ callback(new Error('Service destination policy refuses DNS answer'), '', 4);
130
+ return;
131
+ }
132
+ // These exact checked addresses are handed to the socket. No second DNS lookup.
133
+ if (options.all)
134
+ callback(null, addresses);
135
+ else
136
+ callback(null, addresses[0].address, addresses[0].family);
137
+ });
138
+ };
139
+ return new Promise((resolve, reject) => {
140
+ const req = request(parsed, {
141
+ method: body ? 'POST' : 'GET', agent: false, lookup: checkedLookup,
142
+ ca: ca === undefined ? undefined : [...rootCertificates, ...(Array.isArray(ca) ? ca : [ca])], rejectUnauthorized: true, signal, maxHeaderSize: 8_192,
143
+ headers: { ...(bearer ? { authorization: `Bearer ${bearer}` } : {}), accept: responseTypes.join(', '), 'accept-encoding': 'identity', ...(body ? { 'content-type': wallet ? 'application/x-www-form-urlencoded' : 'application/json', 'content-length': body.length } : {}) },
144
+ }, res => {
145
+ const fail = (error) => { reject(error); req.destroy(error); };
146
+ if (!(agent ? res.statusCode === (body ? 201 : 200) : relay ? [200, 202, 422].includes(res.statusCode ?? 0) : res.statusCode === 200) || !responseTypes.includes(res.headers['content-type']?.split(';')[0]?.trim().toLowerCase() ?? '') || res.headers['content-encoding'] && res.headers['content-encoding'] !== 'identity') {
147
+ fail(new Error('Service HTTP status, content type or encoding refused'));
148
+ return;
149
+ }
150
+ const advertised = res.headers['content-length'];
151
+ if (advertised && (!/^\d+$/.test(advertised) || Number(advertised) > maxBytes)) {
152
+ fail(new Error('Service response too large'));
153
+ return;
154
+ }
155
+ const chunks = [];
156
+ let size = 0;
157
+ res.on('data', (chunk) => {
158
+ if (size + chunk.length > maxBytes) {
159
+ fail(new Error('Service response too large'));
160
+ return;
161
+ }
162
+ size += chunk.length;
163
+ chunks.push(chunk);
164
+ });
165
+ res.on('error', reject);
166
+ res.on('end', () => resolve(Buffer.concat(chunks, size)));
167
+ });
168
+ // Absolute request deadline also bounds DNS/TLS and slow trickle responses.
169
+ const timer = setTimeout(() => req.destroy(new Error('Service HTTP timed out')), agent || wallet ? 30_000 : 5_000);
170
+ req.on('close', () => clearTimeout(timer));
171
+ req.on('error', reject);
172
+ req.end(body);
173
+ });
174
+ },
175
+ };
176
+ }