@odatano/core 2.0.0-rc.5 → 2.0.0-rc.50

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 (208) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +347 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
  6. package/@cds-models/CardanoIndexerService/index.js +64 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +414 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +32 -19
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
  14. package/@cds-models/index.d.ts +101 -1
  15. package/@cds-models/index.js +16 -1
  16. package/@cds-models/odatano/cardano/index.d.ts +437 -32
  17. package/@cds-models/odatano/cardano/index.js +48 -0
  18. package/README.md +207 -167
  19. package/db/schema.cds +2402 -1705
  20. package/db/types.cds +446 -295
  21. package/package.json +41 -16
  22. package/scripts/migrate-schema.mjs +334 -0
  23. package/scripts/migrate-slot-leader.mjs +96 -0
  24. package/src/index.d.ts +20 -21
  25. package/src/index.js +45 -31
  26. package/src/plugin.js +17 -35
  27. package/srv/blockchain/asset-decimals.d.ts +7 -0
  28. package/srv/blockchain/asset-decimals.js +91 -0
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
  30. package/srv/blockchain/backends/blockfrost-backend.js +66 -172
  31. package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
  32. package/srv/blockchain/backends/cardano-backend.js +29 -5
  33. package/srv/blockchain/backends/koios-backend.d.ts +103 -168
  34. package/srv/blockchain/backends/koios-backend.js +428 -360
  35. package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
  36. package/srv/blockchain/backends/odatano-backend.js +169 -0
  37. package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
  38. package/srv/blockchain/backends/ogmios-backend.js +637 -315
  39. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  40. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  41. package/srv/blockchain/cardano-client.d.ts +61 -241
  42. package/srv/blockchain/cardano-client.js +253 -293
  43. package/srv/blockchain/cardano-indexer.d.ts +282 -281
  44. package/srv/blockchain/cardano-indexer.js +1551 -484
  45. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  46. package/srv/blockchain/cardano-tx-builder.js +164 -140
  47. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  48. package/srv/blockchain/circuit-breaker.js +5 -15
  49. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  50. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  51. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  52. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  53. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
  54. package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
  55. package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
  56. package/srv/blockchain/crawler/certificate-backfill.js +162 -0
  57. package/srv/blockchain/crawler/crawler.d.ts +104 -81
  58. package/srv/blockchain/crawler/crawler.js +532 -160
  59. package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
  60. package/srv/blockchain/crawler/credential-backfill.js +124 -0
  61. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  62. package/srv/blockchain/crawler/index.d.ts +1 -8
  63. package/srv/blockchain/crawler/index.js +31 -17
  64. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  65. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  66. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  67. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  68. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  69. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  70. package/srv/blockchain/crawler/sync-state.d.ts +27 -47
  71. package/srv/blockchain/crawler/sync-state.js +113 -63
  72. package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
  73. package/srv/blockchain/crawler/transaction-backfill.js +278 -0
  74. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  75. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  76. package/srv/blockchain/ledger-state.d.ts +62 -0
  77. package/srv/blockchain/ledger-state.js +419 -0
  78. package/srv/blockchain/pending-spends.d.ts +16 -0
  79. package/srv/blockchain/pending-spends.js +81 -0
  80. package/srv/blockchain/pool-metadata.d.ts +15 -0
  81. package/srv/blockchain/pool-metadata.js +132 -0
  82. package/srv/blockchain/request-coalescer.d.ts +2 -16
  83. package/srv/blockchain/request-coalescer.js +2 -16
  84. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  85. package/srv/blockchain/signing/cose-verifier.js +146 -70
  86. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  87. package/srv/blockchain/signing/external-signer.js +17 -126
  88. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  89. package/srv/blockchain/signing/hsm-signer.js +28 -79
  90. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  91. package/srv/blockchain/signing/signature-verifier.js +70 -83
  92. package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
  93. package/srv/blockchain/signing/submission-finalizer.js +219 -86
  94. package/srv/blockchain/stored-chain.d.ts +20 -0
  95. package/srv/blockchain/stored-chain.js +237 -0
  96. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  97. package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
  98. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  99. package/srv/blockchain/transaction-presence.d.ts +5 -0
  100. package/srv/blockchain/transaction-presence.js +29 -0
  101. package/srv/blockchain/transaction-rows.d.ts +12 -0
  102. package/srv/blockchain/transaction-rows.js +44 -0
  103. package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
  104. package/srv/blockchain/wallet-worker/build-request.js +47 -30
  105. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
  106. package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
  107. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  108. package/srv/blockchain/wallet-worker/index.js +3 -11
  109. package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
  110. package/srv/blockchain/wallet-worker/job-store.js +101 -201
  111. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  112. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  113. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  114. package/srv/blockchain/wallet-worker/signers.js +4 -12
  115. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
  116. package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
  117. package/srv/cardano-agent-service.cds +122 -84
  118. package/srv/cardano-agent-service.js +4 -9
  119. package/srv/cardano-backend-service.cds +78 -0
  120. package/srv/cardano-backend-service.d.ts +2 -0
  121. package/srv/cardano-backend-service.js +242 -0
  122. package/srv/cardano-indexer-service.cds +387 -73
  123. package/srv/cardano-indexer-service.d.ts +5 -1
  124. package/srv/cardano-indexer-service.js +532 -16
  125. package/srv/cardano-service.cds +424 -269
  126. package/srv/cardano-service.js +289 -201
  127. package/srv/cardano-sign-service.cds +201 -180
  128. package/srv/cardano-sign-service.js +71 -201
  129. package/srv/cardano-tx-service.cds +451 -370
  130. package/srv/cardano-tx-service.js +271 -289
  131. package/srv/cardano-ui.cds +16 -16
  132. package/srv/cardano-worker-service.cds +118 -125
  133. package/srv/cardano-worker-service.js +52 -61
  134. package/srv/cbor/cip68.d.ts +13 -0
  135. package/srv/cbor/cip68.js +56 -0
  136. package/srv/cbor/index.d.ts +3 -1
  137. package/srv/cbor/index.js +9 -1
  138. package/srv/cbor/parse.d.ts +30 -18
  139. package/srv/cbor/parse.js +44 -9
  140. package/srv/cbor/plutus-data-json.d.ts +20 -0
  141. package/srv/cbor/plutus-data-json.js +32 -0
  142. package/srv/config.d.ts +113 -0
  143. package/srv/config.js +409 -0
  144. package/srv/server.d.ts +15 -110
  145. package/srv/server.js +84 -404
  146. package/srv/utils/agent-access.d.ts +9 -0
  147. package/srv/utils/agent-access.js +67 -0
  148. package/srv/utils/agent-grants-config.d.ts +0 -46
  149. package/srv/utils/agent-grants-config.js +17 -85
  150. package/srv/utils/agent-grants.d.ts +106 -122
  151. package/srv/utils/agent-grants.js +538 -236
  152. package/srv/utils/agent-token-auth.d.ts +4 -99
  153. package/srv/utils/agent-token-auth.js +18 -182
  154. package/srv/utils/backend-request-handler.d.ts +3 -17
  155. package/srv/utils/backend-request-handler.js +3 -18
  156. package/srv/utils/collections.d.ts +3 -10
  157. package/srv/utils/collections.js +3 -10
  158. package/srv/utils/const.d.ts +23 -74
  159. package/srv/utils/const.js +32 -79
  160. package/srv/utils/crypto.d.ts +3 -12
  161. package/srv/utils/crypto.js +6 -21
  162. package/srv/utils/db-indexes.d.ts +27 -0
  163. package/srv/utils/db-indexes.js +120 -0
  164. package/srv/utils/db-sanitize.d.ts +20 -0
  165. package/srv/utils/db-sanitize.js +80 -0
  166. package/srv/utils/deep-json.d.ts +6 -0
  167. package/srv/utils/deep-json.js +240 -0
  168. package/srv/utils/epoch-slots.d.ts +13 -0
  169. package/srv/utils/epoch-slots.js +38 -0
  170. package/srv/utils/error-codes.d.ts +22 -75
  171. package/srv/utils/error-codes.js +23 -72
  172. package/srv/utils/errors.d.ts +46 -187
  173. package/srv/utils/errors.js +114 -230
  174. package/srv/utils/liveness.d.ts +12 -0
  175. package/srv/utils/liveness.js +35 -0
  176. package/srv/utils/mappers.d.ts +102 -223
  177. package/srv/utils/mappers.js +387 -316
  178. package/srv/utils/network-context.js +2 -13
  179. package/srv/utils/paging.d.ts +31 -0
  180. package/srv/utils/paging.js +43 -0
  181. package/srv/utils/pg-inline-json.d.ts +8 -0
  182. package/srv/utils/pg-inline-json.js +58 -0
  183. package/srv/utils/pg-order-nulls.d.ts +14 -0
  184. package/srv/utils/pg-order-nulls.js +54 -0
  185. package/srv/utils/plutus-placeholders.d.ts +16 -22
  186. package/srv/utils/plutus-placeholders.js +62 -33
  187. package/srv/utils/rate-limiter.d.ts +2 -21
  188. package/srv/utils/rate-limiter.js +5 -17
  189. package/srv/utils/readiness.d.ts +12 -0
  190. package/srv/utils/readiness.js +29 -0
  191. package/srv/utils/reference-script.d.ts +19 -0
  192. package/srv/utils/reference-script.js +84 -0
  193. package/srv/utils/result-numbers.d.ts +15 -0
  194. package/srv/utils/result-numbers.js +61 -0
  195. package/srv/utils/service-events.d.ts +0 -24
  196. package/srv/utils/service-events.js +3 -25
  197. package/srv/utils/signing-helper.d.ts +3 -20
  198. package/srv/utils/signing-helper.js +35 -64
  199. package/srv/utils/tx-build-helper.d.ts +10 -105
  200. package/srv/utils/tx-build-helper.js +81 -144
  201. package/srv/utils/tx-request-parsers.d.ts +82 -33
  202. package/srv/utils/tx-request-parsers.js +401 -49
  203. package/srv/utils/tx-utils.d.ts +3 -27
  204. package/srv/utils/tx-utils.js +32 -50
  205. package/srv/utils/types.d.ts +261 -191
  206. package/srv/utils/types.js +2 -6
  207. package/srv/utils/validators.d.ts +22 -92
  208. package/srv/utils/validators.js +50 -149
@@ -11,9 +11,7 @@ const signature_verifier_1 = require("./signature-verifier");
11
11
  const errors_1 = require("../../utils/errors");
12
12
  const types_1 = require("../../utils/types");
13
13
  const logger = cds_1.default.log('ExternalSigner');
14
- /**
15
- * Default TTL for signing requests (30 minutes)
16
- */
14
+ /** Default TTL for signing requests (30 minutes). */
17
15
  const DEFAULT_SIGNING_TTL_MS = 30 * 60 * 1000;
18
16
  /** Network flag for cardano-cli (mainnet vs testnet-magic). */
19
17
  const CLI_NETWORK_FLAG = {
@@ -21,12 +19,7 @@ const CLI_NETWORK_FLAG = {
21
19
  preprod: '--testnet-magic 1',
22
20
  preview: '--testnet-magic 2',
23
21
  };
24
- /**
25
- * Build a copy-pasteable cardano-cli signing recipe for the unsigned tx.
26
- * Templated (the caller supplies their own signing key file); the network flag
27
- * and the unsigned CBOR are filled in. Previously this was always NULL despite
28
- * the schema exposing a `cardanoCliCommand` field.
29
- */
22
+ /** cardano-cli signing recipe for the unsigned tx. The caller supplies the key file. */
30
23
  function buildCardanoCliCommand(network, unsignedTxCbor) {
31
24
  const netFlag = CLI_NETWORK_FLAG[network] ?? '--testnet-magic <MAGIC>';
32
25
  return [
@@ -37,20 +30,7 @@ function buildCardanoCliCommand(network, unsignedTxCbor) {
37
30
  '# 3) Submit the cborHex from tx.signed via SubmitSignedTransaction / SubmitVerifiedTransaction',
38
31
  ].join('\n');
39
32
  }
40
- /**
41
- * ExternalSignerModule - Manages the external signing workflow
42
- *
43
- * This module orchestrates the complete flow:
44
- * 1. Create signing request from build result
45
- * 2. Export unsigned transaction for external signing
46
- * 3. Receive and verify signed transaction
47
- * 4. Prepare for submission
48
- *
49
- * Key security principles:
50
- * - NO private keys are ever handled by this service
51
- * - Signature verification ensures transaction integrity
52
- * - Complete audit trail of the signing workflow
53
- */
33
+ /** External signing workflow. No private keys are ever handled here. */
54
34
  class ExternalSignerModule {
55
35
  verifier;
56
36
  signingTtlMs;
@@ -58,20 +38,7 @@ class ExternalSignerModule {
58
38
  this.verifier = (0, signature_verifier_1.getSignatureVerifier)();
59
39
  this.signingTtlMs = options?.signingTtlMs ?? DEFAULT_SIGNING_TTL_MS;
60
40
  }
61
- /**
62
- * Create an unsigned transaction export payload for external signing
63
- *
64
- * This is the entry point for the external signing workflow.
65
- * Call this after building a transaction to get a standardized
66
- * payload that external signers can use.
67
- *
68
- * @param buildId - The build ID from TransactionBuilds
69
- * @param unsignedTxCbor - The unsigned transaction CBOR
70
- * @param txBodyHash - The transaction body hash
71
- * @param network - The Cardano network
72
- * @param options - Additional options
73
- * @returns Unsigned transaction export payload
74
- */
41
+ /** Create the unsigned-tx export payload that starts a signing request (workflow entry point). */
75
42
  createSigningRequest(buildId, unsignedTxCbor, txBodyHash, network, message, options) {
76
43
  const signingRequestId = cds_1.default.utils.uuid();
77
44
  const now = new Date();
@@ -97,9 +64,7 @@ class ExternalSignerModule {
97
64
  }, 'Created signing request');
98
65
  return payload;
99
66
  }
100
- /**
101
- * Generate signing instructions for different signer types
102
- */
67
+ /** Signing instructions for the different signer types (CIP-30 request + cardano-cli recipe). */
103
68
  generateSigningInstructions(unsignedTxCbor, network, message, signerTypeHint) {
104
69
  return {
105
70
  signerTypeHint,
@@ -112,20 +77,9 @@ class ExternalSignerModule {
112
77
  cardanoCliCommand: buildCardanoCliCommand(network, unsignedTxCbor),
113
78
  };
114
79
  }
115
- /**
116
- * Verify a signed transaction
117
- *
118
- * Call this after receiving a signed transaction from an external signer.
119
- * This verifies the signature integrity before submission.
120
- *
121
- * @param signedTxCbor - The signed transaction CBOR
122
- * @param expectedTxBodyHash - The expected transaction body hash (from the build)
123
- * @param options - Additional verification options
124
- * @returns Verification result
125
- */
80
+ /** Verify a signed tx against the build's body hash; enforces the signing TTL when `expiresAt` is given. */
126
81
  verifySignedTransaction(signedTxCbor, expectedTxBodyHash, options) {
127
82
  logger.debug({ expectedTxBodyHash }, 'Verifying signed transaction');
128
- // Enforce signing TTL if expiresAt is provided
129
83
  if (options?.expiresAt && this.isExpired(options.expiresAt)) {
130
84
  return {
131
85
  isValid: false,
@@ -156,14 +110,7 @@ class ExternalSignerModule {
156
110
  }
157
111
  return result;
158
112
  }
159
- /**
160
- * Verify signed transaction and throw on failure
161
- *
162
- * @param signedTxCbor - The signed transaction CBOR
163
- * @param expectedTxBodyHash - The expected transaction body hash
164
- * @param options - Additional verification options
165
- * @throws {TransactionValidationError} if verification fails
166
- */
113
+ /** Like verifySignedTransaction, but throws TransactionValidationError on failure. */
167
114
  verifyOrThrow(signedTxCbor, expectedTxBodyHash, options) {
168
115
  const result = this.verifySignedTransaction(signedTxCbor, expectedTxBodyHash, options);
169
116
  if (!result.isValid) {
@@ -171,15 +118,7 @@ class ExternalSignerModule {
171
118
  }
172
119
  return result;
173
120
  }
174
- /**
175
- * Create a complete signing workflow state
176
- *
177
- * This creates a trackable workflow state that can be stored
178
- * and updated throughout the signing process.
179
- *
180
- * @param signingRequest - The unsigned transaction export payload
181
- * @returns Initial workflow state
182
- */
121
+ /** Initial (pending) workflow state for a signing request. */
183
122
  createWorkflowState(signingRequest) {
184
123
  return {
185
124
  status: types_1.SigningStatus.PENDING,
@@ -189,13 +128,7 @@ class ExternalSignerModule {
189
128
  },
190
129
  };
191
130
  }
192
- /**
193
- * Update workflow state after signing
194
- *
195
- * @param state - Current workflow state
196
- * @param signedTxCbor - The signed transaction CBOR
197
- * @returns Updated workflow state
198
- */
131
+ /** Workflow state → signed. */
199
132
  markAsSigned(state, signedTxCbor) {
200
133
  return {
201
134
  ...state,
@@ -207,13 +140,7 @@ class ExternalSignerModule {
207
140
  },
208
141
  };
209
142
  }
210
- /**
211
- * Update workflow state after verification
212
- *
213
- * @param state - Current workflow state
214
- * @param verificationResult - The verification result
215
- * @returns Updated workflow state
216
- */
143
+ /** Workflow state → verified, or → failed when the verification result is invalid. */
217
144
  markAsVerified(state, verificationResult) {
218
145
  if (!verificationResult.isValid) {
219
146
  return this.markAsFailed(state, String(verificationResult.errorMessage));
@@ -228,13 +155,7 @@ class ExternalSignerModule {
228
155
  },
229
156
  };
230
157
  }
231
- /**
232
- * Update workflow state after submission
233
- *
234
- * @param state - Current workflow state
235
- * @param txHash - The submitted transaction hash
236
- * @returns Updated workflow state
237
- */
158
+ /** Workflow state → submitted. */
238
159
  markAsSubmitted(state, txHash) {
239
160
  return {
240
161
  ...state,
@@ -246,13 +167,7 @@ class ExternalSignerModule {
246
167
  },
247
168
  };
248
169
  }
249
- /**
250
- * Update workflow state on failure
251
- *
252
- * @param state - Current workflow state
253
- * @param errorMessage - The error message
254
- * @returns Updated workflow state
255
- */
170
+ /** Workflow state → failed. */
256
171
  markAsFailed(state, errorMessage) {
257
172
  return {
258
173
  ...state,
@@ -264,30 +179,12 @@ class ExternalSignerModule {
264
179
  },
265
180
  };
266
181
  }
267
- /**
268
- * Check if a signing request has expired
269
- *
270
- * @param expiresAt - The expiration timestamp (ISO 8601)
271
- * @returns true if expired
272
- */
182
+ /** True when the ISO-8601 `expiresAt` lies in the past. */
273
183
  isExpired(expiresAt) {
274
184
  return new Date(expiresAt) < new Date();
275
185
  }
276
- /**
277
- * Validate a signed transaction payload before submission
278
- *
279
- * This performs all pre-submission checks:
280
- * 1. Verify the signature
281
- * 2. Check transaction hasn't been tampered with
282
- * 3. Ensure the build ID matches
283
- *
284
- * @param payload - The signed transaction payload
285
- * @param originalBuildTxBodyHash - The original transaction body hash from the build
286
- * @returns Validation result with verification details
287
- * @throws {TransactionValidationError} if validation fails
288
- */
186
+ /** Pre-submission check: signature + body-hash integrity against the build; throws TransactionValidationError. */
289
187
  validateForSubmission(payload, originalBuildTxBodyHash) {
290
- // Verify the signature and transaction integrity
291
188
  const result = this.verifyOrThrow(payload.signedTxCbor, originalBuildTxBodyHash);
292
189
  logger.info({
293
190
  signingRequestId: payload.signingRequestId,
@@ -297,9 +194,7 @@ class ExternalSignerModule {
297
194
  }, 'Transaction validated for submission');
298
195
  return result;
299
196
  }
300
- /**
301
- * Get the signature verifier instance
302
- */
197
+ /** The underlying signature verifier. */
303
198
  getVerifier() {
304
199
  return this.verifier;
305
200
  }
@@ -307,18 +202,14 @@ class ExternalSignerModule {
307
202
  exports.ExternalSignerModule = ExternalSignerModule;
308
203
  // Singleton instance
309
204
  let moduleInstance = null;
310
- /**
311
- * Get the singleton ExternalSignerModule instance
312
- */
205
+ /** Singleton ExternalSignerModule. */
313
206
  function getExternalSignerModule() {
314
207
  if (!moduleInstance) {
315
208
  moduleInstance = new ExternalSignerModule();
316
209
  }
317
210
  return moduleInstance;
318
211
  }
319
- /**
320
- * Create a new ExternalSignerModule instance with custom options
321
- */
212
+ /** New ExternalSignerModule with custom options (not the singleton). */
322
213
  function createExternalSignerModule(options) {
323
214
  return new ExternalSignerModule(options);
324
215
  }
@@ -1,19 +1,5 @@
1
1
  import { HsmConfig, HsmSignResult } from '../../utils/types';
2
- /**
3
- * HsmSigner - PKCS#11 Hardware Security Module integration for Cardano transaction signing
4
- *
5
- * Wraps a PKCS#11 compliant HSM (YubiHSM 2, AWS CloudHSM, Thales Luna, etc.)
6
- * to provide Ed25519 signing for Cardano transactions. Private keys never leave
7
- * the HSM chip — only signatures are returned.
8
- *
9
- * Lifecycle:
10
- * 1. constructor(config) — stores config
11
- * 2. init(network) — connects to HSM, locates key, exports public key, derives Cardano address
12
- * 3. sign() / signTransaction() — signing operations
13
- * 4. shutdown() — closes session
14
- */
15
- /** Minimal PKCS#11 module surface used here. Loaded dynamically; no static type
16
- * package is depended on. We narrow to the actual handful of methods invoked. */
2
+ /** Minimal PKCS#11 surface used here; pkcs11js is loaded dynamically, no static type package. */
17
3
  interface PKCS11Instance {
18
4
  load(path: string): void;
19
5
  C_Initialize(): void;
@@ -43,6 +29,7 @@ type Pkcs11JsModule = {
43
29
  type Pkcs11Loader = () => Pkcs11JsModule;
44
30
  /** Test seam: inject a fake pkcs11js module loader (null restores the default). */
45
31
  export declare function setPkcs11Loader(loader: Pkcs11Loader | null): void;
32
+ /** Ed25519 signing through a PKCS#11 HSM. Private keys never leave the device. */
46
33
  export declare class HsmSigner {
47
34
  private pkcs11;
48
35
  private session;
@@ -53,32 +40,11 @@ export declare class HsmSigner {
53
40
  private config;
54
41
  private connected;
55
42
  constructor(config: HsmConfig);
56
- /**
57
- * Initialize PKCS#11 session and locate the signing key.
58
- * Called once during plugin startup.
59
- *
60
- * @param network - Cardano network (mainnet, preview, preprod) for address derivation
61
- */
43
+ /** Opens the session, exports the public key and derives the enterprise address. */
62
44
  init(network: 'mainnet' | 'preview' | 'preprod' | string): Promise<void>;
63
- /**
64
- * Sign a 32-byte transaction body hash using the HSM.
65
- * Returns the Ed25519 signature + public key for witness construction.
66
- *
67
- * @param txBodyHash - 32-byte hash of the transaction body
68
- * @returns HsmSignResult with signature, public key, and key hash
69
- */
45
+ /** Sign a 32-byte tx body hash in the HSM; returns Ed25519 signature + public key for the witness. */
70
46
  sign(txBodyHash: Buffer): HsmSignResult;
71
- /**
72
- * Sign a transaction and produce a complete signed transaction CBOR.
73
- *
74
- * Takes the unsigned transaction CBOR, signs the body hash via HSM,
75
- * builds a VKey witness [publicKey, signature], and merges it into
76
- * the transaction's witness set using raw CBOR manipulation.
77
- *
78
- * @param unsignedTxCbor - Unsigned transaction CBOR (hex)
79
- * @param txBodyHash - Transaction body hash (hex, 64 chars)
80
- * @returns Signed transaction CBOR (hex)
81
- */
47
+ /** Signs the body hash and splices the VKey witness in at the raw CBOR level. */
82
48
  signTransaction(unsignedTxCbor: string, txBodyHash: string): string;
83
49
  /** Get the HSM-derived Cardano enterprise address */
84
50
  getAddress(): string;
@@ -94,26 +60,16 @@ export declare class HsmSigner {
94
60
  publicKeyHash?: string;
95
61
  address?: string;
96
62
  };
97
- /** Graceful shutdown — close PKCS#11 session */
63
+ /** Closes the PKCS#11 session. */
98
64
  shutdown(): void;
99
- /**
100
- * Find a key object (private or public) in the HSM by label and/or ID
101
- */
65
+ /** Finds an Ed25519 key object in the HSM by label or ID. */
102
66
  private _findKey;
103
- /**
104
- * Export the Ed25519 public key from the HSM.
105
- * Handles both DER-wrapped (04 20 <32 bytes>) and raw 32-byte formats.
106
- */
67
+ /** Accepts a DER-wrapped and a raw 32-byte Ed25519 public key. */
107
68
  private _exportPublicKey;
108
69
  }
109
- /**
110
- * Get the initialized HsmSigner instance.
111
- * Returns null if HSM is not configured.
112
- */
70
+ /** The initialized HsmSigner, or null when HSM is not configured. */
113
71
  export declare function getHsmSigner(): HsmSigner | null;
114
- /**
115
- * Set the HsmSigner instance (called during initialization and shutdown).
116
- */
72
+ /** Set the HsmSigner instance (initialization and shutdown). */
117
73
  export declare function setHsmSigner(signer: HsmSigner | null): void;
118
74
  export {};
119
75
  //# sourceMappingURL=hsm-signer.d.ts.map
@@ -9,14 +9,14 @@ exports.getHsmSigner = getHsmSigner;
9
9
  exports.setHsmSigner = setHsmSigner;
10
10
  const cds_1 = __importDefault(require("@sap/cds"));
11
11
  const errors_1 = require("../../utils/errors");
12
+ const config_1 = require("../../config");
12
13
  const error_codes_1 = require("../../utils/error-codes");
13
14
  const cbor_1 = require("@harmoniclabs/cbor");
14
15
  const uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
16
+ const blake2b_1 = __importDefault(require("blake2b"));
17
+ const bech32_1 = require("bech32");
15
18
  const logger = cds_1.default.log('HsmSigner');
16
- /**
17
- * CKM_EDDSA mechanism ID (PKCS#11 v3.0)
18
- * Used for Ed25519 signing operations
19
- */
19
+ /** CKM_EDDSA mechanism ID (PKCS#11 v3.0) for Ed25519 signing. */
20
20
  const CKM_EDDSA = 0x00001057;
21
21
  const defaultPkcs11Loader = () => require('pkcs11js');
22
22
  let pkcs11Loader = defaultPkcs11Loader;
@@ -24,6 +24,7 @@ let pkcs11Loader = defaultPkcs11Loader;
24
24
  function setPkcs11Loader(loader) {
25
25
  pkcs11Loader = loader ?? defaultPkcs11Loader;
26
26
  }
27
+ /** Ed25519 signing through a PKCS#11 HSM. Private keys never leave the device. */
27
28
  class HsmSigner {
28
29
  pkcs11;
29
30
  session;
@@ -36,14 +37,9 @@ class HsmSigner {
36
37
  constructor(config) {
37
38
  this.config = config;
38
39
  }
39
- /**
40
- * Initialize PKCS#11 session and locate the signing key.
41
- * Called once during plugin startup.
42
- *
43
- * @param network - Cardano network (mainnet, preview, preprod) for address derivation
44
- */
40
+ /** Opens the session, exports the public key and derives the enterprise address. */
45
41
  async init(network) {
46
- // Dynamic import — pkcs11js is only loaded when HSM is configured
42
+ // pkcs11js is only loaded when HSM is configured
47
43
  let pkcs11js;
48
44
  try {
49
45
  pkcs11js = pkcs11Loader();
@@ -53,61 +49,49 @@ class HsmSigner {
53
49
  }
54
50
  this.pkcs11 = new pkcs11js.PKCS11();
55
51
  try {
56
- // 1. Load PKCS#11 module
57
52
  this.pkcs11.load(this.config.pkcs11Module);
58
53
  this.pkcs11.C_Initialize();
59
54
  logger.info({ module: this.config.pkcs11Module }, 'PKCS#11 module loaded');
60
- // 2. Open session on configured slot.
61
- // NOTE: `config.slot` is the 0-based INDEX into the list of slots-with-token
62
- // returned by C_GetSlotList(true), NOT the PKCS#11 slot ID (which need not be
63
- // contiguous or zero-based). Configure it as a position, not a hardware slot id.
55
+ // `config.slot` is the 0-based index into C_GetSlotList(true) (slots with a token),
56
+ // not the PKCS#11 slot ID, which need not be contiguous or zero-based.
64
57
  const slots = this.pkcs11.C_GetSlotList(true);
65
58
  if (this.config.slot >= slots.length) {
66
59
  throw new errors_1.HsmError(`HSM slot index ${this.config.slot} not found. ${slots.length} slot(s) with a token present (valid indices 0..${slots.length - 1}).`, 503, error_codes_1.ERROR_CODES.HSM_UNAVAILABLE);
67
60
  }
68
61
  this.session = this.pkcs11.C_OpenSession(slots[this.config.slot], pkcs11js.CKF_SERIAL_SESSION | pkcs11js.CKF_RW_SESSION);
69
62
  logger.debug({ slot: this.config.slot }, 'PKCS#11 session opened');
70
- // 3. Login with PIN
71
63
  try {
72
64
  this.pkcs11.C_Login(this.session, pkcs11js.CKU_USER, this.config.pin);
73
65
  }
74
66
  finally {
75
- // Zero the PIN everywhere it could residue after login (crash-dump /
76
- // heap-inspection hardening), regardless of login outcome:
77
- // - this.config (shared reference with the server-side hsmConfigInstance
78
- // singleton) — mutate IN PLACE, not reassign, so the singleton clears too
79
- // - the HSM_PIN environment variable
80
- // - the CAP config (cds.env.requires['odatano-core'].hsm.pin)
67
+ // Clear the PIN everywhere it could linger, whatever the login outcome.
68
+ // The config object is shared with the server singleton, so it is changed in place.
81
69
  this.config.pin = '';
82
70
  if (process.env.HSM_PIN)
83
71
  delete process.env.HSM_PIN;
84
72
  try {
85
- const hsmCds = cds_1.default.env?.requires?.['odatano-core']?.hsm;
73
+ const hsmCds = (0, config_1.coreCdsConfig)().hsm;
86
74
  if (hsmCds && 'pin' in hsmCds)
87
75
  hsmCds.pin = '';
88
76
  }
89
77
  catch { /* best effort */ }
90
78
  }
91
79
  logger.debug('PKCS#11 login successful');
92
- // 4. Find private key by label or ID
93
80
  this.privateKeyHandle = this._findKey(pkcs11js, pkcs11js.CKO_PRIVATE_KEY);
94
- // 5. Export public key
95
81
  this.publicKeyBytes = this._exportPublicKey(pkcs11js);
96
82
  logger.debug({ publicKeyLength: this.publicKeyBytes.length }, 'Ed25519 public key exported');
97
- // 6. Derive Cardano key hash and enterprise address
98
- const blake2b = require('blake2b');
83
+ // Key hash = blake2b-224 of the public key
99
84
  const hashOut = Buffer.alloc(28);
100
- blake2b(28).update(this.publicKeyBytes).digest(hashOut);
85
+ (0, blake2b_1.default)(28).update(this.publicKeyBytes).digest(hashOut);
101
86
  this.publicKeyHashHex = hashOut.toString('hex');
102
87
  // Enterprise key-hash address: header 0x61 (mainnet) or 0x60 (testnet)
103
- const { bech32 } = require('bech32');
104
88
  const headerByte = network === 'mainnet' ? 0x61 : 0x60;
105
89
  const payload = Buffer.alloc(29);
106
90
  payload[0] = headerByte;
107
91
  hashOut.copy(payload, 1);
108
- const words = bech32.toWords(payload);
92
+ const words = bech32_1.bech32.toWords(payload);
109
93
  const hrp = network === 'mainnet' ? 'addr' : 'addr_test';
110
- this.cardanoAddress = bech32.encode(hrp, words, 120);
94
+ this.cardanoAddress = bech32_1.bech32.encode(hrp, words, 120);
111
95
  this.connected = true;
112
96
  logger.info({
113
97
  keyLabel: this.config.keyLabel,
@@ -124,19 +108,12 @@ class HsmSigner {
124
108
  throw new errors_1.HsmError(`Failed to initialize HSM: ${msg}`, 503, error_codes_1.ERROR_CODES.HSM_UNAVAILABLE, err);
125
109
  }
126
110
  }
127
- /**
128
- * Sign a 32-byte transaction body hash using the HSM.
129
- * Returns the Ed25519 signature + public key for witness construction.
130
- *
131
- * @param txBodyHash - 32-byte hash of the transaction body
132
- * @returns HsmSignResult with signature, public key, and key hash
133
- */
111
+ /** Sign a 32-byte tx body hash in the HSM; returns Ed25519 signature + public key for the witness. */
134
112
  sign(txBodyHash) {
135
113
  if (!this.connected) {
136
114
  throw new errors_1.HsmError('HSM not connected', 503, error_codes_1.ERROR_CODES.HSM_UNAVAILABLE);
137
115
  }
138
116
  try {
139
- // CKM_EDDSA = Ed25519 signing mechanism
140
117
  this.pkcs11.C_SignInit(this.session, { mechanism: CKM_EDDSA }, this.privateKeyHandle);
141
118
  const signature = this.pkcs11.C_Sign(this.session, txBodyHash, Buffer.alloc(64));
142
119
  return {
@@ -150,22 +127,11 @@ class HsmSigner {
150
127
  throw new errors_1.HsmError(`HSM signing failed: ${msg}`, 500, error_codes_1.ERROR_CODES.HSM_SIGNING_FAILED, err);
151
128
  }
152
129
  }
153
- /**
154
- * Sign a transaction and produce a complete signed transaction CBOR.
155
- *
156
- * Takes the unsigned transaction CBOR, signs the body hash via HSM,
157
- * builds a VKey witness [publicKey, signature], and merges it into
158
- * the transaction's witness set using raw CBOR manipulation.
159
- *
160
- * @param unsignedTxCbor - Unsigned transaction CBOR (hex)
161
- * @param txBodyHash - Transaction body hash (hex, 64 chars)
162
- * @returns Signed transaction CBOR (hex)
163
- */
130
+ /** Signs the body hash and splices the VKey witness in at the raw CBOR level. */
164
131
  signTransaction(unsignedTxCbor, txBodyHash) {
165
132
  const hashBytes = Buffer.from(txBodyHash, 'hex');
166
133
  const result = this.sign(hashBytes);
167
134
  try {
168
- // Parse unsigned transaction at raw CBOR level
169
135
  const txObj = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(unsignedTxCbor));
170
136
  if (!(txObj instanceof cbor_1.CborArray) || txObj.array.length < 2) {
171
137
  throw new errors_1.HsmError('Invalid transaction CBOR structure', 400, error_codes_1.ERROR_CODES.HSM_SIGNING_FAILED);
@@ -175,13 +141,10 @@ class HsmSigner {
175
141
  new cbor_1.CborBytes(Buffer.from(result.publicKeyHex, 'hex')),
176
142
  new cbor_1.CborBytes(Buffer.from(result.signatureHex, 'hex')),
177
143
  ]);
178
- // Merge into witness set (txObj.array[1])
179
- // Single-signer design: HSM is the sole signer for unsigned transactions.
180
- // Multi-sig (e.g. wallet + HSM) uses combineTransactionWithWitnesses() instead.
144
+ // The HSM witness replaces all vkey witnesses, since it signs alone. Other keys are kept.
145
+ // Multi-sig goes through combineTransactionWithWitnesses().
181
146
  const origWs = txObj.array[1];
182
147
  if (origWs instanceof cbor_1.CborMap) {
183
- // Replace VKey witnesses (key 0) with HSM witness only
184
- // Preserves all other entries (redeemers key 5, datums key 4, scripts keys 1-3, 6-7)
185
148
  const entries = origWs.map.filter((e) => !(e.k instanceof cbor_1.CborUInt && Number(e.k.num) === 0));
186
149
  entries.push({
187
150
  k: new cbor_1.CborUInt(0),
@@ -230,7 +193,7 @@ class HsmSigner {
230
193
  address: this.connected ? this.cardanoAddress : undefined,
231
194
  };
232
195
  }
233
- /** Graceful shutdown — close PKCS#11 session */
196
+ /** Closes the PKCS#11 session. */
234
197
  shutdown() {
235
198
  if (this.session) {
236
199
  try {
@@ -249,14 +212,12 @@ class HsmSigner {
249
212
  // ---------------------------------------------------------------------------
250
213
  // Private helpers
251
214
  // ---------------------------------------------------------------------------
252
- /**
253
- * Find a key object (private or public) in the HSM by label and/or ID
254
- */
215
+ /** Finds an Ed25519 key object in the HSM by label or ID. */
255
216
  _findKey(pkcs11js, objectClass) {
256
217
  const template = [
257
218
  { type: pkcs11js.CKA_CLASS, value: objectClass },
258
219
  ];
259
- // CKK_EC_EDWARDS (0x40) — PKCS#11 v3.0, may not be defined in older pkcs11js versions
220
+ // CKK_EC_EDWARDS is PKCS#11 v3.0 and may be missing in older pkcs11js versions.
260
221
  const CKK_EC_EDWARDS = pkcs11js.CKK_EC_EDWARDS ?? 0x00000040;
261
222
  template.push({ type: pkcs11js.CKA_KEY_TYPE, value: CKK_EC_EDWARDS });
262
223
  if (this.config.keyLabel) {
@@ -274,18 +235,13 @@ class HsmSigner {
274
235
  }
275
236
  return handles[0];
276
237
  }
277
- /**
278
- * Export the Ed25519 public key from the HSM.
279
- * Handles both DER-wrapped (04 20 <32 bytes>) and raw 32-byte formats.
280
- */
238
+ /** Accepts a DER-wrapped and a raw 32-byte Ed25519 public key. */
281
239
  _exportPublicKey(pkcs11js) {
282
240
  const pubKeyHandle = this._findKey(pkcs11js, pkcs11js.CKO_PUBLIC_KEY);
283
- // Extract CKA_EC_POINT (DER-encoded public key)
284
241
  const attrs = this.pkcs11.C_GetAttributeValue(this.session, pubKeyHandle, [
285
242
  { type: pkcs11js.CKA_EC_POINT },
286
243
  ]);
287
- // CKA_EC_POINT for Ed25519 is DER OCTET STRING wrapping 32-byte public key
288
- // Format: 04 20 <32 bytes>
244
+ // CKA_EC_POINT for Ed25519 is a DER OCTET STRING around the 32-byte key: 04 20 <32 bytes>
289
245
  const ecPoint = Buffer.from(attrs[0].value);
290
246
  if (ecPoint.length === 34 && ecPoint[0] === 0x04 && ecPoint[1] === 0x20) {
291
247
  return ecPoint.slice(2);
@@ -298,20 +254,13 @@ class HsmSigner {
298
254
  }
299
255
  }
300
256
  exports.HsmSigner = HsmSigner;
301
- // ---------------------------------------------------------------------------
302
- // Singleton pattern (same as getExternalSignerModule())
303
- // ---------------------------------------------------------------------------
257
+ // Singleton instance
304
258
  let hsmSignerInstance = null;
305
- /**
306
- * Get the initialized HsmSigner instance.
307
- * Returns null if HSM is not configured.
308
- */
259
+ /** The initialized HsmSigner, or null when HSM is not configured. */
309
260
  function getHsmSigner() {
310
261
  return hsmSignerInstance;
311
262
  }
312
- /**
313
- * Set the HsmSigner instance (called during initialization and shutdown).
314
- */
263
+ /** Set the HsmSigner instance (initialization and shutdown). */
315
264
  function setHsmSigner(signer) {
316
265
  hsmSignerInstance = signer;
317
266
  }
@@ -1,56 +1,18 @@
1
- import { SignatureVerificationResult, VerificationOptions } from '../../utils/types';
2
- /**
3
- * SignatureVerifier - Verifies transaction signatures without accessing private keys
4
- *
5
- * This module provides signature verification for externally signed transactions.
6
- * It ensures:
7
- * 1. The signed CBOR is valid and parseable
8
- * 2. The transaction body hash matches the expected hash (integrity check)
9
- * 3. Required signatures are present (when specified)
10
- * 4. No tampering occurred between build and sign steps
11
- */
1
+ import { SignatureVerificationResult, TxWitnessVerification, VerificationOptions } from '../../utils/types';
2
+ export declare function verifyTxWitnesses(signedTxCbor: string): TxWitnessVerification;
3
+ /** Verifies externally signed transactions without private keys. */
12
4
  export declare class SignatureVerifier {
13
- /**
14
- * Verify a signed transaction
15
- *
16
- * @param signedTxCbor - The signed transaction in CBOR hex format
17
- * @param options - Verification options
18
- * @returns Verification result with details
19
- */
5
+ /** Verify a signed tx (hex CBOR); all failures are reported in the result, never thrown. */
20
6
  verify(signedTxCbor: string, options?: VerificationOptions): SignatureVerificationResult;
21
- /**
22
- * Verify signature and throw on failure
23
- *
24
- * @param signedTxCbor - The signed transaction in CBOR hex format
25
- * @param options - Verification options
26
- * @throws {TransactionValidationError} if verification fails
27
- */
7
+ /** Like verify(), but throws TransactionValidationError on failure. */
28
8
  verifyOrThrow(signedTxCbor: string, options?: VerificationOptions): SignatureVerificationResult;
29
- /**
30
- * Extract transaction body hash from unsigned or signed CBOR
31
- *
32
- * @param txCbor - Transaction CBOR (signed or unsigned)
33
- * @returns Transaction body hash as hex string
34
- * @throws {Error} if CBOR is invalid
35
- */
9
+ /** Body hash (hex) of an unsigned or signed tx CBOR; throws BackendError 400 on invalid CBOR. */
36
10
  extractTxBodyHash(txCbor: string): string;
37
- /**
38
- * Check if a transaction is signed (has witnesses)
39
- *
40
- * @param txCbor - Transaction CBOR
41
- * @returns true if transaction has at least one witness
42
- */
11
+ /** True when the tx carries at least one vkey witness. */
43
12
  isSigned(txCbor: string): boolean;
44
- /**
45
- * Get witness count from transaction
46
- *
47
- * @param txCbor - Transaction CBOR
48
- * @returns Number of witnesses
49
- */
13
+ /** Number of vkey witnesses in the tx (0 on invalid CBOR). */
50
14
  getWitnessCount(txCbor: string): number;
51
15
  }
52
- /**
53
- * Get the singleton SignatureVerifier instance
54
- */
16
+ /** Singleton SignatureVerifier. */
55
17
  export declare function getSignatureVerifier(): SignatureVerifier;
56
18
  //# sourceMappingURL=signature-verifier.d.ts.map