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

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 (208) 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 +347 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
  6. package/@cds-models/CardanoIndexerService/index.js +64 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +414 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +32 -19
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
  14. package/@cds-models/index.d.ts +101 -1
  15. package/@cds-models/index.js +16 -1
  16. package/@cds-models/odatano/cardano/index.d.ts +437 -32
  17. package/@cds-models/odatano/cardano/index.js +48 -0
  18. package/README.md +207 -167
  19. package/db/schema.cds +2402 -1705
  20. package/db/types.cds +446 -295
  21. package/package.json +41 -16
  22. package/scripts/migrate-schema.mjs +334 -0
  23. package/scripts/migrate-slot-leader.mjs +96 -0
  24. package/src/index.d.ts +20 -21
  25. package/src/index.js +45 -31
  26. package/src/plugin.js +17 -35
  27. package/srv/blockchain/asset-decimals.d.ts +7 -0
  28. package/srv/blockchain/asset-decimals.js +91 -0
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
  30. package/srv/blockchain/backends/blockfrost-backend.js +66 -172
  31. package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
  32. package/srv/blockchain/backends/cardano-backend.js +29 -5
  33. package/srv/blockchain/backends/koios-backend.d.ts +103 -168
  34. package/srv/blockchain/backends/koios-backend.js +428 -360
  35. package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
  36. package/srv/blockchain/backends/odatano-backend.js +169 -0
  37. package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
  38. package/srv/blockchain/backends/ogmios-backend.js +637 -315
  39. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  40. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  41. package/srv/blockchain/cardano-client.d.ts +61 -241
  42. package/srv/blockchain/cardano-client.js +253 -293
  43. package/srv/blockchain/cardano-indexer.d.ts +282 -281
  44. package/srv/blockchain/cardano-indexer.js +1551 -484
  45. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  46. package/srv/blockchain/cardano-tx-builder.js +164 -140
  47. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  48. package/srv/blockchain/circuit-breaker.js +5 -15
  49. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  50. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  51. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  52. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  53. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
  54. package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
  55. package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
  56. package/srv/blockchain/crawler/certificate-backfill.js +162 -0
  57. package/srv/blockchain/crawler/crawler.d.ts +104 -81
  58. package/srv/blockchain/crawler/crawler.js +532 -160
  59. package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
  60. package/srv/blockchain/crawler/credential-backfill.js +124 -0
  61. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  62. package/srv/blockchain/crawler/index.d.ts +1 -8
  63. package/srv/blockchain/crawler/index.js +31 -17
  64. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  65. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  66. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  67. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  68. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  69. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  70. package/srv/blockchain/crawler/sync-state.d.ts +27 -47
  71. package/srv/blockchain/crawler/sync-state.js +113 -63
  72. package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
  73. package/srv/blockchain/crawler/transaction-backfill.js +278 -0
  74. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  75. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  76. package/srv/blockchain/ledger-state.d.ts +62 -0
  77. package/srv/blockchain/ledger-state.js +419 -0
  78. package/srv/blockchain/pending-spends.d.ts +16 -0
  79. package/srv/blockchain/pending-spends.js +81 -0
  80. package/srv/blockchain/pool-metadata.d.ts +15 -0
  81. package/srv/blockchain/pool-metadata.js +132 -0
  82. package/srv/blockchain/request-coalescer.d.ts +2 -16
  83. package/srv/blockchain/request-coalescer.js +2 -16
  84. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  85. package/srv/blockchain/signing/cose-verifier.js +146 -70
  86. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  87. package/srv/blockchain/signing/external-signer.js +17 -126
  88. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  89. package/srv/blockchain/signing/hsm-signer.js +28 -79
  90. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  91. package/srv/blockchain/signing/signature-verifier.js +70 -83
  92. package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
  93. package/srv/blockchain/signing/submission-finalizer.js +219 -86
  94. package/srv/blockchain/stored-chain.d.ts +20 -0
  95. package/srv/blockchain/stored-chain.js +237 -0
  96. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  97. package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
  98. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  99. package/srv/blockchain/transaction-presence.d.ts +5 -0
  100. package/srv/blockchain/transaction-presence.js +29 -0
  101. package/srv/blockchain/transaction-rows.d.ts +12 -0
  102. package/srv/blockchain/transaction-rows.js +44 -0
  103. package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
  104. package/srv/blockchain/wallet-worker/build-request.js +47 -30
  105. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
  106. package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
  107. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  108. package/srv/blockchain/wallet-worker/index.js +3 -11
  109. package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
  110. package/srv/blockchain/wallet-worker/job-store.js +101 -201
  111. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  112. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  113. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  114. package/srv/blockchain/wallet-worker/signers.js +4 -12
  115. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
  116. package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
  117. package/srv/cardano-agent-service.cds +122 -84
  118. package/srv/cardano-agent-service.js +4 -9
  119. package/srv/cardano-backend-service.cds +78 -0
  120. package/srv/cardano-backend-service.d.ts +2 -0
  121. package/srv/cardano-backend-service.js +242 -0
  122. package/srv/cardano-indexer-service.cds +387 -73
  123. package/srv/cardano-indexer-service.d.ts +5 -1
  124. package/srv/cardano-indexer-service.js +532 -16
  125. package/srv/cardano-service.cds +424 -269
  126. package/srv/cardano-service.js +289 -201
  127. package/srv/cardano-sign-service.cds +201 -180
  128. package/srv/cardano-sign-service.js +71 -201
  129. package/srv/cardano-tx-service.cds +451 -370
  130. package/srv/cardano-tx-service.js +271 -289
  131. package/srv/cardano-ui.cds +16 -16
  132. package/srv/cardano-worker-service.cds +118 -125
  133. package/srv/cardano-worker-service.js +52 -61
  134. package/srv/cbor/cip68.d.ts +13 -0
  135. package/srv/cbor/cip68.js +56 -0
  136. package/srv/cbor/index.d.ts +3 -1
  137. package/srv/cbor/index.js +9 -1
  138. package/srv/cbor/parse.d.ts +30 -18
  139. package/srv/cbor/parse.js +44 -9
  140. package/srv/cbor/plutus-data-json.d.ts +20 -0
  141. package/srv/cbor/plutus-data-json.js +32 -0
  142. package/srv/config.d.ts +113 -0
  143. package/srv/config.js +409 -0
  144. package/srv/server.d.ts +15 -110
  145. package/srv/server.js +84 -404
  146. package/srv/utils/agent-access.d.ts +9 -0
  147. package/srv/utils/agent-access.js +67 -0
  148. package/srv/utils/agent-grants-config.d.ts +0 -46
  149. package/srv/utils/agent-grants-config.js +17 -85
  150. package/srv/utils/agent-grants.d.ts +106 -122
  151. package/srv/utils/agent-grants.js +538 -236
  152. package/srv/utils/agent-token-auth.d.ts +4 -99
  153. package/srv/utils/agent-token-auth.js +18 -182
  154. package/srv/utils/backend-request-handler.d.ts +3 -17
  155. package/srv/utils/backend-request-handler.js +3 -18
  156. package/srv/utils/collections.d.ts +3 -10
  157. package/srv/utils/collections.js +3 -10
  158. package/srv/utils/const.d.ts +23 -74
  159. package/srv/utils/const.js +32 -79
  160. package/srv/utils/crypto.d.ts +3 -12
  161. package/srv/utils/crypto.js +6 -21
  162. package/srv/utils/db-indexes.d.ts +27 -0
  163. package/srv/utils/db-indexes.js +120 -0
  164. package/srv/utils/db-sanitize.d.ts +20 -0
  165. package/srv/utils/db-sanitize.js +80 -0
  166. package/srv/utils/deep-json.d.ts +6 -0
  167. package/srv/utils/deep-json.js +240 -0
  168. package/srv/utils/epoch-slots.d.ts +13 -0
  169. package/srv/utils/epoch-slots.js +38 -0
  170. package/srv/utils/error-codes.d.ts +22 -75
  171. package/srv/utils/error-codes.js +23 -72
  172. package/srv/utils/errors.d.ts +46 -187
  173. package/srv/utils/errors.js +114 -230
  174. package/srv/utils/liveness.d.ts +12 -0
  175. package/srv/utils/liveness.js +35 -0
  176. package/srv/utils/mappers.d.ts +102 -223
  177. package/srv/utils/mappers.js +387 -316
  178. package/srv/utils/network-context.js +2 -13
  179. package/srv/utils/paging.d.ts +31 -0
  180. package/srv/utils/paging.js +43 -0
  181. package/srv/utils/pg-inline-json.d.ts +8 -0
  182. package/srv/utils/pg-inline-json.js +58 -0
  183. package/srv/utils/pg-order-nulls.d.ts +14 -0
  184. package/srv/utils/pg-order-nulls.js +54 -0
  185. package/srv/utils/plutus-placeholders.d.ts +16 -22
  186. package/srv/utils/plutus-placeholders.js +62 -33
  187. package/srv/utils/rate-limiter.d.ts +2 -21
  188. package/srv/utils/rate-limiter.js +5 -17
  189. package/srv/utils/readiness.d.ts +12 -0
  190. package/srv/utils/readiness.js +29 -0
  191. package/srv/utils/reference-script.d.ts +19 -0
  192. package/srv/utils/reference-script.js +84 -0
  193. package/srv/utils/result-numbers.d.ts +15 -0
  194. package/srv/utils/result-numbers.js +61 -0
  195. package/srv/utils/service-events.d.ts +0 -24
  196. package/srv/utils/service-events.js +3 -25
  197. package/srv/utils/signing-helper.d.ts +3 -20
  198. package/srv/utils/signing-helper.js +35 -64
  199. package/srv/utils/tx-build-helper.d.ts +10 -105
  200. package/srv/utils/tx-build-helper.js +81 -144
  201. package/srv/utils/tx-request-parsers.d.ts +82 -33
  202. package/srv/utils/tx-request-parsers.js +401 -49
  203. package/srv/utils/tx-utils.d.ts +3 -27
  204. package/srv/utils/tx-utils.js +32 -50
  205. package/srv/utils/types.d.ts +261 -191
  206. package/srv/utils/types.js +2 -6
  207. package/srv/utils/validators.d.ts +22 -92
  208. package/srv/utils/validators.js +50 -149
@@ -0,0 +1,9 @@
1
+ export type AgentAccess = 'read' | 'grant' | 'operator';
2
+ type Model = {
3
+ definitions?: Record<string, unknown>;
4
+ };
5
+ export declare function agentAccessOf(service: string, event: string, model?: Model | null | undefined): AgentAccess | 'closed';
6
+ /** Names of the operations a grant may list, in model order. */
7
+ export declare function agentGrantableActions(model?: Model | null | undefined): string[];
8
+ export {};
9
+ //# sourceMappingURL=agent-access.d.ts.map
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.agentAccessOf = agentAccessOf;
7
+ exports.agentGrantableActions = agentGrantableActions;
8
+ const cds_1 = __importDefault(require("@sap/cds"));
9
+ const ANNOTATION = '@odatano.agent';
10
+ const LEVELS = ['read', 'grant', 'operator'];
11
+ const tables = new WeakMap();
12
+ function buildTable(model) {
13
+ const table = { closed: new Set(), operations: new Map() };
14
+ const definitions = Object.entries((model.definitions ?? {}));
15
+ const services = definitions.filter(([, def]) => def.kind === 'service').map(([name]) => name);
16
+ const serviceOf = (name) => services.find((service) => name.startsWith(`${service}.`));
17
+ const add = (service, operation, def) => {
18
+ const access = def[ANNOTATION];
19
+ if (typeof access !== 'string' || !LEVELS.includes(access))
20
+ return;
21
+ const key = `${service}.${operation}`;
22
+ const known = table.operations.get(key);
23
+ // two operations of one service under one name must agree, else the name is refused
24
+ table.operations.set(key, known && known !== access ? 'operator' : access);
25
+ };
26
+ for (const [name, def] of definitions) {
27
+ if (def.kind === 'service' && def[ANNOTATION] === 'closed')
28
+ table.closed.add(name);
29
+ const service = serviceOf(name);
30
+ if (!service)
31
+ continue;
32
+ if (def.kind === 'action' || def.kind === 'function')
33
+ add(service, name.slice(service.length + 1), def);
34
+ for (const [bound, action] of Object.entries(def.actions ?? {}))
35
+ add(service, bound, action);
36
+ }
37
+ return table;
38
+ }
39
+ function tableOf(model) {
40
+ if (!model)
41
+ return undefined;
42
+ let table = tables.get(model);
43
+ if (!table)
44
+ tables.set(model, (table = buildTable(model)));
45
+ return table;
46
+ }
47
+ // Access of an agent token to `event` on `service`. Entity reads are `read`. An operation without
48
+ // the annotation, any other event and everything before the model is loaded are `operator`.
49
+ function agentAccessOf(service, event, model = cds_1.default.model) {
50
+ const table = tableOf(model);
51
+ if (!table)
52
+ return 'operator';
53
+ if (table.closed.has(service))
54
+ return 'closed';
55
+ if (event === 'READ')
56
+ return 'read';
57
+ return table.operations.get(`${service}.${event}`) ?? 'operator';
58
+ }
59
+ /** Names of the operations a grant may list, in model order. */
60
+ function agentGrantableActions(model = cds_1.default.model) {
61
+ const table = tableOf(model);
62
+ if (!table)
63
+ return [];
64
+ const names = [...table.operations].filter(([, access]) => access === 'grant').map(([key]) => key.slice(key.indexOf('.') + 1));
65
+ return [...new Set(names)];
66
+ }
67
+ //# sourceMappingURL=agent-access.js.map
@@ -1,48 +1,2 @@
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" } }
8
- * env: AGENT_GRANTS_ENABLED=true AGENT_GRANTS_DELEGATE=mocked|basic|jwt|xsuaa|ias|dummy
9
- *
10
- * `delegate` names the CAP auth strategy that keeps authenticating every
11
- * request WITHOUT an `x-agent-token` header (the transport lane only adds the
12
- * token path next to it). Default: the configured `cds.requires.auth.kind`.
13
- */
14
- export interface AgentGrantsConfig {
15
- enabled: boolean;
16
- /** CAP auth kind the transport middleware delegates to for non-token requests. */
17
- delegate: string;
18
- }
19
- export declare const AGENT_GRANTS_DELEGATES: readonly string[];
20
- /** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
21
- export declare function configuredAuth(): Record<string, unknown>;
22
- /**
23
- * A custom `cds.requires.auth.impl` the host configured before us (anything
24
- * that is not this package's middleware). It keeps authenticating every
25
- * non-token request: the lane wraps it instead of replacing it.
26
- */
27
- export declare function customAuthImpl(auth?: Record<string, unknown>): string | null;
28
- export declare function loadAgentGrantsConfig(env?: Record<string, string | undefined>): AgentGrantsConfig;
29
- /**
30
- * Switch agent grants on for this process when configured. Called from BOTH
31
- * entry points, because CAP loads `cds-plugin.js` only from a project's
32
- * dependencies, never from the project itself:
33
- * - src/plugin.ts at plugin load (consumer app), and
34
- * - srv/server.ts at module load (standalone `cds serve` / `cds watch`, where
35
- * bin/serve.js imports the local server.js BEFORE cds.server() builds its
36
- * middlewares — the last moment `cds.requires.auth.impl` can still change).
37
- *
38
- * When enabled:
39
- * - the transport auth becomes srv/utils/agent-token-auth, which admits the
40
- * `x-agent-token` header on the six service paths and delegates every other
41
- * request to the strategy that was configured before (kept as the delegate);
42
- * - each of the six services gets the enforcement hook once it is served.
43
- *
44
- * Never throws: a misconfiguration is logged and the feature stays off, so a
45
- * host app never fails to start because of it. Returns whether grants are on.
46
- */
47
1
  export declare function activateAgentGrants(): boolean;
48
2
  //# sourceMappingURL=agent-grants-config.d.ts.map
@@ -3,109 +3,41 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.AGENT_GRANTS_DELEGATES = void 0;
7
- exports.configuredAuth = configuredAuth;
8
- exports.customAuthImpl = customAuthImpl;
9
- exports.loadAgentGrantsConfig = loadAgentGrantsConfig;
10
6
  exports.activateAgentGrants = activateAgentGrants;
7
+ // Switches the agent grant feature on. src/plugin.ts calls it before any service module loads.
11
8
  const cds_1 = __importDefault(require("@sap/cds"));
12
- const path_1 = __importDefault(require("path"));
13
- exports.AGENT_GRANTS_DELEGATES = ['mocked', 'basic', 'jwt', 'xsuaa', 'ias', 'dummy'];
14
- function envRecord() {
15
- const requires = (cds_1.default.env?.requires ?? {});
16
- const core = (requires['odatano-core'] ?? {});
17
- return (core.agentGrants ?? {});
18
- }
19
- /** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
20
- function configuredAuth() {
21
- const auth = cds_1.default.env?.requires?.auth;
22
- if (typeof auth === 'string')
23
- return { kind: auth };
24
- return (auth ?? {});
25
- }
26
- /** Our own middleware module, recognisable in `auth.impl` so activation stays idempotent. */
27
- const OUR_IMPL = 'agent-token-auth';
28
- /**
29
- * A custom `cds.requires.auth.impl` the host configured before us (anything
30
- * that is not this package's middleware). It keeps authenticating every
31
- * non-token request: the lane wraps it instead of replacing it.
32
- */
33
- function customAuthImpl(auth = configuredAuth()) {
34
- const impl = typeof auth.impl === 'string' ? auth.impl.trim() : '';
35
- if (!impl || impl.includes(OUR_IMPL))
36
- return null;
37
- return impl;
38
- }
39
- function loadAgentGrantsConfig(env = process.env) {
40
- const cfg = envRecord();
41
- const enabledRaw = cfg.enabled !== undefined ? cfg.enabled : env.AGENT_GRANTS_ENABLED;
42
- const enabled = enabledRaw === true || String(enabledRaw ?? '').toLowerCase() === 'true';
43
- const auth = configuredAuth();
44
- const authKind = String(auth.kind ?? 'mocked');
45
- // A host with its own auth.impl keeps it as the delegate ("custom") unless
46
- // an explicit delegate says otherwise.
47
- const fallback = customAuthImpl(auth) ? 'custom' : authKind;
48
- const delegateRaw = String(cfg.delegate ?? env.AGENT_GRANTS_DELEGATE ?? fallback);
49
- // `xsuaa-auth` / `basic-auth` spellings are what CAP itself accepts as kinds.
50
- const delegate = delegateRaw.replace(/-auth$/, '');
51
- if (enabled && delegate !== 'custom' && !exports.AGENT_GRANTS_DELEGATES.includes(delegate)) {
52
- throw new Error(`Invalid agentGrants.delegate "${delegateRaw}". Must be one of: ${exports.AGENT_GRANTS_DELEGATES.join(', ')}, custom`);
53
- }
54
- if (enabled && delegate === 'custom' && !customAuthImpl(auth)) {
55
- throw new Error('agentGrants.delegate "custom" needs a custom cds.requires.auth.impl to delegate to');
56
- }
57
- return { enabled, delegate };
58
- }
59
- /**
60
- * Marker on the shared `cds` facade: the activation below must run exactly once
61
- * per process even though this module can be loaded twice (natively by CAP /
62
- * src/plugin.ts and again through a test runner's transform). A module-level
63
- * flag would not survive that; the `cds` singleton does.
64
- */
9
+ const config_1 = require("../config");
10
+ /** Once-per-process marker on the `cds` singleton; a module-level flag would not survive a double load. */
65
11
  const ACTIVATED = Symbol.for('odatano.agentGrants.activated');
66
- /**
67
- * Switch agent grants on for this process when configured. Called from BOTH
68
- * entry points, because CAP loads `cds-plugin.js` only from a project's
69
- * dependencies, never from the project itself:
70
- * - src/plugin.ts at plugin load (consumer app), and
71
- * - srv/server.ts at module load (standalone `cds serve` / `cds watch`, where
72
- * bin/serve.js imports the local server.js BEFORE cds.server() builds its
73
- * middlewares — the last moment `cds.requires.auth.impl` can still change).
74
- *
75
- * When enabled:
76
- * - the transport auth becomes srv/utils/agent-token-auth, which admits the
77
- * `x-agent-token` header on the six service paths and delegates every other
78
- * request to the strategy that was configured before (kept as the delegate);
79
- * - each of the six services gets the enforcement hook once it is served.
80
- *
81
- * Never throws: a misconfiguration is logged and the feature stays off, so a
82
- * host app never fails to start because of it. Returns whether grants are on.
83
- */
12
+ // Installs @odatano/cap-auth with the `x-agent-token` lane and keeps the old strategy as delegate.
13
+ // Must run before cds.server() builds middlewares. Never throws.
84
14
  function activateAgentGrants() {
85
15
  const facade = cds_1.default;
86
16
  if (facade[ACTIVATED] !== undefined)
87
17
  return facade[ACTIVATED] === true;
88
18
  const logger = cds_1.default.log('ODATANO');
89
19
  try {
90
- const agentGrants = loadAgentGrantsConfig();
20
+ const agentGrants = (0, config_1.loadAgentGrantsConfig)();
91
21
  if (!agentGrants.enabled) {
92
22
  facade[ACTIVATED] = false;
93
23
  return false;
94
24
  }
95
- const auth = configuredAuth();
25
+ const auth = (0, config_1.configuredAuth)();
96
26
  const current = typeof auth.impl === 'string' ? auth.impl : '';
97
- if (!current.includes(OUR_IMPL)) {
98
- // A host's own auth.impl is preserved as the delegate: the lane only adds
99
- // the token path in front of it, it never replaces the host's gate.
100
- const original = customAuthImpl(auth);
27
+ if (!current.includes(config_1.AGENT_AUTH_IMPL)) {
28
+ // Host's own auth.impl stays as delegate. Absolute path: in plugin mode cds.root is the
29
+ // consumer app, which need not resolve this package's dependency.
30
+ const original = (0, config_1.customAuthImpl)(auth);
101
31
  cds_1.default.env.requires.auth = {
102
32
  ...auth,
103
- kind: auth.kind ?? agentGrants.delegate,
104
- impl: path_1.default.join(__dirname, OUR_IMPL),
105
- agentGrantsDelegate: agentGrants.delegate,
106
- ...(original ? { agentGrantsDelegateImpl: original } : {})
33
+ kind: agentGrants.delegate === 'custom' ? auth.kind : agentGrants.delegate,
34
+ impl: require.resolve('@odatano/cap-auth'),
35
+ ...(original ? { delegateImpl: original } : {})
107
36
  };
108
37
  }
38
+ const { registerTransportLane } = require('@odatano/cap-auth');
39
+ const { agentTokenLane } = require('./agent-token-auth');
40
+ registerTransportLane(agentTokenLane);
109
41
  cds_1.default.on('serving', (srv) => {
110
42
  const { AGENT_SERVICE_NAMES, attachAgentGrantEnforcement } = require('./agent-grants');
111
43
  if (AGENT_SERVICE_NAMES.includes(srv.name))
@@ -1,29 +1,6 @@
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`: CreateAgentGrant / RevokeAgentGrant /
18
- * GetGrantStatus for CardanoAgentService, on top of the programmatic
19
- * `issueAgentGrant` / `revokeAgentGrantById` that @odatano/x402 uses to sell
20
- * grants.
21
- *
22
- * The token is a capability, not an identity: it never carries the operator's
23
- * roles, so every `@requires: 'Admin'` surface refuses it by construction.
24
- */
25
1
  import cds, { Request } from '@sap/cds';
26
2
  import { BackendError } from './errors';
3
+ import type { CardanoAgentGrant } from '#cds-models/odatano/cardano';
27
4
  export declare const AGENT_TOKEN_HEADER = "x-agent-token";
28
5
  export declare const AGENT_TOKEN_PREFIX = "odat_";
29
6
  /** Role every token principal carries; the only role it ever has. */
@@ -31,45 +8,18 @@ export declare const AGENT_ROLE = "agent-grant";
31
8
  /** `agent:<grantId>`: the principal id a token request runs under. */
32
9
  export declare const AGENT_PRINCIPAL_PREFIX = "agent:";
33
10
  export declare const GRANTS_ENTITY = "odatano.cardano.CardanoAgentGrants";
11
+ /** Daily per-action counters of admitted calls (feeds GetGrantUsage); never exposed as an entity. */
12
+ export declare const GRANT_USAGE_ENTITY = "odatano.cardano.CardanoAgentGrantUsage";
34
13
  /** The services the hook attaches to and the transport lane opens. */
35
14
  export declare const AGENT_SERVICE_NAMES: readonly string[];
36
- /**
37
- * Actions an operator MAY put on a grant's allow list. Each call costs one
38
- * budget unit (a build is the service an agent buys). Everything not here and
39
- * not in AGENT_ALWAYS_ALLOWED_EVENTS is a hard 403 for token requests: HSM
40
- * signing, pause/resume, grant administration are never grantable.
41
- */
42
- export declare const AGENT_ALLOWLISTABLE_ACTIONS: readonly string[];
43
- /** Allow-listable actions that spend from a worker wallet: the grant must be pinned. */
44
- export declare const AGENT_WALLET_ACTIONS: ReadonlySet<string>;
45
- /**
46
- * Events every valid token may use without an allow-list entry and without
47
- * consuming budget: reads, compute-only actions, status polling. `READ` covers
48
- * every entity set; row-level narrowing is done by the `$user.grantId`
49
- * restrictions in the CDS models, not here.
50
- */
51
- export declare const AGENT_ALWAYS_ALLOWED_EVENTS: ReadonlySet<string>;
52
- /** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
53
- export declare const AGENT_JOB_KINDS: readonly string[];
54
- /** Forget every rate-limit window (tests). */
15
+ /** Forget every rate-limit window, the token cache and re-read the knobs from the config (tests). */
55
16
  export declare function __resetGrantRateLimiterForTests(): void;
56
- export interface AgentGrantRow {
17
+ /** A grant row with the fields every grant has set. */
18
+ export type AgentGrantRow = Omit<CardanoAgentGrant, 'ID' | 'userId' | 'allowedActions'> & {
57
19
  ID: string;
58
20
  userId: string;
59
- agentLabel?: string | null;
60
- tokenHash?: string;
61
21
  allowedActions: string;
62
- walletId?: string | null;
63
- allowedJobKinds?: string | null;
64
- maxJobsPerDay?: number | null;
65
- jobsUsedToday?: number | null;
66
- budgetWindow?: string | null;
67
- validUntil?: string | null;
68
- isActive?: boolean;
69
- revokedAt?: string | null;
70
- createdAt?: string | null;
71
- lastUsedAt?: string | null;
72
- }
22
+ };
73
23
  /** Anything that runs a CQL statement: the primary db service or one transaction of it. */
74
24
  export type Runner = {
75
25
  run: (q: unknown) => Promise<unknown>;
@@ -78,6 +28,8 @@ export declare function hashAgentToken(token: string): string;
78
28
  export declare function agentPrincipalId(grantId: string): string;
79
29
  /** The grant's JSON list column as an array; malformed or absent = empty. */
80
30
  export declare function parseGrantList(raw: string | null | undefined): string[];
31
+ /** The stored allow list without names that are no longer grantable. */
32
+ export declare function grantedActions(grant: Pick<AgentGrantRow, 'allowedActions'>): string[];
81
33
  /** The grant a request runs under, or null for an ordinary principal. */
82
34
  export declare function agentGrantOf(req: unknown): AgentGrantRow | null;
83
35
  export type TokenResolution = {
@@ -88,24 +40,18 @@ export type TokenResolution = {
88
40
  status: 401 | 410;
89
41
  message: string;
90
42
  };
91
- /**
92
- * Authenticate a bearer token: prefix, hash lookup among ACTIVE grants (a
93
- * revoked grant is an unknown token, non-leaking), expiry. Detached from any
94
- * ambient transaction: the lane runs before the request transaction exists,
95
- * and on SQLite the pool holds one connection.
96
- */
43
+ /** Test seam: cache lifetime in ms for injected runners too (null = config, injected runners bypass). */
44
+ export declare function __setTokenCacheMsForTests(ms: number | null): void;
45
+ /** Drops the cached resolution of a grant (revoke, rotate, update). */
46
+ export declare function invalidateTokenCache(grantId: string): void;
47
+ /** Entries waiting in the token cache (monitoring, tests). */
48
+ export declare function tokenCacheSize(): number;
49
+ /** Authenticate a token by prefix, hash and expiry. A revoked grant answers like an unknown one. */
97
50
  export declare function resolveAgentToken(token: string, runner?: Runner): Promise<TokenResolution>;
98
- /**
99
- * The principal a token request runs under. Deliberately NOT the operator and
100
- * WITHOUT the operator's roles: `createdBy = $user` gates then scope to jobs
101
- * this grant created, `$user.grantId` restrictions to its own grant row, and
102
- * every `@requires: 'Admin'` refuses it.
103
- */
51
+ /** The user a token request runs as: never the operator, so `$user` restrictions apply and every Admin gate refuses it. */
104
52
  export declare function makeAgentUser(grant: AgentGrantRow): cds.User;
105
53
  export interface IssueAgentGrantInput {
106
54
  allowedActions: string[];
107
- walletId?: string | null;
108
- allowedJobKinds?: string[] | null;
109
55
  maxJobsPerDay?: number | null;
110
56
  validUntil?: string | null;
111
57
  agentLabel?: string | null;
@@ -115,38 +61,91 @@ export interface IssuedAgentGrant {
115
61
  /** Shown once. Never logged, never stored. */
116
62
  token: string;
117
63
  allowedActions: string[];
118
- walletId: string | null;
119
- allowedJobKinds: string[];
120
64
  maxJobsPerDay: number | null;
121
65
  validUntil: string | null;
122
66
  }
123
67
  /** A refused grant input; carries the 400 the action answers with. */
124
68
  export declare class AgentGrantInputError extends BackendError {
125
- constructor(message: string, target?: string);
69
+ constructor(message: string, target?: string, context?: string);
126
70
  }
127
71
  interface NormalizedGrantInput {
128
72
  allowedActions: string[];
129
- walletId: string | null;
130
- allowedJobKinds: string[];
131
73
  maxJobsPerDay: number | null;
132
74
  validUntil: string | null;
133
75
  agentLabel: string | null;
134
76
  }
135
- export declare function validateGrantInput(input: IssueAgentGrantInput, now?: Date): NormalizedGrantInput;
136
- /**
137
- * Mint a grant for `operatorId`. Validation errors surface as
138
- * AgentGrantInputError (400). The INSERT runs on `runner`: the action passes its
139
- * request transaction, x402 passes whatever transaction its settlement runs in.
140
- */
77
+ export declare function validateGrantInput(input: IssueAgentGrantInput, now?: Date, context?: string): NormalizedGrantInput;
78
+ /** Mint a grant for `operatorId` on `runner`; validation errors surface as AgentGrantInputError (400). */
141
79
  export declare function issueAgentGrant(input: IssueAgentGrantInput, operatorId: string, runner?: Runner): Promise<IssuedAgentGrant>;
142
80
  /** Deactivate a grant; false when it does not exist or is already revoked. */
143
81
  export declare function revokeAgentGrantById(grantId: string, runner?: Runner): Promise<boolean>;
82
+ export interface RotatedAgentGrant {
83
+ grantId: string;
84
+ /** Shown once. Never logged, never stored. */
85
+ token: string;
86
+ }
87
+ /** Replace the grant's token and keep everything else. Null when the grant is missing or revoked. */
88
+ export declare function rotateAgentGrantToken(grantId: string, runner?: Runner): Promise<RotatedAgentGrant | null>;
89
+ /** The editable grant fields, as a client sends them: absent = untouched, explicit null = cleared. */
90
+ export interface UpdateAgentGrantInput {
91
+ agentLabel?: string | null;
92
+ allowedActions?: string[] | null;
93
+ maxJobsPerDay?: number | null;
94
+ validUntil?: string | null;
95
+ }
96
+ /** Row fields a grant edit never touches. */
97
+ export declare const GRANT_IMMUTABLE_FIELDS: readonly string[];
98
+ export type UpdateAgentGrantResult = {
99
+ ok: true;
100
+ grantId: string;
101
+ updated: string[];
102
+ } | {
103
+ ok: false;
104
+ status: 404 | 409;
105
+ code?: 'GRANT_REVOKED';
106
+ message: string;
107
+ };
108
+ export declare function updateAgentGrant(grantId: string, input: UpdateAgentGrantInput, runner?: Runner): Promise<UpdateAgentGrantResult>;
109
+ export declare const USAGE_WINDOW_MAX_MS: number;
110
+ export declare const USAGE_WINDOW_DEFAULT_MS: number;
111
+ export type UsageWindow = {
112
+ ok: true;
113
+ since: string;
114
+ until: string;
115
+ sinceDay: string;
116
+ untilDay: string;
117
+ } | {
118
+ ok: false;
119
+ message: string;
120
+ target: string;
121
+ };
122
+ /** since (default until - 30 days) .. until (default now), at most 366 days; whole UTC days at both ends. */
123
+ export declare function resolveUsageWindow(since: unknown, until: unknown, now?: Date): UsageWindow;
124
+ export interface GrantUsageCall {
125
+ service: string;
126
+ action: string;
127
+ /** Admitted and kept (budget charged and not refunded). */
128
+ count: number;
129
+ /** Admitted, then refunded because the handler refused the input. */
130
+ refunded: number;
131
+ }
132
+ export interface AgentGrantUsage {
133
+ grantId: string;
134
+ since: string;
135
+ until: string;
136
+ calls: GrantUsageCall[];
137
+ total: number;
138
+ jobsUsedToday: number;
139
+ maxJobsPerDay: number | null;
140
+ }
141
+ /** Admitted calls of the grant in `window` per service and action. Buffered counters are flushed first. */
142
+ export declare function getGrantUsage(grant: AgentGrantRow, window: Extract<UsageWindow, {
143
+ ok: true;
144
+ }>, runner?: Runner, flushRunner?: Runner): Promise<AgentGrantUsage>;
144
145
  export interface AgentGrantStatus {
145
146
  grantId: string;
146
147
  agentLabel: string | null;
147
148
  allowedActions: string[];
148
- walletId: string | null;
149
- allowedJobKinds: string[];
150
149
  maxJobsPerDay: number | null;
151
150
  jobsUsedToday: number;
152
151
  budgetWindow: string | null;
@@ -154,58 +153,43 @@ export interface AgentGrantStatus {
154
153
  isActive: boolean;
155
154
  }
156
155
  export declare function toGrantStatus(grant: AgentGrantRow): AgentGrantStatus;
157
- /** Validation rejections are thrown BEFORE any transaction work (project convention). */
156
+ /** Validation rejections happen before any transaction work. */
158
157
  export declare function registerAgentGrantHandlers(srv: cds.Service): void;
159
158
  export declare function attachAgentGrantEnforcement(srv: cds.Service, runner?: Runner): void;
160
- /**
161
- * Exported for unit tests; see the module doc for the ladder. Ordinary
162
- * principals pass through untouched: this hook is a no-op without a grant.
163
- */
164
- /**
165
- * Where the hook's own writes go.
166
- *
167
- * Default: DETACHED from the request transaction (`runWithoutAmbientTx`), so
168
- * the spend sticks even when the request later fails and no write lock is held
169
- * across the handler's backend round trips.
170
- *
171
- * Exception: a request that already sits inside an open transaction — the
172
- * second and later parts of a `$batch` changeset (atomicity group) — owns the
173
- * pooled connection. On SQLite the pool has one connection, so a detached
174
- * statement would wait for it until the changeset commits, which waits for
175
- * this hook: a deadlock. Such a request rides its own transaction instead; the
176
- * changeset's rollback is then the refund, and no `failed` listener is needed.
177
- * `ready` is set the moment CAP begins the transaction, `dbc` once the
178
- * connection is acquired; either means "already open".
179
- */
180
159
  export interface BudgetRunner {
181
160
  runner: Runner;
182
161
  /** true: statements run outside the request transaction (and a refused request is refunded). */
183
162
  detached: boolean;
184
163
  }
185
164
  export declare function budgetRunnerFor(req: Request, injected?: Runner, detached?: boolean): BudgetRunner;
186
- /**
187
- * Exported for unit tests; see the module doc for the ladder. Ordinary
188
- * principals pass through untouched: this hook is a no-op without a grant.
189
- * `runner` / `detached` are test seams; production picks them per request.
190
- */
191
- export declare function enforceAgentGrant(req: Request, runner?: Runner, detached?: boolean): Promise<unknown>;
165
+ export declare function errorStatus(err: unknown): number;
166
+ /** The before('*') hook for token requests: closed services, allow list, daily budget and usage. */
167
+ export declare function enforceAgentGrant(req: Request, runner?: Runner, detached?: boolean, serviceName?: string): Promise<unknown>;
192
168
  export interface BudgetCharge {
193
169
  consumed: boolean;
194
170
  /** The UTC day the unit was charged to; the refund must name the same window. */
195
171
  window: string;
196
172
  }
197
- /**
198
- * Consume one unit of the grant's daily budget. Two conditional UPDATEs so
199
- * concurrent requests cannot overspend: a window reset (compare-and-swap on
200
- * the OLD window value) and a bounded increment (`jobsUsedToday < max`). Runs
201
- * on the BudgetRunner the hook chose (detached by default, see budgetRunnerFor).
202
- */
203
173
  export declare function consumeDailyBudget(br: BudgetRunner | Runner, grant: AgentGrantRow): Promise<BudgetCharge>;
204
- /**
205
- * Undo one consumeDailyBudget in the window it was charged to (a refused
206
- * request created nothing). A refund that lands after midnight must not touch
207
- * the new day's counter: the unit was spent yesterday, yesterday keeps it.
208
- */
174
+ /** Undo one consumeDailyBudget in the window it was charged to; never touches a newer day's counter. */
209
175
  export declare function refundDailyBudget(br: BudgetRunner | Runner, grant: AgentGrantRow, window: string): Promise<void>;
176
+ type UsageMode = 'sync' | 'deferred';
177
+ /** Test seam: force a mode (null = derive from cds.db.kind). */
178
+ export declare function __setGrantUsageModeForTests(mode: UsageMode | null): void;
179
+ /** Test seam: forget buffered deltas and the pending timer. */
180
+ export declare function __resetGrantUsageBufferForTests(): void;
181
+ /** How many keys wait for the next flush (monitoring, tests). */
182
+ export declare function pendingGrantUsageKeys(): number;
183
+ /** Test seam: the day the retention last ran (null = not yet). */
184
+ export declare function __setGrantUsagePrunedForTests(day: string | null): void;
185
+ /** Write the buffered deltas per key. A failed delta goes back into the buffer for the next flush. */
186
+ export declare function flushGrantUsage(runner?: Runner): Promise<{
187
+ flushed: number;
188
+ failed: number;
189
+ }>;
190
+ /** Count one admitted call on (grant, UTC day, service, action). Never fails the request; returns the day counted on. */
191
+ export declare function recordGrantUsage(br: BudgetRunner | Runner, grant: AgentGrantRow, service: string, action: string, now?: Date): Promise<string>;
192
+ /** `refunded + 1` on the row the call was counted on; deferred mode buffers it on the same key. */
193
+ export declare function refundGrantUsage(br: BudgetRunner | Runner, grant: AgentGrantRow, service: string, action: string, day: string): Promise<void>;
210
194
  export {};
211
195
  //# sourceMappingURL=agent-grants.d.ts.map