@odatano/core 2.0.0-rc.19 → 2.0.0-rc.20

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 (119) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +1 -5
  2. package/@cds-models/CardanoIndexerService/index.d.ts +51 -2
  3. package/@cds-models/CardanoIndexerService/index.js +7 -0
  4. package/package.json +1 -1
  5. package/src/index.d.ts +4 -10
  6. package/src/index.js +6 -16
  7. package/src/plugin.js +11 -27
  8. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  9. package/srv/blockchain/backends/blockfrost-backend.js +39 -150
  10. package/srv/blockchain/backends/cardano-backend.d.ts +53 -171
  11. package/srv/blockchain/backends/cardano-backend.js +1 -5
  12. package/srv/blockchain/backends/koios-backend.d.ts +26 -71
  13. package/srv/blockchain/backends/koios-backend.js +50 -132
  14. package/srv/blockchain/backends/ogmios-backend.d.ts +43 -124
  15. package/srv/blockchain/backends/ogmios-backend.js +71 -179
  16. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +12 -57
  17. package/srv/blockchain/backends/ogmios-frame-guard.js +27 -66
  18. package/srv/blockchain/cardano-client.d.ts +43 -216
  19. package/srv/blockchain/cardano-client.js +49 -234
  20. package/srv/blockchain/cardano-indexer.d.ts +79 -357
  21. package/srv/blockchain/cardano-indexer.js +98 -406
  22. package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
  23. package/srv/blockchain/cardano-tx-builder.js +21 -107
  24. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  25. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  26. package/srv/blockchain/crawler/crawler.d.ts +41 -145
  27. package/srv/blockchain/crawler/crawler.js +57 -172
  28. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  29. package/srv/blockchain/crawler/index.d.ts +2 -6
  30. package/srv/blockchain/crawler/index.js +4 -9
  31. package/srv/blockchain/crawler/sync-state.d.ts +17 -39
  32. package/srv/blockchain/crawler/sync-state.js +23 -55
  33. package/srv/blockchain/crawler/utxo-set-import.d.ts +5 -22
  34. package/srv/blockchain/crawler/utxo-set-import.js +8 -28
  35. package/srv/blockchain/ledger-state.d.ts +3 -12
  36. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  37. package/srv/blockchain/signing/cose-verifier.js +6 -12
  38. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  39. package/srv/blockchain/signing/external-signer.js +19 -122
  40. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  41. package/srv/blockchain/signing/hsm-signer.js +23 -63
  42. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  43. package/srv/blockchain/signing/signature-verifier.js +13 -54
  44. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  45. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  46. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +65 -174
  47. package/srv/blockchain/transaction-building/buildooor-tx.js +107 -266
  48. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  49. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  50. package/srv/blockchain/wallet-worker/build-request.js +9 -22
  51. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +12 -35
  52. package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -32
  53. package/srv/blockchain/wallet-worker/index.js +2 -8
  54. package/srv/blockchain/wallet-worker/job-store.d.ts +33 -111
  55. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  56. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  57. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  58. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  59. package/srv/blockchain/wallet-worker/signers.js +3 -8
  60. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  61. package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
  62. package/srv/cardano-agent-service.cds +1 -5
  63. package/srv/cardano-agent-service.js +3 -7
  64. package/srv/cardano-indexer-service.cds +32 -4
  65. package/srv/cardano-indexer-service.js +83 -15
  66. package/srv/cardano-service.js +36 -98
  67. package/srv/cardano-sign-service.cds +1 -1
  68. package/srv/cardano-sign-service.js +55 -173
  69. package/srv/cardano-tx-service.cds +1 -1
  70. package/srv/cardano-tx-service.js +54 -174
  71. package/srv/cardano-worker-service.js +7 -15
  72. package/srv/server.d.ts +27 -86
  73. package/srv/server.js +52 -148
  74. package/srv/utils/agent-grants-config.d.ts +11 -50
  75. package/srv/utils/agent-grants-config.js +12 -45
  76. package/srv/utils/agent-grants.d.ts +34 -123
  77. package/srv/utils/agent-grants.js +57 -156
  78. package/srv/utils/agent-token-auth.d.ts +2 -5
  79. package/srv/utils/agent-token-auth.js +2 -5
  80. package/srv/utils/backend-request-handler.d.ts +2 -16
  81. package/srv/utils/backend-request-handler.js +3 -18
  82. package/srv/utils/collections.d.ts +4 -8
  83. package/srv/utils/collections.js +4 -8
  84. package/srv/utils/const.d.ts +19 -68
  85. package/srv/utils/const.js +20 -69
  86. package/srv/utils/crypto.d.ts +3 -12
  87. package/srv/utils/crypto.js +5 -18
  88. package/srv/utils/db-indexes.d.ts +2 -7
  89. package/srv/utils/db-indexes.js +7 -34
  90. package/srv/utils/db-sanitize.d.ts +5 -18
  91. package/srv/utils/db-sanitize.js +6 -19
  92. package/srv/utils/error-codes.d.ts +18 -73
  93. package/srv/utils/error-codes.js +17 -70
  94. package/srv/utils/errors.d.ts +29 -191
  95. package/srv/utils/errors.js +44 -229
  96. package/srv/utils/liveness.d.ts +2 -9
  97. package/srv/utils/liveness.js +3 -11
  98. package/srv/utils/mappers.d.ts +50 -298
  99. package/srv/utils/mappers.js +80 -386
  100. package/srv/utils/network-context.js +2 -11
  101. package/srv/utils/pg-order-nulls.js +4 -23
  102. package/srv/utils/plutus-placeholders.d.ts +6 -18
  103. package/srv/utils/plutus-placeholders.js +6 -20
  104. package/srv/utils/rate-limiter.d.ts +6 -17
  105. package/srv/utils/rate-limiter.js +5 -15
  106. package/srv/utils/service-events.d.ts +2 -22
  107. package/srv/utils/service-events.js +3 -23
  108. package/srv/utils/signing-helper.d.ts +3 -18
  109. package/srv/utils/signing-helper.js +10 -32
  110. package/srv/utils/tx-build-helper.d.ts +18 -92
  111. package/srv/utils/tx-build-helper.js +32 -123
  112. package/srv/utils/tx-request-parsers.d.ts +7 -26
  113. package/srv/utils/tx-request-parsers.js +7 -26
  114. package/srv/utils/tx-utils.d.ts +4 -23
  115. package/srv/utils/tx-utils.js +12 -41
  116. package/srv/utils/types.d.ts +67 -206
  117. package/srv/utils/types.js +2 -6
  118. package/srv/utils/validators.d.ts +19 -89
  119. package/srv/utils/validators.js +31 -138
@@ -1,30 +1,8 @@
1
1
  "use strict";
2
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`: the grant lifecycle for CardanoAgentService
19
- * (CreateAgentGrant / UpdateAgentGrant / RotateAgentGrantToken /
20
- * RevokeAgentGrant, GetGrantStatus / GetGrantUsage), on top of the
21
- * programmatic `issueAgentGrant` / `updateAgentGrant` /
22
- * `rotateAgentGrantToken` / `revokeAgentGrantById` that @odatano/x402 uses
23
- * to sell grants. Names are this repo's PascalCase; semantics follow
24
- * NIGHTGATE's so a gateway (ODATANO ACCESS) drives both with one code path.
25
- *
26
- * The token is a capability, not an identity: it never carries the operator's
27
- * roles, so every `@requires: 'Admin'` surface refuses it by construction.
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.
28
6
  */
29
7
  var __importDefault = (this && this.__importDefault) || function (mod) {
30
8
  return (mod && mod.__esModule) ? mod : { "default": mod };
@@ -90,10 +68,8 @@ exports.AGENT_SERVICE_NAMES = [
90
68
  'CardanoAgentService',
91
69
  ];
92
70
  /**
93
- * Actions an operator MAY put on a grant's allow list. Each call costs one
94
- * budget unit (a build is the service an agent buys). Everything not here and
95
- * not in AGENT_ALWAYS_ALLOWED_EVENTS is a hard 403 for token requests: HSM
96
- * signing, pause/resume, grant administration are never grantable.
71
+ * Actions an operator may put on a grant's allow list; each call costs one budget unit. Anything else
72
+ * not in AGENT_ALWAYS_ALLOWED_EVENTS (HSM signing, pause/resume, grant administration) is a 403.
97
73
  */
98
74
  exports.AGENT_ALLOWLISTABLE_ACTIONS = [
99
75
  // CardanoTransactionService: unsigned CBOR
@@ -117,10 +93,8 @@ exports.AGENT_ALLOWLISTABLE_ACTIONS = [
117
93
  /** Allow-listable actions that spend from a worker wallet: the grant must be pinned. */
118
94
  exports.AGENT_WALLET_ACTIONS = new Set(['SubmitWalletJob', 'CancelJob']);
119
95
  /**
120
- * Events every valid token may use without an allow-list entry and without
121
- * consuming budget: reads, compute-only actions, status polling. `READ` covers
122
- * every entity set; row-level narrowing is done by the `$user.grantId`
123
- * restrictions in the CDS models, not here.
96
+ * Events every valid token may use without allow-list entry or budget: reads, compute-only actions,
97
+ * status polling. Row-level narrowing is done by the `$user.grantId` restrictions in the CDS models.
124
98
  */
125
99
  exports.AGENT_ALWAYS_ALLOWED_EVENTS = new Set([
126
100
  'READ',
@@ -141,12 +115,7 @@ exports.AGENT_ALWAYS_ALLOWED_EVENTS = new Set([
141
115
  ]);
142
116
  /** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
143
117
  exports.AGENT_JOB_KINDS = ['simpleAda', 'metadata', 'multiAsset', 'mint', 'plutusSpend', 'submitSigned'];
144
- /**
145
- * Grant administration (Create / Update / Rotate / Revoke): N per principal per
146
- * hour, N from `agentGrants.adminRateLimit` / `AGENT_GRANT_ADMIN_RATE_LIMIT`
147
- * (default 10, NIGHTGATE's `NIGHTGATE_GRANT_ADMIN_RATE_LIMIT`). Built on first
148
- * use so the knob is read once the config is loaded, and re-read after a reset.
149
- */
118
+ /** Grant administration limiter: `adminRateLimit` calls per principal per hour, built on first use. */
150
119
  let grantAdminRateLimiter = null;
151
120
  function grantAdminLimiter() {
152
121
  grantAdminRateLimiter ??= new rate_limiter_1.RateLimiter({ windowMs: 60 * 60 * 1000, maxRequests: (0, agent_grants_config_1.loadGrantAdminRateLimit)() });
@@ -233,7 +202,7 @@ function tokenCacheSize() {
233
202
  }
234
203
  function rememberToken(hash, grant, ttl) {
235
204
  if (tokenCache.size >= TOKEN_CACHE_MAX) {
236
- // Bounded: a flood of distinct tokens must not grow the map without end.
205
+ // bounded against a flood of distinct tokens
237
206
  tokenCache.clear();
238
207
  tokenHashOfGrant.clear();
239
208
  }
@@ -241,11 +210,8 @@ function rememberToken(hash, grant, ttl) {
241
210
  tokenHashOfGrant.set(grant.ID, hash);
242
211
  }
243
212
  /**
244
- * Authenticate a bearer token: prefix, hash lookup among ACTIVE grants (a
245
- * revoked grant is an unknown token, non-leaking), expiry. Detached from any
246
- * ambient transaction: the lane runs before the request transaction exists,
247
- * and on SQLite the pool holds one connection. The lookup is cached for a few
248
- * seconds (see the token cache above).
213
+ * Authenticate a bearer token: prefix, hash lookup among active grants (revoked = unknown, non-leaking),
214
+ * expiry. Runs detached from any ambient transaction; the lookup is cached (see above).
249
215
  */
250
216
  async function resolveAgentToken(token, runner = dbRunner()) {
251
217
  if (typeof token !== 'string' || !token.startsWith(exports.AGENT_TOKEN_PREFIX)) {
@@ -270,17 +236,14 @@ async function resolveAgentToken(token, runner = dbRunner()) {
270
236
  return { ok: false, status: 401, message: 'invalid agent token' };
271
237
  if (isExpired(grant))
272
238
  return { ok: false, status: 410, message: 'agent grant expired' };
273
- // Not remembered when a revoke / rotate / update ran while the SELECT was in
274
- // flight: the row read before the UPDATE would outlive the invalidation.
239
+ // not remembered when an invalidation ran while the SELECT was in flight
275
240
  if (cacheable && generation === tokenCacheGeneration)
276
241
  rememberToken(hash, grant, ttl);
277
242
  return { ok: true, grant };
278
243
  }
279
244
  /**
280
- * The principal a token request runs under. Deliberately NOT the operator and
281
- * WITHOUT the operator's roles: `createdBy = $user` gates then scope to jobs
282
- * this grant created, `$user.grantId` restrictions to its own grant row, and
283
- * every `@requires: 'Admin'` refuses it.
245
+ * The principal a token request runs under: not the operator and without the operator's roles, so
246
+ * `createdBy = $user` and `$user.grantId` restrictions narrow it and every `@requires: 'Admin'` refuses it.
284
247
  */
285
248
  function makeAgentUser(grant) {
286
249
  return new cds_1.default.User({
@@ -348,11 +311,7 @@ function validateGrantInput(input, now = new Date(), context = 'CreateAgentGrant
348
311
  throw fail('agentLabel must be at most 100 characters', 'agentLabel');
349
312
  return { allowedActions: uniqueActions, walletId, allowedJobKinds, maxJobsPerDay, validUntil, agentLabel };
350
313
  }
351
- /**
352
- * Mint a grant for `operatorId`. Validation errors surface as
353
- * AgentGrantInputError (400). The INSERT runs on `runner`: the action passes its
354
- * request transaction, x402 passes whatever transaction its settlement runs in.
355
- */
314
+ /** Mint a grant for `operatorId` on `runner`; validation errors surface as AgentGrantInputError (400). */
356
315
  async function issueAgentGrant(input, operatorId, runner = dbRunner()) {
357
316
  if (!operatorId)
358
317
  throw new AgentGrantInputError('an operator id is required');
@@ -376,7 +335,7 @@ async function issueAgentGrant(input, operatorId, runner = dbRunner()) {
376
335
  lastUsedAt: null,
377
336
  };
378
337
  await runner.run(INSERT.into(exports.GRANTS_ENTITY).entries(grant));
379
- // Deliberately logs the id, the label and the shape, never the token.
338
+ // never logs the token
380
339
  logger.info(`agent grant ${grant.ID} issued by ${operatorId}` +
381
340
  `${n.agentLabel ? ` for '${n.agentLabel}'` : ''} (actions: ${n.allowedActions.join(', ')}` +
382
341
  `${n.walletId ? `, wallet ${n.walletId}` : ''}${n.maxJobsPerDay ? `, budget ${n.maxJobsPerDay}/day` : ''}` +
@@ -405,11 +364,8 @@ async function revokeAgentGrantById(grantId, runner = dbRunner()) {
405
364
  return revoked;
406
365
  }
407
366
  /**
408
- * Replace the grant's token; the old one is an unknown token from the next
409
- * request on this process (its cache entry is dropped here; another replica
410
- * keeps it for at most AGENT_TOKEN_CACHE_MS; a request in flight with the old
411
- * token completes). Budget, wallet, allow list and expiry survive. Null when
412
- * the grant does not exist or is revoked.
367
+ * Replace the grant's token; budget, wallet, allow list and expiry survive. The old token is unknown
368
+ * from the next request (another replica: after AGENT_TOKEN_CACHE_MS). Null when missing or revoked.
413
369
  */
414
370
  async function rotateAgentGrantToken(grantId, runner = dbRunner()) {
415
371
  if (!grantId)
@@ -422,24 +378,14 @@ async function rotateAgentGrantToken(grantId, runner = dbRunner()) {
422
378
  logger.info(`agent grant ${grantId} token rotated`);
423
379
  return { grantId, token };
424
380
  }
425
- /** Row fields a grant edit never touches; a different wallet binding is a different grant (NIGHTGATE: sessionId). */
381
+ /** Row fields a grant edit never touches; a different wallet binding is a different grant. */
426
382
  exports.GRANT_IMMUTABLE_FIELDS = ['walletId', 'userId', 'tokenHash'];
427
383
  const GRANT_EDITABLE_FIELDS = [
428
384
  'agentLabel', 'allowedActions', 'allowedJobKinds', 'maxJobsPerDay', 'validUntil',
429
385
  ];
430
386
  /**
431
- * Change the given fields of an ACTIVE grant. A field absent from `input`
432
- * keeps its value; an explicit null clears agentLabel, allowedJobKinds,
433
- * maxJobsPerDay or validUntil (NIGHTGATE's updateAgentGrant semantics).
434
- * allowedActions cannot be emptied. The merged row goes through
435
- * validateGrantInput, so the cross-field rules hold: wallet actions need the
436
- * grant's (immutable) wallet, job kinds need SubmitWalletJob, a given
437
- * validUntil lies in the future. Lowering maxJobsPerDay below jobsUsedToday is
438
- * allowed; the grant is simply over budget until the UTC day rolls.
439
- *
440
- * Validation errors surface as AgentGrantInputError (400); an unknown grant is
441
- * 404 and a revoked one 409 GRANT_REVOKED (revoked grants are never edited;
442
- * re-mint instead).
387
+ * Edit an active grant: absent field = untouched, explicit null = cleared (allowedActions cannot be emptied).
388
+ * The merged row passes validateGrantInput. Unknown grant 404, revoked 409 GRANT_REVOKED, invalid input 400.
443
389
  */
444
390
  async function updateAgentGrant(grantId, input, runner = dbRunner()) {
445
391
  const has = (k) => Object.prototype.hasOwnProperty.call(input, k);
@@ -448,8 +394,7 @@ async function updateAgentGrant(grantId, input, runner = dbRunner()) {
448
394
  return { ok: false, status: 404, message: 'Grant not found' };
449
395
  if (existing.isActive === false)
450
396
  return { ok: false, status: 409, code: 'GRANT_REVOKED', message: 'Grant is revoked' };
451
- // The merged row. validUntil only when given: an untouched expiry that has
452
- // meanwhile passed is the lane's 410, not this edit's 400.
397
+ // validUntil only when given: an untouched, already passed expiry is the lane's 410, not this edit's 400
453
398
  const n = validateGrantInput({
454
399
  allowedActions: has('allowedActions') ? input.allowedActions : parseGrantList(existing.allowedActions),
455
400
  walletId: existing.walletId ?? null,
@@ -472,7 +417,7 @@ async function updateAgentGrant(grantId, input, runner = dbRunner()) {
472
417
  const updated = GRANT_EDITABLE_FIELDS.filter((f) => has(f));
473
418
  if (updated.length === 0)
474
419
  return { ok: true, grantId, updated: [] };
475
- // Conditional on isActive: a concurrent revoke wins over the edit.
420
+ // conditional on isActive: a concurrent revoke wins
476
421
  const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY).set(patch).where({ ID: grantId, isActive: true }));
477
422
  invalidateTokenCache(grantId);
478
423
  if (Number(affected) === 0)
@@ -492,11 +437,7 @@ function parseTimestamp(raw) {
492
437
  const t = new Date(String(raw));
493
438
  return Number.isNaN(t.getTime()) ? null : t.toISOString();
494
439
  }
495
- /**
496
- * since (default until - 30 days) .. until (default now), at most 366 days
497
- * (NIGHTGATE's rules and wording). Counters are per UTC day, so the days both
498
- * ends fall on are included whole.
499
- */
440
+ /** since (default until - 30 days) .. until (default now), at most 366 days; whole UTC days at both ends. */
500
441
  function resolveUsageWindow(since, until, now = new Date()) {
501
442
  const to = parseTimestamp(until);
502
443
  const from = parseTimestamp(since);
@@ -515,12 +456,8 @@ function resolveUsageWindow(since, until, now = new Date()) {
515
456
  return { ok: true, since: sinceIso, until: untilIso, sinceDay: sinceIso.slice(0, 10), untilDay: untilIso.slice(0, 10) };
516
457
  }
517
458
  /**
518
- * The grant's admitted calls in `window`, grouped by service and action (one
519
- * SUM per group). `runner` is the request's transaction (the read); deferred
520
- * counters (Postgres / HANA) are flushed first on `flushRunner`, the detached
521
- * primary db service: written inside the request transaction they would hold
522
- * the rows' locks until the GET commits and vanish with its rollback, while a
523
- * separate autocommit is visible to the following SELECT under read committed.
459
+ * Admitted calls of the grant in `window`, grouped by service and action. Deferred counters are flushed
460
+ * first on `flushRunner` (detached autocommit), so the read on `runner` sees them without holding locks.
524
461
  */
525
462
  async function getGrantUsage(grant, window, runner = dbRunner(), flushRunner = dbRunner()) {
526
463
  if (pendingGrantUsageKeys() > 0)
@@ -556,7 +493,7 @@ function toGrantStatus(grant) {
556
493
  walletId: grant.walletId ?? null,
557
494
  allowedJobKinds: parseGrantList(grant.allowedJobKinds),
558
495
  maxJobsPerDay: grant.maxJobsPerDay ?? null,
559
- // A counter from an earlier UTC day is spent budget of a window that is over.
496
+ // a counter from an earlier UTC day belongs to a window that is over
560
497
  jobsUsedToday: grant.budgetWindow === utcDay() ? Number(grant.jobsUsedToday ?? 0) : 0,
561
498
  budgetWindow: grant.budgetWindow ?? null,
562
499
  validUntil: grant.validUntil ?? null,
@@ -567,11 +504,8 @@ function toGrantStatus(grant) {
567
504
  // CardanoAgentService handlers
568
505
  // ---------------------------------------------------------------------------
569
506
  /**
570
- * The common prelude of the four administration actions: the rate limit first
571
- * (refusals consume the window, like NIGHTGATE), then the token principal
572
- * (belt and braces: none of these is always-allowed or allow-listable, so the
573
- * hook 403s, and @requires: 'Admin' refuses the role-less principal anyway),
574
- * then authentication. False after a reject.
507
+ * Prelude of the administration actions: rate limit (refusals consume the window), then no token
508
+ * principal, then authentication. False after a reject.
575
509
  */
576
510
  function checkGrantAdmin(req, verb) {
577
511
  const rate = grantAdminLimiter().check((0, rate_limiter_1.principalRateKey)(req, 'grant-admin'));
@@ -593,7 +527,7 @@ function userIs(req, role) {
593
527
  const user = req.user;
594
528
  return typeof user?.is === 'function' ? user.is(role) === true : false;
595
529
  }
596
- /** Validation rejections are thrown BEFORE any transaction work (project convention). */
530
+ /** Validation rejections happen before any transaction work. */
597
531
  function registerAgentGrantHandlers(srv) {
598
532
  srv.on('CreateAgentGrant', async (req) => {
599
533
  if (!checkGrantAdmin(req, 'issue'))
@@ -668,8 +602,7 @@ function registerAgentGrantHandlers(srv) {
668
602
  }
669
603
  return { grantId: result.grantId, updated: result.updated };
670
604
  });
671
- // GetGrantStatus: the calling token's own grant, read fresh so the budget
672
- // counter is current. An operator without a token lists AgentGrants instead.
605
+ // The calling token's own grant, read fresh so the budget counter is current
673
606
  srv.on('GetGrantStatus', async (req) => {
674
607
  const grant = agentGrantOf(req);
675
608
  if (!grant)
@@ -677,8 +610,7 @@ function registerAgentGrantHandlers(srv) {
677
610
  const fresh = (await cds_1.default.tx(req).run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: grant.ID })));
678
611
  return toGrantStatus(fresh ?? grant);
679
612
  });
680
- // GetGrantUsage: an Admin sees any grant (revoked ones keep their history), a
681
- // token only its own — the hook already narrowed it (404, non-leaking).
613
+ // Admin sees any grant (revoked ones keep their history), a token only its own (404 otherwise)
682
614
  srv.on('GetGrantUsage', async (req) => {
683
615
  const data = (req.data ?? {});
684
616
  if (!data.grantId)
@@ -723,16 +655,14 @@ async function runStmt(br, statement) {
723
655
  return br.detached ? (0, tx_utils_1.runWithoutAmbientTx)(() => br.runner.run(statement)) : br.runner.run(statement);
724
656
  }
725
657
  /**
726
- * Exported for unit tests; see the module doc for the ladder. Ordinary
727
- * principals pass through untouched: this hook is a no-op without a grant.
728
- * `runner` / `detached` are test seams; production picks them per request.
658
+ * The before('*') hook: allow list, wallet pinning, daily budget, usage, lastUsedAt. No-op without a grant.
659
+ * `runner` / `detached` are test seams.
729
660
  */
730
661
  async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown') {
731
662
  const grant = agentGrantOf(req);
732
663
  if (!grant)
733
664
  return;
734
- // Defence in depth: the lane already refused inactive and expired grants, but
735
- // a grant can be revoked between two parts of a $batch, or expire mid-flight.
665
+ // A grant can be revoked between two parts of a $batch, or expire mid-flight
736
666
  if (grant.isActive === false)
737
667
  return req.reject(401, 'invalid agent token');
738
668
  if (isExpired(grant))
@@ -740,8 +670,7 @@ async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown')
740
670
  const br = budgetRunnerFor(req, runner, detached);
741
671
  const event = String(req.event ?? '');
742
672
  if (exports.AGENT_ALWAYS_ALLOWED_EVENTS.has(event)) {
743
- // The handler's Admin gate alone would answer for every grant: a token sees
744
- // its own usage only, and a foreign id is not found (non-leaking, NIGHTGATE).
673
+ // a token sees its own usage only; a foreign id is not found (non-leaking)
745
674
  if (event === 'GetGrantUsage') {
746
675
  const asked = String(req.data?.grantId ?? '');
747
676
  if (asked !== grant.ID)
@@ -770,8 +699,7 @@ async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown')
770
699
  return req.reject(403, `job kind '${String(data.kind ?? '')}' is not allowed for this agent grant (allowed: ${kinds.join(', ')})`);
771
700
  }
772
701
  }
773
- // CancelJob: the job lookup is owner-scoped by createdBy = agent:<grantId>
774
- // in the worker service, so a foreign job is a 404 there already.
702
+ // CancelJob: the worker service scopes the job lookup by createdBy = agent:<grantId>
775
703
  }
776
704
  }
777
705
  let charge = null;
@@ -781,23 +709,19 @@ async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown')
781
709
  return req.reject(429, `agent grant daily budget exhausted (${grant.maxJobsPerDay}/day)`);
782
710
  }
783
711
  }
784
- // Admitted: one usage unit on (grant, day, service, action), budgeted or not.
712
+ // one usage unit on (grant, day, service, action), budgeted or not
785
713
  const usageDay = await recordGrantUsage(br, grant, serviceName, event);
786
- // Detached writes: a request the handler refuses as invalid (400..428)
787
- // admitted nothing, so give the budget unit back — in the window it was
788
- // charged to, not in whatever day it is when the refund runs — and mark the
789
- // usage unit refunded. 429 and every 5xx keep both (over-count, never
790
- // under-count). Writes made inside the request's own transaction need none
791
- // of this: its rollback undoes them.
714
+ // Detached writes: a request refused as invalid (400..428) admitted nothing, so refund the budget unit
715
+ // in the window it was charged to and mark the usage unit refunded; 429 and 5xx keep both.
716
+ // Writes inside the request's own transaction are undone by its rollback.
792
717
  if (br.detached) {
793
718
  const chargedWindow = charge?.window ?? null;
794
719
  req.on?.('failed', (err) => {
795
720
  const e = err;
796
721
  const status = Number(e?.status ?? e?.statusCode ?? e?.code);
797
722
  if (Number.isInteger(status) && status >= 400 && status < 429) {
798
- // Off the failing request's tick: its transaction is still rolling
799
- // back when 'failed' fires, and a write on a second connection at
800
- // that moment is the SQLite lock contention this module must never cause.
723
+ // Off the failing request's tick: its transaction is still rolling back when 'failed' fires,
724
+ // and a concurrent write on a second SQLite connection would contend for the lock
801
725
  setImmediate(() => {
802
726
  if (chargedWindow) {
803
727
  void refundDailyBudget(br, grant, chargedWindow).catch((refundErr) => logger.warn(`daily budget refund for grant ${grant.ID} failed: ${String(refundErr?.message ?? refundErr)}`));
@@ -810,10 +734,8 @@ async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown')
810
734
  await touchLastUsed(grant, br);
811
735
  }
812
736
  /**
813
- * Consume one unit of the grant's daily budget. Two conditional UPDATEs so
814
- * concurrent requests cannot overspend: a window reset (compare-and-swap on
815
- * the OLD window value) and a bounded increment (`jobsUsedToday < max`). Runs
816
- * on the BudgetRunner the hook chose (detached by default, see budgetRunnerFor).
737
+ * Consume one unit of the daily budget with two conditional UPDATEs, so concurrent requests cannot
738
+ * overspend: a compare-and-swap window reset and a bounded increment (`jobsUsedToday < max`).
817
739
  */
818
740
  async function consumeDailyBudget(br, grant) {
819
741
  const runner = 'runner' in br ? br : { runner: br, detached: true };
@@ -825,18 +747,14 @@ async function consumeDailyBudget(br, grant) {
825
747
  .where({ ID: grant.ID, budgetWindow: grant.budgetWindow ?? null }));
826
748
  if (Number(reset))
827
749
  return { consumed: true, window: today };
828
- // Lost the reset race: another request already moved the window.
750
+ // lost the reset race: another request already moved the window
829
751
  }
830
752
  const incremented = await runStmt(runner, UPDATE.entity(exports.GRANTS_ENTITY)
831
753
  .set({ jobsUsedToday: { '+=': 1 } })
832
754
  .where({ ID: grant.ID, budgetWindow: today, jobsUsedToday: { '<': max } }));
833
755
  return { consumed: Number(incremented) > 0, window: today };
834
756
  }
835
- /**
836
- * Undo one consumeDailyBudget in the window it was charged to (a refused
837
- * request created nothing). A refund that lands after midnight must not touch
838
- * the new day's counter: the unit was spent yesterday, yesterday keeps it.
839
- */
757
+ /** Undo one consumeDailyBudget in the window it was charged to; never touches a newer day's counter. */
840
758
  async function refundDailyBudget(br, grant, window) {
841
759
  const runner = 'runner' in br ? br : { runner: br, detached: true };
842
760
  await runStmt(runner, UPDATE.entity(exports.GRANTS_ENTITY)
@@ -880,8 +798,7 @@ function bufferUsage(key, calls, refunded) {
880
798
  }
881
799
  else
882
800
  usageBuffer.set(k, { ...key, calls, refunded });
883
- // Under a test override the tests flush explicitly: a timer racing them drained
884
- // the buffer mid-test on a slow run (seen in the full unit suite, 2026-09-23).
801
+ // under a test override the tests flush explicitly; no timer may race them
885
802
  if (!usageFlushTimer && !usageModeOverride) {
886
803
  usageFlushTimer = setTimeout(() => {
887
804
  usageFlushTimer = null;
@@ -895,16 +812,14 @@ function bufferUsage(key, calls, refunded) {
895
812
  }
896
813
  }
897
814
  /**
898
- * Writes the buffered deltas: `calls + n, refunded + m` per key, an INSERT when
899
- * the row does not exist yet, one more UPDATE when a racing writer created it.
900
- * A delta whose write fails goes back into the buffer for the next flush.
901
- * `runner` defaults to the primary db service (tests pass their fake).
815
+ * Writes the buffered deltas per key: UPDATE, INSERT when the row is missing, one more UPDATE when a racing
816
+ * writer created it. A failed delta goes back into the buffer for the next flush.
902
817
  */
903
818
  async function flushGrantUsage(runner = dbRunner()) {
904
819
  if (usageBuffer.size === 0)
905
820
  return { flushed: 0, failed: 0 };
906
821
  if (!runner) {
907
- // No database service yet (early boot, tests without cds.db): keep the deltas.
822
+ // no database service yet: keep the deltas
908
823
  logger.debug('usage flush skipped: no database service');
909
824
  return { flushed: 0, failed: usageBuffer.size };
910
825
  }
@@ -922,8 +837,7 @@ async function flushGrantUsage(runner = dbRunner()) {
922
837
  await runStmt(br, INSERT.into(exports.GRANT_USAGE_ENTITY).entries({ ...key, calls: d.calls, refunded: d.refunded }));
923
838
  }
924
839
  catch (insertErr) {
925
- // Lost the insert race: the row exists now. Anything else (the row is
926
- // still missing) is the INSERT's own failure: keep the delta.
840
+ // lost the insert race (row exists now); if it is still missing, the INSERT itself failed
927
841
  if (Number(await bump()) === 0)
928
842
  throw insertErr;
929
843
  }
@@ -939,13 +853,8 @@ async function flushGrantUsage(runner = dbRunner()) {
939
853
  return { flushed, failed };
940
854
  }
941
855
  /**
942
- * One admitted call: `calls + 1` on (grant, UTC day, service, action).
943
- * Deferred mode (Postgres / HANA, detached runner): the delta goes into the
944
- * buffer, nothing is written here. Sync mode: a conditional UPDATE first (the
945
- * common path), an INSERT when the row does not exist yet, one more UPDATE
946
- * when a racing request inserted it first, AWAITED like every other write of
947
- * the hook (see touchLastUsed). Never fails the request: usage is accounting,
948
- * not admission. Returns the day the call was counted on (the refund names it).
856
+ * One admitted call: `calls + 1` on (grant, UTC day, service, action). Deferred mode buffers the delta;
857
+ * sync mode writes UPDATE / INSERT / UPDATE awaited. Never fails the request. Returns the day counted on.
949
858
  */
950
859
  async function recordGrantUsage(br, grant, service, action, now = new Date()) {
951
860
  const runner = 'runner' in br ? br : { runner: br, detached: true };
@@ -971,11 +880,7 @@ async function recordGrantUsage(br, grant, service, action, now = new Date()) {
971
880
  }
972
881
  return day;
973
882
  }
974
- /**
975
- * `refunded + 1` on the row the call was counted on: a refused request admitted
976
- * nothing. Deferred mode: into the buffer, on the same key the call went to,
977
- * whether or not that call has been flushed yet (the flush adds deltas).
978
- */
883
+ /** `refunded + 1` on the row the call was counted on; deferred mode buffers it on the same key. */
979
884
  async function refundGrantUsage(br, grant, service, action, day) {
980
885
  const runner = 'runner' in br ? br : { runner: br, detached: true };
981
886
  const key = { grant_ID: grant.ID, day, service, action };
@@ -988,12 +893,8 @@ async function refundGrantUsage(br, grant, service, action, day) {
988
893
  .where(key));
989
894
  }
990
895
  /**
991
- * lastUsedAt, at most once a minute per grant. AWAITED, like the budget
992
- * statements: every write this hook makes must be finished before the handler
993
- * opens the request's own transaction. A fire-and-forget write on a second
994
- * connection races the handler's reads and, on SQLite in WAL mode, turns the
995
- * handler's first UPSERT into "database is locked" (SQLITE_BUSY_SNAPSHOT) —
996
- * seen live on 2026-09-05. A failed touch is logged and never fails the request.
896
+ * lastUsedAt, at most once a minute per grant. Awaited: a fire-and-forget write on a second connection
897
+ * races the handler's reads (SQLITE_BUSY_SNAPSHOT in WAL mode). A failed touch never fails the request.
997
898
  */
998
899
  const lastUsedTouched = new Map();
999
900
  const LAST_USED_INTERVAL_MS = 60_000;
@@ -1,9 +1,6 @@
1
1
  /**
2
- * The `x-agent-token` transport lane for `@odatano/cap-auth`: a token on one
3
- * of the ODATANO service paths is authenticated here (unknown 401, expired
4
- * 410, non-leaking) and the request continues as `agent:<grantId>` with the
5
- * role `agent-grant`; the grant rides on the express request for the
6
- * enforcement hook. A token on any other path is left to the delegate.
2
+ * `x-agent-token` transport lane: a token on a service path runs as `agent:<grantId>` with
3
+ * role `agent-grant` (unknown 401, expired 410); other paths fall through to the delegate.
7
4
  * Failed attempts are throttled per client address (20 per 15 minutes).
8
5
  */
9
6
  import { type TransportLane } from '@odatano/cap-auth';
@@ -1,10 +1,7 @@
1
1
  "use strict";
2
2
  /**
3
- * The `x-agent-token` transport lane for `@odatano/cap-auth`: a token on one
4
- * of the ODATANO service paths is authenticated here (unknown 401, expired
5
- * 410, non-leaking) and the request continues as `agent:<grantId>` with the
6
- * role `agent-grant`; the grant rides on the express request for the
7
- * enforcement hook. A token on any other path is left to the delegate.
3
+ * `x-agent-token` transport lane: a token on a service path runs as `agent:<grantId>` with
4
+ * role `agent-grant` (unknown 401, expired 410); other paths fall through to the delegate.
8
5
  * Failed attempts are throttled per client address (20 per 15 minutes).
9
6
  */
10
7
  var __importDefault = (this && this.__importDefault) || function (mod) {
@@ -1,20 +1,6 @@
1
1
  import cds, { Request } from '@sap/cds';
2
- /**
3
- * BackendRequestHandler - Provides standardized handling for backend requests
4
- */
5
- /**
6
- * BackendRequestHandler - Wraps a backend method call with standardized error handling
7
- * @param fn - The async function to execute
8
- * @param backendName - Name of the backend (for error context)
9
- * @param resourceName - Name of the resource being accessed (e.g., "Transaction", "Address")
10
- * @returns {Promise<T>} The result of the backend call or a normalized error
11
- */
2
+ /** Wraps a backend call and normalizes any thrown error to a BackendError subclass. */
12
3
  export declare function handleBackendRequest<T>(fn: () => Promise<T>, backendName: string): Promise<T>;
13
- /**
14
- * General request handler for CardanoService
15
- * @param req - The incoming request
16
- * @param handler - The async function containing business logic
17
- * @returns {Promise<unknown>} The result of the handler or a mapped error response
18
- */
4
+ /** Runs a service handler inside the request transaction and maps errors to OData responses. */
19
5
  export declare function handleRequest(req: Request, handler: (db: cds.Transaction) => Promise<unknown>): Promise<unknown>;
20
6
  //# sourceMappingURL=backend-request-handler.d.ts.map
@@ -9,16 +9,7 @@ const errors_1 = require("./errors");
9
9
  const cds_1 = __importDefault(require("@sap/cds"));
10
10
  const mappers_1 = require("./mappers");
11
11
  const logger = cds_1.default.log('BackendRequestHandler');
12
- /**
13
- * BackendRequestHandler - Provides standardized handling for backend requests
14
- */
15
- /**
16
- * BackendRequestHandler - Wraps a backend method call with standardized error handling
17
- * @param fn - The async function to execute
18
- * @param backendName - Name of the backend (for error context)
19
- * @param resourceName - Name of the resource being accessed (e.g., "Transaction", "Address")
20
- * @returns {Promise<T>} The result of the backend call or a normalized error
21
- */
12
+ /** Wraps a backend call and normalizes any thrown error to a BackendError subclass. */
22
13
  async function handleBackendRequest(fn, backendName) {
23
14
  try {
24
15
  return await fn();
@@ -27,16 +18,10 @@ async function handleBackendRequest(fn, backendName) {
27
18
  throw (0, errors_1.normalizeBackendError)(err, backendName);
28
19
  }
29
20
  }
30
- /**
31
- * General request handler for CardanoService
32
- * @param req - The incoming request
33
- * @param handler - The async function containing business logic
34
- * @returns {Promise<unknown>} The result of the handler or a mapped error response
35
- */
21
+ /** Runs a service handler inside the request transaction and maps errors to OData responses. */
36
22
  async function handleRequest(req, handler) {
37
23
  const context = req.target?.name || req.event;
38
- // cds.tx(req) returns the request's managed transaction — CAP auto-rolls back
39
- // on req.reject()/req.error() (called by mapError). No explicit rollback needed.
24
+ // Managed transaction: CAP rolls back on req.reject()/req.error(), no explicit rollback.
40
25
  const db = cds_1.default.tx(req);
41
26
  try {
42
27
  return await handler(db);
@@ -1,13 +1,9 @@
1
+ /** Small collection helpers shared across the blockchain layer. */
1
2
  /**
2
- * Small collection helpers shared across the blockchain layer.
3
- */
4
- /**
5
- * Split an array into fixed-size chunks. Used to keep CQL IN-lists below DB driver
6
- * bind-variable limits (SQLite caps at 999 on older builds / 32766 on node:sqlite).
7
- * @param arr source array (not mutated)
8
- * @param size chunk size (must be > 0; guarded to avoid an infinite loop)
3
+ * Split an array into fixed-size chunks; keeps CQL IN-lists below driver bind-variable limits
4
+ * (SQLite: 999 on older builds, 32766 on node:sqlite).
9
5
  */
10
6
  export declare function chunk<T>(arr: T[], size: number): T[][];
11
- /** Max bind variables per IN-list — well below every supported driver's cap. */
7
+ /** Max bind variables per IN-list, below every supported driver's cap. */
12
8
  export declare const IN_CHUNK = 500;
13
9
  //# sourceMappingURL=collections.d.ts.map
@@ -1,15 +1,11 @@
1
1
  "use strict";
2
- /**
3
- * Small collection helpers shared across the blockchain layer.
4
- */
2
+ /** Small collection helpers shared across the blockchain layer. */
5
3
  Object.defineProperty(exports, "__esModule", { value: true });
6
4
  exports.IN_CHUNK = void 0;
7
5
  exports.chunk = chunk;
8
6
  /**
9
- * Split an array into fixed-size chunks. Used to keep CQL IN-lists below DB driver
10
- * bind-variable limits (SQLite caps at 999 on older builds / 32766 on node:sqlite).
11
- * @param arr source array (not mutated)
12
- * @param size chunk size (must be > 0; guarded to avoid an infinite loop)
7
+ * Split an array into fixed-size chunks; keeps CQL IN-lists below driver bind-variable limits
8
+ * (SQLite: 999 on older builds, 32766 on node:sqlite).
13
9
  */
14
10
  function chunk(arr, size) {
15
11
  if (size <= 0)
@@ -19,6 +15,6 @@ function chunk(arr, size) {
19
15
  out.push(arr.slice(i, i + size));
20
16
  return out;
21
17
  }
22
- /** Max bind variables per IN-list — well below every supported driver's cap. */
18
+ /** Max bind variables per IN-list, below every supported driver's cap. */
23
19
  exports.IN_CHUNK = 500;
24
20
  //# sourceMappingURL=collections.js.map