@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
@@ -1,106 +1,11 @@
1
- /**
2
- * Transport authentication with lanes: CAP's configured strategy PLUS an
3
- * `x-agent-token` lane (AGENT_GRANTS_DESIGN.md §3).
4
- *
5
- * CAP's auth middleware 401s a request without transport credentials before any
6
- * service hook runs, so an agent holding only an `odat_` token could never
7
- * reach a service. This middleware is installed as `cds.requires.auth.impl` by
8
- * src/plugin.ts when `odatano-core.agentGrants.enabled` is set, and:
9
- *
10
- * - runs every registered LANE first. The built-in lane admits a request that
11
- * carries `x-agent-token` on one of the six ODATANO service paths (exact
12
- * segment match, no lookalike prefixes): the token is authenticated HERE
13
- * (unknown 401, expired 410, non-leaking) and the request continues as the
14
- * principal `agent:<grantId>` with the role `agent-grant`. The resolved grant
15
- * rides on the express request (`req.agentGrant`) for the enforcement hook.
16
- * Other packages (@odatano/x402) add lanes with `registerTransportLane`
17
- * instead of fighting for the single `auth.impl` slot.
18
- * - otherwise DELEGATES to CAP's own strategy for the configured kind
19
- * (mocked/basic → basic-auth, jwt/xsuaa → jwt-auth, ias, dummy): behaviour
20
- * for every request without a token is exactly what it was before.
21
- *
22
- * Failed token attempts are throttled per client address (20 per 15 minutes):
23
- * one static hash lookup must not become an offline-speed guessing oracle.
24
- */
25
- import cds from '@sap/cds';
26
- import type { IncomingMessage, ServerResponse } from 'node:http';
27
- import { type AgentGrantRow } from './agent-grants';
28
- type ExpressReq = IncomingMessage & {
29
- headers: Record<string, string | string[] | undefined>;
30
- originalUrl?: string;
31
- baseUrl?: string;
32
- path?: string;
33
- ip?: string;
34
- user?: unknown;
35
- agentGrant?: AgentGrantRow;
36
- };
37
- type ExpressRes = ServerResponse & {
38
- status?: (code: number) => ExpressRes;
39
- set?: (name: string, value: string) => ExpressRes;
40
- json?: (body: unknown) => void;
41
- };
42
- type Next = (err?: unknown) => void;
43
- export type AuthMiddleware = (req: ExpressReq, res: ExpressRes, next: Next) => unknown;
44
- /** What a lane's `authenticate` may answer. */
45
- export type LaneOutcome =
46
- /** The lane authenticated the request; continue as this principal. */
47
- {
48
- user: cds.User;
49
- }
50
- /** The lane already sent a response (401/410/429); stop here. */
51
- | {
52
- handled: true;
53
- }
54
- /** Not this lane's request after all; try the next lane, then the delegate. */
55
- | null;
56
- export interface TransportLane {
57
- /** Unique name; registering the same name twice replaces the lane. */
58
- name: string;
59
- /** Cheap check on headers/path; no I/O. */
60
- match: (req: ExpressReq) => boolean;
61
- /** Authenticate; may respond itself. */
62
- authenticate: (req: ExpressReq, res: ExpressRes) => Promise<LaneOutcome>;
63
- }
64
- /** Add (or replace) a lane. Lanes run in registration order, the built-in agent-token lane first. */
65
- export declare function registerTransportLane(lane: TransportLane): void;
66
- /** Registered lane names, in order (tests, diagnostics). */
67
- export declare function transportLanes(): string[];
68
- /** Remove every lane except the built-in one (tests). */
69
- export declare function __resetTransportLanesForTests(): void;
1
+ import { type TransportLane } from '@odatano/cap-auth';
70
2
  /** Test seam: pin the service paths instead of reading `cds.services`. `null` resets. */
71
3
  export declare function __setAgentServicePathsForTests(paths: string[] | null): void;
4
+ /** Forget throttle state and the path cache (tests). */
5
+ export declare function __resetAgentTokenLaneForTests(): void;
72
6
  /** Mount paths of the six services, read from `cds.services` once they are served. */
73
7
  export declare function agentServicePaths(): string[];
74
- /** Exact segment boundary: `/odata/v4/cardano-odata` and below, never `/odata/v4/cardano-odata-evil`. */
8
+ /** Exact segment boundary: `/odata/v4/cardano` and below, never `/odata/v4/cardano-evil`. */
75
9
  export declare function inAgentLane(path: string, servicePaths?: string[]): boolean;
76
10
  export declare const agentTokenLane: TransportLane;
77
- interface AuthOptions {
78
- kind?: string;
79
- impl?: string;
80
- /** Set by activateAgentGrants: the strategy that keeps authenticating non-token requests. */
81
- agentGrantsDelegate?: string;
82
- /**
83
- * Set by activateAgentGrants when the host had its own `auth.impl` before us:
84
- * that module (path as configured, resolved like CAP does it) is the delegate,
85
- * whatever `kind` says. The host's gate keeps running for every non-token
86
- * request, on every path.
87
- */
88
- agentGrantsDelegateImpl?: string;
89
- [key: string]: unknown;
90
- }
91
- /** Load CAP's own middleware for `kind`; exported so the wrapper can be unit-tested with a stub. */
92
- /**
93
- * Resolve a host-configured `auth.impl` the way CAP's auth factory does
94
- * (@sap/cds/lib/srv/middlewares/auth/index.js): as a module relative to
95
- * cds.root, else with a `./` prefix. Exported for the unit tests.
96
- */
97
- export declare function resolveCustomImpl(impl: string, root?: string): string;
98
- export declare function loadDelegate(options: AuthOptions, kind: string): AuthMiddleware;
99
- export declare function createAgentTokenAuth(options: AuthOptions, delegate?: AuthMiddleware): AuthMiddleware;
100
- /**
101
- * CAP requires this module and, seeing a function with fewer than three
102
- * parameters, calls it with the merged auth options to obtain the middleware.
103
- */
104
- export default function agentTokenAuthFactory(options: AuthOptions): AuthMiddleware;
105
- export {};
106
11
  //# sourceMappingURL=agent-token-auth.d.ts.map
@@ -1,78 +1,19 @@
1
1
  "use strict";
2
- /**
3
- * Transport authentication with lanes: CAP's configured strategy PLUS an
4
- * `x-agent-token` lane (AGENT_GRANTS_DESIGN.md §3).
5
- *
6
- * CAP's auth middleware 401s a request without transport credentials before any
7
- * service hook runs, so an agent holding only an `odat_` token could never
8
- * reach a service. This middleware is installed as `cds.requires.auth.impl` by
9
- * src/plugin.ts when `odatano-core.agentGrants.enabled` is set, and:
10
- *
11
- * - runs every registered LANE first. The built-in lane admits a request that
12
- * carries `x-agent-token` on one of the six ODATANO service paths (exact
13
- * segment match, no lookalike prefixes): the token is authenticated HERE
14
- * (unknown 401, expired 410, non-leaking) and the request continues as the
15
- * principal `agent:<grantId>` with the role `agent-grant`. The resolved grant
16
- * rides on the express request (`req.agentGrant`) for the enforcement hook.
17
- * Other packages (@odatano/x402) add lanes with `registerTransportLane`
18
- * instead of fighting for the single `auth.impl` slot.
19
- * - otherwise DELEGATES to CAP's own strategy for the configured kind
20
- * (mocked/basic → basic-auth, jwt/xsuaa → jwt-auth, ias, dummy): behaviour
21
- * for every request without a token is exactly what it was before.
22
- *
23
- * Failed token attempts are throttled per client address (20 per 15 minutes):
24
- * one static hash lookup must not become an offline-speed guessing oracle.
25
- */
2
+ // A token on a service path runs as `agent:<grantId>` with role `agent-grant`. Other paths go to the delegate.
3
+ // Unknown tokens get 401, expired ones 410. Failed attempts are throttled per client address.
26
4
  var __importDefault = (this && this.__importDefault) || function (mod) {
27
5
  return (mod && mod.__esModule) ? mod : { "default": mod };
28
6
  };
29
7
  Object.defineProperty(exports, "__esModule", { value: true });
30
8
  exports.agentTokenLane = void 0;
31
- exports.registerTransportLane = registerTransportLane;
32
- exports.transportLanes = transportLanes;
33
- exports.__resetTransportLanesForTests = __resetTransportLanesForTests;
34
9
  exports.__setAgentServicePathsForTests = __setAgentServicePathsForTests;
10
+ exports.__resetAgentTokenLaneForTests = __resetAgentTokenLaneForTests;
35
11
  exports.agentServicePaths = agentServicePaths;
36
12
  exports.inAgentLane = inAgentLane;
37
- exports.resolveCustomImpl = resolveCustomImpl;
38
- exports.loadDelegate = loadDelegate;
39
- exports.createAgentTokenAuth = createAgentTokenAuth;
40
- exports.default = agentTokenAuthFactory;
41
13
  const cds_1 = __importDefault(require("@sap/cds"));
14
+ const cap_auth_1 = require("@odatano/cap-auth");
42
15
  const agent_grants_1 = require("./agent-grants");
43
16
  const rate_limiter_1 = require("./rate-limiter");
44
- const lanes = [];
45
- /** Add (or replace) a lane. Lanes run in registration order, the built-in agent-token lane first. */
46
- function registerTransportLane(lane) {
47
- const i = lanes.findIndex((l) => l.name === lane.name);
48
- if (i >= 0)
49
- lanes[i] = lane;
50
- else
51
- lanes.push(lane);
52
- }
53
- /** Registered lane names, in order (tests, diagnostics). */
54
- function transportLanes() {
55
- return lanes.map((l) => l.name);
56
- }
57
- /** Remove every lane except the built-in one (tests). */
58
- function __resetTransportLanesForTests() {
59
- lanes.length = 0;
60
- tokenFailures.reset();
61
- servicePathsCache = null;
62
- servicePathsPinned = false;
63
- }
64
- /** Built-in CAP strategies by kind, same table as @sap/cds/lib/srv/middlewares/auth/index.js. */
65
- const BUILTIN = {
66
- mocked: 'basic-auth',
67
- basic: 'basic-auth',
68
- ias: 'ias-auth',
69
- jwt: 'jwt-auth',
70
- xsuaa: 'jwt-auth',
71
- dummy: 'dummy-auth',
72
- };
73
- // ---------------------------------------------------------------------------
74
- // Built-in lane: x-agent-token on the ODATANO service paths
75
- // ---------------------------------------------------------------------------
76
17
  const tokenFailures = new rate_limiter_1.RateLimiter({ windowMs: 15 * 60 * 1000, maxRequests: 20, maxKeys: 10_000 });
77
18
  let servicePathsCache = null;
78
19
  let servicePathsPinned = false;
@@ -81,6 +22,12 @@ function __setAgentServicePathsForTests(paths) {
81
22
  servicePathsCache = paths;
82
23
  servicePathsPinned = paths !== null;
83
24
  }
25
+ /** Forget throttle state and the path cache (tests). */
26
+ function __resetAgentTokenLaneForTests() {
27
+ tokenFailures.reset();
28
+ servicePathsCache = null;
29
+ servicePathsPinned = false;
30
+ }
84
31
  /** Mount paths of the six services, read from `cds.services` once they are served. */
85
32
  function agentServicePaths() {
86
33
  if (servicePathsPinned && servicePathsCache)
@@ -94,146 +41,35 @@ function agentServicePaths() {
94
41
  servicePathsCache = paths;
95
42
  return paths;
96
43
  }
97
- function requestPath(req) {
98
- const raw = String(req.originalUrl || req.url || req.path || '');
99
- return raw.split('?')[0];
100
- }
101
- /** Exact segment boundary: `/odata/v4/cardano-odata` and below, never `/odata/v4/cardano-odata-evil`. */
44
+ /** Exact segment boundary: `/odata/v4/cardano` and below, never `/odata/v4/cardano-evil`. */
102
45
  function inAgentLane(path, servicePaths = agentServicePaths()) {
103
- return servicePaths.some((p) => path === p || path.startsWith(p + '/'));
46
+ const bare = path.split('?')[0];
47
+ return servicePaths.some((p) => (0, cap_auth_1.inLaneOf)(bare, p));
104
48
  }
105
49
  function clientKey(req) {
106
50
  const ip = req.ip ?? req.socket?.remoteAddress ?? 'unknown';
107
51
  return `ip=${String(ip).replace(/:/g, '.')}:agent-token`;
108
52
  }
109
- function respond(res, status, message, retryAfterMs) {
110
- if (retryAfterMs !== undefined)
111
- res.set?.('Retry-After', String(Math.max(1, Math.ceil(retryAfterMs / 1000))));
112
- const body = { error: { code: String(status), message } };
113
- if (typeof res.status === 'function' && typeof res.json === 'function') {
114
- res.status(status);
115
- res.json(body);
116
- }
117
- else {
118
- res.statusCode = status;
119
- res.setHeader('content-type', 'application/json');
120
- res.end(JSON.stringify(body));
121
- }
122
- return { handled: true };
123
- }
124
53
  exports.agentTokenLane = {
125
54
  name: 'agent-token',
126
55
  match: (req) => typeof req.headers?.[agent_grants_1.AGENT_TOKEN_HEADER] === 'string' && req.headers[agent_grants_1.AGENT_TOKEN_HEADER].length > 0,
127
56
  authenticate: async (req, res) => {
128
57
  const token = req.headers[agent_grants_1.AGENT_TOKEN_HEADER];
129
- if (!inAgentLane(requestPath(req))) {
130
- // A token on any other path is not ours to admit; the delegate decides
131
- // (and will 401 a request that carries nothing else).
132
- return null;
133
- }
58
+ if (!inAgentLane((0, cap_auth_1.requestPath)(req)))
59
+ return { next: true };
134
60
  const key = clientKey(req);
135
61
  const locked = tokenFailures.peek(key);
136
62
  if (!locked.allowed)
137
- return respond(res, 429, 'Too many failed agent token attempts', locked.retryAfterMs);
63
+ return (0, cap_auth_1.respondError)(res, 429, 'Too many failed agent token attempts', locked.retryAfterMs);
138
64
  const resolution = await (0, agent_grants_1.resolveAgentToken)(token);
139
65
  if (!resolution.ok) {
140
66
  const failed = tokenFailures.check(key);
141
67
  if (!failed.allowed)
142
- return respond(res, 429, 'Too many failed agent token attempts', failed.retryAfterMs);
143
- return respond(res, resolution.status, resolution.message);
68
+ return (0, cap_auth_1.respondError)(res, 429, 'Too many failed agent token attempts', failed.retryAfterMs);
69
+ return (0, cap_auth_1.respondError)(res, resolution.status, resolution.message);
144
70
  }
145
71
  req.agentGrant = resolution.grant;
146
72
  return { user: (0, agent_grants_1.makeAgentUser)(resolution.grant) };
147
73
  },
148
74
  };
149
- function ensureBuiltinLane() {
150
- if (!lanes.some((l) => l.name === exports.agentTokenLane.name))
151
- lanes.unshift(exports.agentTokenLane);
152
- }
153
- /** Load CAP's own middleware for `kind`; exported so the wrapper can be unit-tested with a stub. */
154
- /**
155
- * Resolve a host-configured `auth.impl` the way CAP's auth factory does
156
- * (@sap/cds/lib/srv/middlewares/auth/index.js): as a module relative to
157
- * cds.root, else with a `./` prefix. Exported for the unit tests.
158
- */
159
- function resolveCustomImpl(impl, root = String(cds_1.default.root ?? process.cwd())) {
160
- try {
161
- return require.resolve(impl, { paths: [root] });
162
- }
163
- catch {
164
- return require.resolve(`./${impl}`, { paths: [root] });
165
- }
166
- }
167
- function asMiddleware(loaded, delegateOptions, what) {
168
- // default export of an ESM / .ts module
169
- const candidate = loaded?.default ?? loaded;
170
- const mw = typeof candidate === 'function' && candidate.length < 3
171
- ? candidate(delegateOptions)
172
- : candidate;
173
- if (typeof mw !== 'function') {
174
- throw new Error(`agent-token-auth: ${what} did not yield a middleware function`);
175
- }
176
- return mw;
177
- }
178
- function loadDelegate(options, kind) {
179
- // The delegate must not see our impl (it would recurse) nor our private keys.
180
- const delegateOptions = { ...options };
181
- delete delegateOptions.impl;
182
- delete delegateOptions.agentGrantsDelegate;
183
- delete delegateOptions.agentGrantsDelegateImpl;
184
- // A host that brought its own auth.impl keeps it: whatever it enforced
185
- // before agent grants were switched on, it still enforces for every request
186
- // that does not carry a token, on every path.
187
- const custom = options.agentGrantsDelegateImpl;
188
- if (custom) {
189
- const resolved = resolveCustomImpl(custom);
190
- return asMiddleware(require(resolved), { ...delegateOptions, impl: custom }, `custom auth impl '${custom}'`);
191
- }
192
- const builtin = BUILTIN[kind.replace(/-auth$/, '')];
193
- if (!builtin)
194
- throw new Error(`agent-token-auth: no built-in CAP auth strategy for kind '${kind}'`);
195
- // Same module CAP itself would have loaded for this kind. Pinned by the
196
- // @sap/cds peer dependency; the self-test in asMiddleware fails fast if the shape moves.
197
- const factory = require(`@sap/cds/lib/srv/middlewares/auth/${builtin}`);
198
- return asMiddleware(factory, { ...delegateOptions, kind }, `CAP auth strategy '${builtin}'`);
199
- }
200
- function createAgentTokenAuth(options, delegate) {
201
- const delegateKind = String(options.agentGrantsDelegate ?? options.kind ?? 'mocked');
202
- const inner = delegate ?? loadDelegate(options, delegateKind);
203
- ensureBuiltinLane();
204
- const delegateLabel = options.agentGrantsDelegateImpl ? `custom impl ${options.agentGrantsDelegateImpl}` : `'${delegateKind}'`;
205
- cds_1.default.log('AgentGrants').info(`agent-token transport lane active, delegating other requests to ${delegateLabel}`);
206
- return async function agentTokenAuth(req, res, next) {
207
- for (const lane of lanes) {
208
- if (!lane.match(req))
209
- continue;
210
- let outcome;
211
- try {
212
- outcome = await lane.authenticate(req, res);
213
- }
214
- catch (err) {
215
- cds_1.default.log('AgentGrants').error(`transport lane '${lane.name}' failed: ${String(err?.message ?? err)}`);
216
- respond(res, 500, 'authentication lane failed');
217
- return;
218
- }
219
- if (outcome === null)
220
- continue;
221
- if ('handled' in outcome)
222
- return;
223
- req.user = outcome.user;
224
- const ctx = cds_1.default.context;
225
- if (ctx)
226
- ctx.user = outcome.user;
227
- return next();
228
- }
229
- return inner(req, res, next);
230
- };
231
- }
232
- /**
233
- * CAP requires this module and, seeing a function with fewer than three
234
- * parameters, calls it with the merged auth options to obtain the middleware.
235
- */
236
- function agentTokenAuthFactory(options) {
237
- return createAgentTokenAuth(options);
238
- }
239
75
  //# sourceMappingURL=agent-token-auth.js.map
@@ -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
- */
19
- export declare function handleRequest(req: Request, handler: (db: cds.Transaction) => Promise<unknown>): Promise<unknown>;
4
+ /** Runs a service handler inside the request transaction and maps errors to OData responses. */
5
+ export declare function handleRequest<T>(req: Request, handler: (db: cds.Transaction) => Promise<T>): Promise<T>;
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,6 @@
1
- /**
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)
9
- */
1
+ /** Small collection helpers shared across the blockchain layer. */
2
+ /** Splits an array into chunks so CQL IN-lists stay below the driver's bind-variable limit. */
10
3
  export declare function chunk<T>(arr: T[], size: number): T[][];
11
- /** Max bind variables per IN-list — well below every supported driver's cap. */
4
+ /** Max bind variables per IN-list, below every supported driver's cap. */
12
5
  export declare const IN_CHUNK = 500;
13
6
  //# sourceMappingURL=collections.d.ts.map
@@ -1,16 +1,9 @@
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
- /**
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)
13
- */
6
+ /** Splits an array into chunks so CQL IN-lists stay below the driver's bind-variable limit. */
14
7
  function chunk(arr, size) {
15
8
  if (size <= 0)
16
9
  throw new RangeError(`chunk size must be > 0, got ${size}`);
@@ -19,6 +12,6 @@ function chunk(arr, size) {
19
12
  out.push(arr.slice(i, i + size));
20
13
  return out;
21
14
  }
22
- /** Max bind variables per IN-list — well below every supported driver's cap. */
15
+ /** Max bind variables per IN-list, below every supported driver's cap. */
23
16
  exports.IN_CHUNK = 500;
24
17
  //# sourceMappingURL=collections.js.map
@@ -1,77 +1,45 @@
1
- /**
2
- * Cardano protocol constants
3
- */
1
+ /** Cardano protocol constants */
4
2
  export declare const CARDANO_DEFAULTS: {
5
3
  /** Maximum ADA supply in lovelace (45 billion ADA) */
6
4
  MAX_LOVELACE_SUPPLY: string;
7
5
  /** Milliseconds per slot */
8
6
  MS_PER_SLOT: number;
9
7
  };
10
- /**
11
- * Network-specific epoch geometry, anchored at the Shelley transition:
12
- * `epochStartSlot(epoch) = shelleyStartSlot + (epoch - shelleyStartEpoch) * slotsPerEpoch`.
13
- * A single global SLOTS_PER_EPOCH is wrong twice over — preview uses 86 400 (1 day),
14
- * and mainnet/preprod epochs are offset by their Byron era.
15
- */
16
8
  export declare const EPOCH_CONFIG_BY_NETWORK: {
17
9
  readonly mainnet: {
18
10
  readonly shelleyStartEpoch: 208;
19
11
  readonly shelleyStartSlot: 4492800;
20
12
  readonly slotsPerEpoch: 432000;
13
+ readonly securityParam: 2160;
21
14
  };
22
15
  readonly preprod: {
23
16
  readonly shelleyStartEpoch: 4;
24
17
  readonly shelleyStartSlot: 86400;
25
18
  readonly slotsPerEpoch: 432000;
19
+ readonly securityParam: 2160;
26
20
  };
27
21
  readonly preview: {
28
22
  readonly shelleyStartEpoch: 0;
29
23
  readonly shelleyStartSlot: 0;
30
24
  readonly slotsPerEpoch: 86400;
25
+ readonly securityParam: 432;
31
26
  };
32
27
  };
33
- /**
34
- * Default execution units for Plutus scripts
35
- * Used when dynamic evaluation is not available
36
- */
28
+ /** Default Plutus execution units when dynamic evaluation is not available */
37
29
  export declare const DEFAULT_EXECUTION_UNITS: {
38
- /** Memory units for script execution */
39
30
  mem: number;
40
- /** CPU steps for script execution */
41
31
  cpu: number;
42
32
  };
43
- /**
44
- * High execution units for initial transaction build (before evaluation)
45
- * Set higher than DEFAULT to ensure fee estimation is sufficient before actual evaluation
46
- */
33
+ /** High execution units for the initial build pass, so the fee estimate holds before evaluation */
47
34
  export declare const HIGH_EXECUTION_UNITS: {
48
- /** Memory units - high for evaluation pass */
49
35
  mem: number;
50
- /** CPU steps - high for evaluation pass */
51
36
  cpu: number;
52
37
  };
53
- /**
54
- * Execution unit buffer — relative multiplier applied to evaluator output.
55
- * Combined with ABS_* floors below so small validators also get a meaningful cushion.
56
- */
38
+ /** Relative multiplier on evaluator ExUnits; combined with the ABS_* floors below. */
57
39
  export declare const EXECUTION_UNIT_BUFFER = 1.1;
58
- /**
59
- * Absolute ExUnits floor added on top of the relative multiplier.
60
- *
61
- * Rationale: validators that iterate reference inputs and decode inline CBOR
62
- * datums (e.g. oracle-consuming mint policies) show a larger ScriptContext →
63
- * ledger drift than the documented ~10k–30k CPU / ~50–100 mem band — real-world
64
- * cases overshot a 50k/1k floor by ~27k CPU / ~56 mem, burning the submit fee.
65
- * The floor is sized to cover reference-input + CBOR-decoding drift on top of
66
- * the 10% relative multiplier; `max_tx_ex_units` still caps build-time totals,
67
- * so oversizing here cannot push a tx past network limits — it only trades a
68
- * few extra lovelace of fee for avoiding an opaque PlutusFailure on submit.
69
- */
70
40
  export declare const ABS_CPU_BUFFER = 200000;
71
41
  export declare const ABS_MEM_BUFFER = 5000;
72
- /**
73
- * Transaction building constants
74
- */
42
+ /** Transaction building constants */
75
43
  /** Collateral amount in lovelace (5 ADA) */
76
44
  export declare const COLLATERAL_LOVELACE = 5000000n;
77
45
  /** Fee buffer in lovelace (1 ADA) */
@@ -90,13 +58,12 @@ export declare const HRP: {
90
58
  stake: RegExp;
91
59
  };
92
60
  };
93
- /**
94
- * Input validation limits to prevent DoS attacks
95
- */
61
+ /** Input validation limits to prevent DoS attacks */
96
62
  /** Maximum JSON string length in bytes (1MB) */
97
63
  export declare const MAX_JSON_SIZE = 1048576;
98
64
  /** Maximum nesting depth for JSON objects/arrays */
99
65
  export declare const MAX_DEPTH = 10;
66
+ export declare const PLUTUS_DATA_MAX_DEPTH = 64;
100
67
  /** Maximum number of keys in a JSON object */
101
68
  export declare const MAX_KEYS = 100;
102
69
  /** Maximum number of elements in a JSON array */
@@ -105,12 +72,7 @@ export declare const MAX_ARRAY_LENGTH = 1000;
105
72
  export declare const MAX_STRING_LENGTH = 65536;
106
73
  /** Maximum ech32 string length to prevent DoS */
107
74
  export declare const BECH32_MAX_LENGTH = 2000;
108
- /**
109
- * Maximum hex length of transaction CBOR accepted by ParseTransactionCbor.
110
- * Mainnet `maxTxSize` is currently 16 KiB; 64 KiB raw (= 128 KiB hex) leaves
111
- * generous headroom for future protocol bumps and reference-script outputs
112
- * while keeping the parser from being a memory-exhaustion vector.
113
- */
75
+ /** Max tx CBOR hex accepted by ParseTransactionCbor: 64 KiB raw, well above mainnet maxTxSize (16 KiB). */
114
76
  export declare const MAX_TX_CBOR_HEX_LENGTH: number;
115
77
  /** Maximum reasonable epoch number */
116
78
  export declare const MAX_EPOCH = 100000;
@@ -128,14 +90,9 @@ export declare const ED25519_KEY_HASH_HEX_LENGTH = 56;
128
90
  export declare const ED25519_KEY_HASH_REGEX: RegExp;
129
91
  /** Minimum lovelace for a change output carrying native assets (2 ADA) */
130
92
  export declare const MIN_CHANGE_LOVELACE = 2000000;
131
- /**
132
- * Shelley-era genesis parameters per network, used to construct Buildooor's
133
- * GenesisInfos so `TxBuilder.posixToSlot()` can convert validity-window
134
- * Posix ms into ledger slots. `slotLengthMs` is 1000 ms on all current networks.
135
- */
136
93
  export declare const GENESIS_INFOS_BY_NETWORK: {
137
94
  readonly mainnet: {
138
- readonly systemStartPosixMs: 1596491091000;
95
+ readonly systemStartPosixMs: 1596059091000;
139
96
  readonly slotLengthMs: 1000;
140
97
  readonly startSlotNo: 4492800;
141
98
  };
@@ -152,32 +109,24 @@ export declare const GENESIS_INFOS_BY_NETWORK: {
152
109
  };
153
110
  /** Default validity-window start offset: `now - 2 min` to absorb clock skew. */
154
111
  export declare const DEFAULT_VALIDITY_START_OFFSET_MS = 120000;
155
- /** Default validity-window end offset: `now + 1 h` — generous enough for human-latency sign+submit flows. */
112
+ /** Default validity-window end offset: `now + 1 h`, enough for human-latency sign+submit flows. */
156
113
  export declare const DEFAULT_VALIDITY_END_OFFSET_MS: number;
157
114
  /** Max accepted digits in a Posix-ms string (13 digits covers Unix ms timestamps through ~Nov 2286). */
158
115
  export declare const MAX_POSIX_MS_DIGITS = 13;
159
- /**
160
- * Generic 64-character hex string (used for block hashes and other 32-byte hex identifiers)
161
- */
116
+ /** Generic 64-character hex string (block hashes and other 32-byte identifiers) */
162
117
  export declare const HEX_64_REGEX: RegExp;
163
- /**
164
- * Generic 56-character hex string — 28-byte hashes (Blake2b-224 / payment credential / script hash / pool key hash).
165
- */
118
+ /** Generic 56-character hex string: 28-byte hashes (Blake2b-224, payment credential, script hash, pool key hash) */
166
119
  export declare const HEX_56_REGEX: RegExp;
167
- /**
168
- * Transaction hash Regex - 64-character hexadecimal string
169
- */
120
+ /** How long a stored address, account, pool, DRep or asset answers before it is read again. */
121
+ export declare const DEFAULT_INDEX_TTL_MS = 3600000;
122
+ /** How long protocol parameters answer before the backend is asked again. */
123
+ export declare const PROTOCOL_PARAMS_TTL_MS: number;
124
+ /** Transaction hash: 64-character hex string */
170
125
  export declare const TX_HASH_REGEX: RegExp;
171
- /**
172
- * Asset unit Regex - policy ID (56 hex chars) + asset name (0-128 hex chars)
173
- */
126
+ /** Asset unit: policy ID (56 hex) + asset name (0-32 bytes = 0-64 hex, even length; total <= 120 = String(120) key column) */
174
127
  export declare const ASSET_UNIT_REGEX: RegExp;
175
- /**
176
- * Pool ID Regex - bech32 with HRP "pool" and 28 bytes payload
177
- */
128
+ /** Pool ID: bech32 with HRP "pool" and 28-byte payload */
178
129
  export declare const POOL_ID_REGEX: RegExp;
179
- /**
180
- * DRep ID Regex - bech32 with HRP "drep" and 50-60 chars payload
181
- */
130
+ /** DRep ID: bech32 with HRP "drep" and 50-60 chars payload */
182
131
  export declare const DREP_ID_REGEX: RegExp;
183
132
  //# sourceMappingURL=const.d.ts.map