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

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 (151) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +14 -3
  2. package/@cds-models/CardanoBackendService/index.js +1 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +98 -0
  4. package/@cds-models/CardanoIndexerService/index.js +10 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +3 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +13 -0
  7. package/@cds-models/CardanoSignService/index.js +1 -0
  8. package/@cds-models/CardanoTransactionService/index.d.ts +12 -0
  9. package/@cds-models/CardanoTransactionService/index.js +1 -0
  10. package/@cds-models/CardanoWorkerService/index.d.ts +28 -0
  11. package/@cds-models/CardanoWorkerService/index.js +2 -0
  12. package/@cds-models/index.d.ts +13 -3
  13. package/@cds-models/index.js +4 -3
  14. package/@cds-models/odatano/cardano/index.d.ts +14 -0
  15. package/README.md +45 -149
  16. package/db/schema.cds +63 -10
  17. package/db/types.cds +10 -0
  18. package/package.json +7 -44
  19. package/scripts/deploy-schema.mjs +113 -0
  20. package/scripts/migrate-schema.mjs +209 -15
  21. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -4
  22. package/srv/blockchain/backends/blockfrost-backend.js +61 -45
  23. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  24. package/srv/blockchain/backends/call-signal.js +22 -0
  25. package/srv/blockchain/backends/cardano-backend.d.ts +6 -3
  26. package/srv/blockchain/backends/koios-backend.d.ts +9 -6
  27. package/srv/blockchain/backends/koios-backend.js +145 -207
  28. package/srv/blockchain/backends/odatano-backend.d.ts +2 -1
  29. package/srv/blockchain/backends/odatano-backend.js +51 -9
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +1 -2
  31. package/srv/blockchain/backends/ogmios-backend.js +82 -48
  32. package/srv/blockchain/cardano-client.d.ts +15 -5
  33. package/srv/blockchain/cardano-client.js +143 -71
  34. package/srv/blockchain/cardano-indexer.d.ts +27 -16
  35. package/srv/blockchain/cardano-indexer.js +223 -102
  36. package/srv/blockchain/circuit-breaker.d.ts +1 -0
  37. package/srv/blockchain/circuit-breaker.js +6 -0
  38. package/srv/blockchain/crawler/account-snapshots.js +22 -2
  39. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +2 -0
  40. package/srv/blockchain/crawler/asset-decimals-backfill.js +29 -29
  41. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +3 -0
  42. package/srv/blockchain/crawler/asset-registry-backfill.js +4 -0
  43. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  44. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  45. package/srv/blockchain/crawler/certificate-backfill.d.ts +4 -0
  46. package/srv/blockchain/crawler/certificate-backfill.js +15 -3
  47. package/srv/blockchain/crawler/crawler.d.ts +22 -1
  48. package/srv/blockchain/crawler/crawler.js +223 -24
  49. package/srv/blockchain/crawler/credential-backfill.d.ts +2 -0
  50. package/srv/blockchain/crawler/credential-backfill.js +43 -66
  51. package/srv/blockchain/crawler/input-asset-copies.d.ts +4 -4
  52. package/srv/blockchain/crawler/input-asset-copies.js +17 -27
  53. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  54. package/srv/blockchain/crawler/key-pages.js +48 -0
  55. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +6 -0
  56. package/srv/blockchain/crawler/metadata-position-backfill.js +23 -19
  57. package/srv/blockchain/crawler/output-datum-backfill.d.ts +3 -1
  58. package/srv/blockchain/crawler/output-datum-backfill.js +8 -18
  59. package/srv/blockchain/crawler/sync-state.d.ts +5 -1
  60. package/srv/blockchain/crawler/sync-state.js +63 -106
  61. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  62. package/srv/blockchain/crawler/transaction-backfill.js +6 -13
  63. package/srv/blockchain/crawler/utxo-set-import.js +2 -2
  64. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  65. package/srv/blockchain/crawler/window-plan.js +59 -0
  66. package/srv/blockchain/ledger-state.d.ts +2 -2
  67. package/srv/blockchain/ledger-state.js +139 -37
  68. package/srv/blockchain/signing/external-signer.js +5 -5
  69. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  70. package/srv/blockchain/signing/failed-recheck.js +135 -0
  71. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  72. package/srv/blockchain/signing/landing-proof.js +224 -0
  73. package/srv/blockchain/signing/signature-verifier.js +10 -13
  74. package/srv/blockchain/signing/submission-finalizer.d.ts +17 -3
  75. package/srv/blockchain/signing/submission-finalizer.js +90 -29
  76. package/srv/blockchain/stored-chain.d.ts +1 -2
  77. package/srv/blockchain/stored-chain.js +36 -15
  78. package/srv/blockchain/transaction-building/buildooor-tx.js +16 -10
  79. package/srv/blockchain/transaction-presence.d.ts +8 -1
  80. package/srv/blockchain/transaction-presence.js +12 -12
  81. package/srv/blockchain/wallet-worker/build-request.d.ts +6 -6
  82. package/srv/blockchain/wallet-worker/build-request.js +35 -365
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +23 -2
  84. package/srv/blockchain/wallet-worker/confirmation-tracker.js +140 -23
  85. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  86. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  87. package/srv/blockchain/wallet-worker/job-store.d.ts +28 -2
  88. package/srv/blockchain/wallet-worker/job-store.js +107 -80
  89. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +21 -2
  90. package/srv/blockchain/wallet-worker/wallet-worker.js +241 -57
  91. package/srv/cardano-agent-service.cds +1 -1
  92. package/srv/cardano-agent-service.js +8 -0
  93. package/srv/cardano-backend-service.cds +4 -1
  94. package/srv/cardano-backend-service.js +26 -9
  95. package/srv/cardano-indexer-service.cds +448 -387
  96. package/srv/cardano-indexer-service.js +226 -281
  97. package/srv/cardano-service.cds +7 -5
  98. package/srv/cardano-service.js +404 -69
  99. package/srv/cardano-sign-service.cds +11 -1
  100. package/srv/cardano-sign-service.js +161 -108
  101. package/srv/cardano-tx-service.cds +23 -12
  102. package/srv/cardano-tx-service.js +105 -604
  103. package/srv/cardano-worker-service.cds +25 -2
  104. package/srv/cardano-worker-service.js +56 -4
  105. package/srv/config.d.ts +4 -0
  106. package/srv/config.js +10 -0
  107. package/srv/server.js +5 -7
  108. package/srv/utils/agent-access.d.ts +4 -2
  109. package/srv/utils/agent-access.js +26 -7
  110. package/srv/utils/agent-grants.d.ts +1 -1
  111. package/srv/utils/agent-grants.js +7 -8
  112. package/srv/utils/agent-token-auth.js +45 -5
  113. package/srv/utils/build-request.d.ts +52 -0
  114. package/srv/utils/build-request.js +487 -0
  115. package/srv/utils/collections.d.ts +1 -0
  116. package/srv/utils/collections.js +11 -0
  117. package/srv/utils/const.d.ts +10 -2
  118. package/srv/utils/const.js +13 -6
  119. package/srv/utils/crypto.js +5 -4
  120. package/srv/utils/db-indexes.d.ts +5 -1
  121. package/srv/utils/db-indexes.js +79 -14
  122. package/srv/utils/db-kind.d.ts +23 -0
  123. package/srv/utils/db-kind.js +42 -0
  124. package/srv/utils/detached-run.d.ts +41 -0
  125. package/srv/utils/detached-run.js +101 -0
  126. package/srv/utils/epoch-slots.d.ts +1 -0
  127. package/srv/utils/epoch-slots.js +7 -0
  128. package/srv/utils/error-codes.d.ts +4 -0
  129. package/srv/utils/error-codes.js +4 -0
  130. package/srv/utils/errors.d.ts +10 -1
  131. package/srv/utils/errors.js +51 -9
  132. package/srv/utils/lease.d.ts +20 -0
  133. package/srv/utils/lease.js +62 -0
  134. package/srv/utils/mappers.d.ts +9 -0
  135. package/srv/utils/mappers.js +57 -67
  136. package/srv/utils/navigation.d.ts +17 -0
  137. package/srv/utils/navigation.js +52 -0
  138. package/srv/utils/network-context.d.ts +0 -1
  139. package/srv/utils/network-context.js +8 -3
  140. package/srv/utils/pg-inline-json.js +3 -3
  141. package/srv/utils/pg-order-nulls.js +3 -3
  142. package/srv/utils/resolution.d.ts +13 -0
  143. package/srv/utils/resolution.js +47 -0
  144. package/srv/utils/row-values.d.ts +7 -0
  145. package/srv/utils/row-values.js +27 -0
  146. package/srv/utils/tx-build-helper.d.ts +15 -0
  147. package/srv/utils/tx-build-helper.js +28 -13
  148. package/srv/utils/types.d.ts +36 -44
  149. package/srv/utils/types.js +1 -17
  150. package/srv/utils/validators.d.ts +2 -2
  151. package/srv/utils/validators.js +14 -25
@@ -1,4 +1,4 @@
1
- using { WalletJobKind } from '../db/types';
1
+ using { WalletJobKind, ResolvedOutcome } from '../db/types';
2
2
  using {odatano.cardano as db} from '../db/schema';
3
3
 
4
4
  // Async wallet jobs signed with server-held keys, which are never accepted or returned here.
@@ -44,6 +44,8 @@ service CardanoWorkerService @(impl: './cardano-worker-service') {
44
44
  submittedAt : Timestamp;
45
45
  confirmedAt : Timestamp;
46
46
  finishedAt : Timestamp;
47
+ resolution : String(500);
48
+ invalidationTxHash : String(64);
47
49
  }
48
50
 
49
51
  @title : 'Worker Status'
@@ -53,6 +55,7 @@ service CardanoWorkerService @(impl: './cardano-worker-service') {
53
55
  executing : many String;
54
56
  awaitingConfirmation : Integer;
55
57
  pendingJobs : Integer;
58
+ unresolvedJobs : Integer; // jobs an operator has to resolve (ResolveJob)
56
59
  }
57
60
 
58
61
  /** Terminal job outcome. Subscribe in process, or wait over HTTP with GetJobStatus(waitMs). */
@@ -72,6 +75,15 @@ service CardanoWorkerService @(impl: './cardano-worker-service') {
72
75
  errorMessage : String(500);
73
76
  }
74
77
 
78
+ /** The transaction can no longer land and nothing shows whether it did; ResolveJob settles it. */
79
+ event jobUnresolved {
80
+ jobId : UUID;
81
+ walletId : String(50);
82
+ kind : String(12);
83
+ txHash : String(64);
84
+ errorMessage : String(500);
85
+ }
86
+
75
87
  @title : 'Submit Wallet Job'
76
88
  @description: 'Queue an asynchronous transaction job for a worker wallet. Returns immediately with a jobId; poll GetJobStatus for the outcome. The request JSON is the same payload shape as the corresponding Build* action; senderAddress is always overridden with the wallet address. A retry with the same idempotencyKey and request returns the job that holds the key; another request under that key is a 409.'
77
89
  @odatano.agent: 'operator'
@@ -92,7 +104,7 @@ service CardanoWorkerService @(impl: './cardano-worker-service') {
92
104
  ) returns Boolean;
93
105
 
94
106
  @title : 'Get Job Status'
95
- @description: 'Current lifecycle state of a wallet job (non-admins: own jobs only). With waitMs the call answers as soon as the job is confirmed, failed or cancelled, or after that time with the state it has then. Keep waitMs below the timeout of the proxies in front of the service.'
107
+ @description: 'Current lifecycle state of a wallet job (non-admins: own jobs only). With waitMs the call answers as soon as the job is confirmed, failed, cancelled or unresolved, or after that time with the state it has then. Keep waitMs below the timeout of the proxies in front of the service.'
96
108
  @odatano.agent: 'operator'
97
109
  function GetJobStatus(
98
110
  @title: 'Job Id' jobId : UUID,
@@ -104,6 +116,17 @@ service CardanoWorkerService @(impl: './cardano-worker-service') {
104
116
  @odatano.agent: 'operator'
105
117
  function GetWorkerStatus() returns WorkerStatus;
106
118
 
119
+ @title : 'Resolve Job'
120
+ @description: 'Settle an unresolved job after reading the chain: confirmed when its transaction is on chain with passing scripts, failed when it is not and can no longer land. failed is refused with 409 while the transaction is not expired and an input of it is unspent. txHash, when given, must be the job transaction. The job and its submission record follow the outcome; the job keeps its idempotency key either way.'
121
+ @requires : 'Admin'
122
+ @odatano.agent: 'operator'
123
+ action ResolveJob(
124
+ @title: 'Job Id' jobId : UUID not null,
125
+ @title: 'Outcome' @assert.range outcome : ResolvedOutcome not null,
126
+ @title: 'Transaction Hash' txHash : String(64),
127
+ @title: 'Note' note : String(300)
128
+ ) returns JobStatus;
129
+
107
130
  @title : 'Pause Worker'
108
131
  @description: 'Stop the local worker instance (finishes in-flight steps; queued jobs stay pending).'
109
132
  @requires : 'Admin'
@@ -9,13 +9,20 @@ const errors_1 = require("./utils/errors");
9
9
  const error_codes_1 = require("./utils/error-codes");
10
10
  const validators_1 = require("./utils/validators");
11
11
  const result_numbers_1 = require("./utils/result-numbers");
12
+ const mappers_1 = require("./utils/mappers");
12
13
  const wallet_worker_1 = require("./blockchain/wallet-worker");
13
14
  const job_store_1 = require("./blockchain/wallet-worker/job-store");
14
15
  const server_1 = require("./server");
15
16
  const config_1 = require("./config");
17
+ const build_request_1 = require("./blockchain/wallet-worker/build-request");
18
+ const network_context_1 = require("./utils/network-context");
16
19
  const CardanoWorkerService_1 = require("#cds-models/CardanoWorkerService");
20
+ const resolution_1 = require("./utils/resolution");
21
+ const tx_utils_1 = require("./utils/tx-utils");
22
+ const cardano_1 = require("#cds-models/odatano/cardano");
23
+ const service_events_1 = require("./utils/service-events");
17
24
  const logger = cds_1.default.log('CardanoWorkerService');
18
- const TERMINAL_JOB_STATUS = new Set(['confirmed', 'failed', 'cancelled']);
25
+ const TERMINAL_JOB_STATUS = new Set(['confirmed', 'failed', 'cancelled', 'unresolved']);
19
26
  const JOB_WAIT_POLL_MS = 1000;
20
27
  function isAdmin(req) {
21
28
  return req.user?.is?.('Admin') ?? false;
@@ -39,6 +46,8 @@ function toJobStatus(job) {
39
46
  submittedAt: job.submittedAt,
40
47
  confirmedAt: job.confirmedAt,
41
48
  finishedAt: job.finishedAt,
49
+ resolution: job.resolution,
50
+ invalidationTxHash: job.invalidationTxHash,
42
51
  };
43
52
  }
44
53
  /** CardanoWorkerService handlers: job submission and status, worker control. */
@@ -57,12 +66,23 @@ module.exports = (srv) => {
57
66
  const jsonResult = (0, validators_1.validateJsonWithLimits)(requestJson, 'requestJson');
58
67
  if (!jsonResult.valid)
59
68
  return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', jsonResult.error, 'requestJson');
69
+ const request = (0, build_request_1.parseJobRequest)(requestJson);
70
+ if (!request)
71
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'requestJson must be a JSON object', 'requestJson');
60
72
  if (notBefore != null && Number.isNaN(Date.parse(String(notBefore)))) {
61
73
  return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'notBefore must be a valid timestamp', 'notBefore');
62
74
  }
63
75
  if (idempotencyKey != null && String(idempotencyKey).length > 100) {
64
76
  return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'idempotencyKey exceeds 100 characters', 'idempotencyKey');
65
77
  }
78
+ if (kind === 'submitSigned') {
79
+ const network = (0, network_context_1.getActiveNetwork)();
80
+ if (!network)
81
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'No network is configured');
82
+ const problem = (0, build_request_1.submitSignedProblem)(request, network);
83
+ if (problem)
84
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', problem, 'requestJson');
85
+ }
66
86
  let config;
67
87
  try {
68
88
  config = (0, config_1.loadWalletWorkerConfigFromEnv)();
@@ -76,7 +96,7 @@ module.exports = (srv) => {
76
96
  // Role gate on this instance's config, mirroring the sign service's 403.
77
97
  const configuredRole = missingWalletRole(req, config.wallets.find((w) => w.walletId === walletId));
78
98
  if (configuredRole) {
79
- return req.reject(403, `SubmitWalletJob on wallet "${walletId}" requires role '${configuredRole}'`);
99
+ return (0, mappers_1.mapError)(req, new errors_1.BackendError(`SubmitWalletJob on wallet "${walletId}" requires role '${configuredRole}'`, 403, error_codes_1.ERROR_CODES.FORBIDDEN, undefined, undefined, 'walletId'), 'SubmitWalletJob');
80
100
  }
81
101
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
82
102
  const wallet = await (0, job_store_1.readWallet)(db, walletId);
@@ -122,8 +142,40 @@ module.exports = (srv) => {
122
142
  return true;
123
143
  });
124
144
  });
145
+ // ResolveJob (Admin): settles an unresolved job as an operator read it on the chain. The job keeps
146
+ // its idempotency key, and the terminal event goes out after the commit.
147
+ srv.on(CardanoWorkerService_1.ResolveJob, async (req) => {
148
+ const { jobId, outcome, txHash, note } = req.data;
149
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
150
+ // read and ask the chain before the request takes its connection
151
+ const job = await (0, tx_utils_1.readOutside)(db, (d) => (0, job_store_1.getJobById)(d, jobId));
152
+ if (!job)
153
+ throw new errors_1.NotFoundError(`Job ${jobId}`);
154
+ if (job.status !== 'unresolved')
155
+ (0, errors_1.rejectInvalid)(req, 'ResolveJob', `Job ${jobId} is ${job.status}: only an unresolved job can be resolved`, 'jobId');
156
+ (0, resolution_1.checkResolvedTxHash)(req, 'ResolveJob', txHash, job.txHash);
157
+ const resolved = outcome === 'confirmed' ? 'confirmed' : 'failed';
158
+ await (0, resolution_1.refuseFailedWhileItCanLand)('ResolveJob', resolved, job.signedTxCbor, (0, server_1.getCardanoClient)());
159
+ if (!(await (0, job_store_1.resolveUnresolvedJob)(db, job.ID, resolved, (0, resolution_1.resolutionNote)(resolved, req.user?.id, note)))) {
160
+ throw (0, resolution_1.resolvedConcurrently)('ResolveJob');
161
+ }
162
+ await (0, job_store_1.bumpWalletStats)(db, job.walletId, resolved);
163
+ // the job's submission record follows its outcome
164
+ if (job.txHash) {
165
+ await db.run(cds_1.default.ql.UPDATE.entity(cardano_1.TransactionSubmissions).set({ status: resolved === 'confirmed' ? 'confirmed' : 'failed' })
166
+ .where({ txHash: job.txHash, status: { in: ['submitted', 'pending', 'unresolved'] } }));
167
+ }
168
+ logger.warn(`Job ${job.ID}: unresolved outcome resolved as ${resolved} by ${req.user?.id ?? 'unknown'}`);
169
+ const after = (await (0, job_store_1.getJobById)(db, job.ID));
170
+ req.on('succeeded', () => (0, service_events_1.emitServiceEvent)('CardanoWorkerService', resolved === 'confirmed' ? 'jobConfirmed' : 'jobFailed', {
171
+ jobId: after.ID, walletId: after.walletId, kind: after.kind, txHash: after.txHash,
172
+ ...(resolved === 'failed' ? { errorCode: after.errorCode, errorMessage: after.errorMessage } : {}),
173
+ }));
174
+ return toJobStatus(after);
175
+ });
176
+ });
125
177
  // GetJobStatus: scoped to the creator unless Admin. With waitMs it answers once the job is
126
- // confirmed, failed or cancelled, or when the time is up. Each read has its own transaction,
178
+ // confirmed, failed, cancelled or unresolved, or when the time is up. Each read has its own transaction,
127
179
  // so a waiting request holds no database connection.
128
180
  srv.on(CardanoWorkerService_1.GetJobStatus, async (req) => {
129
181
  const { jobId, waitMs } = req.data;
@@ -150,7 +202,7 @@ module.exports = (srv) => {
150
202
  const summary = worker?.getStatusSummary() ?? {
151
203
  running: false, wallets: [], executing: [], awaitingConfirmation: 0,
152
204
  };
153
- return { ...summary, pendingJobs: await (0, job_store_1.countPendingJobs)(db) };
205
+ return { ...summary, pendingJobs: await (0, job_store_1.countPendingJobs)(db), unresolvedJobs: await (0, job_store_1.countJobs)(db, 'unresolved') };
154
206
  });
155
207
  });
156
208
  // PauseWorker: stop the local instance; queued jobs stay pending.
package/srv/config.d.ts CHANGED
@@ -73,6 +73,10 @@ export interface AgentGrantsCdsSection {
73
73
  export declare function coreCdsConfig(): OdatanoCoreCdsConfig;
74
74
  /** The network as written, unchecked: for probes that answer even when the configuration is invalid. */
75
75
  export declare function configuredNetworkName(): string;
76
+ /** NODE_ENV=production, read per call like every other setting here. */
77
+ export declare function isProduction(): boolean;
78
+ /** ENCRYPTION_KEY: the secret that encrypts worker signing keys given as `iv:authTag:ciphertext`. */
79
+ export declare function encryptionSecret(): string | undefined;
76
80
  /** SKIP_AUTO_INIT=true: tests mount the services without starting backends, crawler or worker. */
77
81
  export declare function autoInitSkipped(): boolean;
78
82
  /** ODATANO_DETACHED_TX_TIMEOUT_MS when it is a positive number; read per call. */
package/srv/config.js CHANGED
@@ -6,6 +6,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.AGENT_AUTH_IMPL = exports.AGENT_GRANT_USAGE_RETENTION_DAYS_DEFAULT = exports.AGENT_TOKEN_CACHE_MS_DEFAULT = exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = exports.AGENT_GRANTS_DELEGATES = void 0;
7
7
  exports.coreCdsConfig = coreCdsConfig;
8
8
  exports.configuredNetworkName = configuredNetworkName;
9
+ exports.isProduction = isProduction;
10
+ exports.encryptionSecret = encryptionSecret;
9
11
  exports.autoInitSkipped = autoInitSkipped;
10
12
  exports.detachedTxTimeoutMs = detachedTxTimeoutMs;
11
13
  exports.loadConfigFromEnv = loadConfigFromEnv;
@@ -36,6 +38,14 @@ function coreCdsConfig() {
36
38
  function configuredNetworkName() {
37
39
  return String(coreCdsConfig().network || process_1.env.NETWORK || 'preview');
38
40
  }
41
+ /** NODE_ENV=production, read per call like every other setting here. */
42
+ function isProduction() {
43
+ return process_1.env.NODE_ENV === 'production';
44
+ }
45
+ /** ENCRYPTION_KEY: the secret that encrypts worker signing keys given as `iv:authTag:ciphertext`. */
46
+ function encryptionSecret() {
47
+ return process_1.env.ENCRYPTION_KEY || undefined;
48
+ }
39
49
  /** SKIP_AUTO_INIT=true: tests mount the services without starting backends, crawler or worker. */
40
50
  function autoInitSkipped() {
41
51
  return process_1.env.SKIP_AUTO_INIT === 'true';
package/srv/server.js CHANGED
@@ -42,12 +42,10 @@ async function initializeAppContext(config, protocolParams, hsmConfig) {
42
42
  // then the secondary indexes the model cannot declare.
43
43
  (0, pg_order_nulls_1.installPostgresOrderNulls)();
44
44
  (0, pg_inline_json_1.installPostgresInlineJson)();
45
- try {
46
- await (0, db_indexes_1.ensureDbIndexes)();
47
- }
48
- catch (err) {
49
- logger.warn('secondary indexes not ensured (non-fatal):', err);
50
- }
45
+ // PostgreSQL builds its indexes CONCURRENTLY, so the service answers while a large one builds.
46
+ const indexes = (0, db_indexes_1.ensureDbIndexes)().catch((err) => { logger.warn('secondary indexes not ensured (non-fatal):', err); });
47
+ if (cds_1.default.db?.kind !== 'postgres')
48
+ await indexes;
51
49
  const cardanoClient = new cardano_client_1.CardanoClient(config);
52
50
  // Lets leaf utilities (network-aware validators) read the network without importing this module.
53
51
  (0, network_context_1.setActiveNetwork)(config.network);
@@ -130,7 +128,7 @@ async function initializeFromConfig(config, protocolParams, hsmConfig) {
130
128
  }
131
129
  /** Reset the application context (tests only); lets tests inject their own instances. */
132
130
  function resetAppContext(context) {
133
- if (process.env.NODE_ENV === 'production') {
131
+ if ((0, config_1.isProduction)()) {
134
132
  throw new Error('resetAppContext() is not available in production');
135
133
  }
136
134
  appContext = context;
@@ -3,7 +3,9 @@ type Model = {
3
3
  definitions?: Record<string, unknown>;
4
4
  };
5
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[];
6
+ /** The operations a grant may list, as `Service.operation`, in model order. */
7
+ export declare function agentGrantableActions(model?: Model | null | undefined): readonly string[];
8
+ export declare function qualifyGrantName(name: string, model?: Model | null | undefined): string | null;
9
+ export declare function storedGrantNames(name: string, model?: Model | null | undefined): readonly string[];
8
10
  export {};
9
11
  //# sourceMappingURL=agent-access.d.ts.map
@@ -5,6 +5,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.agentAccessOf = agentAccessOf;
7
7
  exports.agentGrantableActions = agentGrantableActions;
8
+ exports.qualifyGrantName = qualifyGrantName;
9
+ exports.storedGrantNames = storedGrantNames;
8
10
  const cds_1 = __importDefault(require("@sap/cds"));
9
11
  const ANNOTATION = '@odatano.agent';
10
12
  const LEVELS = ['read', 'grant', 'operator'];
@@ -34,7 +36,8 @@ function buildTable(model) {
34
36
  for (const [bound, action] of Object.entries(def.actions ?? {}))
35
37
  add(service, bound, action);
36
38
  }
37
- return table;
39
+ const grantable = Object.freeze([...table.operations].filter(([, access]) => access === 'grant').map(([key]) => key));
40
+ return { ...table, grantable };
38
41
  }
39
42
  function tableOf(model) {
40
43
  if (!model)
@@ -56,12 +59,28 @@ function agentAccessOf(service, event, model = cds_1.default.model) {
56
59
  return 'read';
57
60
  return table.operations.get(`${service}.${event}`) ?? 'operator';
58
61
  }
59
- /** Names of the operations a grant may list, in model order. */
62
+ /** The operations a grant may list, as `Service.operation`, in model order. */
60
63
  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)];
64
+ return tableOf(model)?.grantable ?? [];
65
+ }
66
+ /** The service whose operations a new unqualified grant name never means: it takes raw provider calls. */
67
+ const BACKEND_SERVICE = 'CardanoBackendService';
68
+ const named = (grantable, name) => grantable.filter((key) => key.endsWith(`.${name}`));
69
+ // The grantable `Service.operation` a new grant entry names, or null. A name without a service means
70
+ // the operation of that name in the transaction or the sign service.
71
+ function qualifyGrantName(name, model = cds_1.default.model) {
72
+ const grantable = agentGrantableActions(model);
73
+ if (name.includes('.'))
74
+ return grantable.includes(name) ? name : null;
75
+ const matches = named(grantable, name).filter((key) => !key.startsWith(`${BACKEND_SERVICE}.`));
76
+ return matches.length === 1 ? matches[0] : null;
77
+ }
78
+ // What a stored grant entry allows. A name without a service was stored before allow lists were
79
+ // qualified, and it allowed the operation of that name in every service.
80
+ function storedGrantNames(name, model = cds_1.default.model) {
81
+ const grantable = agentGrantableActions(model);
82
+ if (name.includes('.'))
83
+ return grantable.includes(name) ? [name] : [];
84
+ return named(grantable, name);
66
85
  }
67
86
  //# sourceMappingURL=agent-access.js.map
@@ -28,7 +28,7 @@ export declare function hashAgentToken(token: string): string;
28
28
  export declare function agentPrincipalId(grantId: string): string;
29
29
  /** The grant's JSON list column as an array; malformed or absent = empty. */
30
30
  export declare function parseGrantList(raw: string | null | undefined): string[];
31
- /** The stored allow list without names that are no longer grantable. */
31
+ /** The stored allow list as `Service.operation`, without names that are no longer grantable. */
32
32
  export declare function grantedActions(grant: Pick<AgentGrantRow, 'allowedActions'>): string[];
33
33
  /** The grant a request runs under, or null for an ordinary principal. */
34
34
  export declare function agentGrantOf(req: unknown): AgentGrantRow | null;
@@ -108,10 +108,9 @@ function parseGrantList(raw) {
108
108
  return [];
109
109
  }
110
110
  }
111
- /** The stored allow list without names that are no longer grantable. */
111
+ /** The stored allow list as `Service.operation`, without names that are no longer grantable. */
112
112
  function grantedActions(grant) {
113
- const grantable = (0, agent_access_1.agentGrantableActions)();
114
- return parseGrantList(grant.allowedActions).filter((a) => grantable.includes(a));
113
+ return [...new Set(parseGrantList(grant.allowedActions).flatMap((a) => (0, agent_access_1.storedGrantNames)(a)))];
115
114
  }
116
115
  function utcDay(now = new Date()) {
117
116
  return now.toISOString().slice(0, 10);
@@ -219,12 +218,12 @@ function validateGrantInput(input, now = new Date(), context = 'CreateAgentGrant
219
218
  if (!Array.isArray(actions) || actions.length === 0) {
220
219
  throw fail('allowedActions must be a non-empty array', 'allowedActions');
221
220
  }
222
- const grantable = (0, agent_access_1.agentGrantableActions)();
223
- const unknown = actions.filter((a) => !grantable.includes(a));
221
+ const qualified = actions.map((a) => (typeof a === 'string' ? (0, agent_access_1.qualifyGrantName)(a.trim()) : null));
222
+ const unknown = actions.filter((_, i) => qualified[i] === null);
224
223
  if (unknown.length > 0) {
225
- throw fail(`allowedActions contains non-grantable entries: ${unknown.join(', ')}. Grantable: ${grantable.join(', ')}`, 'allowedActions');
224
+ throw fail(`allowedActions contains non-grantable entries: ${unknown.join(', ')}. Grantable: ${(0, agent_access_1.agentGrantableActions)().join(', ')}`, 'allowedActions');
226
225
  }
227
- const uniqueActions = [...new Set(actions)];
226
+ const uniqueActions = [...new Set(qualified)];
228
227
  let maxJobsPerDay = null;
229
228
  if (input.maxJobsPerDay !== undefined && input.maxJobsPerDay !== null) {
230
229
  const n = Number(input.maxJobsPerDay);
@@ -613,7 +612,7 @@ async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown')
613
612
  await touchLastUsed(grant, br);
614
613
  return;
615
614
  }
616
- if (access !== 'grant' || !grantedActions(grant).includes(event)) {
615
+ if (access !== 'grant' || !grantedActions(grant).includes(`${serviceName}.${event}`)) {
617
616
  return req.reject(403, `action '${event}' is not allowed for this agent grant`);
618
617
  }
619
618
  let charge = null;
@@ -1,6 +1,39 @@
1
1
  "use strict";
2
2
  // A token on a service path runs as `agent:<grantId>` with role `agent-grant`. Other paths go to the delegate.
3
3
  // Unknown tokens get 401, expired ones 410. Failed attempts are throttled per client address.
4
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
+ if (k2 === undefined) k2 = k;
6
+ var desc = Object.getOwnPropertyDescriptor(m, k);
7
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8
+ desc = { enumerable: true, get: function() { return m[k]; } };
9
+ }
10
+ Object.defineProperty(o, k2, desc);
11
+ }) : (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ o[k2] = m[k];
14
+ }));
15
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
17
+ }) : function(o, v) {
18
+ o["default"] = v;
19
+ });
20
+ var __importStar = (this && this.__importStar) || (function () {
21
+ var ownKeys = function(o) {
22
+ ownKeys = Object.getOwnPropertyNames || function (o) {
23
+ var ar = [];
24
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
25
+ return ar;
26
+ };
27
+ return ownKeys(o);
28
+ };
29
+ return function (mod) {
30
+ if (mod && mod.__esModule) return mod;
31
+ var result = {};
32
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
33
+ __setModuleDefault(result, mod);
34
+ return result;
35
+ };
36
+ })();
4
37
  var __importDefault = (this && this.__importDefault) || function (mod) {
5
38
  return (mod && mod.__esModule) ? mod : { "default": mod };
6
39
  };
@@ -11,6 +44,7 @@ exports.__resetAgentTokenLaneForTests = __resetAgentTokenLaneForTests;
11
44
  exports.agentServicePaths = agentServicePaths;
12
45
  exports.inAgentLane = inAgentLane;
13
46
  const cds_1 = __importDefault(require("@sap/cds"));
47
+ const capAuth = __importStar(require("@odatano/cap-auth"));
14
48
  const cap_auth_1 = require("@odatano/cap-auth");
15
49
  const agent_grants_1 = require("./agent-grants");
16
50
  const rate_limiter_1 = require("./rate-limiter");
@@ -46,9 +80,13 @@ function inAgentLane(path, servicePaths = agentServicePaths()) {
46
80
  const bare = path.split('?')[0];
47
81
  return servicePaths.some((p) => (0, cap_auth_1.inLaneOf)(bare, p));
48
82
  }
83
+ // The login package's own reading of the client address and of `trustProxy`, so a token and a
84
+ // password are throttled per the same client. A release without `trustedProxyCount` has no proxy setting.
85
+ const clientAddressOf = capAuth.clientAddress;
86
+ const proxyCountOf = capAuth.trustedProxyCount;
49
87
  function clientKey(req) {
50
- const ip = req.ip ?? req.socket?.remoteAddress ?? 'unknown';
51
- return `ip=${String(ip).replace(/:/g, '.')}:agent-token`;
88
+ const trustProxy = cds_1.default.env.requires.auth?.trustProxy;
89
+ return `ip=${clientAddressOf(req, proxyCountOf ? proxyCountOf(trustProxy) : 0)}:agent-token`;
52
90
  }
53
91
  exports.agentTokenLane = {
54
92
  name: 'agent-token',
@@ -58,11 +96,13 @@ exports.agentTokenLane = {
58
96
  if (!inAgentLane((0, cap_auth_1.requestPath)(req)))
59
97
  return { next: true };
60
98
  const key = clientKey(req);
61
- const locked = tokenFailures.peek(key);
62
- if (!locked.allowed)
63
- return (0, cap_auth_1.respondError)(res, 429, 'Too many failed agent token attempts', locked.retryAfterMs);
99
+ // A token is 32 random bytes, so a valid one cannot be guessed: it passes even while its client
100
+ // is locked, and other clients' failures never shut it out. A locked client gets 429 for any other.
64
101
  const resolution = await (0, agent_grants_1.resolveAgentToken)(token);
65
102
  if (!resolution.ok) {
103
+ const locked = tokenFailures.peek(key);
104
+ if (!locked.allowed)
105
+ return (0, cap_auth_1.respondError)(res, 429, 'Too many failed agent token attempts', locked.retryAfterMs);
66
106
  const failed = tokenFailures.check(key);
67
107
  if (!failed.allowed)
68
108
  return (0, cap_auth_1.respondError)(res, 429, 'Too many failed agent token attempts', failed.retryAfterMs);
@@ -0,0 +1,52 @@
1
+ import type { MintAction, TxBuildPlutusRequest, TxBuildPlutusSpendRequest, TxBuildRequest } from './types';
2
+ import type { Network } from '../blockchain/cardano-client';
3
+ type RawRequest = Record<string, unknown>;
4
+ /** A prepared request; for lockOnScript also the script hash and address the output goes to. */
5
+ export interface PreparedBuild<T> {
6
+ request: T;
7
+ scriptHash?: string;
8
+ scriptAddress?: string;
9
+ }
10
+ /** What a request that does not pass says: a missing field, or why a field is invalid. */
11
+ export interface BuildRequestError {
12
+ error: string;
13
+ field?: string;
14
+ missing?: boolean;
15
+ }
16
+ export type Prepared<T> = PreparedBuild<T> | BuildRequestError;
17
+ /** The network, read only where a script address is derived. */
18
+ export type NetworkOf = () => Network;
19
+ /** The kinds of build a stored request can be for. */
20
+ export type BuildKind = 'simpleAda' | 'metadata' | 'multiAsset' | 'mint' | 'plutusSpend';
21
+ /** Policy id of a Plutus script given as CBOR hex. Throws the library's error for bytes that are no script. */
22
+ export declare function scriptHashOf(scriptHex: string): string;
23
+ /** The texts each action answers with; they are API. */
24
+ declare const MINT_TEXTS: {
25
+ readonly mint: {
26
+ readonly quantityFirst: false;
27
+ readonly noQuantity: () => string;
28
+ readonly badQuantity: (q: unknown) => string;
29
+ readonly noUnit: (u: unknown) => string;
30
+ readonly badUnit: (u: unknown) => string;
31
+ };
32
+ readonly spend: {
33
+ readonly quantityFirst: true;
34
+ readonly noQuantity: (q: unknown) => string;
35
+ readonly badQuantity: (q: unknown) => string;
36
+ readonly noUnit: (_unit: unknown) => string;
37
+ readonly badUnit: (u: unknown) => string;
38
+ };
39
+ };
40
+ export declare function parseMintActions(raw: RawRequest, allowBareNames: boolean, texts?: keyof typeof MINT_TEXTS): MintAction[];
41
+ export declare function prepareSimpleAdaRequest(raw: RawRequest, network: NetworkOf): Prepared<TxBuildRequest>;
42
+ export declare function prepareMetadataRequest(raw: RawRequest): Prepared<TxBuildRequest>;
43
+ export declare function prepareMultiAssetRequest(raw: RawRequest): Prepared<TxBuildRequest>;
44
+ export declare function prepareMintRequest(raw: RawRequest, network: NetworkOf): Prepared<TxBuildRequest>;
45
+ export declare function preparePlutusSpendRequest(raw: RawRequest, network: NetworkOf): Prepared<TxBuildPlutusSpendRequest>;
46
+ /** Most recipients one payout takes; the transaction size limit may be reached earlier. */
47
+ export declare const MAX_PAYOUT_OUTPUTS = 150;
48
+ export declare function preparePayoutRequest(raw: RawRequest): Prepared<TxBuildPlutusRequest>;
49
+ /** The prepared request for a build kind. */
50
+ export declare function prepareBuildRequest(kind: BuildKind, raw: RawRequest, network: NetworkOf): Prepared<TxBuildRequest>;
51
+ export {};
52
+ //# sourceMappingURL=build-request.d.ts.map