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

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