@odatano/core 2.0.0-rc.49 → 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 (120) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +6 -12
  2. package/@cds-models/CardanoIndexerService/index.d.ts +200 -2
  3. package/@cds-models/CardanoIndexerService/index.js +24 -0
  4. package/@cds-models/CardanoODataService/index.d.ts +49 -6
  5. package/@cds-models/CardanoODataService/index.js +4 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +3 -3
  7. package/@cds-models/CardanoWorkerService/index.d.ts +4 -3
  8. package/@cds-models/index.d.ts +9 -1
  9. package/@cds-models/index.js +2 -1
  10. package/@cds-models/odatano/cardano/index.d.ts +59 -5
  11. package/@cds-models/odatano/cardano/index.js +6 -0
  12. package/README.md +29 -17
  13. package/db/schema.cds +117 -24
  14. package/db/types.cds +8 -0
  15. package/package.json +17 -15
  16. package/scripts/migrate-schema.mjs +334 -0
  17. package/src/index.d.ts +7 -5
  18. package/src/index.js +12 -10
  19. package/src/plugin.js +6 -7
  20. package/srv/blockchain/backends/blockfrost-backend.js +9 -1
  21. package/srv/blockchain/backends/cardano-backend.d.ts +15 -0
  22. package/srv/blockchain/backends/cardano-backend.js +5 -0
  23. package/srv/blockchain/backends/koios-backend.js +16 -10
  24. package/srv/blockchain/backends/ogmios-backend.d.ts +9 -3
  25. package/srv/blockchain/backends/ogmios-backend.js +60 -18
  26. package/srv/blockchain/cardano-client.d.ts +5 -4
  27. package/srv/blockchain/cardano-client.js +46 -13
  28. package/srv/blockchain/cardano-indexer.d.ts +116 -9
  29. package/srv/blockchain/cardano-indexer.js +436 -189
  30. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  31. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  32. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +23 -1
  33. package/srv/blockchain/crawler/asset-registry-backfill.js +91 -1
  34. package/srv/blockchain/crawler/certificate-backfill.d.ts +2 -0
  35. package/srv/blockchain/crawler/certificate-backfill.js +10 -3
  36. package/srv/blockchain/crawler/crawler.d.ts +15 -0
  37. package/srv/blockchain/crawler/crawler.js +68 -3
  38. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  39. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  40. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  41. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  42. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  43. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  44. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  45. package/srv/blockchain/crawler/transaction-backfill.js +12 -8
  46. package/srv/blockchain/pool-metadata.d.ts +15 -0
  47. package/srv/blockchain/pool-metadata.js +132 -0
  48. package/srv/blockchain/signing/cose-verifier.d.ts +3 -1
  49. package/srv/blockchain/signing/cose-verifier.js +144 -56
  50. package/srv/blockchain/signing/hsm-signer.js +2 -1
  51. package/srv/blockchain/signing/submission-finalizer.d.ts +15 -4
  52. package/srv/blockchain/signing/submission-finalizer.js +201 -69
  53. package/srv/blockchain/stored-chain.js +1 -1
  54. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +1 -3
  55. package/srv/blockchain/transaction-building/buildooor-tx.js +34 -54
  56. package/srv/blockchain/transaction-presence.d.ts +5 -0
  57. package/srv/blockchain/transaction-presence.js +29 -0
  58. package/srv/blockchain/transaction-rows.js +1 -1
  59. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -1
  60. package/srv/blockchain/wallet-worker/build-request.js +25 -0
  61. package/srv/blockchain/wallet-worker/confirmation-tracker.js +1 -1
  62. package/srv/blockchain/wallet-worker/job-store.d.ts +17 -7
  63. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  64. package/srv/blockchain/wallet-worker/signers.d.ts +2 -0
  65. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +2 -0
  66. package/srv/blockchain/wallet-worker/wallet-worker.js +42 -32
  67. package/srv/cardano-agent-service.cds +11 -12
  68. package/srv/cardano-agent-service.js +2 -0
  69. package/srv/cardano-backend-service.cds +34 -1
  70. package/srv/cardano-backend-service.js +20 -17
  71. package/srv/cardano-indexer-service.cds +153 -12
  72. package/srv/cardano-indexer-service.js +175 -29
  73. package/srv/cardano-service.cds +67 -3
  74. package/srv/cardano-service.js +132 -67
  75. package/srv/cardano-sign-service.cds +30 -20
  76. package/srv/cardano-sign-service.js +13 -10
  77. package/srv/cardano-tx-service.cds +15 -1
  78. package/srv/cardano-tx-service.js +4 -1
  79. package/srv/cardano-worker-service.cds +16 -7
  80. package/srv/cardano-worker-service.js +31 -22
  81. package/srv/cbor/parse.js +11 -34
  82. package/srv/config.d.ts +113 -0
  83. package/srv/config.js +409 -0
  84. package/srv/server.d.ts +9 -14
  85. package/srv/server.js +32 -316
  86. package/srv/utils/agent-access.d.ts +9 -0
  87. package/srv/utils/agent-access.js +67 -0
  88. package/srv/utils/agent-grants-config.d.ts +0 -17
  89. package/srv/utils/agent-grants-config.js +6 -81
  90. package/srv/utils/agent-grants.d.ts +6 -19
  91. package/srv/utils/agent-grants.js +69 -130
  92. package/srv/utils/const.d.ts +4 -0
  93. package/srv/utils/const.js +5 -1
  94. package/srv/utils/db-indexes.js +11 -3
  95. package/srv/utils/error-codes.d.ts +4 -0
  96. package/srv/utils/error-codes.js +4 -0
  97. package/srv/utils/errors.d.ts +6 -0
  98. package/srv/utils/errors.js +23 -1
  99. package/srv/utils/liveness.js +2 -5
  100. package/srv/utils/mappers.d.ts +5 -7
  101. package/srv/utils/mappers.js +22 -9
  102. package/srv/utils/pg-order-nulls.js +4 -3
  103. package/srv/utils/readiness.d.ts +12 -0
  104. package/srv/utils/readiness.js +29 -0
  105. package/srv/utils/result-numbers.d.ts +15 -0
  106. package/srv/utils/result-numbers.js +61 -0
  107. package/srv/utils/tx-request-parsers.d.ts +1 -1
  108. package/srv/utils/tx-request-parsers.js +3 -3
  109. package/srv/utils/tx-utils.d.ts +3 -0
  110. package/srv/utils/tx-utils.js +17 -3
  111. package/srv/utils/types.d.ts +16 -3
  112. package/scripts/migrate-txseq.mjs +0 -138
  113. package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +0 -13
  114. package/srv/blockchain/transaction-building/buildooor-fee-patch.js +0 -71
  115. package/srv/blockchain/transaction-building/caller-datums.d.ts +0 -15
  116. package/srv/blockchain/transaction-building/caller-datums.js +0 -133
  117. package/srv/cbor/redeemer-tag-patch.d.ts +0 -3
  118. package/srv/cbor/redeemer-tag-patch.js +0 -61
  119. package/srv/utils/legacy-service-paths.d.ts +0 -11
  120. package/srv/utils/legacy-service-paths.js +0 -58
package/srv/server.js CHANGED
@@ -3,21 +3,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.activateAgentGrants = exports.loadAgentGrantsConfig = void 0;
7
6
  exports.getAppContext = getAppContext;
8
7
  exports.getCardanoIndexer = getCardanoIndexer;
9
8
  exports.getCardanoClient = getCardanoClient;
10
9
  exports.getCardanoTxBuilder = getCardanoTxBuilder;
11
10
  exports.getHsmConfig = getHsmConfig;
11
+ exports.readinessParts = readinessParts;
12
12
  exports.initializeFromConfig = initializeFromConfig;
13
13
  exports.resetAppContext = resetAppContext;
14
14
  exports.createTestContext = createTestContext;
15
15
  exports.shutdownAppContext = shutdownAppContext;
16
- exports.loadConfigFromEnv = loadConfigFromEnv;
17
- exports.loadHsmConfigFromEnv = loadHsmConfigFromEnv;
18
- exports.loadCrawlerConfigFromEnv = loadCrawlerConfigFromEnv;
19
16
  exports.startCrawlerIfConfigured = startCrawlerIfConfigured;
20
- exports.loadWalletWorkerConfigFromEnv = loadWalletWorkerConfigFromEnv;
21
17
  exports.startWalletWorkerIfConfigured = startWalletWorkerIfConfigured;
22
18
  exports.redriveInterruptedSubmissionsIfConfigured = redriveInterruptedSubmissionsIfConfigured;
23
19
  const cds_1 = __importDefault(require("@sap/cds"));
@@ -34,46 +30,8 @@ const pg_inline_json_1 = require("./utils/pg-inline-json");
34
30
  const crawler_1 = require("./blockchain/crawler");
35
31
  const wallet_worker_1 = require("./blockchain/wallet-worker");
36
32
  const agent_grants_config_1 = require("./utils/agent-grants-config");
37
- const legacy_service_paths_1 = require("./utils/legacy-service-paths");
38
- const process_1 = require("process");
33
+ const config_1 = require("./config");
39
34
  const logger = cds_1.default.log('ODATANO');
40
- const VALID_NETWORKS = ['mainnet', 'preview', 'preprod'];
41
- function coreCdsConfig() {
42
- const requires = cds_1.default.env?.requires;
43
- return requires?.['odatano-core'] ?? {};
44
- }
45
- const VALID_BACKENDS = ['blockfrost', 'koios', 'ogmios', 'odatano'];
46
- const CRAWLER_LIMITS = {
47
- batchSize: { min: 1, max: 100 },
48
- confirmationDepth: { min: 0, max: 2160 },
49
- pollIntervalMs: { min: 1000, max: 3_600_000 },
50
- assetEnrichRate: { min: 1, max: 20 },
51
- };
52
- const VALID_ASSET_CATALOGUE_MODES = ['off', 'bare', 'enrich'];
53
- /** Parse a boolean crawler flag that defaults to `fallback` when unset. */
54
- function crawlerBoolean(raw, name, fallback) {
55
- if (raw === undefined || raw === null)
56
- return fallback;
57
- if (raw === true || raw === 'true')
58
- return true;
59
- if (raw === false || raw === 'false')
60
- return false;
61
- throw new errors_1.ConfigError(`Invalid ${name} "${String(raw)}". Must be true or false.`);
62
- }
63
- /** Parse an integer without allowing JavaScript's lossy/implicit coercions. */
64
- function crawlerInteger(raw, name, min, max, defaultValue) {
65
- if (raw == null)
66
- return defaultValue;
67
- if ((typeof raw !== 'number' && typeof raw !== 'string')
68
- || (typeof raw === 'string' && raw.trim() === '')) {
69
- throw new errors_1.ConfigError(`Invalid ${name} "${String(raw)}". Must be an integer between ${min} and ${max}.`);
70
- }
71
- const parsed = typeof raw === 'number' ? raw : Number(raw);
72
- if (!Number.isSafeInteger(parsed) || parsed < min || parsed > max) {
73
- throw new errors_1.ConfigError(`Invalid ${name} "${String(raw)}". Must be an integer between ${min} and ${max}.`);
74
- }
75
- return parsed;
76
- }
77
35
  let appContext = null;
78
36
  let bootstrapError = null;
79
37
  /** Every start path, standalone hook and plugin, comes through here. */
@@ -99,6 +57,7 @@ async function initializeAppContext(config, protocolParams, hsmConfig) {
99
57
  if ((0, db_sanitize_1.installDbSanitizer)())
100
58
  logger.debug('DB NUL sanitizer installed');
101
59
  const cardanoIndexer = new cardano_indexer_1.CardanoIndexer(cardanoClient, cardanoTxBuilder);
60
+ cardanoIndexer.setPoolMetadataFetch((0, config_1.loadPoolMetadataFetchFromEnv)());
102
61
  // HSM signer failure is non-fatal
103
62
  if (hsmConfig?.enabled) {
104
63
  try {
@@ -119,14 +78,9 @@ async function initializeAppContext(config, protocolParams, hsmConfig) {
119
78
  cardanoTxBuilder,
120
79
  };
121
80
  }
122
- /** Agent-grant feature switch; its own module so src/plugin.ts can read it at load. */
123
- var agent_grants_config_2 = require("./utils/agent-grants-config");
124
- Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get: function () { return agent_grants_config_2.loadAgentGrantsConfig; } });
125
- Object.defineProperty(exports, "activateAgentGrants", { enumerable: true, get: function () { return agent_grants_config_2.activateAgentGrants; } });
126
81
  // Standalone mode never loads src/plugin.ts, so swap the auth impl here as well
127
82
  // (bin/serve.js imports this file before the middlewares exist). Idempotent.
128
83
  (0, agent_grants_config_1.activateAgentGrants)();
129
- (0, legacy_service_paths_1.registerLegacyServicePaths)();
130
84
  /** Throws 503 when uninitialized, with a bootstrap failure appended as cause. */
131
85
  function getAppContext() {
132
86
  if (!appContext) {
@@ -152,6 +106,10 @@ let hsmConfigInstance;
152
106
  function getHsmConfig() {
153
107
  return hsmConfigInstance;
154
108
  }
109
+ /** What getReadiness() reports about this process: the app context and, when configured, the HSM session. */
110
+ function readinessParts() {
111
+ return { context: appContext !== null, hsm: hsmConfigInstance ? (0, hsm_signer_1.getHsmSigner)()?.isConnected() === true : null };
112
+ }
155
113
  // Plugin path. Idempotent, so a second call never creates a duplicate CardanoClient.
156
114
  // Tests reinitialize with resetAppContext() or createTestContext().
157
115
  async function initializeFromConfig(config, protocolParams, hsmConfig) {
@@ -180,24 +138,9 @@ function resetAppContext(context) {
180
138
  (0, network_context_1.setActiveNetwork)(context?.cardanoClient.network ?? null);
181
139
  logger.debug('Application context reset');
182
140
  }
183
- // Isolated test context with the given backends.
184
- // _txBuilderName is ignored and kept for signature compatibility.
185
- async function createTestContext(backends, _txBuilderName = 'buildooor', protocolParams) {
186
- const config = {
187
- network: process_1.env.NETWORK || 'preview',
188
- backends,
189
- blockfrostApiKey: process_1.env.BLOCKFROST_API_KEY || '',
190
- blockfrostCustomBackend: process_1.env.BLOCKFROST_CUSTOM_BACKEND || undefined,
191
- koiosApiKey: process_1.env.KOIOS_API_KEY || '',
192
- ogmiosUrl: process_1.env.OGMIOS_URL || '',
193
- odatanoUrl: process_1.env.ODATANO_URL || undefined,
194
- odatanoApiKey: process_1.env.ODATANO_API_KEY || undefined,
195
- transactionBuilders: ['buildooor'],
196
- primaryTimeoutMs: Number(process_1.env.PRIMARY_TIMEOUT_MS) || 30000, // || intentional: NaN (missing env var) falls back to default
197
- fallbackTimeoutMs: Number(process_1.env.FALLBACK_TIMEOUT_MS) || 60000,
198
- indexTtlMs: Number(process_1.env.INDEX_TTL_MS) || 3600000,
199
- };
200
- return await initializeAppContext(config, protocolParams);
141
+ /** Isolated test context: the configuration of the environment with the given backends. */
142
+ async function createTestContext(backends, protocolParams) {
143
+ return await initializeAppContext({ ...(0, config_1.loadConfigFromEnv)(), backends }, protocolParams);
201
144
  }
202
145
  let shutdownInFlight = null;
203
146
  /** Stop worker and crawler, then close all backend connections. Concurrent callers share one run. */
@@ -206,6 +149,10 @@ function shutdownAppContext() {
206
149
  return shutdownInFlight;
207
150
  }
208
151
  async function runShutdown() {
152
+ if (submissionReconcilerStarted) {
153
+ submissionFinalizer().stopSubmissionReconciler();
154
+ submissionReconcilerStarted = false;
155
+ }
209
156
  // Worker and crawler first: their in-flight writes must not hit a torn-down client.
210
157
  try {
211
158
  await (0, wallet_worker_1.stopWalletWorker)();
@@ -232,174 +179,13 @@ async function runShutdown() {
232
179
  (0, network_context_1.setActiveNetwork)(null);
233
180
  }
234
181
  }
235
- // cds.env.requires["odatano-core"] wins over process.env, which wins over the default.
236
- // Throws ConfigError for an invalid value.
237
- function loadConfigFromEnv() {
238
- const cdsConfig = coreCdsConfig();
239
- const network = (cdsConfig.network || process_1.env.NETWORK || 'preview');
240
- if (!VALID_NETWORKS.includes(network)) {
241
- throw new errors_1.ConfigError(`Invalid NETWORK "${cdsConfig.network || process_1.env.NETWORK}". Must be one of: ${VALID_NETWORKS.join(', ')}`);
242
- }
243
- const backendsRaw = cdsConfig.backends ?? process_1.env.BACKENDS;
244
- const backendStrings = Array.isArray(backendsRaw) ? backendsRaw
245
- : backendsRaw ? String(backendsRaw).split(',').map(b => b.trim()) : ['koios'];
246
- const invalidBackends = backendStrings.filter(b => !VALID_BACKENDS.includes(b));
247
- if (invalidBackends.length > 0) {
248
- throw new errors_1.ConfigError(`Invalid BACKENDS: "${invalidBackends.join(', ')}". Must be one of: ${VALID_BACKENDS.join(', ')}`);
249
- }
250
- const backends = backendStrings;
251
- // Buildooor is the sole transaction builder; txBuilders/TX_BUILDERS config is ignored.
252
- const txBuilders = ['buildooor'];
253
- const primaryTimeout = cdsConfig.primaryTimeoutMs ?? process_1.env.PRIMARY_TIMEOUT_MS;
254
- const fallbackTimeout = cdsConfig.fallbackTimeoutMs ?? process_1.env.FALLBACK_TIMEOUT_MS;
255
- // `!= null`, not truthiness: a CDS-config 0 must reach the <= 0 check.
256
- if (primaryTimeout != null && isNaN(Number(primaryTimeout))) {
257
- throw new errors_1.ConfigError(`Invalid PRIMARY_TIMEOUT_MS "${primaryTimeout}". Must be a number.`);
258
- }
259
- if (primaryTimeout != null && Number(primaryTimeout) <= 0) {
260
- throw new errors_1.ConfigError(`Invalid PRIMARY_TIMEOUT_MS "${primaryTimeout}". Must be a positive number.`);
261
- }
262
- if (fallbackTimeout != null && isNaN(Number(fallbackTimeout))) {
263
- throw new errors_1.ConfigError(`Invalid FALLBACK_TIMEOUT_MS "${fallbackTimeout}". Must be a number.`);
264
- }
265
- if (fallbackTimeout != null && Number(fallbackTimeout) <= 0) {
266
- throw new errors_1.ConfigError(`Invalid FALLBACK_TIMEOUT_MS "${fallbackTimeout}". Must be a positive number.`);
267
- }
268
- const blockfrostApiKey = cdsConfig.blockfrostApiKey || process_1.env.BLOCKFROST_API_KEY || '';
269
- const blockfrostCustomBackend = cdsConfig.blockfrostCustomBackend || process_1.env.BLOCKFROST_CUSTOM_BACKEND || '';
270
- if (blockfrostCustomBackend && !/^https?:\/\//i.test(blockfrostCustomBackend)) {
271
- throw new errors_1.ConfigError(`Invalid BLOCKFROST_CUSTOM_BACKEND "${blockfrostCustomBackend}". Must be an http(s) URL ` +
272
- `(e.g. http://localhost:3010/api/v0).`);
273
- }
274
- const koiosApiKey = cdsConfig.koiosApiKey || process_1.env.KOIOS_API_KEY || '';
275
- const ogmiosUrl = cdsConfig.ogmiosUrl || process_1.env.OGMIOS_URL || '';
276
- const odatanoUrl = cdsConfig.odatanoUrl || process_1.env.ODATANO_URL || '';
277
- const odatanoApiKey = cdsConfig.odatanoApiKey || process_1.env.ODATANO_API_KEY || '';
278
- if (odatanoUrl && !/^https?:\/\//i.test(odatanoUrl)) {
279
- throw new errors_1.ConfigError(`Invalid ODATANO_URL "${odatanoUrl}". Must be an http(s) URL (e.g. https://api.preprod.odatano.dev).`);
280
- }
281
- if (backends.includes('odatano') && !odatanoUrl && network === 'mainnet') {
282
- throw new errors_1.ConfigError('ODATANO_URL is required for the odatano backend on mainnet.');
283
- }
284
- if (backends.includes('odatano') && !odatanoApiKey) {
285
- logger.warn('ODATANO_API_KEY is not set but odatano is listed in BACKENDS; the public API refuses calls without a key');
286
- }
287
- if (backends.includes('blockfrost') && !blockfrostApiKey && !blockfrostCustomBackend) {
288
- logger.warn('Neither BLOCKFROST_API_KEY nor BLOCKFROST_CUSTOM_BACKEND is set but blockfrost is listed in BACKENDS');
289
- }
290
- else if (backends.includes('blockfrost') && blockfrostCustomBackend) {
291
- logger.info(`Blockfrost will use customBackend: ${blockfrostCustomBackend}`);
292
- }
293
- if (backends.includes('ogmios') && !ogmiosUrl) {
294
- logger.warn('OGMIOS_URL is not set but ogmios is listed in BACKENDS');
295
- }
296
- return {
297
- network,
298
- backends,
299
- blockfrostApiKey,
300
- blockfrostCustomBackend: blockfrostCustomBackend || undefined,
301
- koiosApiKey,
302
- ogmiosUrl,
303
- odatanoUrl: odatanoUrl || undefined,
304
- odatanoApiKey: odatanoApiKey || undefined,
305
- transactionBuilders: txBuilders,
306
- primaryTimeoutMs: Number(primaryTimeout) || 30000, // || intentional: NaN (missing config) falls back to default
307
- fallbackTimeoutMs: Number(fallbackTimeout) || 60000,
308
- indexTtlMs: Number(cdsConfig.indexTtlMs ?? process_1.env.INDEX_TTL_MS) || 3600000,
309
- };
310
- }
311
- /** From cds.requires.odatano-core.hsm or HSM_* env vars. Undefined when HSM is off. */
312
- function loadHsmConfigFromEnv() {
313
- const cdsConfig = coreCdsConfig();
314
- const hsmCds = cdsConfig.hsm ?? {};
315
- const hsmEnabled = hsmCds.enabled === true || process_1.env.HSM_ENABLED === 'true';
316
- if (!hsmEnabled)
317
- return undefined;
318
- const pkcs11Module = hsmCds.pkcs11Module || process_1.env.HSM_PKCS11_MODULE || '';
319
- if (!pkcs11Module) {
320
- throw new errors_1.ConfigError('HSM_PKCS11_MODULE is required when HSM is enabled');
321
- }
322
- const pin = hsmCds.pin || process_1.env.HSM_PIN || '';
323
- if (!pin) {
324
- throw new errors_1.ConfigError('HSM_PIN is required when HSM is enabled');
325
- }
326
- const slot = Number(hsmCds.slot ?? process_1.env.HSM_SLOT ?? 0);
327
- if (!Number.isInteger(slot) || slot < 0) {
328
- throw new errors_1.ConfigError(`Invalid HSM slot: "${hsmCds.slot ?? process_1.env.HSM_SLOT}": must be a non-negative integer`);
329
- }
330
- // Fail closed: the HSM holds a real signing key, so an explicit role gate is mandatory.
331
- const requiresRole = hsmCds.requiresRole || process_1.env.HSM_REQUIRES_ROLE || '';
332
- if (!requiresRole) {
333
- throw new errors_1.ConfigError('HSM_REQUIRES_ROLE (or cds.requires.odatano-core.hsm.requiresRole) is required when HSM is enabled. Set it to the XSUAA scope name allowed to invoke HSM signing actions');
334
- }
335
- return {
336
- enabled: true,
337
- pkcs11Module,
338
- slot,
339
- pin,
340
- keyId: hsmCds.keyId || process_1.env.HSM_KEY_ID,
341
- keyLabel: hsmCds.keyLabel || process_1.env.HSM_KEY_LABEL,
342
- requiresRole,
343
- };
344
- }
345
- /** From cds.requires.odatano-core.crawler or CRAWLER_* env vars. Off by default. */
346
- function loadCrawlerConfigFromEnv() {
347
- const cdsConfig = coreCdsConfig();
348
- const c = cdsConfig.crawler ?? {};
349
- // A CDS value, including an explicit `false`, wins over the environment.
350
- const enabledRaw = c.enabled !== undefined ? c.enabled : process_1.env.CRAWLER_ENABLED;
351
- let enabled = false;
352
- if (enabledRaw === true || enabledRaw === 'true') {
353
- enabled = true;
354
- }
355
- else if (enabledRaw !== undefined && enabledRaw !== false && enabledRaw !== 'false') {
356
- throw new errors_1.ConfigError(`Invalid CRAWLER_ENABLED "${String(enabledRaw)}". Must be true or false.`);
357
- }
358
- const startSlot = crawlerInteger(c.startSlot ?? process_1.env.CRAWLER_START_SLOT, 'CRAWLER_START_SLOT', 0, Number.MAX_SAFE_INTEGER);
359
- const startHeight = crawlerInteger(c.startHeight ?? process_1.env.CRAWLER_START_HEIGHT, 'CRAWLER_START_HEIGHT', 0, Number.MAX_SAFE_INTEGER);
360
- const startBlockHashRaw = c.startBlockHash ?? process_1.env.CRAWLER_START_HASH;
361
- if (startBlockHashRaw != null && (typeof startBlockHashRaw !== 'string' || !/^[0-9a-f]{64}$/i.test(startBlockHashRaw.trim()))) {
362
- throw new errors_1.ConfigError('Invalid CRAWLER_START_HASH. Must be exactly 64 hexadecimal characters.');
363
- }
364
- const startBlockHash = startBlockHashRaw?.trim() || undefined;
365
- const source = (c.source ?? process_1.env.CRAWLER_SOURCE ?? 'auto');
366
- const batchSize = crawlerInteger(c.batchSize ?? process_1.env.CRAWLER_BATCH_SIZE, 'CRAWLER_BATCH_SIZE', CRAWLER_LIMITS.batchSize.min, CRAWLER_LIMITS.batchSize.max, 20);
367
- const confirmationDepth = crawlerInteger(c.confirmationDepth ?? process_1.env.CRAWLER_CONFIRMATION_DEPTH, 'CRAWLER_CONFIRMATION_DEPTH', CRAWLER_LIMITS.confirmationDepth.min, CRAWLER_LIMITS.confirmationDepth.max, 3);
368
- const pollIntervalMs = crawlerInteger(c.pollIntervalMs ?? process_1.env.CRAWLER_POLL_INTERVAL_MS, 'CRAWLER_POLL_INTERVAL_MS', CRAWLER_LIMITS.pollIntervalMs.min, CRAWLER_LIMITS.pollIntervalMs.max, 20_000);
369
- if (enabled && (startSlot == null || Number.isNaN(startSlot) || !startBlockHash)) {
370
- throw new errors_1.ConfigError('Crawler is enabled but no start block is configured. Set crawler.startSlot + crawler.startBlockHash ' +
371
- '(or CRAWLER_START_SLOT + CRAWLER_START_HASH).');
372
- }
373
- if (!['ogmios', 'pagination', 'auto'].includes(source)) {
374
- throw new errors_1.ConfigError(`Invalid CRAWLER_SOURCE "${source}". Must be one of: ogmios, pagination, auto.`);
375
- }
376
- // Analytics coverage: mint/burn and the bare catalogue are free by-products of a crawled
377
- // block and on by default; enrichment and epoch snapshots cost provider calls and are opt-in.
378
- const assetHistory = crawlerBoolean(c.assetHistory ?? process_1.env.CRAWLER_ASSET_HISTORY, 'CRAWLER_ASSET_HISTORY', true);
379
- const assetCatalogue = (c.assetCatalogue ?? process_1.env.CRAWLER_ASSET_CATALOGUE ?? 'bare');
380
- if (!VALID_ASSET_CATALOGUE_MODES.includes(assetCatalogue)) {
381
- throw new errors_1.ConfigError(`Invalid CRAWLER_ASSET_CATALOGUE "${assetCatalogue}". Must be one of: ${VALID_ASSET_CATALOGUE_MODES.join(', ')}.`);
382
- }
383
- const assetEnrichRate = crawlerInteger(c.assetEnrichRate ?? process_1.env.CRAWLER_ASSET_ENRICH_RATE, 'CRAWLER_ASSET_ENRICH_RATE', CRAWLER_LIMITS.assetEnrichRate.min, CRAWLER_LIMITS.assetEnrichRate.max, 2);
384
- const epochSnapshots = crawlerBoolean(c.epochSnapshots ?? process_1.env.CRAWLER_EPOCH_SNAPSHOTS, 'CRAWLER_EPOCH_SNAPSHOTS', false);
385
- // Certificates + withdrawals are block content (no extra request) but opt-in to keep write volume stable.
386
- const certificates = crawlerBoolean(c.certificates ?? process_1.env.CRAWLER_CERTIFICATES, 'CRAWLER_CERTIFICATES', false);
387
- // UTxO set: opt-in, inert until a snapshot has been imported (importUtxoSet).
388
- const utxoSet = crawlerBoolean(c.utxoSet ?? process_1.env.CRAWLER_UTXO_SET, 'CRAWLER_UTXO_SET', false);
389
- // Crawled chain answers misses with 404 instead of a provider call.
390
- const authoritative = crawlerBoolean(c.authoritative ?? process_1.env.CRAWLER_AUTHORITATIVE, 'CRAWLER_AUTHORITATIVE', false);
391
- return {
392
- enabled, startSlot, startBlockHash, startHeight, source, batchSize, confirmationDepth, pollIntervalMs,
393
- assetHistory, assetCatalogue, assetEnrichRate, epochSnapshots, certificates, utxoSet, authoritative,
394
- };
395
- }
396
182
  /** Start the crawler if enabled and the app context is ready. Never throws; idempotent. */
397
183
  async function startCrawlerIfConfigured() {
398
- if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
184
+ if ((0, config_1.autoInitSkipped)() || !appContext)
399
185
  return;
400
186
  let config;
401
187
  try {
402
- config = loadCrawlerConfigFromEnv();
188
+ config = (0, config_1.loadCrawlerConfigFromEnv)();
403
189
  }
404
190
  catch (err) {
405
191
  logger.error('Invalid crawler configuration, crawler not started:', err);
@@ -420,88 +206,13 @@ async function startCrawlerIfConfigured() {
420
206
  logger.error('Failed to start chain crawler (non-fatal):', err);
421
207
  }
422
208
  }
423
- const WALLET_WORKER_LIMITS = {
424
- maxConcurrentWallets: { min: 1, max: 64 },
425
- confirmationDepth: { min: 1, max: 2160 },
426
- confirmationTimeoutMs: { min: 30_000, max: 86_400_000 },
427
- pollIntervalMs: { min: 500, max: 3_600_000 },
428
- maxAttempts: { min: 1, max: 10 },
429
- };
430
- /** From cds.requires.odatano-core.walletWorker or WALLET_WORKER_* env vars. Off by default. */
431
- function loadWalletWorkerConfigFromEnv() {
432
- const cdsConfig = coreCdsConfig();
433
- const w = cdsConfig.walletWorker ?? {};
434
- const enabledRaw = w.enabled !== undefined ? w.enabled : process_1.env.WALLET_WORKER_ENABLED;
435
- let enabled = false;
436
- if (enabledRaw === true || enabledRaw === 'true') {
437
- enabled = true;
438
- }
439
- else if (enabledRaw !== undefined && enabledRaw !== false && enabledRaw !== 'false') {
440
- throw new errors_1.ConfigError(`Invalid WALLET_WORKER_ENABLED "${String(enabledRaw)}". Must be true or false.`);
441
- }
442
- let walletsRaw = w.wallets ?? undefined;
443
- if (walletsRaw === undefined && process_1.env.WALLET_WORKER_WALLETS) {
444
- try {
445
- walletsRaw = JSON.parse(process_1.env.WALLET_WORKER_WALLETS);
446
- }
447
- catch {
448
- throw new errors_1.ConfigError('Invalid WALLET_WORKER_WALLETS: must be a JSON array of { walletId, signerType, keyEnv? }.');
449
- }
450
- }
451
- const wallets = [];
452
- if (walletsRaw !== undefined) {
453
- if (!Array.isArray(walletsRaw)) {
454
- throw new errors_1.ConfigError('Invalid walletWorker.wallets: must be an array of { walletId, signerType, keyEnv? }.');
455
- }
456
- for (const entry of walletsRaw) {
457
- const walletId = typeof entry?.walletId === 'string' ? entry.walletId.trim() : '';
458
- const signerType = entry?.signerType;
459
- if (!walletId || (signerType !== 'hsm' && signerType !== 'software')) {
460
- throw new errors_1.ConfigError(`Invalid wallet entry ${JSON.stringify(entry)}: walletId and signerType (hsm|software) are required.`);
461
- }
462
- if (signerType === 'software' && (typeof entry.keyEnv !== 'string' || !entry.keyEnv.trim())) {
463
- throw new errors_1.ConfigError(`Wallet "${walletId}" is signerType=software but has no keyEnv (name of the env var holding the signing key).`);
464
- }
465
- if (wallets.some((existing) => existing.walletId === walletId)) {
466
- throw new errors_1.ConfigError(`Duplicate walletId "${walletId}" in walletWorker.wallets.`);
467
- }
468
- wallets.push({ walletId, signerType, keyEnv: entry.keyEnv });
469
- }
470
- }
471
- const maxConcurrentWallets = crawlerInteger(w.maxConcurrentWallets ?? process_1.env.WALLET_WORKER_MAX_CONCURRENT, 'WALLET_WORKER_MAX_CONCURRENT', WALLET_WORKER_LIMITS.maxConcurrentWallets.min, WALLET_WORKER_LIMITS.maxConcurrentWallets.max, 4);
472
- const confirmationDepth = crawlerInteger(w.confirmationDepth ?? process_1.env.WALLET_WORKER_CONFIRMATION_DEPTH, 'WALLET_WORKER_CONFIRMATION_DEPTH', WALLET_WORKER_LIMITS.confirmationDepth.min, WALLET_WORKER_LIMITS.confirmationDepth.max, 3);
473
- const confirmationTimeoutMs = crawlerInteger(w.confirmationTimeoutMs ?? process_1.env.WALLET_WORKER_CONFIRMATION_TIMEOUT_MS, 'WALLET_WORKER_CONFIRMATION_TIMEOUT_MS', WALLET_WORKER_LIMITS.confirmationTimeoutMs.min, WALLET_WORKER_LIMITS.confirmationTimeoutMs.max, 600_000);
474
- const pollIntervalMs = crawlerInteger(w.pollIntervalMs ?? process_1.env.WALLET_WORKER_POLL_INTERVAL_MS, 'WALLET_WORKER_POLL_INTERVAL_MS', WALLET_WORKER_LIMITS.pollIntervalMs.min, WALLET_WORKER_LIMITS.pollIntervalMs.max, 2_000);
475
- const defaultMaxAttempts = crawlerInteger(w.defaultMaxAttempts ?? process_1.env.WALLET_WORKER_MAX_ATTEMPTS, 'WALLET_WORKER_MAX_ATTEMPTS', WALLET_WORKER_LIMITS.maxAttempts.min, WALLET_WORKER_LIMITS.maxAttempts.max, 3);
476
- const resubmitRaw = w.resubmitOnRollback !== undefined ? w.resubmitOnRollback : process_1.env.WALLET_WORKER_RESUBMIT_ON_ROLLBACK;
477
- let resubmitOnRollback = true;
478
- if (resubmitRaw === false || resubmitRaw === 'false') {
479
- resubmitOnRollback = false;
480
- }
481
- else if (resubmitRaw !== undefined && resubmitRaw !== true && resubmitRaw !== 'true') {
482
- throw new errors_1.ConfigError(`Invalid WALLET_WORKER_RESUBMIT_ON_ROLLBACK "${String(resubmitRaw)}". Must be true or false.`);
483
- }
484
- if (enabled && wallets.length === 0) {
485
- throw new errors_1.ConfigError('Wallet worker is enabled but no wallets are configured. Set walletWorker.wallets (or WALLET_WORKER_WALLETS).');
486
- }
487
- return {
488
- enabled,
489
- wallets,
490
- maxConcurrentWallets,
491
- confirmationDepth,
492
- confirmationTimeoutMs,
493
- pollIntervalMs,
494
- defaultMaxAttempts,
495
- resubmitOnRollback,
496
- };
497
- }
498
209
  /** Start the wallet worker if enabled and the app context is ready. Never throws; idempotent. */
499
210
  async function startWalletWorkerIfConfigured() {
500
- if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
211
+ if ((0, config_1.autoInitSkipped)() || !appContext)
501
212
  return;
502
213
  let config;
503
214
  try {
504
- config = loadWalletWorkerConfigFromEnv();
215
+ config = (0, config_1.loadWalletWorkerConfigFromEnv)();
505
216
  }
506
217
  catch (err) {
507
218
  logger.error('Invalid wallet-worker configuration, worker not started:', err);
@@ -522,38 +233,43 @@ async function startWalletWorkerIfConfigured() {
522
233
  logger.error('Failed to start wallet worker (non-fatal):', err);
523
234
  }
524
235
  }
525
- // Retries submissions left in 'submitting' because the process died first. Idempotent,
526
- // because an already submitted tx finalizes on TransactionAlreadySubmittedError. Never throws.
236
+ let submissionReconcilerStarted = false;
237
+ function submissionFinalizer() {
238
+ return require('./blockchain/signing/submission-finalizer');
239
+ }
240
+ // Resolves submits left open by a crash or by a submit without a verdict, now and then on a timer.
241
+ // Idempotent, because a transaction the node already holds finalizes as submitted. Never throws.
527
242
  async function redriveInterruptedSubmissionsIfConfigured() {
528
- if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
243
+ if ((0, config_1.autoInitSkipped)() || !appContext)
529
244
  return;
530
245
  // Without a database there are no signing requests to re-drive
531
246
  if (!cds_1.default.db)
532
247
  return;
533
248
  try {
534
- const { redriveInterruptedSubmissions } = require('./blockchain/signing/submission-finalizer');
535
- const attempted = await redriveInterruptedSubmissions();
249
+ const attempted = await submissionFinalizer().redriveInterruptedSubmissions();
536
250
  if (attempted > 0)
537
- logger.info(`Re-drove ${attempted} interrupted deferred submission(s)`);
251
+ logger.info(`Resolved or retried ${attempted} open submission(s)`);
538
252
  }
539
253
  catch (err) {
540
254
  logger.error('Failed to re-drive interrupted submissions (non-fatal):', err);
541
255
  }
256
+ submissionFinalizer().startSubmissionReconciler();
257
+ submissionReconcilerStarted = true;
542
258
  }
543
259
  // Standalone bootstrap; skipped when the plugin already initialized the context.
544
260
  cds_1.default.on('served', async () => {
545
261
  if (appContext)
546
262
  return;
547
263
  // SKIP_AUTO_INIT: tests with mocked backends
548
- if (process_1.env.SKIP_AUTO_INIT === 'true') {
264
+ if ((0, config_1.autoInitSkipped)()) {
549
265
  logger.info('Skipping auto-initialization (SKIP_AUTO_INIT=true)');
550
266
  return;
551
267
  }
552
268
  // Config loading stays inside the try: a ConfigError must never crash the host app.
553
269
  let config;
554
270
  try {
555
- config = loadConfigFromEnv();
556
- const hsmConfig = loadHsmConfigFromEnv();
271
+ config = (0, config_1.loadConfigFromEnv)();
272
+ const hsmConfig = (0, config_1.loadHsmConfigFromEnv)();
557
273
  hsmConfigInstance = hsmConfig;
558
274
  appContext = await initializeAppContext(config, undefined, hsmConfig);
559
275
  bootstrapError = null;
@@ -0,0 +1,9 @@
1
+ export type AgentAccess = 'read' | 'grant' | 'operator';
2
+ type Model = {
3
+ definitions?: Record<string, unknown>;
4
+ };
5
+ export declare function agentAccessOf(service: string, event: string, model?: Model | null | undefined): AgentAccess | 'closed';
6
+ /** Names of the operations a grant may list, in model order. */
7
+ export declare function agentGrantableActions(model?: Model | null | undefined): string[];
8
+ export {};
9
+ //# sourceMappingURL=agent-access.d.ts.map
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.agentAccessOf = agentAccessOf;
7
+ exports.agentGrantableActions = agentGrantableActions;
8
+ const cds_1 = __importDefault(require("@sap/cds"));
9
+ const ANNOTATION = '@odatano.agent';
10
+ const LEVELS = ['read', 'grant', 'operator'];
11
+ const tables = new WeakMap();
12
+ function buildTable(model) {
13
+ const table = { closed: new Set(), operations: new Map() };
14
+ const definitions = Object.entries((model.definitions ?? {}));
15
+ const services = definitions.filter(([, def]) => def.kind === 'service').map(([name]) => name);
16
+ const serviceOf = (name) => services.find((service) => name.startsWith(`${service}.`));
17
+ const add = (service, operation, def) => {
18
+ const access = def[ANNOTATION];
19
+ if (typeof access !== 'string' || !LEVELS.includes(access))
20
+ return;
21
+ const key = `${service}.${operation}`;
22
+ const known = table.operations.get(key);
23
+ // two operations of one service under one name must agree, else the name is refused
24
+ table.operations.set(key, known && known !== access ? 'operator' : access);
25
+ };
26
+ for (const [name, def] of definitions) {
27
+ if (def.kind === 'service' && def[ANNOTATION] === 'closed')
28
+ table.closed.add(name);
29
+ const service = serviceOf(name);
30
+ if (!service)
31
+ continue;
32
+ if (def.kind === 'action' || def.kind === 'function')
33
+ add(service, name.slice(service.length + 1), def);
34
+ for (const [bound, action] of Object.entries(def.actions ?? {}))
35
+ add(service, bound, action);
36
+ }
37
+ return table;
38
+ }
39
+ function tableOf(model) {
40
+ if (!model)
41
+ return undefined;
42
+ let table = tables.get(model);
43
+ if (!table)
44
+ tables.set(model, (table = buildTable(model)));
45
+ return table;
46
+ }
47
+ // Access of an agent token to `event` on `service`. Entity reads are `read`. An operation without
48
+ // the annotation, any other event and everything before the model is loaded are `operator`.
49
+ function agentAccessOf(service, event, model = cds_1.default.model) {
50
+ const table = tableOf(model);
51
+ if (!table)
52
+ return 'operator';
53
+ if (table.closed.has(service))
54
+ return 'closed';
55
+ if (event === 'READ')
56
+ return 'read';
57
+ return table.operations.get(`${service}.${event}`) ?? 'operator';
58
+ }
59
+ /** Names of the operations a grant may list, in model order. */
60
+ function agentGrantableActions(model = cds_1.default.model) {
61
+ const table = tableOf(model);
62
+ if (!table)
63
+ return [];
64
+ const names = [...table.operations].filter(([, access]) => access === 'grant').map(([key]) => key.slice(key.indexOf('.') + 1));
65
+ return [...new Set(names)];
66
+ }
67
+ //# sourceMappingURL=agent-access.js.map
@@ -1,19 +1,2 @@
1
- export interface AgentGrantsConfig {
2
- enabled: boolean;
3
- /** CAP auth kind the transport middleware delegates to for non-token requests. */
4
- delegate: string;
5
- /** Grant administration calls per principal per hour (integer >= 1). */
6
- adminRateLimit: number;
7
- }
8
- export declare const AGENT_GRANTS_DELEGATES: readonly string[];
9
- export declare const AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = 10;
10
- export declare function loadGrantAdminRateLimit(env?: Record<string, string | undefined>): number;
11
- export declare const AGENT_TOKEN_CACHE_MS_DEFAULT = 10000;
12
- export declare function loadTokenCacheMs(env?: Record<string, string | undefined>): number;
13
- /** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
14
- export declare function configuredAuth(): Record<string, unknown>;
15
- /** A host-configured custom `cds.requires.auth.impl` (not this package's middleware); the lane wraps it. */
16
- export declare function customAuthImpl(auth?: Record<string, unknown>): string | null;
17
- export declare function loadAgentGrantsConfig(env?: Record<string, string | undefined>): AgentGrantsConfig;
18
1
  export declare function activateAgentGrants(): boolean;
19
2
  //# sourceMappingURL=agent-grants-config.d.ts.map