@odatano/core 2.0.0-rc.3 → 2.0.0-rc.30

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 (162) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +294 -7
  8. package/@cds-models/CardanoODataService/index.js +33 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +52 -19
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +18 -0
  14. package/@cds-models/index.js +3 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +677 -13
  19. package/db/types.cds +27 -0
  20. package/package.json +182 -173
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +11 -10
  24. package/src/index.js +28 -14
  25. package/src/plugin.js +39 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +49 -160
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +356 -217
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +548 -197
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +78 -205
  39. package/srv/blockchain/cardano-client.js +186 -242
  40. package/srv/blockchain/cardano-indexer.d.ts +302 -242
  41. package/srv/blockchain/cardano-indexer.js +1191 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +43 -81
  43. package/srv/blockchain/cardano-tx-builder.js +177 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  68. package/srv/blockchain/signing/signature-verifier.js +13 -54
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +108 -160
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +620 -285
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +17 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +50 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +48 -24
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +56 -1
  102. package/srv/cardano-service.js +52 -113
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +55 -173
  105. package/srv/cardano-tx-service.cds +439 -364
  106. package/srv/cardano-tx-service.js +305 -209
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/parse.js +13 -1
  110. package/srv/server.d.ts +28 -86
  111. package/srv/server.js +127 -135
  112. package/srv/utils/agent-grants-config.d.ts +37 -0
  113. package/srv/utils/agent-grants-config.js +138 -0
  114. package/srv/utils/agent-grants.d.ts +262 -0
  115. package/srv/utils/agent-grants.js +922 -0
  116. package/srv/utils/agent-token-auth.d.ts +16 -0
  117. package/srv/utils/agent-token-auth.js +78 -0
  118. package/srv/utils/backend-request-handler.d.ts +2 -16
  119. package/srv/utils/backend-request-handler.js +3 -18
  120. package/srv/utils/collections.d.ts +4 -8
  121. package/srv/utils/collections.js +4 -8
  122. package/srv/utils/const.d.ts +30 -67
  123. package/srv/utils/const.js +32 -72
  124. package/srv/utils/crypto.d.ts +3 -12
  125. package/srv/utils/crypto.js +5 -18
  126. package/srv/utils/db-indexes.d.ts +25 -0
  127. package/srv/utils/db-indexes.js +94 -0
  128. package/srv/utils/db-sanitize.d.ts +27 -0
  129. package/srv/utils/db-sanitize.js +85 -0
  130. package/srv/utils/epoch-slots.d.ts +13 -0
  131. package/srv/utils/epoch-slots.js +25 -0
  132. package/srv/utils/error-codes.d.ts +20 -73
  133. package/srv/utils/error-codes.js +19 -70
  134. package/srv/utils/errors.d.ts +50 -177
  135. package/srv/utils/errors.js +94 -218
  136. package/srv/utils/liveness.d.ts +16 -0
  137. package/srv/utils/liveness.js +40 -0
  138. package/srv/utils/mappers.d.ts +128 -214
  139. package/srv/utils/mappers.js +354 -299
  140. package/srv/utils/network-context.js +2 -11
  141. package/srv/utils/pg-inline-json.d.ts +8 -0
  142. package/srv/utils/pg-inline-json.js +62 -0
  143. package/srv/utils/pg-order-nulls.d.ts +14 -0
  144. package/srv/utils/pg-order-nulls.js +56 -0
  145. package/srv/utils/plutus-placeholders.d.ts +23 -16
  146. package/srv/utils/plutus-placeholders.js +63 -27
  147. package/srv/utils/rate-limiter.d.ts +46 -0
  148. package/srv/utils/rate-limiter.js +116 -0
  149. package/srv/utils/service-events.d.ts +2 -22
  150. package/srv/utils/service-events.js +3 -23
  151. package/srv/utils/signing-helper.d.ts +3 -18
  152. package/srv/utils/signing-helper.js +10 -32
  153. package/srv/utils/tx-build-helper.d.ts +26 -92
  154. package/srv/utils/tx-build-helper.js +68 -123
  155. package/srv/utils/tx-request-parsers.d.ts +107 -21
  156. package/srv/utils/tx-request-parsers.js +433 -34
  157. package/srv/utils/tx-utils.d.ts +4 -23
  158. package/srv/utils/tx-utils.js +12 -41
  159. package/srv/utils/types.d.ts +238 -169
  160. package/srv/utils/types.js +2 -6
  161. package/srv/utils/validators.d.ts +24 -90
  162. package/srv/utils/validators.js +50 -147
@@ -0,0 +1,922 @@
1
+ "use strict";
2
+ /**
3
+ * Agent grants: scoped, budgeted bearer capabilities. The transport lane turns `x-agent-token` into the
4
+ * principal `agent:<grantId>` (role `agent-grant`) before any hook runs; `attachAgentGrantEnforcement`
5
+ * applies allow list, wallet pinning and daily budget; `registerAgentGrantHandlers` is the lifecycle API.
6
+ */
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.USAGE_WINDOW_DEFAULT_MS = exports.USAGE_WINDOW_MAX_MS = exports.GRANT_IMMUTABLE_FIELDS = exports.AgentGrantInputError = exports.AGENT_JOB_KINDS = exports.AGENT_ALWAYS_ALLOWED_EVENTS = exports.AGENT_WALLET_ACTIONS = exports.AGENT_ALLOWLISTABLE_ACTIONS = exports.AGENT_SERVICE_NAMES = exports.GRANT_USAGE_ENTITY = exports.GRANTS_ENTITY = exports.AGENT_PRINCIPAL_PREFIX = exports.AGENT_ROLE = exports.AGENT_TOKEN_PREFIX = exports.AGENT_TOKEN_HEADER = void 0;
12
+ exports.__resetGrantRateLimiterForTests = __resetGrantRateLimiterForTests;
13
+ exports.hashAgentToken = hashAgentToken;
14
+ exports.agentPrincipalId = agentPrincipalId;
15
+ exports.parseGrantList = parseGrantList;
16
+ exports.agentGrantOf = agentGrantOf;
17
+ exports.__setTokenCacheMsForTests = __setTokenCacheMsForTests;
18
+ exports.invalidateTokenCache = invalidateTokenCache;
19
+ exports.tokenCacheSize = tokenCacheSize;
20
+ exports.resolveAgentToken = resolveAgentToken;
21
+ exports.makeAgentUser = makeAgentUser;
22
+ exports.validateGrantInput = validateGrantInput;
23
+ exports.issueAgentGrant = issueAgentGrant;
24
+ exports.revokeAgentGrantById = revokeAgentGrantById;
25
+ exports.rotateAgentGrantToken = rotateAgentGrantToken;
26
+ exports.updateAgentGrant = updateAgentGrant;
27
+ exports.resolveUsageWindow = resolveUsageWindow;
28
+ exports.getGrantUsage = getGrantUsage;
29
+ exports.toGrantStatus = toGrantStatus;
30
+ exports.registerAgentGrantHandlers = registerAgentGrantHandlers;
31
+ exports.attachAgentGrantEnforcement = attachAgentGrantEnforcement;
32
+ exports.budgetRunnerFor = budgetRunnerFor;
33
+ exports.enforceAgentGrant = enforceAgentGrant;
34
+ exports.consumeDailyBudget = consumeDailyBudget;
35
+ exports.refundDailyBudget = refundDailyBudget;
36
+ exports.__setGrantUsageModeForTests = __setGrantUsageModeForTests;
37
+ exports.__resetGrantUsageBufferForTests = __resetGrantUsageBufferForTests;
38
+ exports.pendingGrantUsageKeys = pendingGrantUsageKeys;
39
+ exports.flushGrantUsage = flushGrantUsage;
40
+ exports.recordGrantUsage = recordGrantUsage;
41
+ exports.refundGrantUsage = refundGrantUsage;
42
+ const cds_1 = __importDefault(require("@sap/cds"));
43
+ const node_crypto_1 = __importDefault(require("node:crypto"));
44
+ const tx_utils_1 = require("./tx-utils");
45
+ const rate_limiter_1 = require("./rate-limiter");
46
+ const errors_1 = require("./errors");
47
+ const error_codes_1 = require("./error-codes");
48
+ const agent_grants_config_1 = require("./agent-grants-config");
49
+ const { SELECT, INSERT, UPDATE } = cds_1.default.ql;
50
+ const logger = cds_1.default.log('AgentGrants');
51
+ exports.AGENT_TOKEN_HEADER = 'x-agent-token';
52
+ exports.AGENT_TOKEN_PREFIX = 'odat_';
53
+ const TOKEN_BYTES = 32;
54
+ /** Role every token principal carries; the only role it ever has. */
55
+ exports.AGENT_ROLE = 'agent-grant';
56
+ /** `agent:<grantId>`: the principal id a token request runs under. */
57
+ exports.AGENT_PRINCIPAL_PREFIX = 'agent:';
58
+ exports.GRANTS_ENTITY = 'odatano.cardano.CardanoAgentGrants';
59
+ /** Daily per-action counters of admitted calls (feeds GetGrantUsage); never exposed as an entity. */
60
+ exports.GRANT_USAGE_ENTITY = 'odatano.cardano.CardanoAgentGrantUsage';
61
+ /** The services the hook attaches to and the transport lane opens. */
62
+ exports.AGENT_SERVICE_NAMES = [
63
+ 'CardanoODataService',
64
+ 'CardanoTransactionService',
65
+ 'CardanoSignService',
66
+ 'CardanoWorkerService',
67
+ 'CardanoIndexerService',
68
+ 'CardanoAgentService',
69
+ 'CardanoBackendService',
70
+ ];
71
+ /**
72
+ * Actions an operator may put on a grant's allow list; each call costs one budget unit. Anything else
73
+ * not in AGENT_ALWAYS_ALLOWED_EVENTS (HSM signing, pause/resume, grant administration) is a 403.
74
+ */
75
+ exports.AGENT_ALLOWLISTABLE_ACTIONS = [
76
+ // CardanoTransactionService: unsigned CBOR
77
+ 'BuildSimpleAdaTransaction',
78
+ 'BuildTransactionWithMetadata',
79
+ 'BuildMultiAssetTransaction',
80
+ 'BuildMintTransaction',
81
+ 'BuildPlutusSpendTransaction',
82
+ 'BuildPlutusTransaction',
83
+ 'SetCollateral',
84
+ // externally signed transactions
85
+ 'CreateSigningRequest',
86
+ 'VerifySignature',
87
+ 'SubmitTransaction',
88
+ 'SubmitSignedTransaction',
89
+ 'SubmitVerifiedTransaction',
90
+ 'CheckSubmissionStatus',
91
+ // server-side wallets (need walletId on the grant)
92
+ 'SubmitWalletJob',
93
+ 'CancelJob',
94
+ ];
95
+ /** Allow-listable actions that spend from a worker wallet: the grant must be pinned. */
96
+ exports.AGENT_WALLET_ACTIONS = new Set(['SubmitWalletJob', 'CancelJob']);
97
+ /**
98
+ * Events every valid token may use without allow-list entry or budget: reads, compute-only actions,
99
+ * status polling. Row-level narrowing is done by the `$user.grantId` restrictions in the CDS models.
100
+ */
101
+ exports.AGENT_ALWAYS_ALLOWED_EVENTS = new Set([
102
+ 'READ',
103
+ // CardanoODataService: chain reads through the backends
104
+ 'GetNetworkInformation', 'GetBlockByHash', 'GetEpochByNumber', 'GetPoolById', 'GetDrepById',
105
+ 'GetAssetInfo', 'GetAssetHistory', 'GetAccountByStakeAddress', 'GetTransactionByHash',
106
+ 'GetMetadataByTxHash', 'GetAddressByBech32', 'GetUTxOsByAddress', 'GetUTxOsByCredential',
107
+ 'GetAssetsByAddress', 'GetLatestTransactionsByAddress', 'GetLatestBlock', 'GetLatestEpoch',
108
+ 'GetLedgerProtocolParameters', 'ParseTransactionCbor',
109
+ // CardanoTransactionService: compute-only
110
+ 'GetBuildDetails', 'GetTransactionBuildsByAddress', 'DeriveScriptAddress', 'ExtractPaymentKeyHash',
111
+ // CardanoSignService: reads and stateless verification
112
+ 'GetSigningRequest', 'GetSigningRequestsByAddress', 'VerifyDataSignature', 'GetHsmStatus',
113
+ // CardanoWorkerService / CardanoIndexerService: status and liveness
114
+ 'GetJobStatus', 'GetWorkerStatus', 'getStatus', 'getLiveness',
115
+ // CardanoAgentService: the token's own grant (GetGrantUsage is narrowed to it in enforceAgentGrant)
116
+ 'GetGrantStatus', 'GetGrantUsage',
117
+ // CardanoBackendService: reads and evaluation for another ODATANO instance (submit is allow-listed)
118
+ 'GetTransaction', 'GetTransactionsBatch', 'GetTransactionMetadata', 'GetBlock', 'GetBlockByHeight',
119
+ 'GetNextBlocks', 'GetBlockTransactions', 'GetCurrentSlot', 'GetEpoch', 'GetAddress', 'GetAddressUtxos',
120
+ 'GetAddressTransactions', 'GetAddressTransactionHashes', 'GetCredentialUtxos', 'IsUtxoUnspent',
121
+ 'GetUnspentOutputs', 'GetAccount', 'GetPool', 'GetPoolIds', 'GetPools', 'GetDrep', 'GetDrepIds', 'GetDreps',
122
+ 'GetProtocolParameters', 'EvaluateTransaction',
123
+ ]);
124
+ /** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
125
+ exports.AGENT_JOB_KINDS = ['simpleAda', 'metadata', 'multiAsset', 'mint', 'plutusSpend', 'submitSigned'];
126
+ /** Grant administration limiter: `adminRateLimit` calls per principal per hour, built on first use. */
127
+ let grantAdminRateLimiter = null;
128
+ function grantAdminLimiter() {
129
+ grantAdminRateLimiter ??= new rate_limiter_1.RateLimiter({ windowMs: 60 * 60 * 1000, maxRequests: (0, agent_grants_config_1.loadGrantAdminRateLimit)() });
130
+ return grantAdminRateLimiter;
131
+ }
132
+ /** Forget every rate-limit window, the token cache and re-read the knobs from the config (tests). */
133
+ function __resetGrantRateLimiterForTests() {
134
+ grantAdminRateLimiter = null;
135
+ lastUsedTouched.clear();
136
+ tokenCache.clear();
137
+ tokenHashOfGrant.clear();
138
+ tokenCacheMs = null;
139
+ tokenCacheOverride = null;
140
+ }
141
+ function dbRunner() {
142
+ return cds_1.default.db;
143
+ }
144
+ // ---------------------------------------------------------------------------
145
+ // Small helpers
146
+ // ---------------------------------------------------------------------------
147
+ function hashAgentToken(token) {
148
+ return node_crypto_1.default.createHash('sha256').update(token).digest('hex');
149
+ }
150
+ function agentPrincipalId(grantId) {
151
+ return `${exports.AGENT_PRINCIPAL_PREFIX}${grantId}`;
152
+ }
153
+ /** The grant's JSON list column as an array; malformed or absent = empty. */
154
+ function parseGrantList(raw) {
155
+ if (!raw)
156
+ return [];
157
+ try {
158
+ const v = JSON.parse(raw);
159
+ return Array.isArray(v) ? v.filter((x) => typeof x === 'string') : [];
160
+ }
161
+ catch {
162
+ return [];
163
+ }
164
+ }
165
+ function utcDay(now = new Date()) {
166
+ return now.toISOString().slice(0, 10);
167
+ }
168
+ function isExpired(grant, now = new Date()) {
169
+ return !!grant.validUntil && new Date(grant.validUntil).getTime() < now.getTime();
170
+ }
171
+ /** The grant a request runs under, or null for an ordinary principal. */
172
+ function agentGrantOf(req) {
173
+ const r = req;
174
+ const fromHttp = r?.http?.req?.agentGrant ?? r?._?.req?.agentGrant;
175
+ if (fromHttp)
176
+ return fromHttp;
177
+ const ctx = cds_1.default.context;
178
+ return ctx?.http?.req?.agentGrant ?? null;
179
+ }
180
+ const TOKEN_CACHE_MAX = 10_000;
181
+ const tokenCache = new Map();
182
+ const tokenHashOfGrant = new Map();
183
+ let tokenCacheMs = null;
184
+ let tokenCacheOverride = null;
185
+ let tokenCacheGeneration = 0;
186
+ function tokenCacheTtl() {
187
+ if (tokenCacheOverride !== null)
188
+ return tokenCacheOverride;
189
+ tokenCacheMs ??= (0, agent_grants_config_1.loadTokenCacheMs)();
190
+ return tokenCacheMs;
191
+ }
192
+ /** Test seam: cache lifetime in ms for injected runners too (null = config, injected runners bypass). */
193
+ function __setTokenCacheMsForTests(ms) {
194
+ tokenCacheOverride = ms;
195
+ tokenCache.clear();
196
+ tokenHashOfGrant.clear();
197
+ }
198
+ /** Drops the cached resolution of a grant (revoke, rotate, update). */
199
+ function invalidateTokenCache(grantId) {
200
+ tokenCacheGeneration++;
201
+ const hash = tokenHashOfGrant.get(grantId);
202
+ if (hash !== undefined) {
203
+ tokenCache.delete(hash);
204
+ tokenHashOfGrant.delete(grantId);
205
+ }
206
+ }
207
+ /** Entries waiting in the token cache (monitoring, tests). */
208
+ function tokenCacheSize() {
209
+ return tokenCache.size;
210
+ }
211
+ function rememberToken(hash, grant, ttl) {
212
+ if (tokenCache.size >= TOKEN_CACHE_MAX) {
213
+ // bounded against a flood of distinct tokens
214
+ tokenCache.clear();
215
+ tokenHashOfGrant.clear();
216
+ }
217
+ tokenCache.set(hash, { grant, until: Date.now() + ttl });
218
+ tokenHashOfGrant.set(grant.ID, hash);
219
+ }
220
+ /**
221
+ * Authenticate a bearer token: prefix, hash lookup among active grants (revoked = unknown, non-leaking),
222
+ * expiry. Runs detached from any ambient transaction; the lookup is cached (see above).
223
+ */
224
+ async function resolveAgentToken(token, runner = dbRunner()) {
225
+ if (typeof token !== 'string' || !token.startsWith(exports.AGENT_TOKEN_PREFIX)) {
226
+ return { ok: false, status: 401, message: 'invalid agent token' };
227
+ }
228
+ const hash = hashAgentToken(token);
229
+ const ttl = tokenCacheTtl();
230
+ const cacheable = ttl > 0 && (tokenCacheOverride !== null || runner === dbRunner());
231
+ if (cacheable) {
232
+ const hit = tokenCache.get(hash);
233
+ if (hit && hit.until > Date.now()) {
234
+ if (isExpired(hit.grant))
235
+ return { ok: false, status: 410, message: 'agent grant expired' };
236
+ return { ok: true, grant: hit.grant };
237
+ }
238
+ if (hit)
239
+ tokenCache.delete(hash);
240
+ }
241
+ const generation = tokenCacheGeneration;
242
+ const grant = (await (0, tx_utils_1.runWithoutAmbientTx)(() => runner.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ tokenHash: hash, isActive: true }))));
243
+ if (!grant)
244
+ return { ok: false, status: 401, message: 'invalid agent token' };
245
+ if (isExpired(grant))
246
+ return { ok: false, status: 410, message: 'agent grant expired' };
247
+ // not remembered when an invalidation ran while the SELECT was in flight
248
+ if (cacheable && generation === tokenCacheGeneration)
249
+ rememberToken(hash, grant, ttl);
250
+ return { ok: true, grant };
251
+ }
252
+ /**
253
+ * The principal a token request runs under: not the operator and without the operator's roles, so
254
+ * `createdBy = $user` and `$user.grantId` restrictions narrow it and every `@requires: 'Admin'` refuses it.
255
+ */
256
+ function makeAgentUser(grant) {
257
+ return new cds_1.default.User({
258
+ id: agentPrincipalId(grant.ID),
259
+ roles: [exports.AGENT_ROLE],
260
+ attr: { grantId: grant.ID, operator: grant.userId, walletId: grant.walletId ?? '' },
261
+ });
262
+ }
263
+ /** A refused grant input; carries the 400 the action answers with. */
264
+ class AgentGrantInputError extends errors_1.BackendError {
265
+ constructor(message, target, context = 'CreateAgentGrant') {
266
+ super(`${context}: ${message}`, 400, error_codes_1.ERROR_CODES.INVALID_INPUT, undefined, undefined, target);
267
+ }
268
+ }
269
+ exports.AgentGrantInputError = AgentGrantInputError;
270
+ function validateGrantInput(input, now = new Date(), context = 'CreateAgentGrant') {
271
+ const fail = (message, target) => new AgentGrantInputError(message, target, context);
272
+ const actions = input.allowedActions;
273
+ if (!Array.isArray(actions) || actions.length === 0) {
274
+ throw fail('allowedActions must be a non-empty array', 'allowedActions');
275
+ }
276
+ const unknown = actions.filter((a) => !exports.AGENT_ALLOWLISTABLE_ACTIONS.includes(a));
277
+ if (unknown.length > 0) {
278
+ throw fail(`allowedActions contains non-grantable entries: ${unknown.join(', ')}. Grantable: ${exports.AGENT_ALLOWLISTABLE_ACTIONS.join(', ')}`, 'allowedActions');
279
+ }
280
+ const uniqueActions = [...new Set(actions)];
281
+ const walletId = typeof input.walletId === 'string' && input.walletId.trim() ? input.walletId.trim() : null;
282
+ const wantsWallet = uniqueActions.some((a) => exports.AGENT_WALLET_ACTIONS.has(a));
283
+ if (wantsWallet && !walletId) {
284
+ throw fail('walletId is required when SubmitWalletJob or CancelJob is allowed', 'walletId');
285
+ }
286
+ if (walletId && walletId.length > 50)
287
+ throw fail('walletId must be at most 50 characters', 'walletId');
288
+ let allowedJobKinds = [];
289
+ if (input.allowedJobKinds !== undefined && input.allowedJobKinds !== null) {
290
+ if (!Array.isArray(input.allowedJobKinds))
291
+ throw fail('allowedJobKinds must be an array', 'allowedJobKinds');
292
+ const badKinds = input.allowedJobKinds.filter((k) => !exports.AGENT_JOB_KINDS.includes(k));
293
+ if (badKinds.length > 0) {
294
+ throw fail(`allowedJobKinds contains unknown kinds: ${badKinds.join(', ')}. Known: ${exports.AGENT_JOB_KINDS.join(', ')}`, 'allowedJobKinds');
295
+ }
296
+ allowedJobKinds = [...new Set(input.allowedJobKinds)];
297
+ if (allowedJobKinds.length > 0 && !wantsWallet) {
298
+ throw fail('allowedJobKinds needs SubmitWalletJob in allowedActions', 'allowedJobKinds');
299
+ }
300
+ }
301
+ let maxJobsPerDay = null;
302
+ if (input.maxJobsPerDay !== undefined && input.maxJobsPerDay !== null) {
303
+ const n = Number(input.maxJobsPerDay);
304
+ if (!Number.isInteger(n) || n < 1)
305
+ throw fail('maxJobsPerDay must be a positive integer', 'maxJobsPerDay');
306
+ maxJobsPerDay = n;
307
+ }
308
+ let validUntil = null;
309
+ if (input.validUntil) {
310
+ const t = new Date(input.validUntil);
311
+ if (Number.isNaN(t.getTime()))
312
+ throw fail('validUntil must be a valid ISO-8601 timestamp', 'validUntil');
313
+ if (t.getTime() <= now.getTime())
314
+ throw fail('validUntil must be in the future', 'validUntil');
315
+ validUntil = t.toISOString();
316
+ }
317
+ const agentLabel = typeof input.agentLabel === 'string' && input.agentLabel.trim() ? input.agentLabel.trim() : null;
318
+ if (agentLabel && agentLabel.length > 100)
319
+ throw fail('agentLabel must be at most 100 characters', 'agentLabel');
320
+ return { allowedActions: uniqueActions, walletId, allowedJobKinds, maxJobsPerDay, validUntil, agentLabel };
321
+ }
322
+ /** Mint a grant for `operatorId` on `runner`; validation errors surface as AgentGrantInputError (400). */
323
+ async function issueAgentGrant(input, operatorId, runner = dbRunner()) {
324
+ if (!operatorId)
325
+ throw new AgentGrantInputError('an operator id is required');
326
+ const n = validateGrantInput(input);
327
+ const token = exports.AGENT_TOKEN_PREFIX + node_crypto_1.default.randomBytes(TOKEN_BYTES).toString('hex');
328
+ const grant = {
329
+ ID: cds_1.default.utils.uuid(),
330
+ userId: operatorId,
331
+ agentLabel: n.agentLabel,
332
+ tokenHash: hashAgentToken(token),
333
+ allowedActions: JSON.stringify(n.allowedActions),
334
+ walletId: n.walletId,
335
+ allowedJobKinds: n.allowedJobKinds.length > 0 ? JSON.stringify(n.allowedJobKinds) : null,
336
+ maxJobsPerDay: n.maxJobsPerDay,
337
+ jobsUsedToday: 0,
338
+ budgetWindow: null,
339
+ validUntil: n.validUntil,
340
+ isActive: true,
341
+ revokedAt: null,
342
+ createdAt: new Date().toISOString(),
343
+ lastUsedAt: null,
344
+ };
345
+ await runner.run(INSERT.into(exports.GRANTS_ENTITY).entries(grant));
346
+ // never logs the token
347
+ logger.info(`agent grant ${grant.ID} issued by ${operatorId}` +
348
+ `${n.agentLabel ? ` for '${n.agentLabel}'` : ''} (actions: ${n.allowedActions.join(', ')}` +
349
+ `${n.walletId ? `, wallet ${n.walletId}` : ''}${n.maxJobsPerDay ? `, budget ${n.maxJobsPerDay}/day` : ''}` +
350
+ `${n.validUntil ? `, until ${n.validUntil}` : ''})`);
351
+ return {
352
+ grantId: grant.ID,
353
+ token,
354
+ allowedActions: n.allowedActions,
355
+ walletId: n.walletId,
356
+ allowedJobKinds: n.allowedJobKinds,
357
+ maxJobsPerDay: n.maxJobsPerDay,
358
+ validUntil: n.validUntil,
359
+ };
360
+ }
361
+ /** Deactivate a grant; false when it does not exist or is already revoked. */
362
+ async function revokeAgentGrantById(grantId, runner = dbRunner()) {
363
+ if (!grantId)
364
+ return false;
365
+ const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY)
366
+ .set({ isActive: false, revokedAt: new Date().toISOString() })
367
+ .where({ ID: grantId, isActive: true }));
368
+ const revoked = Number(affected) > 0;
369
+ invalidateTokenCache(grantId);
370
+ if (revoked)
371
+ logger.info(`agent grant ${grantId} revoked`);
372
+ return revoked;
373
+ }
374
+ /**
375
+ * Replace the grant's token; budget, wallet, allow list and expiry survive. The old token is unknown
376
+ * from the next request (another replica: after AGENT_TOKEN_CACHE_MS). Null when missing or revoked.
377
+ */
378
+ async function rotateAgentGrantToken(grantId, runner = dbRunner()) {
379
+ if (!grantId)
380
+ return null;
381
+ const token = exports.AGENT_TOKEN_PREFIX + node_crypto_1.default.randomBytes(TOKEN_BYTES).toString('hex');
382
+ const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY).set({ tokenHash: hashAgentToken(token) }).where({ ID: grantId, isActive: true }));
383
+ invalidateTokenCache(grantId);
384
+ if (Number(affected) === 0)
385
+ return null;
386
+ logger.info(`agent grant ${grantId} token rotated`);
387
+ return { grantId, token };
388
+ }
389
+ /** Row fields a grant edit never touches; a different wallet binding is a different grant. */
390
+ exports.GRANT_IMMUTABLE_FIELDS = ['walletId', 'userId', 'tokenHash'];
391
+ const GRANT_EDITABLE_FIELDS = [
392
+ 'agentLabel', 'allowedActions', 'allowedJobKinds', 'maxJobsPerDay', 'validUntil',
393
+ ];
394
+ /**
395
+ * Edit an active grant: absent field = untouched, explicit null = cleared (allowedActions cannot be emptied).
396
+ * The merged row passes validateGrantInput. Unknown grant 404, revoked 409 GRANT_REVOKED, invalid input 400.
397
+ */
398
+ async function updateAgentGrant(grantId, input, runner = dbRunner()) {
399
+ const has = (k) => Object.prototype.hasOwnProperty.call(input, k);
400
+ const existing = (await runner.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: grantId })));
401
+ if (!existing)
402
+ return { ok: false, status: 404, message: 'Grant not found' };
403
+ if (existing.isActive === false)
404
+ return { ok: false, status: 409, code: 'GRANT_REVOKED', message: 'Grant is revoked' };
405
+ // validUntil only when given: an untouched, already passed expiry is the lane's 410, not this edit's 400
406
+ const n = validateGrantInput({
407
+ allowedActions: has('allowedActions') ? input.allowedActions : parseGrantList(existing.allowedActions),
408
+ walletId: existing.walletId ?? null,
409
+ allowedJobKinds: has('allowedJobKinds') ? input.allowedJobKinds : parseGrantList(existing.allowedJobKinds),
410
+ maxJobsPerDay: has('maxJobsPerDay') ? input.maxJobsPerDay : existing.maxJobsPerDay,
411
+ validUntil: has('validUntil') ? input.validUntil : null,
412
+ agentLabel: has('agentLabel') ? input.agentLabel : existing.agentLabel,
413
+ }, new Date(), 'UpdateAgentGrant');
414
+ const patch = {};
415
+ if (has('allowedActions'))
416
+ patch.allowedActions = JSON.stringify(n.allowedActions);
417
+ if (has('allowedJobKinds'))
418
+ patch.allowedJobKinds = n.allowedJobKinds.length > 0 ? JSON.stringify(n.allowedJobKinds) : null;
419
+ if (has('maxJobsPerDay'))
420
+ patch.maxJobsPerDay = n.maxJobsPerDay;
421
+ if (has('validUntil'))
422
+ patch.validUntil = n.validUntil;
423
+ if (has('agentLabel'))
424
+ patch.agentLabel = n.agentLabel;
425
+ const updated = GRANT_EDITABLE_FIELDS.filter((f) => has(f));
426
+ if (updated.length === 0)
427
+ return { ok: true, grantId, updated: [] };
428
+ // conditional on isActive: a concurrent revoke wins
429
+ const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY).set(patch).where({ ID: grantId, isActive: true }));
430
+ invalidateTokenCache(grantId);
431
+ if (Number(affected) === 0)
432
+ return { ok: false, status: 409, code: 'GRANT_REVOKED', message: 'Grant is revoked' };
433
+ logger.info(`agent grant ${grantId} updated (${updated.join(', ')})`);
434
+ return { ok: true, grantId, updated };
435
+ }
436
+ // ---------------------------------------------------------------------------
437
+ // Usage history (GetGrantUsage)
438
+ // ---------------------------------------------------------------------------
439
+ exports.USAGE_WINDOW_MAX_MS = 366 * 24 * 60 * 60 * 1000;
440
+ exports.USAGE_WINDOW_DEFAULT_MS = 30 * 24 * 60 * 60 * 1000;
441
+ /** ISO timestamp or undefined; `null` when the value does not parse. */
442
+ function parseTimestamp(raw) {
443
+ if (raw === undefined || raw === null || raw === '')
444
+ return undefined;
445
+ const t = new Date(String(raw));
446
+ return Number.isNaN(t.getTime()) ? null : t.toISOString();
447
+ }
448
+ /** since (default until - 30 days) .. until (default now), at most 366 days; whole UTC days at both ends. */
449
+ function resolveUsageWindow(since, until, now = new Date()) {
450
+ const to = parseTimestamp(until);
451
+ const from = parseTimestamp(since);
452
+ if (to === null)
453
+ return { ok: false, message: 'until must be a valid ISO-8601 timestamp', target: 'until' };
454
+ if (from === null)
455
+ return { ok: false, message: 'since must be a valid ISO-8601 timestamp', target: 'since' };
456
+ const toMs = to ? new Date(to).getTime() : now.getTime();
457
+ const fromMs = from ? new Date(from).getTime() : toMs - exports.USAGE_WINDOW_DEFAULT_MS;
458
+ if (fromMs > toMs)
459
+ return { ok: false, message: 'since must not lie after until', target: 'since' };
460
+ if (toMs - fromMs > exports.USAGE_WINDOW_MAX_MS)
461
+ return { ok: false, message: 'the window may span at most 366 days', target: 'since' };
462
+ const sinceIso = new Date(fromMs).toISOString();
463
+ const untilIso = new Date(toMs).toISOString();
464
+ return { ok: true, since: sinceIso, until: untilIso, sinceDay: sinceIso.slice(0, 10), untilDay: untilIso.slice(0, 10) };
465
+ }
466
+ /**
467
+ * Admitted calls of the grant in `window`, grouped by service and action. Deferred counters are flushed
468
+ * first on `flushRunner` (detached autocommit), so the read on `runner` sees them without holding locks.
469
+ */
470
+ async function getGrantUsage(grant, window, runner = dbRunner(), flushRunner = dbRunner()) {
471
+ if (pendingGrantUsageKeys() > 0)
472
+ await flushGrantUsage(flushRunner);
473
+ const rows = ((await runner.run(SELECT.from(exports.GRANT_USAGE_ENTITY)
474
+ .columns('service', 'action', { func: 'sum', args: [{ ref: ['calls'] }], as: 'calls' }, { func: 'sum', args: [{ ref: ['refunded'] }], as: 'refunded' })
475
+ .where({ grant_ID: grant.ID, day: { '>=': window.sinceDay } })
476
+ .and({ day: { '<=': window.untilDay } })
477
+ .groupBy('service', 'action'))) ?? []);
478
+ const calls = rows
479
+ .map((r) => {
480
+ const admitted = Number(r.calls ?? 0);
481
+ const refunded = Number(r.refunded ?? 0);
482
+ return { service: String(r.service ?? ''), action: String(r.action ?? ''), count: Math.max(admitted - refunded, 0), refunded };
483
+ })
484
+ .sort((a, b) => a.service.localeCompare(b.service) || a.action.localeCompare(b.action));
485
+ const status = toGrantStatus(grant);
486
+ return {
487
+ grantId: grant.ID,
488
+ since: window.since,
489
+ until: window.until,
490
+ calls,
491
+ total: calls.reduce((sum, c) => sum + c.count, 0),
492
+ jobsUsedToday: status.jobsUsedToday,
493
+ maxJobsPerDay: status.maxJobsPerDay,
494
+ };
495
+ }
496
+ function toGrantStatus(grant) {
497
+ return {
498
+ grantId: grant.ID,
499
+ agentLabel: grant.agentLabel ?? null,
500
+ allowedActions: parseGrantList(grant.allowedActions),
501
+ walletId: grant.walletId ?? null,
502
+ allowedJobKinds: parseGrantList(grant.allowedJobKinds),
503
+ maxJobsPerDay: grant.maxJobsPerDay ?? null,
504
+ // a counter from an earlier UTC day belongs to a window that is over
505
+ jobsUsedToday: grant.budgetWindow === utcDay() ? Number(grant.jobsUsedToday ?? 0) : 0,
506
+ budgetWindow: grant.budgetWindow ?? null,
507
+ validUntil: grant.validUntil ?? null,
508
+ isActive: grant.isActive !== false,
509
+ };
510
+ }
511
+ // ---------------------------------------------------------------------------
512
+ // CardanoAgentService handlers
513
+ // ---------------------------------------------------------------------------
514
+ /**
515
+ * Prelude of the administration actions: rate limit (refusals consume the window), then no token
516
+ * principal, then authentication. False after a reject.
517
+ */
518
+ function checkGrantAdmin(req, verb) {
519
+ const rate = grantAdminLimiter().check((0, rate_limiter_1.principalRateKey)(req, 'grant-admin'));
520
+ if (!rate.allowed) {
521
+ req.reject(429, `Rate limited. Retry after ${Math.ceil(rate.retryAfterMs / 1000)}s`);
522
+ return false;
523
+ }
524
+ if (agentGrantOf(req)) {
525
+ req.reject(403, `an agent grant cannot ${verb} grants`);
526
+ return false;
527
+ }
528
+ if (!req.user?.id) {
529
+ req.reject(401, 'authentication required');
530
+ return false;
531
+ }
532
+ return true;
533
+ }
534
+ function userIs(req, role) {
535
+ const user = req.user;
536
+ return typeof user?.is === 'function' ? user.is(role) === true : false;
537
+ }
538
+ /** Validation rejections happen before any transaction work. */
539
+ function registerAgentGrantHandlers(srv) {
540
+ srv.on('CreateAgentGrant', async (req) => {
541
+ if (!checkGrantAdmin(req, 'issue'))
542
+ return;
543
+ const operatorId = String(req.user.id);
544
+ const data = (req.data ?? {});
545
+ let normalized;
546
+ try {
547
+ normalized = validateGrantInput(data);
548
+ }
549
+ catch (err) {
550
+ if (err instanceof errors_1.BackendError)
551
+ return req.reject(err.statusCode, err.message, err.target);
552
+ throw err;
553
+ }
554
+ const issued = await issueAgentGrant(normalized, operatorId, cds_1.default.tx(req));
555
+ return {
556
+ grantId: issued.grantId,
557
+ token: issued.token,
558
+ allowedActions: issued.allowedActions,
559
+ walletId: issued.walletId,
560
+ allowedJobKinds: issued.allowedJobKinds,
561
+ maxJobsPerDay: issued.maxJobsPerDay,
562
+ validUntil: issued.validUntil,
563
+ };
564
+ });
565
+ srv.on('RevokeAgentGrant', async (req) => {
566
+ if (!checkGrantAdmin(req, 'revoke'))
567
+ return;
568
+ const { grantId } = (req.data ?? {});
569
+ if (!grantId)
570
+ return req.reject(400, 'grantId is required', 'grantId');
571
+ const revoked = await revokeAgentGrantById(grantId, cds_1.default.tx(req));
572
+ if (!revoked)
573
+ return req.reject(404, 'Grant not found or already revoked', 'grantId');
574
+ return true;
575
+ });
576
+ srv.on('RotateAgentGrantToken', async (req) => {
577
+ if (!checkGrantAdmin(req, 'rotate'))
578
+ return;
579
+ const { grantId } = (req.data ?? {});
580
+ if (!grantId)
581
+ return req.reject(400, 'grantId is required', 'grantId');
582
+ const rotated = await rotateAgentGrantToken(grantId, cds_1.default.tx(req));
583
+ if (!rotated)
584
+ return req.reject(404, 'Grant not found or already revoked', 'grantId');
585
+ return rotated;
586
+ });
587
+ srv.on('UpdateAgentGrant', async (req) => {
588
+ if (!checkGrantAdmin(req, 'update'))
589
+ return;
590
+ const data = (req.data ?? {});
591
+ if (!data.grantId)
592
+ return req.reject(400, 'grantId is required', 'grantId');
593
+ const immutable = exports.GRANT_IMMUTABLE_FIELDS.filter((f) => Object.prototype.hasOwnProperty.call(data, f));
594
+ if (immutable.length > 0) {
595
+ return req.reject(400, `${immutable.join(', ')} cannot be changed; issue a new grant for a different binding`, immutable[0]);
596
+ }
597
+ let result;
598
+ try {
599
+ result = await updateAgentGrant(data.grantId, data, cds_1.default.tx(req));
600
+ }
601
+ catch (err) {
602
+ if (err instanceof errors_1.BackendError)
603
+ return req.reject(err.statusCode, err.message, err.target);
604
+ throw err;
605
+ }
606
+ if (!result.ok) {
607
+ if (result.code)
608
+ return req.reject({ status: result.status, code: result.code, message: result.message });
609
+ return req.reject(result.status, result.message, 'grantId');
610
+ }
611
+ return { grantId: result.grantId, updated: result.updated };
612
+ });
613
+ // The calling token's own grant, read fresh so the budget counter is current
614
+ srv.on('GetGrantStatus', async (req) => {
615
+ const grant = agentGrantOf(req);
616
+ if (!grant)
617
+ return req.reject(400, 'GetGrantStatus needs an x-agent-token; operators read the AgentGrants entity');
618
+ const fresh = (await cds_1.default.tx(req).run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: grant.ID })));
619
+ return toGrantStatus(fresh ?? grant);
620
+ });
621
+ // Admin sees any grant (revoked ones keep their history), a token only its own (404 otherwise)
622
+ srv.on('GetGrantUsage', async (req) => {
623
+ const data = (req.data ?? {});
624
+ if (!data.grantId)
625
+ return req.reject(400, 'grantId is required', 'grantId');
626
+ const window = resolveUsageWindow(data.since, data.until);
627
+ if (!window.ok)
628
+ return req.reject(400, window.message, window.target);
629
+ const own = agentGrantOf(req);
630
+ if (own && own.ID !== data.grantId)
631
+ return req.reject(404, 'Grant not found', 'grantId');
632
+ if (!own && !userIs(req, 'Admin'))
633
+ return req.reject(403, "GetGrantUsage needs Admin or the grant's own token");
634
+ const tx = cds_1.default.tx(req);
635
+ const grant = (await tx.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: data.grantId })));
636
+ if (!grant)
637
+ return req.reject(404, 'Grant not found', 'grantId');
638
+ return getGrantUsage(grant, window, tx, dbRunner());
639
+ });
640
+ }
641
+ // ---------------------------------------------------------------------------
642
+ // Enforcement (before('*') on the six services)
643
+ // ---------------------------------------------------------------------------
644
+ function attachAgentGrantEnforcement(srv, runner) {
645
+ const serviceName = String(srv.name ?? 'unknown');
646
+ srv.before('*', (req) => enforceAgentGrant(req, runner, undefined, serviceName));
647
+ }
648
+ function budgetRunnerFor(req, injected, detached) {
649
+ if (injected)
650
+ return { runner: injected, detached: detached ?? true };
651
+ let tx = null;
652
+ try {
653
+ tx = cds_1.default.tx(req);
654
+ }
655
+ catch {
656
+ tx = null;
657
+ }
658
+ if (tx && (tx.dbc || tx.ready))
659
+ return { runner: tx, detached: false };
660
+ return { runner: dbRunner(), detached: true };
661
+ }
662
+ async function runStmt(br, statement) {
663
+ return br.detached ? (0, tx_utils_1.runWithoutAmbientTx)(() => br.runner.run(statement)) : br.runner.run(statement);
664
+ }
665
+ /**
666
+ * The before('*') hook: allow list, wallet pinning, daily budget, usage, lastUsedAt. No-op without a grant.
667
+ * `runner` / `detached` are test seams.
668
+ */
669
+ async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown') {
670
+ const grant = agentGrantOf(req);
671
+ if (!grant)
672
+ return;
673
+ // A grant can be revoked between two parts of a $batch, or expire mid-flight
674
+ if (grant.isActive === false)
675
+ return req.reject(401, 'invalid agent token');
676
+ if (isExpired(grant))
677
+ return req.reject(410, 'agent grant expired');
678
+ const br = budgetRunnerFor(req, runner, detached);
679
+ const event = String(req.event ?? '');
680
+ if (exports.AGENT_ALWAYS_ALLOWED_EVENTS.has(event)) {
681
+ // a token sees its own usage only; a foreign id is not found (non-leaking)
682
+ if (event === 'GetGrantUsage') {
683
+ const asked = String(req.data?.grantId ?? '');
684
+ if (asked !== grant.ID)
685
+ return req.reject(404, 'Grant not found', 'grantId');
686
+ }
687
+ await touchLastUsed(grant, br);
688
+ return;
689
+ }
690
+ const allowed = parseGrantList(grant.allowedActions);
691
+ if (!allowed.includes(event)) {
692
+ return req.reject(403, `action '${event}' is not allowed for this agent grant`);
693
+ }
694
+ const data = req.data;
695
+ if (exports.AGENT_WALLET_ACTIONS.has(event)) {
696
+ if (!grant.walletId) {
697
+ return req.reject(403, 'this agent grant has no wallet binding; issue it with walletId to queue wallet jobs');
698
+ }
699
+ if (data && typeof data === 'object') {
700
+ if (event === 'SubmitWalletJob') {
701
+ if (data.walletId !== undefined && data.walletId !== null && data.walletId !== '' && data.walletId !== grant.walletId) {
702
+ return req.reject(403, 'walletId does not match this agent grant');
703
+ }
704
+ data.walletId = grant.walletId;
705
+ const kinds = parseGrantList(grant.allowedJobKinds);
706
+ if (kinds.length > 0 && !kinds.includes(String(data.kind ?? ''))) {
707
+ return req.reject(403, `job kind '${String(data.kind ?? '')}' is not allowed for this agent grant (allowed: ${kinds.join(', ')})`);
708
+ }
709
+ }
710
+ // CancelJob: the worker service scopes the job lookup by createdBy = agent:<grantId>
711
+ }
712
+ }
713
+ let charge = null;
714
+ if (grant.maxJobsPerDay !== undefined && grant.maxJobsPerDay !== null) {
715
+ charge = await consumeDailyBudget(br, grant);
716
+ if (!charge.consumed) {
717
+ return req.reject(429, `agent grant daily budget exhausted (${grant.maxJobsPerDay}/day)`);
718
+ }
719
+ }
720
+ // one usage unit on (grant, day, service, action), budgeted or not
721
+ const usageDay = await recordGrantUsage(br, grant, serviceName, event);
722
+ // Detached writes: a request refused as invalid (400..428) admitted nothing, so refund the budget unit
723
+ // in the window it was charged to and mark the usage unit refunded; 429 and 5xx keep both.
724
+ // Writes inside the request's own transaction are undone by its rollback.
725
+ if (br.detached) {
726
+ const chargedWindow = charge?.window ?? null;
727
+ req.on?.('failed', (err) => {
728
+ const e = err;
729
+ const status = Number(e?.status ?? e?.statusCode ?? e?.code);
730
+ if (Number.isInteger(status) && status >= 400 && status < 429) {
731
+ // Off the failing request's tick: its transaction is still rolling back when 'failed' fires,
732
+ // and a concurrent write on a second SQLite connection would contend for the lock
733
+ setImmediate(() => {
734
+ if (chargedWindow) {
735
+ void refundDailyBudget(br, grant, chargedWindow).catch((refundErr) => logger.warn(`daily budget refund for grant ${grant.ID} failed: ${String(refundErr?.message ?? refundErr)}`));
736
+ }
737
+ void refundGrantUsage(br, grant, serviceName, event, usageDay).catch((refundErr) => logger.warn(`usage refund for grant ${grant.ID} failed: ${String(refundErr?.message ?? refundErr)}`));
738
+ });
739
+ }
740
+ });
741
+ }
742
+ await touchLastUsed(grant, br);
743
+ }
744
+ /**
745
+ * Consume one unit of the daily budget with two conditional UPDATEs, so concurrent requests cannot
746
+ * overspend: a compare-and-swap window reset and a bounded increment (`jobsUsedToday < max`).
747
+ */
748
+ async function consumeDailyBudget(br, grant) {
749
+ const runner = 'runner' in br ? br : { runner: br, detached: true };
750
+ const today = utcDay();
751
+ const max = grant.maxJobsPerDay;
752
+ if (grant.budgetWindow !== today) {
753
+ const reset = await runStmt(runner, UPDATE.entity(exports.GRANTS_ENTITY)
754
+ .set({ budgetWindow: today, jobsUsedToday: 1 })
755
+ .where({ ID: grant.ID, budgetWindow: grant.budgetWindow ?? null }));
756
+ if (Number(reset))
757
+ return { consumed: true, window: today };
758
+ // lost the reset race: another request already moved the window
759
+ }
760
+ const incremented = await runStmt(runner, UPDATE.entity(exports.GRANTS_ENTITY)
761
+ .set({ jobsUsedToday: { '+=': 1 } })
762
+ .where({ ID: grant.ID, budgetWindow: today, jobsUsedToday: { '<': max } }));
763
+ return { consumed: Number(incremented) > 0, window: today };
764
+ }
765
+ /** Undo one consumeDailyBudget in the window it was charged to; never touches a newer day's counter. */
766
+ async function refundDailyBudget(br, grant, window) {
767
+ const runner = 'runner' in br ? br : { runner: br, detached: true };
768
+ await runStmt(runner, UPDATE.entity(exports.GRANTS_ENTITY)
769
+ .set({ jobsUsedToday: { '-=': 1 } })
770
+ .where({ ID: grant.ID, budgetWindow: window, jobsUsedToday: { '>': 0 } }));
771
+ }
772
+ const USAGE_FLUSH_INTERVAL_MS = 1000;
773
+ const usageBuffer = new Map();
774
+ let usageFlushTimer = null;
775
+ let usageModeOverride = null;
776
+ let usageShutdownHooked = false;
777
+ /** Deferred on the databases whose writers do not block readers; sync everywhere else (SQLite, tests). */
778
+ function usageMode() {
779
+ if (usageModeOverride)
780
+ return usageModeOverride;
781
+ const kind = String(cds_1.default.db?.kind ?? '');
782
+ return kind === 'postgres' || kind === 'hana' ? 'deferred' : 'sync';
783
+ }
784
+ /** Test seam: force a mode (null = derive from cds.db.kind). */
785
+ function __setGrantUsageModeForTests(mode) {
786
+ usageModeOverride = mode;
787
+ }
788
+ /** Test seam: forget buffered deltas and the pending timer. */
789
+ function __resetGrantUsageBufferForTests() {
790
+ usageBuffer.clear();
791
+ if (usageFlushTimer) {
792
+ clearTimeout(usageFlushTimer);
793
+ usageFlushTimer = null;
794
+ }
795
+ }
796
+ /** How many keys wait for the next flush (monitoring, tests). */
797
+ function pendingGrantUsageKeys() {
798
+ return usageBuffer.size;
799
+ }
800
+ function bufferUsage(key, calls, refunded) {
801
+ const k = `${key.grant_ID}|${key.day}|${key.service}|${key.action}`;
802
+ const d = usageBuffer.get(k);
803
+ if (d) {
804
+ d.calls += calls;
805
+ d.refunded += refunded;
806
+ }
807
+ else
808
+ usageBuffer.set(k, { ...key, calls, refunded });
809
+ // under a test override the tests flush explicitly; no timer may race them
810
+ if (!usageFlushTimer && !usageModeOverride) {
811
+ usageFlushTimer = setTimeout(() => {
812
+ usageFlushTimer = null;
813
+ void flushGrantUsage().catch((err) => logger.warn(`usage flush failed: ${String(err?.message ?? err)}`));
814
+ }, USAGE_FLUSH_INTERVAL_MS);
815
+ usageFlushTimer.unref?.();
816
+ }
817
+ if (!usageShutdownHooked) {
818
+ usageShutdownHooked = true;
819
+ cds_1.default.on('shutdown', () => flushGrantUsage().catch(() => undefined));
820
+ }
821
+ }
822
+ /**
823
+ * Writes the buffered deltas per key: UPDATE, INSERT when the row is missing, one more UPDATE when a racing
824
+ * writer created it. A failed delta goes back into the buffer for the next flush.
825
+ */
826
+ async function flushGrantUsage(runner = dbRunner()) {
827
+ if (usageBuffer.size === 0)
828
+ return { flushed: 0, failed: 0 };
829
+ if (!runner) {
830
+ // no database service yet: keep the deltas
831
+ logger.debug('usage flush skipped: no database service');
832
+ return { flushed: 0, failed: usageBuffer.size };
833
+ }
834
+ const batch = [...usageBuffer.values()];
835
+ usageBuffer.clear();
836
+ const br = { runner, detached: true };
837
+ let flushed = 0;
838
+ let failed = 0;
839
+ for (const d of batch) {
840
+ const key = { grant_ID: d.grant_ID, day: d.day, service: d.service, action: d.action };
841
+ const bump = () => runStmt(br, UPDATE.entity(exports.GRANT_USAGE_ENTITY).set({ calls: { '+=': d.calls }, refunded: { '+=': d.refunded } }).where(key));
842
+ try {
843
+ if (Number(await bump()) === 0) {
844
+ try {
845
+ await runStmt(br, INSERT.into(exports.GRANT_USAGE_ENTITY).entries({ ...key, calls: d.calls, refunded: d.refunded }));
846
+ }
847
+ catch (insertErr) {
848
+ // lost the insert race (row exists now); if it is still missing, the INSERT itself failed
849
+ if (Number(await bump()) === 0)
850
+ throw insertErr;
851
+ }
852
+ }
853
+ flushed++;
854
+ }
855
+ catch (err) {
856
+ failed++;
857
+ bufferUsage(key, d.calls, d.refunded); // retried on the next flush
858
+ logger.warn(`usage flush for grant ${d.grant_ID} (${d.service}.${d.action}) failed, kept for retry: ${String(err?.message ?? err)}`);
859
+ }
860
+ }
861
+ return { flushed, failed };
862
+ }
863
+ /**
864
+ * One admitted call: `calls + 1` on (grant, UTC day, service, action). Deferred mode buffers the delta;
865
+ * sync mode writes UPDATE / INSERT / UPDATE awaited. Never fails the request. Returns the day counted on.
866
+ */
867
+ async function recordGrantUsage(br, grant, service, action, now = new Date()) {
868
+ const runner = 'runner' in br ? br : { runner: br, detached: true };
869
+ const day = utcDay(now);
870
+ const key = { grant_ID: grant.ID, day, service, action };
871
+ if (runner.detached && usageMode() === 'deferred') {
872
+ bufferUsage(key, 1, 0);
873
+ return day;
874
+ }
875
+ const bump = () => runStmt(runner, UPDATE.entity(exports.GRANT_USAGE_ENTITY).set({ calls: { '+=': 1 } }).where(key));
876
+ try {
877
+ if (Number(await bump()) > 0)
878
+ return day;
879
+ try {
880
+ await runStmt(runner, INSERT.into(exports.GRANT_USAGE_ENTITY).entries({ ...key, calls: 1, refunded: 0 }));
881
+ }
882
+ catch {
883
+ await bump(); // lost the insert race: the row exists now
884
+ }
885
+ }
886
+ catch (err) {
887
+ logger.warn(`usage record for grant ${grant.ID} (${service}.${action}) failed: ${String(err?.message ?? err)}`);
888
+ }
889
+ return day;
890
+ }
891
+ /** `refunded + 1` on the row the call was counted on; deferred mode buffers it on the same key. */
892
+ async function refundGrantUsage(br, grant, service, action, day) {
893
+ const runner = 'runner' in br ? br : { runner: br, detached: true };
894
+ const key = { grant_ID: grant.ID, day, service, action };
895
+ if (runner.detached && usageMode() === 'deferred') {
896
+ bufferUsage(key, 0, 1);
897
+ return;
898
+ }
899
+ await runStmt(runner, UPDATE.entity(exports.GRANT_USAGE_ENTITY)
900
+ .set({ refunded: { '+=': 1 } })
901
+ .where(key));
902
+ }
903
+ /**
904
+ * lastUsedAt, at most once a minute per grant. Awaited: a fire-and-forget write on a second connection
905
+ * races the handler's reads (SQLITE_BUSY_SNAPSHOT in WAL mode). A failed touch never fails the request.
906
+ */
907
+ const lastUsedTouched = new Map();
908
+ const LAST_USED_INTERVAL_MS = 60_000;
909
+ async function touchLastUsed(grant, br) {
910
+ const now = Date.now();
911
+ const last = lastUsedTouched.get(grant.ID) ?? 0;
912
+ if (now - last < LAST_USED_INTERVAL_MS)
913
+ return;
914
+ lastUsedTouched.set(grant.ID, now);
915
+ try {
916
+ await runStmt(br, UPDATE.entity(exports.GRANTS_ENTITY).set({ lastUsedAt: new Date(now).toISOString() }).where({ ID: grant.ID }));
917
+ }
918
+ catch (err) {
919
+ logger.debug(`lastUsedAt update for grant ${grant.ID} failed: ${String(err?.message ?? err)}`);
920
+ }
921
+ }
922
+ //# sourceMappingURL=agent-grants.js.map