@odatano/core 1.11.0 → 2.0.0-rc.10

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 (133) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +255 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +177 -0
  4. package/@cds-models/CardanoIndexerService/index.js +27 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +693 -2172
  6. package/@cds-models/CardanoODataService/index.js +88 -390
  7. package/@cds-models/CardanoSignService/index.d.ts +448 -1576
  8. package/@cds-models/CardanoSignService/index.js +62 -293
  9. package/@cds-models/CardanoTransactionService/index.d.ts +437 -1494
  10. package/@cds-models/CardanoTransactionService/index.js +60 -271
  11. package/@cds-models/CardanoWorkerService/index.d.ts +224 -0
  12. package/@cds-models/CardanoWorkerService/index.js +32 -0
  13. package/@cds-models/_/index.d.ts +70 -40
  14. package/@cds-models/_/index.js +17 -32
  15. package/@cds-models/cds/outbox/index.d.ts +28 -0
  16. package/@cds-models/index.d.ts +225 -522
  17. package/@cds-models/index.js +35 -218
  18. package/@cds-models/odatano/cardano/index.d.ts +919 -2884
  19. package/@cds-models/odatano/cardano/index.js +115 -536
  20. package/@cds-models/sap/common/index.d.ts +196 -600
  21. package/@cds-models/sap/common/index.js +28 -269
  22. package/README.md +194 -102
  23. package/db/schema.cds +388 -1
  24. package/db/types.cds +48 -0
  25. package/package.json +48 -33
  26. package/src/index.d.ts +7 -1
  27. package/src/index.js +30 -2
  28. package/src/plugin.js +33 -20
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +21 -2
  30. package/srv/blockchain/backends/blockfrost-backend.js +69 -25
  31. package/srv/blockchain/backends/cardano-backend.d.ts +69 -0
  32. package/srv/blockchain/backends/cardano-backend.js +13 -0
  33. package/srv/blockchain/backends/koios-backend.d.ts +26 -2
  34. package/srv/blockchain/backends/koios-backend.js +148 -25
  35. package/srv/blockchain/backends/ogmios-backend.d.ts +60 -9
  36. package/srv/blockchain/backends/ogmios-backend.js +326 -10
  37. package/srv/blockchain/cardano-client.d.ts +19 -0
  38. package/srv/blockchain/cardano-client.js +36 -0
  39. package/srv/blockchain/cardano-indexer.d.ts +50 -1
  40. package/srv/blockchain/cardano-indexer.js +193 -0
  41. package/srv/blockchain/crawler/crawler.d.ts +176 -0
  42. package/srv/blockchain/crawler/crawler.js +744 -0
  43. package/srv/blockchain/crawler/hooks.d.ts +43 -0
  44. package/srv/blockchain/crawler/hooks.js +62 -0
  45. package/srv/blockchain/crawler/index.d.ts +35 -0
  46. package/srv/blockchain/crawler/index.js +168 -0
  47. package/srv/blockchain/crawler/sync-state.d.ts +106 -0
  48. package/srv/blockchain/crawler/sync-state.js +287 -0
  49. package/srv/blockchain/signing/hsm-signer.d.ts +45 -0
  50. package/srv/blockchain/signing/hsm-signer.js +8 -1
  51. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
  52. package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
  53. package/srv/blockchain/wallet-worker/build-request.d.ts +26 -0
  54. package/srv/blockchain/wallet-worker/build-request.js +370 -0
  55. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +117 -0
  56. package/srv/blockchain/wallet-worker/confirmation-tracker.js +290 -0
  57. package/srv/blockchain/wallet-worker/index.d.ts +14 -0
  58. package/srv/blockchain/wallet-worker/index.js +80 -0
  59. package/srv/blockchain/wallet-worker/job-store.d.ts +272 -0
  60. package/srv/blockchain/wallet-worker/job-store.js +597 -0
  61. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +43 -0
  62. package/srv/blockchain/wallet-worker/lease-heartbeat.js +99 -0
  63. package/srv/blockchain/wallet-worker/signers.d.ts +57 -0
  64. package/srv/blockchain/wallet-worker/signers.js +131 -0
  65. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +145 -0
  66. package/srv/blockchain/wallet-worker/wallet-worker.js +542 -0
  67. package/srv/cardano-agent-service.cds +150 -0
  68. package/srv/cardano-agent-service.d.ts +2 -0
  69. package/srv/cardano-agent-service.js +16 -0
  70. package/srv/cardano-indexer-service.cds +106 -0
  71. package/srv/cardano-indexer-service.d.ts +2 -0
  72. package/srv/cardano-indexer-service.js +79 -0
  73. package/srv/cardano-service.js +79 -4
  74. package/srv/cardano-sign-service.cds +200 -180
  75. package/srv/cardano-tx-service.cds +32 -26
  76. package/srv/cardano-tx-service.d.ts +1 -11
  77. package/srv/cardano-tx-service.js +107 -200
  78. package/srv/cardano-worker-service.cds +125 -0
  79. package/srv/cardano-worker-service.d.ts +2 -0
  80. package/srv/cardano-worker-service.js +199 -0
  81. package/srv/server.d.ts +34 -2
  82. package/srv/server.js +246 -36
  83. package/srv/utils/agent-grants-config.d.ts +65 -0
  84. package/srv/utils/agent-grants-config.js +148 -0
  85. package/srv/utils/agent-grants.d.ts +314 -0
  86. package/srv/utils/agent-grants.js +821 -0
  87. package/srv/utils/agent-token-auth.d.ts +19 -0
  88. package/srv/utils/agent-token-auth.js +81 -0
  89. package/srv/utils/collections.d.ts +13 -0
  90. package/srv/utils/collections.js +24 -0
  91. package/srv/utils/crypto.d.ts +16 -0
  92. package/srv/utils/crypto.js +75 -0
  93. package/srv/utils/db-sanitize.d.ts +40 -0
  94. package/srv/utils/db-sanitize.js +98 -0
  95. package/srv/utils/error-codes.d.ts +6 -0
  96. package/srv/utils/error-codes.js +6 -0
  97. package/srv/utils/errors.d.ts +12 -0
  98. package/srv/utils/errors.js +45 -0
  99. package/srv/utils/liveness.d.ts +23 -0
  100. package/srv/utils/liveness.js +49 -0
  101. package/srv/utils/mappers.d.ts +27 -0
  102. package/srv/utils/mappers.js +80 -10
  103. package/srv/utils/rate-limiter.d.ts +57 -0
  104. package/srv/utils/rate-limiter.js +126 -0
  105. package/srv/utils/service-events.d.ts +26 -0
  106. package/srv/utils/service-events.js +46 -0
  107. package/srv/utils/tx-request-parsers.d.ts +71 -0
  108. package/srv/utils/tx-request-parsers.js +202 -0
  109. package/srv/utils/tx-utils.d.ts +2 -1
  110. package/srv/utils/tx-utils.js +3 -2
  111. package/srv/utils/types.d.ts +17 -1
  112. package/@cds-models/CardanoODataService/index.d.ts.map +0 -1
  113. package/@cds-models/CardanoODataService/index.js.map +0 -1
  114. package/@cds-models/CardanoODataService/index.ts +0 -776
  115. package/@cds-models/CardanoSignService/index.d.ts.map +0 -1
  116. package/@cds-models/CardanoSignService/index.js.map +0 -1
  117. package/@cds-models/CardanoSignService/index.ts +0 -569
  118. package/@cds-models/CardanoTransactionService/index.d.ts.map +0 -1
  119. package/@cds-models/CardanoTransactionService/index.js.map +0 -1
  120. package/@cds-models/CardanoTransactionService/index.ts +0 -526
  121. package/@cds-models/_/index.d.ts.map +0 -1
  122. package/@cds-models/_/index.js.map +0 -1
  123. package/@cds-models/_/index.ts +0 -96
  124. package/@cds-models/cds/outbox/index.ts +0 -27
  125. package/@cds-models/index.d.ts.map +0 -1
  126. package/@cds-models/index.js.map +0 -1
  127. package/@cds-models/index.ts +0 -245
  128. package/@cds-models/odatano/cardano/index.d.ts.map +0 -1
  129. package/@cds-models/odatano/cardano/index.js.map +0 -1
  130. package/@cds-models/odatano/cardano/index.ts +0 -789
  131. package/@cds-models/sap/common/index.d.ts.map +0 -1
  132. package/@cds-models/sap/common/index.js.map +0 -1
  133. package/@cds-models/sap/common/index.ts +0 -249
@@ -0,0 +1,199 @@
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
+ const cds_1 = __importDefault(require("@sap/cds"));
7
+ const backend_request_handler_1 = require("./utils/backend-request-handler");
8
+ const errors_1 = require("./utils/errors");
9
+ const error_codes_1 = require("./utils/error-codes");
10
+ const validators_1 = require("./utils/validators");
11
+ const wallet_worker_1 = require("./blockchain/wallet-worker");
12
+ const job_store_1 = require("./blockchain/wallet-worker/job-store");
13
+ const server_1 = require("./server");
14
+ const logger = cds_1.default.log('CardanoWorkerService');
15
+ /**
16
+ * CardanoWorkerService handlers — thin control surface over the wallet-worker
17
+ * singleton (srv/blockchain/wallet-worker). Engine logic lives there; this only
18
+ * validates inputs, inserts/reads job rows and starts/stops the worker.
19
+ *
20
+ * Validation rejections happen BEFORE handleRequest (project convention); the
21
+ * job INSERT runs on the request's ambient transaction (NIGHTGATE lesson 1).
22
+ */
23
+ function isAdmin(req) {
24
+ return req.user?.is?.('Admin') ?? false;
25
+ }
26
+ /**
27
+ * A job on an HSM-backed wallet spends the same server-held key as the synchronous
28
+ * SignWithHsm path, so it inherits that path's role gate (enforceHsmRole in
29
+ * cardano-sign-service.ts) — 'authenticated-user' alone must not reach the HSM.
30
+ * Returns the role the caller is missing, or null when the wallet is not HSM-backed,
31
+ * no role is configured, or the caller holds it.
32
+ */
33
+ function missingHsmRole(req, signerType) {
34
+ if (signerType !== 'hsm')
35
+ return null;
36
+ const requiresRole = (0, server_1.getHsmConfig)()?.requiresRole;
37
+ if (!requiresRole || req.user?.is(requiresRole))
38
+ return null;
39
+ return requiresRole;
40
+ }
41
+ function toJobStatus(job) {
42
+ return {
43
+ jobId: job.ID,
44
+ walletId: job.walletId,
45
+ kind: job.kind,
46
+ status: job.status,
47
+ attempt: job.attempt,
48
+ txHash: job.txHash,
49
+ fee: job.fee != null ? String(job.fee) : null,
50
+ errorCode: job.errorCode,
51
+ errorMessage: job.errorMessage,
52
+ submittedAt: job.submittedAt,
53
+ confirmedAt: job.confirmedAt,
54
+ finishedAt: job.finishedAt,
55
+ };
56
+ }
57
+ module.exports = (srv) => {
58
+ // SubmitWalletJob — queue an async transaction job; returns the jobId immediately.
59
+ srv.on('SubmitWalletJob', async (req) => {
60
+ const { walletId, kind, requestJson, idempotencyKey, priority, notBefore } = req.data;
61
+ if (!walletId?.trim())
62
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'walletId is required', 'walletId');
63
+ if (!kind || !job_store_1.WALLET_JOB_KINDS.includes(kind)) {
64
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', `Invalid kind "${String(kind)}" — must be one of: ${job_store_1.WALLET_JOB_KINDS.join(', ')}`, 'kind');
65
+ }
66
+ if (!requestJson?.trim())
67
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'requestJson is required', 'requestJson');
68
+ const jsonResult = (0, validators_1.validateJsonWithLimits)(requestJson, 'requestJson');
69
+ if (!jsonResult.valid)
70
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', jsonResult.error, 'requestJson');
71
+ if (priority != null && (!Number.isInteger(priority) || priority < 0 || priority > 10_000)) {
72
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'priority must be an integer between 0 and 10000', 'priority');
73
+ }
74
+ if (notBefore != null && Number.isNaN(Date.parse(String(notBefore)))) {
75
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'notBefore must be a valid timestamp', 'notBefore');
76
+ }
77
+ if (idempotencyKey != null && String(idempotencyKey).length > 100) {
78
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'idempotencyKey exceeds 100 characters', 'idempotencyKey');
79
+ }
80
+ let config;
81
+ try {
82
+ config = (0, server_1.loadWalletWorkerConfigFromEnv)();
83
+ }
84
+ catch (err) {
85
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', err instanceof Error ? err.message : String(err));
86
+ }
87
+ if (!config.enabled) {
88
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'Wallet worker is not enabled — set cds.requires.odatano-core.walletWorker.enabled (or WALLET_WORKER_ENABLED=true) with configured wallets.');
89
+ }
90
+ // Role gate on this instance's config, mirroring the sign service's 403.
91
+ const configuredRole = missingHsmRole(req, config.wallets.find((w) => w.walletId === walletId)?.signerType);
92
+ if (configuredRole) {
93
+ return req.reject(403, `SubmitWalletJob on HSM-backed wallet "${walletId}" requires role '${configuredRole}'`);
94
+ }
95
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
96
+ const wallet = await (0, job_store_1.readWallet)(db, walletId);
97
+ if (!wallet)
98
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', `Unknown wallet "${walletId}" — configured wallets are registered at worker start`, 'walletId');
99
+ if (!wallet.enabled)
100
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', `Wallet "${walletId}" is disabled`, 'walletId');
101
+ // Registered row too: another instance may run the HSM wallet this one has no config for.
102
+ const registeredRole = missingHsmRole(req, wallet.signerType);
103
+ if (registeredRole) {
104
+ throw new errors_1.BackendError(`Wallet "${walletId}" is HSM-backed and requires role '${registeredRole}'`, 403, error_codes_1.ERROR_CODES.FORBIDDEN, undefined, undefined, 'walletId');
105
+ }
106
+ const result = await (0, job_store_1.insertJob)(db, {
107
+ walletId,
108
+ kind: kind,
109
+ request: requestJson,
110
+ idempotencyKey: idempotencyKey ?? null,
111
+ priority,
112
+ notBefore: notBefore ? new Date(notBefore).toISOString() : null,
113
+ maxAttempts: config.defaultMaxAttempts,
114
+ createdBy: req.user?.id ?? null,
115
+ });
116
+ logger.info(`Job ${result.jobId} accepted (wallet=${walletId}, kind=${kind}, dedup=${result.deduplicated})`);
117
+ return result;
118
+ });
119
+ });
120
+ // CancelJob — pending jobs only; scoped to the creator unless Admin.
121
+ srv.on('CancelJob', async (req) => {
122
+ const { jobId } = req.data;
123
+ if (!jobId)
124
+ return (0, errors_1.rejectInvalid)(req, 'CancelJob', 'jobId is required', 'jobId');
125
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
126
+ const job = await (0, job_store_1.getJobById)(db, jobId);
127
+ if (!job || (!isAdmin(req) && job.createdBy !== req.user?.id)) {
128
+ // Same 404 for "not found" and "not yours" — no existence oracle.
129
+ // THROW, don't req.reject: we are inside handleRequest, whose catch would
130
+ // see a plain CAP error and remap it to 500 (mapError). A BackendError
131
+ // carries its status through.
132
+ throw new errors_1.NotFoundError(`Job ${jobId}`);
133
+ }
134
+ const cancelled = await (0, job_store_1.markCancelled)(db, jobId);
135
+ if (!cancelled) {
136
+ return (0, errors_1.rejectInvalid)(req, 'CancelJob', `Job ${jobId} is ${job.status} — only pending jobs can be cancelled`, 'jobId');
137
+ }
138
+ return true;
139
+ });
140
+ });
141
+ // GetJobStatus — scoped to the creator unless Admin.
142
+ srv.on('GetJobStatus', async (req) => {
143
+ const { jobId } = req.data;
144
+ if (!jobId)
145
+ return (0, errors_1.rejectInvalid)(req, 'GetJobStatus', 'jobId is required', 'jobId');
146
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
147
+ const job = await (0, job_store_1.getJobById)(db, jobId);
148
+ if (!job || (!isAdmin(req) && job.createdBy !== req.user?.id)) {
149
+ throw new errors_1.NotFoundError(`Job ${jobId}`); // see CancelJob: reject() here becomes a 500
150
+ }
151
+ return toJobStatus(job);
152
+ });
153
+ });
154
+ // GetWorkerStatus — live summary of the local worker instance.
155
+ srv.on('GetWorkerStatus', async (req) => {
156
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
157
+ const worker = (0, wallet_worker_1.getWalletWorker)();
158
+ const summary = worker?.getStatusSummary() ?? {
159
+ running: false, wallets: [], executing: [], awaitingConfirmation: 0,
160
+ };
161
+ const pending = await (0, job_store_1.findDueJobs)(db, new Date(8640000000000000)); // all pending, ignore notBefore
162
+ return { ...summary, pendingJobs: pending.length };
163
+ });
164
+ });
165
+ // PauseWorker — stop the local instance; queued jobs stay pending.
166
+ srv.on('PauseWorker', async (req) => {
167
+ return (0, backend_request_handler_1.handleRequest)(req, async () => {
168
+ await (0, wallet_worker_1.stopWalletWorker)();
169
+ logger.info('Wallet worker paused via control action');
170
+ return true;
171
+ });
172
+ });
173
+ // ResumeWorker — (re)start the local instance from config. Gated on enabled,
174
+ // mirroring resumeCrawler.
175
+ srv.on('ResumeWorker', async (req) => {
176
+ let config;
177
+ try {
178
+ config = (0, server_1.loadWalletWorkerConfigFromEnv)();
179
+ }
180
+ catch (err) {
181
+ return (0, errors_1.rejectInvalid)(req, 'ResumeWorker', err instanceof Error ? err.message : String(err));
182
+ }
183
+ if (!config.enabled) {
184
+ return (0, errors_1.rejectInvalid)(req, 'ResumeWorker', 'Wallet worker is not enabled — set cds.requires.odatano-core.walletWorker.enabled (or WALLET_WORKER_ENABLED=true) before resuming.');
185
+ }
186
+ return (0, backend_request_handler_1.handleRequest)(req, async () => {
187
+ const client = (0, server_1.getCardanoClient)();
188
+ await (0, wallet_worker_1.startWalletWorker)({
189
+ client,
190
+ indexer: (0, server_1.getCardanoIndexer)(),
191
+ network: client.network,
192
+ config,
193
+ });
194
+ logger.info('Wallet worker resumed via control action');
195
+ return (0, wallet_worker_1.isWalletWorkerRunning)();
196
+ });
197
+ });
198
+ };
199
+ //# sourceMappingURL=cardano-worker-service.js.map
package/srv/server.d.ts CHANGED
@@ -2,6 +2,8 @@ import { CardanoClient, CardanoClientConfig, BackendName, TransactionBuilderName
2
2
  import { CardanoIndexer } from './blockchain/cardano-indexer';
3
3
  import { CardanoTransactionBuilder } from './blockchain/cardano-tx-builder';
4
4
  import type { LedgerProtocolParameters, HsmConfig } from './utils/types';
5
+ import type { CrawlerConfig } from './blockchain/crawler/crawler';
6
+ import type { WalletWorkerConfig } from './blockchain/wallet-worker';
5
7
  /**
6
8
  * Application context holding initialized blockchain components
7
9
  * These are created once during CAP bootstrap and shared across services
@@ -11,6 +13,8 @@ interface AppContext {
11
13
  cardanoIndexer: CardanoIndexer;
12
14
  cardanoTxBuilder: CardanoTransactionBuilder;
13
15
  }
16
+ /** Agent-grant feature switch (AGENT_GRANTS_DESIGN.md); lives in its own module so src/plugin.ts can read it at load. */
17
+ export { loadAgentGrantsConfig, activateAgentGrants } from './utils/agent-grants-config';
14
18
  /**
15
19
  * Get the application context (must be called after bootstrap)
16
20
  * @throws {ProviderUnavailableError} 503 when uninitialized — request handlers using
@@ -86,13 +90,41 @@ export declare function loadConfigFromEnv(): CardanoClientConfig;
86
90
  * @returns HsmConfig or undefined
87
91
  */
88
92
  export declare function loadHsmConfigFromEnv(): HsmConfig | undefined;
93
+ /**
94
+ * Load the chain-crawler configuration from CDS config or environment variables.
95
+ * Returns { enabled:false } when the crawler is not switched on (the default), so
96
+ * existing deployments are unaffected.
97
+ *
98
+ * Plugin mode: cds.requires.odatano-core.crawler.{enabled,startSlot,startBlockHash,...}
99
+ * Env mode: CRAWLER_ENABLED / CRAWLER_START_SLOT / CRAWLER_START_HASH / ...
100
+ */
101
+ export declare function loadCrawlerConfigFromEnv(): CrawlerConfig;
102
+ /**
103
+ * Start the chain crawler if it is enabled and the app context is ready. Never throws
104
+ * (crawler failure must not affect request serving) — errors are logged. Idempotent:
105
+ * startCrawler() is a no-op when one is already running.
106
+ */
107
+ export declare function startCrawlerIfConfigured(): Promise<void>;
108
+ /**
109
+ * Load the wallet-worker configuration from CDS config or environment variables.
110
+ * Returns { enabled:false } when the worker is not switched on (the default).
111
+ *
112
+ * Plugin mode: cds.requires.odatano-core.walletWorker.{enabled,wallets,...}
113
+ * Env mode: WALLET_WORKER_ENABLED / WALLET_WORKER_WALLETS (JSON) / ...
114
+ */
115
+ export declare function loadWalletWorkerConfigFromEnv(): WalletWorkerConfig;
116
+ /**
117
+ * Start the wallet worker if it is enabled and the app context is ready. Never
118
+ * throws (worker failure must not affect request serving) — errors are logged.
119
+ * Idempotent: startWalletWorker() is a no-op when one is already running.
120
+ */
121
+ export declare function startWalletWorkerIfConfigured(): Promise<void>;
89
122
  /**
90
123
  * Re-drive deferred submissions that were claimed (status 'submitting' with
91
124
  * persisted signedTxCbor) but whose detached submit never ran because the
92
125
  * process died first (KNOWN_ISSUES #11, Layer 2). Idempotent — an already
93
126
  * submitted tx finalizes via the TransactionAlreadySubmittedError path.
94
- * Non-fatal.
127
+ * Non-fatal, mirrors startCrawlerIfConfigured/startWalletWorkerIfConfigured.
95
128
  */
96
129
  export declare function redriveInterruptedSubmissionsIfConfigured(): Promise<void>;
97
- export {};
98
130
  //# sourceMappingURL=server.d.ts.map
package/srv/server.js CHANGED
@@ -1,41 +1,9 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
36
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
4
  };
38
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.activateAgentGrants = exports.loadAgentGrantsConfig = void 0;
39
7
  exports.getAppContext = getAppContext;
40
8
  exports.getCardanoIndexer = getCardanoIndexer;
41
9
  exports.getCardanoClient = getCardanoClient;
@@ -47,6 +15,10 @@ exports.createTestContext = createTestContext;
47
15
  exports.shutdownAppContext = shutdownAppContext;
48
16
  exports.loadConfigFromEnv = loadConfigFromEnv;
49
17
  exports.loadHsmConfigFromEnv = loadHsmConfigFromEnv;
18
+ exports.loadCrawlerConfigFromEnv = loadCrawlerConfigFromEnv;
19
+ exports.startCrawlerIfConfigured = startCrawlerIfConfigured;
20
+ exports.loadWalletWorkerConfigFromEnv = loadWalletWorkerConfigFromEnv;
21
+ exports.startWalletWorkerIfConfigured = startWalletWorkerIfConfigured;
50
22
  exports.redriveInterruptedSubmissionsIfConfigured = redriveInterruptedSubmissionsIfConfigured;
51
23
  const cds_1 = __importDefault(require("@sap/cds"));
52
24
  const cardano_client_1 = require("./blockchain/cardano-client");
@@ -55,10 +27,33 @@ const cardano_tx_builder_1 = require("./blockchain/cardano-tx-builder");
55
27
  const hsm_signer_1 = require("./blockchain/signing/hsm-signer");
56
28
  const errors_1 = require("./utils/errors");
57
29
  const network_context_1 = require("./utils/network-context");
30
+ const db_sanitize_1 = require("./utils/db-sanitize");
31
+ const crawler_1 = require("./blockchain/crawler");
32
+ const wallet_worker_1 = require("./blockchain/wallet-worker");
33
+ const agent_grants_config_1 = require("./utils/agent-grants-config");
58
34
  const process_1 = require("process");
59
35
  const logger = cds_1.default.log('ODATANO');
60
36
  const VALID_NETWORKS = ['mainnet', 'preview', 'preprod'];
61
37
  const VALID_BACKENDS = ['blockfrost', 'koios', 'ogmios'];
38
+ const CRAWLER_LIMITS = {
39
+ batchSize: { min: 1, max: 100 },
40
+ confirmationDepth: { min: 0, max: 2160 },
41
+ pollIntervalMs: { min: 1000, max: 3_600_000 },
42
+ };
43
+ /** Parse an integer without allowing JavaScript's lossy/implicit coercions. */
44
+ function crawlerInteger(raw, name, min, max, defaultValue) {
45
+ if (raw == null)
46
+ return defaultValue;
47
+ if ((typeof raw !== 'number' && typeof raw !== 'string')
48
+ || (typeof raw === 'string' && raw.trim() === '')) {
49
+ throw new errors_1.ConfigError(`Invalid ${name} "${String(raw)}". Must be an integer between ${min} and ${max}.`);
50
+ }
51
+ const parsed = typeof raw === 'number' ? raw : Number(raw);
52
+ if (!Number.isSafeInteger(parsed) || parsed < min || parsed > max) {
53
+ throw new errors_1.ConfigError(`Invalid ${name} "${String(raw)}". Must be an integer between ${min} and ${max}.`);
54
+ }
55
+ return parsed;
56
+ }
62
57
  let appContext = null;
63
58
  let bootstrapError = null;
64
59
  /**
@@ -77,6 +72,10 @@ async function initializeAppContext(config, protocolParams, hsmConfig) {
77
72
  // Create CardanoTransactionBuilder with the client
78
73
  const cardanoTxBuilder = new cardano_tx_builder_1.CardanoTransactionBuilder(cardanoClient);
79
74
  await cardanoTxBuilder.init(protocolParams);
75
+ // PostgreSQL rejects U+0000 in text/JSON. One db-level `before` hook covers every
76
+ // write of this plugin — crawler bulk UPSERTs and the lazy indexing paths alike.
77
+ if ((0, db_sanitize_1.installDbSanitizer)())
78
+ logger.debug('DB NUL sanitizer installed');
80
79
  // Create CardanoIndexer with client and transaction builder
81
80
  const cardanoIndexer = new cardano_indexer_1.CardanoIndexer(cardanoClient, cardanoTxBuilder);
82
81
  // Initialize HSM signer if configured (failure is non-fatal — won't crash the app)
@@ -99,6 +98,16 @@ async function initializeAppContext(config, protocolParams, hsmConfig) {
99
98
  cardanoTxBuilder,
100
99
  };
101
100
  }
101
+ /** Agent-grant feature switch (AGENT_GRANTS_DESIGN.md); lives in its own module so src/plugin.ts can read it at load. */
102
+ var agent_grants_config_2 = require("./utils/agent-grants-config");
103
+ Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get: function () { return agent_grants_config_2.loadAgentGrantsConfig; } });
104
+ Object.defineProperty(exports, "activateAgentGrants", { enumerable: true, get: function () { return agent_grants_config_2.activateAgentGrants; } });
105
+ // Standalone mode (`cds serve` / `cds watch` in this project): CAP loads
106
+ // cds-plugin.js only from dependencies, so src/plugin.ts never runs here and
107
+ // agent grants would stay off regardless of AGENT_GRANTS_ENABLED. bin/serve.js
108
+ // imports this file before cds.server() instantiates the middlewares, so the
109
+ // auth impl can still be swapped. Idempotent: a no-op after the plugin's call.
110
+ (0, agent_grants_config_1.activateAgentGrants)();
102
111
  /**
103
112
  * Get the application context (must be called after bootstrap)
104
113
  * @throws {ProviderUnavailableError} 503 when uninitialized — request handlers using
@@ -214,6 +223,20 @@ protocolParams) {
214
223
  * Closes all backend connections to allow process to exit cleanly
215
224
  */
216
225
  async function shutdownAppContext() {
226
+ // Stop the wallet worker first — its in-flight submit must not hit a torn-down client.
227
+ try {
228
+ await (0, wallet_worker_1.stopWalletWorker)();
229
+ }
230
+ catch (err) {
231
+ logger.warn('Wallet worker shutdown failed (continuing):', err);
232
+ }
233
+ // Stop the crawler so its in-flight block writes don't hit a torn-down client.
234
+ try {
235
+ await (0, crawler_1.stopCrawler)();
236
+ }
237
+ catch (err) {
238
+ logger.warn('Crawler shutdown failed (continuing):', err);
239
+ }
217
240
  if (appContext) {
218
241
  logger.info('Shutting down application context...');
219
242
  // Shutdown HSM signer if active
@@ -345,18 +368,201 @@ function loadHsmConfigFromEnv() {
345
368
  requiresRole,
346
369
  };
347
370
  }
371
+ /**
372
+ * Load the chain-crawler configuration from CDS config or environment variables.
373
+ * Returns { enabled:false } when the crawler is not switched on (the default), so
374
+ * existing deployments are unaffected.
375
+ *
376
+ * Plugin mode: cds.requires.odatano-core.crawler.{enabled,startSlot,startBlockHash,...}
377
+ * Env mode: CRAWLER_ENABLED / CRAWLER_START_SLOT / CRAWLER_START_HASH / ...
378
+ */
379
+ function loadCrawlerConfigFromEnv() {
380
+ const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
381
+ const c = cdsConfig.crawler ?? {};
382
+ // A CDS value, including explicit `false`, wins over the environment.
383
+ const enabledRaw = c.enabled !== undefined ? c.enabled : process_1.env.CRAWLER_ENABLED;
384
+ let enabled = false;
385
+ if (enabledRaw === true || enabledRaw === 'true') {
386
+ enabled = true;
387
+ }
388
+ else if (enabledRaw !== undefined && enabledRaw !== false && enabledRaw !== 'false') {
389
+ throw new errors_1.ConfigError(`Invalid CRAWLER_ENABLED "${String(enabledRaw)}". Must be true or false.`);
390
+ }
391
+ const startSlot = crawlerInteger(c.startSlot ?? process_1.env.CRAWLER_START_SLOT, 'CRAWLER_START_SLOT', 0, Number.MAX_SAFE_INTEGER);
392
+ const startHeight = crawlerInteger(c.startHeight ?? process_1.env.CRAWLER_START_HEIGHT, 'CRAWLER_START_HEIGHT', 0, Number.MAX_SAFE_INTEGER);
393
+ const startBlockHashRaw = c.startBlockHash ?? process_1.env.CRAWLER_START_HASH;
394
+ if (startBlockHashRaw != null && (typeof startBlockHashRaw !== 'string' || !/^[0-9a-f]{64}$/i.test(startBlockHashRaw.trim()))) {
395
+ throw new errors_1.ConfigError('Invalid CRAWLER_START_HASH. Must be exactly 64 hexadecimal characters.');
396
+ }
397
+ const startBlockHash = startBlockHashRaw?.trim() || undefined;
398
+ const source = (c.source ?? process_1.env.CRAWLER_SOURCE ?? 'auto');
399
+ const batchSize = crawlerInteger(c.batchSize ?? process_1.env.CRAWLER_BATCH_SIZE, 'CRAWLER_BATCH_SIZE', CRAWLER_LIMITS.batchSize.min, CRAWLER_LIMITS.batchSize.max, 20);
400
+ const confirmationDepth = crawlerInteger(c.confirmationDepth ?? process_1.env.CRAWLER_CONFIRMATION_DEPTH, 'CRAWLER_CONFIRMATION_DEPTH', CRAWLER_LIMITS.confirmationDepth.min, CRAWLER_LIMITS.confirmationDepth.max, 3);
401
+ 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);
402
+ if (enabled && (startSlot == null || Number.isNaN(startSlot) || !startBlockHash)) {
403
+ throw new errors_1.ConfigError('Crawler is enabled but no start block is configured — set crawler.startSlot + crawler.startBlockHash ' +
404
+ '(or CRAWLER_START_SLOT + CRAWLER_START_HASH).');
405
+ }
406
+ if (!['ogmios', 'pagination', 'auto'].includes(source)) {
407
+ throw new errors_1.ConfigError(`Invalid CRAWLER_SOURCE "${source}". Must be one of: ogmios, pagination, auto.`);
408
+ }
409
+ return { enabled, startSlot, startBlockHash, startHeight, source, batchSize, confirmationDepth, pollIntervalMs };
410
+ }
411
+ /**
412
+ * Start the chain crawler if it is enabled and the app context is ready. Never throws
413
+ * (crawler failure must not affect request serving) — errors are logged. Idempotent:
414
+ * startCrawler() is a no-op when one is already running.
415
+ */
416
+ async function startCrawlerIfConfigured() {
417
+ if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
418
+ return;
419
+ let config;
420
+ try {
421
+ config = loadCrawlerConfigFromEnv();
422
+ }
423
+ catch (err) {
424
+ logger.error('Invalid crawler configuration — crawler not started:', err);
425
+ return;
426
+ }
427
+ if (!config.enabled)
428
+ return;
429
+ try {
430
+ await (0, crawler_1.startCrawler)({
431
+ client: appContext.cardanoClient,
432
+ indexer: appContext.cardanoIndexer,
433
+ network: appContext.cardanoClient.network,
434
+ config,
435
+ });
436
+ logger.info(`Chain crawler started (source=${config.source}, start=${config.startBlockHash})`);
437
+ }
438
+ catch (err) {
439
+ logger.error('Failed to start chain crawler (non-fatal):', err);
440
+ }
441
+ }
442
+ const WALLET_WORKER_LIMITS = {
443
+ maxConcurrentWallets: { min: 1, max: 64 },
444
+ confirmationDepth: { min: 1, max: 2160 },
445
+ confirmationTimeoutMs: { min: 30_000, max: 86_400_000 },
446
+ pollIntervalMs: { min: 500, max: 3_600_000 },
447
+ maxAttempts: { min: 1, max: 10 },
448
+ };
449
+ /**
450
+ * Load the wallet-worker configuration from CDS config or environment variables.
451
+ * Returns { enabled:false } when the worker is not switched on (the default).
452
+ *
453
+ * Plugin mode: cds.requires.odatano-core.walletWorker.{enabled,wallets,...}
454
+ * Env mode: WALLET_WORKER_ENABLED / WALLET_WORKER_WALLETS (JSON) / ...
455
+ */
456
+ function loadWalletWorkerConfigFromEnv() {
457
+ const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
458
+ const w = cdsConfig.walletWorker ?? {};
459
+ const enabledRaw = w.enabled !== undefined ? w.enabled : process_1.env.WALLET_WORKER_ENABLED;
460
+ let enabled = false;
461
+ if (enabledRaw === true || enabledRaw === 'true') {
462
+ enabled = true;
463
+ }
464
+ else if (enabledRaw !== undefined && enabledRaw !== false && enabledRaw !== 'false') {
465
+ throw new errors_1.ConfigError(`Invalid WALLET_WORKER_ENABLED "${String(enabledRaw)}". Must be true or false.`);
466
+ }
467
+ let walletsRaw = w.wallets ?? undefined;
468
+ if (walletsRaw === undefined && process_1.env.WALLET_WORKER_WALLETS) {
469
+ try {
470
+ walletsRaw = JSON.parse(process_1.env.WALLET_WORKER_WALLETS);
471
+ }
472
+ catch {
473
+ throw new errors_1.ConfigError('Invalid WALLET_WORKER_WALLETS — must be a JSON array of { walletId, signerType, keyEnv? }.');
474
+ }
475
+ }
476
+ const wallets = [];
477
+ if (walletsRaw !== undefined) {
478
+ if (!Array.isArray(walletsRaw)) {
479
+ throw new errors_1.ConfigError('Invalid walletWorker.wallets — must be an array of { walletId, signerType, keyEnv? }.');
480
+ }
481
+ for (const entry of walletsRaw) {
482
+ const walletId = typeof entry?.walletId === 'string' ? entry.walletId.trim() : '';
483
+ const signerType = entry?.signerType;
484
+ if (!walletId || (signerType !== 'hsm' && signerType !== 'software')) {
485
+ throw new errors_1.ConfigError(`Invalid wallet entry ${JSON.stringify(entry)} — walletId and signerType (hsm|software) are required.`);
486
+ }
487
+ if (signerType === 'software' && (typeof entry.keyEnv !== 'string' || !entry.keyEnv.trim())) {
488
+ throw new errors_1.ConfigError(`Wallet "${walletId}" is signerType=software but has no keyEnv (name of the env var holding the signing key).`);
489
+ }
490
+ if (wallets.some((existing) => existing.walletId === walletId)) {
491
+ throw new errors_1.ConfigError(`Duplicate walletId "${walletId}" in walletWorker.wallets.`);
492
+ }
493
+ wallets.push({ walletId, signerType, keyEnv: entry.keyEnv });
494
+ }
495
+ }
496
+ 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);
497
+ 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);
498
+ 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);
499
+ 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);
500
+ 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);
501
+ const resubmitRaw = w.resubmitOnRollback !== undefined ? w.resubmitOnRollback : process_1.env.WALLET_WORKER_RESUBMIT_ON_ROLLBACK;
502
+ let resubmitOnRollback = true;
503
+ if (resubmitRaw === false || resubmitRaw === 'false') {
504
+ resubmitOnRollback = false;
505
+ }
506
+ else if (resubmitRaw !== undefined && resubmitRaw !== true && resubmitRaw !== 'true') {
507
+ throw new errors_1.ConfigError(`Invalid WALLET_WORKER_RESUBMIT_ON_ROLLBACK "${String(resubmitRaw)}". Must be true or false.`);
508
+ }
509
+ if (enabled && wallets.length === 0) {
510
+ throw new errors_1.ConfigError('Wallet worker is enabled but no wallets are configured — set walletWorker.wallets (or WALLET_WORKER_WALLETS).');
511
+ }
512
+ return {
513
+ enabled,
514
+ wallets,
515
+ maxConcurrentWallets,
516
+ confirmationDepth,
517
+ confirmationTimeoutMs,
518
+ pollIntervalMs,
519
+ defaultMaxAttempts,
520
+ resubmitOnRollback,
521
+ };
522
+ }
523
+ /**
524
+ * Start the wallet worker if it is enabled and the app context is ready. Never
525
+ * throws (worker failure must not affect request serving) — errors are logged.
526
+ * Idempotent: startWalletWorker() is a no-op when one is already running.
527
+ */
528
+ async function startWalletWorkerIfConfigured() {
529
+ if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
530
+ return;
531
+ let config;
532
+ try {
533
+ config = loadWalletWorkerConfigFromEnv();
534
+ }
535
+ catch (err) {
536
+ logger.error('Invalid wallet-worker configuration — worker not started:', err);
537
+ return;
538
+ }
539
+ if (!config.enabled)
540
+ return;
541
+ try {
542
+ await (0, wallet_worker_1.startWalletWorker)({
543
+ client: appContext.cardanoClient,
544
+ indexer: appContext.cardanoIndexer,
545
+ network: appContext.cardanoClient.network,
546
+ config,
547
+ });
548
+ logger.info(`Wallet worker started (wallets=${config.wallets.map((w2) => w2.walletId).join(',')})`);
549
+ }
550
+ catch (err) {
551
+ logger.error('Failed to start wallet worker (non-fatal):', err);
552
+ }
553
+ }
348
554
  /**
349
555
  * Re-drive deferred submissions that were claimed (status 'submitting' with
350
556
  * persisted signedTxCbor) but whose detached submit never ran because the
351
557
  * process died first (KNOWN_ISSUES #11, Layer 2). Idempotent — an already
352
558
  * submitted tx finalizes via the TransactionAlreadySubmittedError path.
353
- * Non-fatal.
559
+ * Non-fatal, mirrors startCrawlerIfConfigured/startWalletWorkerIfConfigured.
354
560
  */
355
561
  async function redriveInterruptedSubmissionsIfConfigured() {
356
562
  if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
357
563
  return;
358
564
  try {
359
- const { redriveInterruptedSubmissions } = await Promise.resolve().then(() => __importStar(require('./blockchain/signing/submission-finalizer')));
565
+ const { redriveInterruptedSubmissions } = require('./blockchain/signing/submission-finalizer');
360
566
  const attempted = await redriveInterruptedSubmissions();
361
567
  if (attempted > 0)
362
568
  logger.info(`Re-drove ${attempted} interrupted deferred submission(s)`);
@@ -394,12 +600,16 @@ cds_1.default.on('served', async () => {
394
600
  // instead of the raw "Application not initialized" Error landing as a generic 500.
395
601
  bootstrapError = err instanceof Error ? err : new Error(String(err));
396
602
  // Write to stderr directly so the cause stays visible even when test runners
397
- // suppress console.error (jest.setup.ts in this repo silences it).
603
+ // suppress console.error (vitest.setup.ts in this repo silences it).
398
604
  const where = config ? `backends={${config.backends.join(',')}} network=${config.network}` : 'config load';
399
605
  const msg = err instanceof Error ? `${err.name}: ${err.message}\n${err.stack ?? ''}` : String(err);
400
606
  process.stderr.write(`[ODATANO] Failed to initialize blockchain components — ${where}\n${msg}\n`);
401
607
  logger.error('Failed to initialize blockchain components:', err);
402
608
  }
609
+ // Start the pre-sync crawler if configured (standalone mode). Non-fatal.
610
+ await startCrawlerIfConfigured();
611
+ // Start the wallet worker if configured (standalone mode). Non-fatal.
612
+ await startWalletWorkerIfConfigured();
403
613
  // Re-drive deferred submissions interrupted by a restart (standalone mode). Non-fatal.
404
614
  await redriveInterruptedSubmissionsIfConfigured();
405
615
  });