@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,21 +1,7 @@
1
1
  /**
2
- * Agent-grant feature switch. Read from `cds.requires.odatano-core.agentGrants`
3
- * first, then from the environment; kept in its own tiny module because
4
- * src/plugin.ts reads it at plugin load, before any blockchain module may be
5
- * required.
6
- *
7
- * cds: "odatano-core": { "agentGrants": { "enabled": true, "delegate": "mocked", "adminRateLimit": 10 } }
8
- * env: AGENT_GRANTS_ENABLED=true AGENT_GRANTS_DELEGATE=mocked|basic|jwt|xsuaa|ias|dummy
9
- * AGENT_GRANT_ADMIN_RATE_LIMIT=10
10
- *
11
- * `delegate` names the CAP auth strategy that keeps authenticating every
12
- * request WITHOUT an `x-agent-token` header (the transport lane only adds the
13
- * token path next to it). Default: the configured `cds.requires.auth.kind`.
14
- *
15
- * `adminRateLimit` is the number of grant-administration calls
16
- * (CreateAgentGrant, UpdateAgentGrant, RotateAgentGrantToken, RevokeAgentGrant)
17
- * one principal may make per hour; NIGHTGATE's `NIGHTGATE_GRANT_ADMIN_RATE_LIMIT`.
18
- * A gateway that mints for everybody (ODATANO ACCESS) raises it.
2
+ * Agent-grant feature switch from `cds.requires.odatano-core.agentGrants`, else the environment
3
+ * (AGENT_GRANTS_ENABLED, AGENT_GRANTS_DELEGATE, AGENT_GRANT_ADMIN_RATE_LIMIT). Own module because
4
+ * src/plugin.ts reads it at plugin load, before any blockchain module is required.
19
5
  */
20
6
  export interface AgentGrantsConfig {
21
7
  enabled: boolean;
@@ -27,50 +13,25 @@ export interface AgentGrantsConfig {
27
13
  export declare const AGENT_GRANTS_DELEGATES: readonly string[];
28
14
  export declare const AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = 10;
29
15
  /**
30
- * The admin rate limit: `agentGrants.adminRateLimit`, then
31
- * `AGENT_GRANT_ADMIN_RATE_LIMIT`, default 10. An unusable value (not an
32
- * integer, below 1) is logged once and falls back to the default — a typo in
33
- * this knob must not switch the whole feature off, unlike a wrong delegate.
16
+ * Grant-administration calls per principal per hour: `agentGrants.adminRateLimit`, then
17
+ * `AGENT_GRANT_ADMIN_RATE_LIMIT`, default 10. An unusable value is logged and falls back, never disables the feature.
34
18
  */
35
19
  export declare function loadGrantAdminRateLimit(env?: Record<string, string | undefined>): number;
36
20
  export declare const AGENT_TOKEN_CACHE_MS_DEFAULT = 10000;
37
21
  /**
38
- * How long the transport lane may reuse a resolved token (the grant row) before
39
- * it reads the database again: `agentGrants.tokenCacheMs`, then
40
- * `AGENT_TOKEN_CACHE_MS`, default 10 s, 0 switches the cache off. Seconds, not
41
- * minutes, on purpose: a busy grant sends many requests per second, so a few
42
- * seconds already spare almost every lookup, while a revoke on ANOTHER replica
43
- * is honoured at most this much later (on the same process it is immediate).
44
- * An unusable value (not an integer, below 0) is logged once and falls back.
22
+ * How long the transport lane reuses a resolved grant row before re-reading the DB: `agentGrants.tokenCacheMs`,
23
+ * then `AGENT_TOKEN_CACHE_MS`, default 10 s, 0 disables. Bounds how late a revoke on another replica takes effect.
45
24
  */
46
25
  export declare function loadTokenCacheMs(env?: Record<string, string | undefined>): number;
47
26
  /** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
48
27
  export declare function configuredAuth(): Record<string, unknown>;
49
- /**
50
- * A custom `cds.requires.auth.impl` the host configured before us (anything
51
- * that is not this package's middleware). It keeps authenticating every
52
- * non-token request: the lane wraps it instead of replacing it.
53
- */
28
+ /** A host-configured custom `cds.requires.auth.impl` (not this package's middleware); the lane wraps it. */
54
29
  export declare function customAuthImpl(auth?: Record<string, unknown>): string | null;
55
30
  export declare function loadAgentGrantsConfig(env?: Record<string, string | undefined>): AgentGrantsConfig;
56
31
  /**
57
- * Switch agent grants on for this process when configured. Called from BOTH
58
- * entry points, because CAP loads `cds-plugin.js` only from a project's
59
- * dependencies, never from the project itself:
60
- * - src/plugin.ts at plugin load (consumer app), and
61
- * - srv/server.ts at module load (standalone `cds serve` / `cds watch`, where
62
- * bin/serve.js imports the local server.js BEFORE cds.server() builds its
63
- * middlewares — the last moment `cds.requires.auth.impl` can still change).
64
- *
65
- * When enabled:
66
- * - the transport auth becomes @odatano/cap-auth (unless the host runs it
67
- * already) with the `x-agent-token` lane of srv/utils/agent-token-auth
68
- * registered; every other request goes to the strategy that was configured
69
- * before (CAP's own for `kind`, or the host's custom impl as `delegateImpl`);
70
- * - each of the six services gets the enforcement hook once it is served.
71
- *
72
- * Never throws: a misconfiguration is logged and the feature stays off, so a
73
- * host app never fails to start because of it. Returns whether grants are on.
32
+ * Switch agent grants on when configured: installs @odatano/cap-auth with the `x-agent-token` lane
33
+ * (previous strategy kept as delegate) and attaches the enforcement hook to each service on `serving`.
34
+ * Called from src/plugin.ts and srv/server.ts, before cds.server() builds middlewares. Never throws.
74
35
  */
75
36
  export declare function activateAgentGrants(): boolean;
76
37
  //# sourceMappingURL=agent-grants-config.d.ts.map
@@ -14,10 +14,8 @@ const cds_1 = __importDefault(require("@sap/cds"));
14
14
  exports.AGENT_GRANTS_DELEGATES = ['mocked', 'basic', 'jwt', 'xsuaa', 'ias', 'dummy'];
15
15
  exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = 10;
16
16
  /**
17
- * The admin rate limit: `agentGrants.adminRateLimit`, then
18
- * `AGENT_GRANT_ADMIN_RATE_LIMIT`, default 10. An unusable value (not an
19
- * integer, below 1) is logged once and falls back to the default — a typo in
20
- * this knob must not switch the whole feature off, unlike a wrong delegate.
17
+ * Grant-administration calls per principal per hour: `agentGrants.adminRateLimit`, then
18
+ * `AGENT_GRANT_ADMIN_RATE_LIMIT`, default 10. An unusable value is logged and falls back, never disables the feature.
21
19
  */
22
20
  function loadGrantAdminRateLimit(env = process.env) {
23
21
  const cfg = envRecord();
@@ -33,13 +31,8 @@ function loadGrantAdminRateLimit(env = process.env) {
33
31
  }
34
32
  exports.AGENT_TOKEN_CACHE_MS_DEFAULT = 10_000;
35
33
  /**
36
- * How long the transport lane may reuse a resolved token (the grant row) before
37
- * it reads the database again: `agentGrants.tokenCacheMs`, then
38
- * `AGENT_TOKEN_CACHE_MS`, default 10 s, 0 switches the cache off. Seconds, not
39
- * minutes, on purpose: a busy grant sends many requests per second, so a few
40
- * seconds already spare almost every lookup, while a revoke on ANOTHER replica
41
- * is honoured at most this much later (on the same process it is immediate).
42
- * An unusable value (not an integer, below 0) is logged once and falls back.
34
+ * How long the transport lane reuses a resolved grant row before re-reading the DB: `agentGrants.tokenCacheMs`,
35
+ * then `AGENT_TOKEN_CACHE_MS`, default 10 s, 0 disables. Bounds how late a revoke on another replica takes effect.
43
36
  */
44
37
  function loadTokenCacheMs(env = process.env) {
45
38
  const cfg = envRecord();
@@ -67,11 +60,7 @@ function configuredAuth() {
67
60
  }
68
61
  /** The transport middleware, recognisable in `auth.impl` so activation stays idempotent. */
69
62
  const OUR_IMPL = 'cap-auth';
70
- /**
71
- * A custom `cds.requires.auth.impl` the host configured before us (anything
72
- * that is not this package's middleware). It keeps authenticating every
73
- * non-token request: the lane wraps it instead of replacing it.
74
- */
63
+ /** A host-configured custom `cds.requires.auth.impl` (not this package's middleware); the lane wraps it. */
75
64
  function customAuthImpl(auth = configuredAuth()) {
76
65
  const impl = typeof auth.impl === 'string' ? auth.impl.trim() : '';
77
66
  if (!impl || impl.includes(OUR_IMPL))
@@ -84,8 +73,7 @@ function loadAgentGrantsConfig(env = process.env) {
84
73
  const enabled = enabledRaw === true || String(enabledRaw ?? '').toLowerCase() === 'true';
85
74
  const auth = configuredAuth();
86
75
  const authKind = String(auth.kind ?? 'mocked');
87
- // A host with its own auth.impl keeps it as the delegate ("custom") unless
88
- // an explicit delegate says otherwise.
76
+ // A host's own auth.impl becomes the delegate ("custom") unless configured otherwise.
89
77
  const fallback = customAuthImpl(auth) ? 'custom' : authKind;
90
78
  const delegateRaw = String(cfg.delegate ?? env.AGENT_GRANTS_DELEGATE ?? fallback);
91
79
  // `xsuaa-auth` / `basic-auth` spellings are what CAP itself accepts as kinds.
@@ -98,31 +86,12 @@ function loadAgentGrantsConfig(env = process.env) {
98
86
  }
99
87
  return { enabled, delegate, adminRateLimit: loadGrantAdminRateLimit(env) };
100
88
  }
101
- /**
102
- * Marker on the shared `cds` facade: the activation below must run exactly once
103
- * per process even though this module can be loaded twice (natively by CAP /
104
- * src/plugin.ts and again through a test runner's transform). A module-level
105
- * flag would not survive that; the `cds` singleton does.
106
- */
89
+ /** Once-per-process marker on the `cds` singleton; a module-level flag would not survive a double load. */
107
90
  const ACTIVATED = Symbol.for('odatano.agentGrants.activated');
108
91
  /**
109
- * Switch agent grants on for this process when configured. Called from BOTH
110
- * entry points, because CAP loads `cds-plugin.js` only from a project's
111
- * dependencies, never from the project itself:
112
- * - src/plugin.ts at plugin load (consumer app), and
113
- * - srv/server.ts at module load (standalone `cds serve` / `cds watch`, where
114
- * bin/serve.js imports the local server.js BEFORE cds.server() builds its
115
- * middlewares — the last moment `cds.requires.auth.impl` can still change).
116
- *
117
- * When enabled:
118
- * - the transport auth becomes @odatano/cap-auth (unless the host runs it
119
- * already) with the `x-agent-token` lane of srv/utils/agent-token-auth
120
- * registered; every other request goes to the strategy that was configured
121
- * before (CAP's own for `kind`, or the host's custom impl as `delegateImpl`);
122
- * - each of the six services gets the enforcement hook once it is served.
123
- *
124
- * Never throws: a misconfiguration is logged and the feature stays off, so a
125
- * host app never fails to start because of it. Returns whether grants are on.
92
+ * Switch agent grants on when configured: installs @odatano/cap-auth with the `x-agent-token` lane
93
+ * (previous strategy kept as delegate) and attaches the enforcement hook to each service on `serving`.
94
+ * Called from src/plugin.ts and srv/server.ts, before cds.server() builds middlewares. Never throws.
126
95
  */
127
96
  function activateAgentGrants() {
128
97
  const facade = cds_1.default;
@@ -138,10 +107,8 @@ function activateAgentGrants() {
138
107
  const auth = configuredAuth();
139
108
  const current = typeof auth.impl === 'string' ? auth.impl : '';
140
109
  if (!current.includes(OUR_IMPL)) {
141
- // A host's own auth.impl is preserved as the delegate: the lane only adds
142
- // the token path in front of it, it never replaces the host's gate.
143
- // The absolute path: in plugin mode cds.root is the consumer app, which
144
- // need not resolve this package's dependency.
110
+ // Host's own auth.impl stays as delegate. Absolute path: in plugin mode cds.root is the
111
+ // consumer app, which need not resolve this package's dependency.
145
112
  const original = customAuthImpl(auth);
146
113
  cds_1.default.env.requires.auth = {
147
114
  ...auth,
@@ -1,29 +1,7 @@
1
1
  /**
2
- * Agent grants: scoped, budgeted bearer capabilities for agents.
3
- * Design: AGENT_GRANTS_DESIGN.md. Reference: NIGHTGATE srv/sessions/agent-grants.ts.
4
- *
5
- * Three exports carry the feature:
6
- * - `resolveAgentToken` + `makeAgentUser`: used by the transport lane
7
- * (agent-token-auth.ts) to turn an `x-agent-token` header into the principal
8
- * `agent:<grantId>` with the role `agent-grant` BEFORE any service hook runs.
9
- * Doing the authentication at the transport (not in a before-hook) matters:
10
- * CAP runs before-handlers in parallel, so CAP's own @requires / @restrict
11
- * evaluation must already see the final principal.
12
- * - `attachAgentGrantEnforcement`: the before('*') hook on all six ODATANO
13
- * services. Allow list (403), wallet pinning (403), daily budget (429),
14
- * lastUsedAt. Ownership needs no special code: a token's jobs are created
15
- * with createdBy = `agent:<grantId>`, so the existing `createdBy = $user`
16
- * gates and the `$user.grantId` row restrictions do the narrowing.
17
- * - `registerAgentGrantHandlers`: the grant lifecycle for CardanoAgentService
18
- * (CreateAgentGrant / UpdateAgentGrant / RotateAgentGrantToken /
19
- * RevokeAgentGrant, GetGrantStatus / GetGrantUsage), on top of the
20
- * programmatic `issueAgentGrant` / `updateAgentGrant` /
21
- * `rotateAgentGrantToken` / `revokeAgentGrantById` that @odatano/x402 uses
22
- * to sell grants. Names are this repo's PascalCase; semantics follow
23
- * NIGHTGATE's so a gateway (ODATANO ACCESS) drives both with one code path.
24
- *
25
- * The token is a capability, not an identity: it never carries the operator's
26
- * roles, so every `@requires: 'Admin'` surface refuses it by construction.
2
+ * Agent grants: scoped, budgeted bearer capabilities. The transport lane turns `x-agent-token` into the
3
+ * principal `agent:<grantId>` (role `agent-grant`) before any hook runs; `attachAgentGrantEnforcement`
4
+ * applies allow list, wallet pinning and daily budget; `registerAgentGrantHandlers` is the lifecycle API.
27
5
  */
28
6
  import cds, { Request } from '@sap/cds';
29
7
  import { BackendError } from './errors';
@@ -39,19 +17,15 @@ export declare const GRANT_USAGE_ENTITY = "odatano.cardano.CardanoAgentGrantUsag
39
17
  /** The services the hook attaches to and the transport lane opens. */
40
18
  export declare const AGENT_SERVICE_NAMES: readonly string[];
41
19
  /**
42
- * Actions an operator MAY put on a grant's allow list. Each call costs one
43
- * budget unit (a build is the service an agent buys). Everything not here and
44
- * not in AGENT_ALWAYS_ALLOWED_EVENTS is a hard 403 for token requests: HSM
45
- * signing, pause/resume, grant administration are never grantable.
20
+ * Actions an operator may put on a grant's allow list; each call costs one budget unit. Anything else
21
+ * not in AGENT_ALWAYS_ALLOWED_EVENTS (HSM signing, pause/resume, grant administration) is a 403.
46
22
  */
47
23
  export declare const AGENT_ALLOWLISTABLE_ACTIONS: readonly string[];
48
24
  /** Allow-listable actions that spend from a worker wallet: the grant must be pinned. */
49
25
  export declare const AGENT_WALLET_ACTIONS: ReadonlySet<string>;
50
26
  /**
51
- * Events every valid token may use without an allow-list entry and without
52
- * consuming budget: reads, compute-only actions, status polling. `READ` covers
53
- * every entity set; row-level narrowing is done by the `$user.grantId`
54
- * restrictions in the CDS models, not here.
27
+ * Events every valid token may use without allow-list entry or budget: reads, compute-only actions,
28
+ * status polling. Row-level narrowing is done by the `$user.grantId` restrictions in the CDS models.
55
29
  */
56
30
  export declare const AGENT_ALWAYS_ALLOWED_EVENTS: ReadonlySet<string>;
57
31
  /** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
@@ -100,18 +74,13 @@ export declare function invalidateTokenCache(grantId: string): void;
100
74
  /** Entries waiting in the token cache (monitoring, tests). */
101
75
  export declare function tokenCacheSize(): number;
102
76
  /**
103
- * Authenticate a bearer token: prefix, hash lookup among ACTIVE grants (a
104
- * revoked grant is an unknown token, non-leaking), expiry. Detached from any
105
- * ambient transaction: the lane runs before the request transaction exists,
106
- * and on SQLite the pool holds one connection. The lookup is cached for a few
107
- * seconds (see the token cache above).
77
+ * Authenticate a bearer token: prefix, hash lookup among active grants (revoked = unknown, non-leaking),
78
+ * expiry. Runs detached from any ambient transaction; the lookup is cached (see above).
108
79
  */
109
80
  export declare function resolveAgentToken(token: string, runner?: Runner): Promise<TokenResolution>;
110
81
  /**
111
- * The principal a token request runs under. Deliberately NOT the operator and
112
- * WITHOUT the operator's roles: `createdBy = $user` gates then scope to jobs
113
- * this grant created, `$user.grantId` restrictions to its own grant row, and
114
- * every `@requires: 'Admin'` refuses it.
82
+ * The principal a token request runs under: not the operator and without the operator's roles, so
83
+ * `createdBy = $user` and `$user.grantId` restrictions narrow it and every `@requires: 'Admin'` refuses it.
115
84
  */
116
85
  export declare function makeAgentUser(grant: AgentGrantRow): cds.User;
117
86
  export interface IssueAgentGrantInput {
@@ -145,11 +114,7 @@ interface NormalizedGrantInput {
145
114
  agentLabel: string | null;
146
115
  }
147
116
  export declare function validateGrantInput(input: IssueAgentGrantInput, now?: Date, context?: string): NormalizedGrantInput;
148
- /**
149
- * Mint a grant for `operatorId`. Validation errors surface as
150
- * AgentGrantInputError (400). The INSERT runs on `runner`: the action passes its
151
- * request transaction, x402 passes whatever transaction its settlement runs in.
152
- */
117
+ /** Mint a grant for `operatorId` on `runner`; validation errors surface as AgentGrantInputError (400). */
153
118
  export declare function issueAgentGrant(input: IssueAgentGrantInput, operatorId: string, runner?: Runner): Promise<IssuedAgentGrant>;
154
119
  /** Deactivate a grant; false when it does not exist or is already revoked. */
155
120
  export declare function revokeAgentGrantById(grantId: string, runner?: Runner): Promise<boolean>;
@@ -159,11 +124,8 @@ export interface RotatedAgentGrant {
159
124
  token: string;
160
125
  }
161
126
  /**
162
- * Replace the grant's token; the old one is an unknown token from the next
163
- * request on this process (its cache entry is dropped here; another replica
164
- * keeps it for at most AGENT_TOKEN_CACHE_MS; a request in flight with the old
165
- * token completes). Budget, wallet, allow list and expiry survive. Null when
166
- * the grant does not exist or is revoked.
127
+ * Replace the grant's token; budget, wallet, allow list and expiry survive. The old token is unknown
128
+ * from the next request (another replica: after AGENT_TOKEN_CACHE_MS). Null when missing or revoked.
167
129
  */
168
130
  export declare function rotateAgentGrantToken(grantId: string, runner?: Runner): Promise<RotatedAgentGrant | null>;
169
131
  /** The editable grant fields, as a client sends them: absent = untouched, explicit null = cleared. */
@@ -174,7 +136,7 @@ export interface UpdateAgentGrantInput {
174
136
  maxJobsPerDay?: number | null;
175
137
  validUntil?: string | null;
176
138
  }
177
- /** Row fields a grant edit never touches; a different wallet binding is a different grant (NIGHTGATE: sessionId). */
139
+ /** Row fields a grant edit never touches; a different wallet binding is a different grant. */
178
140
  export declare const GRANT_IMMUTABLE_FIELDS: readonly string[];
179
141
  export type UpdateAgentGrantResult = {
180
142
  ok: true;
@@ -187,18 +149,8 @@ export type UpdateAgentGrantResult = {
187
149
  message: string;
188
150
  };
189
151
  /**
190
- * Change the given fields of an ACTIVE grant. A field absent from `input`
191
- * keeps its value; an explicit null clears agentLabel, allowedJobKinds,
192
- * maxJobsPerDay or validUntil (NIGHTGATE's updateAgentGrant semantics).
193
- * allowedActions cannot be emptied. The merged row goes through
194
- * validateGrantInput, so the cross-field rules hold: wallet actions need the
195
- * grant's (immutable) wallet, job kinds need SubmitWalletJob, a given
196
- * validUntil lies in the future. Lowering maxJobsPerDay below jobsUsedToday is
197
- * allowed; the grant is simply over budget until the UTC day rolls.
198
- *
199
- * Validation errors surface as AgentGrantInputError (400); an unknown grant is
200
- * 404 and a revoked one 409 GRANT_REVOKED (revoked grants are never edited;
201
- * re-mint instead).
152
+ * Edit an active grant: absent field = untouched, explicit null = cleared (allowedActions cannot be emptied).
153
+ * The merged row passes validateGrantInput. Unknown grant 404, revoked 409 GRANT_REVOKED, invalid input 400.
202
154
  */
203
155
  export declare function updateAgentGrant(grantId: string, input: UpdateAgentGrantInput, runner?: Runner): Promise<UpdateAgentGrantResult>;
204
156
  export declare const USAGE_WINDOW_MAX_MS: number;
@@ -214,11 +166,7 @@ export type UsageWindow = {
214
166
  message: string;
215
167
  target: string;
216
168
  };
217
- /**
218
- * since (default until - 30 days) .. until (default now), at most 366 days
219
- * (NIGHTGATE's rules and wording). Counters are per UTC day, so the days both
220
- * ends fall on are included whole.
221
- */
169
+ /** since (default until - 30 days) .. until (default now), at most 366 days; whole UTC days at both ends. */
222
170
  export declare function resolveUsageWindow(since: unknown, until: unknown, now?: Date): UsageWindow;
223
171
  export interface GrantUsageCall {
224
172
  service: string;
@@ -238,12 +186,8 @@ export interface AgentGrantUsage {
238
186
  maxJobsPerDay: number | null;
239
187
  }
240
188
  /**
241
- * The grant's admitted calls in `window`, grouped by service and action (one
242
- * SUM per group). `runner` is the request's transaction (the read); deferred
243
- * counters (Postgres / HANA) are flushed first on `flushRunner`, the detached
244
- * primary db service: written inside the request transaction they would hold
245
- * the rows' locks until the GET commits and vanish with its rollback, while a
246
- * separate autocommit is visible to the following SELECT under read committed.
189
+ * Admitted calls of the grant in `window`, grouped by service and action. Deferred counters are flushed
190
+ * first on `flushRunner` (detached autocommit), so the read on `runner` sees them without holding locks.
247
191
  */
248
192
  export declare function getGrantUsage(grant: AgentGrantRow, window: Extract<UsageWindow, {
249
193
  ok: true;
@@ -261,28 +205,13 @@ export interface AgentGrantStatus {
261
205
  isActive: boolean;
262
206
  }
263
207
  export declare function toGrantStatus(grant: AgentGrantRow): AgentGrantStatus;
264
- /** Validation rejections are thrown BEFORE any transaction work (project convention). */
208
+ /** Validation rejections happen before any transaction work. */
265
209
  export declare function registerAgentGrantHandlers(srv: cds.Service): void;
266
210
  export declare function attachAgentGrantEnforcement(srv: cds.Service, runner?: Runner): void;
267
211
  /**
268
- * Exported for unit tests; see the module doc for the ladder. Ordinary
269
- * principals pass through untouched: this hook is a no-op without a grant.
270
- */
271
- /**
272
- * Where the hook's own writes go.
273
- *
274
- * Default: DETACHED from the request transaction (`runWithoutAmbientTx`), so
275
- * the spend sticks even when the request later fails and no write lock is held
276
- * across the handler's backend round trips.
277
- *
278
- * Exception: a request that already sits inside an open transaction — the
279
- * second and later parts of a `$batch` changeset (atomicity group) — owns the
280
- * pooled connection. On SQLite the pool has one connection, so a detached
281
- * statement would wait for it until the changeset commits, which waits for
282
- * this hook: a deadlock. Such a request rides its own transaction instead; the
283
- * changeset's rollback is then the refund, and no `failed` listener is needed.
284
- * `ready` is set the moment CAP begins the transaction, `dbc` once the
285
- * connection is acquired; either means "already open".
212
+ * Where the hook's writes go: detached from the request transaction by default (the spend sticks, no lock
213
+ * across backend round trips). A request already inside an open transaction (`$batch` changeset parts,
214
+ * `ready` or `dbc` set) rides its own, since a detached statement would deadlock on SQLite's single connection.
286
215
  */
287
216
  export interface BudgetRunner {
288
217
  runner: Runner;
@@ -291,9 +220,8 @@ export interface BudgetRunner {
291
220
  }
292
221
  export declare function budgetRunnerFor(req: Request, injected?: Runner, detached?: boolean): BudgetRunner;
293
222
  /**
294
- * Exported for unit tests; see the module doc for the ladder. Ordinary
295
- * principals pass through untouched: this hook is a no-op without a grant.
296
- * `runner` / `detached` are test seams; production picks them per request.
223
+ * The before('*') hook: allow list, wallet pinning, daily budget, usage, lastUsedAt. No-op without a grant.
224
+ * `runner` / `detached` are test seams.
297
225
  */
298
226
  export declare function enforceAgentGrant(req: Request, runner?: Runner, detached?: boolean, serviceName?: string): Promise<unknown>;
299
227
  export interface BudgetCharge {
@@ -302,17 +230,11 @@ export interface BudgetCharge {
302
230
  window: string;
303
231
  }
304
232
  /**
305
- * Consume one unit of the grant's daily budget. Two conditional UPDATEs so
306
- * concurrent requests cannot overspend: a window reset (compare-and-swap on
307
- * the OLD window value) and a bounded increment (`jobsUsedToday < max`). Runs
308
- * on the BudgetRunner the hook chose (detached by default, see budgetRunnerFor).
233
+ * Consume one unit of the daily budget with two conditional UPDATEs, so concurrent requests cannot
234
+ * overspend: a compare-and-swap window reset and a bounded increment (`jobsUsedToday < max`).
309
235
  */
310
236
  export declare function consumeDailyBudget(br: BudgetRunner | Runner, grant: AgentGrantRow): Promise<BudgetCharge>;
311
- /**
312
- * Undo one consumeDailyBudget in the window it was charged to (a refused
313
- * request created nothing). A refund that lands after midnight must not touch
314
- * the new day's counter: the unit was spent yesterday, yesterday keeps it.
315
- */
237
+ /** Undo one consumeDailyBudget in the window it was charged to; never touches a newer day's counter. */
316
238
  export declare function refundDailyBudget(br: BudgetRunner | Runner, grant: AgentGrantRow, window: string): Promise<void>;
317
239
  type UsageMode = 'sync' | 'deferred';
318
240
  /** Test seam: force a mode (null = derive from cds.db.kind). */
@@ -322,30 +244,19 @@ export declare function __resetGrantUsageBufferForTests(): void;
322
244
  /** How many keys wait for the next flush (monitoring, tests). */
323
245
  export declare function pendingGrantUsageKeys(): number;
324
246
  /**
325
- * Writes the buffered deltas: `calls + n, refunded + m` per key, an INSERT when
326
- * the row does not exist yet, one more UPDATE when a racing writer created it.
327
- * A delta whose write fails goes back into the buffer for the next flush.
328
- * `runner` defaults to the primary db service (tests pass their fake).
247
+ * Writes the buffered deltas per key: UPDATE, INSERT when the row is missing, one more UPDATE when a racing
248
+ * writer created it. A failed delta goes back into the buffer for the next flush.
329
249
  */
330
250
  export declare function flushGrantUsage(runner?: Runner): Promise<{
331
251
  flushed: number;
332
252
  failed: number;
333
253
  }>;
334
254
  /**
335
- * One admitted call: `calls + 1` on (grant, UTC day, service, action).
336
- * Deferred mode (Postgres / HANA, detached runner): the delta goes into the
337
- * buffer, nothing is written here. Sync mode: a conditional UPDATE first (the
338
- * common path), an INSERT when the row does not exist yet, one more UPDATE
339
- * when a racing request inserted it first, AWAITED like every other write of
340
- * the hook (see touchLastUsed). Never fails the request: usage is accounting,
341
- * not admission. Returns the day the call was counted on (the refund names it).
255
+ * One admitted call: `calls + 1` on (grant, UTC day, service, action). Deferred mode buffers the delta;
256
+ * sync mode writes UPDATE / INSERT / UPDATE awaited. Never fails the request. Returns the day counted on.
342
257
  */
343
258
  export declare function recordGrantUsage(br: BudgetRunner | Runner, grant: AgentGrantRow, service: string, action: string, now?: Date): Promise<string>;
344
- /**
345
- * `refunded + 1` on the row the call was counted on: a refused request admitted
346
- * nothing. Deferred mode: into the buffer, on the same key the call went to,
347
- * whether or not that call has been flushed yet (the flush adds deltas).
348
- */
259
+ /** `refunded + 1` on the row the call was counted on; deferred mode buffers it on the same key. */
349
260
  export declare function refundGrantUsage(br: BudgetRunner | Runner, grant: AgentGrantRow, service: string, action: string, day: string): Promise<void>;
350
261
  export {};
351
262
  //# sourceMappingURL=agent-grants.d.ts.map