@odatano/core 2.0.0-rc.43 → 2.0.0-rc.45

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 (171) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +0 -46
  2. package/@cds-models/CardanoBackendService/index.d.ts +0 -10
  3. package/@cds-models/CardanoIndexerService/index.d.ts +36 -20
  4. package/@cds-models/CardanoIndexerService/index.js +4 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +19 -47
  6. package/@cds-models/CardanoSignService/index.d.ts +3 -18
  7. package/@cds-models/CardanoTransactionService/index.d.ts +9 -31
  8. package/@cds-models/CardanoWorkerService/index.d.ts +3 -19
  9. package/@cds-models/index.d.ts +17 -0
  10. package/@cds-models/index.js +2 -0
  11. package/@cds-models/odatano/cardano/index.d.ts +1 -34
  12. package/README.md +6 -6
  13. package/db/schema.cds +29 -44
  14. package/db/types.cds +22 -5
  15. package/package.json +3 -1
  16. package/scripts/migrate-slot-leader.mjs +3 -11
  17. package/scripts/migrate-txseq.mjs +3 -12
  18. package/src/index.d.ts +0 -4
  19. package/src/index.js +3 -5
  20. package/src/plugin.js +4 -8
  21. package/srv/blockchain/asset-decimals.d.ts +7 -0
  22. package/srv/blockchain/asset-decimals.js +91 -0
  23. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -10
  24. package/srv/blockchain/backends/blockfrost-backend.js +15 -21
  25. package/srv/blockchain/backends/cardano-backend.d.ts +12 -71
  26. package/srv/blockchain/backends/koios-backend.d.ts +14 -147
  27. package/srv/blockchain/backends/koios-backend.js +40 -164
  28. package/srv/blockchain/backends/odatano-backend.d.ts +1 -11
  29. package/srv/blockchain/backends/odatano-backend.js +11 -12
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +13 -160
  31. package/srv/blockchain/backends/ogmios-backend.js +48 -175
  32. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +2 -18
  33. package/srv/blockchain/backends/ogmios-frame-guard.js +8 -20
  34. package/srv/blockchain/cardano-client.d.ts +12 -80
  35. package/srv/blockchain/cardano-client.js +36 -88
  36. package/srv/blockchain/cardano-indexer.d.ts +12 -192
  37. package/srv/blockchain/cardano-indexer.js +132 -222
  38. package/srv/blockchain/cardano-tx-builder.d.ts +1 -28
  39. package/srv/blockchain/cardano-tx-builder.js +17 -34
  40. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  41. package/srv/blockchain/circuit-breaker.js +5 -15
  42. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  43. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +0 -17
  45. package/srv/blockchain/crawler/certificate-backfill.js +8 -22
  46. package/srv/blockchain/crawler/crawler.d.ts +16 -93
  47. package/srv/blockchain/crawler/crawler.js +85 -160
  48. package/srv/blockchain/crawler/credential-backfill.d.ts +0 -9
  49. package/srv/blockchain/crawler/credential-backfill.js +6 -6
  50. package/srv/blockchain/crawler/hooks.d.ts +1 -5
  51. package/srv/blockchain/crawler/index.d.ts +0 -12
  52. package/srv/blockchain/crawler/index.js +6 -20
  53. package/srv/blockchain/crawler/sync-state.d.ts +6 -44
  54. package/srv/blockchain/crawler/sync-state.js +18 -53
  55. package/srv/blockchain/crawler/transaction-backfill.d.ts +0 -11
  56. package/srv/blockchain/crawler/transaction-backfill.js +11 -30
  57. package/srv/blockchain/crawler/utxo-set-import.d.ts +1 -30
  58. package/srv/blockchain/crawler/utxo-set-import.js +27 -53
  59. package/srv/blockchain/ledger-state.d.ts +10 -54
  60. package/srv/blockchain/ledger-state.js +11 -27
  61. package/srv/blockchain/pending-spends.d.ts +0 -12
  62. package/srv/blockchain/pending-spends.js +4 -12
  63. package/srv/blockchain/request-coalescer.d.ts +2 -16
  64. package/srv/blockchain/request-coalescer.js +2 -16
  65. package/srv/blockchain/signing/cose-verifier.d.ts +0 -9
  66. package/srv/blockchain/signing/cose-verifier.js +4 -10
  67. package/srv/blockchain/signing/external-signer.d.ts +1 -4
  68. package/srv/blockchain/signing/external-signer.js +2 -8
  69. package/srv/blockchain/signing/hsm-signer.d.ts +6 -18
  70. package/srv/blockchain/signing/hsm-signer.js +16 -28
  71. package/srv/blockchain/signing/signature-verifier.d.ts +1 -8
  72. package/srv/blockchain/signing/signature-verifier.js +9 -19
  73. package/srv/blockchain/signing/submission-finalizer.d.ts +10 -16
  74. package/srv/blockchain/signing/submission-finalizer.js +48 -19
  75. package/srv/blockchain/stored-chain.d.ts +1 -14
  76. package/srv/blockchain/stored-chain.js +3 -8
  77. package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +0 -4
  78. package/srv/blockchain/transaction-building/buildooor-fee-patch.js +4 -9
  79. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +7 -150
  80. package/srv/blockchain/transaction-building/buildooor-tx.js +91 -196
  81. package/srv/blockchain/transaction-building/caller-datums.d.ts +0 -14
  82. package/srv/blockchain/transaction-building/caller-datums.js +3 -9
  83. package/srv/blockchain/transaction-building/cardano-tx.d.ts +1 -4
  84. package/srv/blockchain/wallet-worker/build-request.d.ts +0 -5
  85. package/srv/blockchain/wallet-worker/build-request.js +6 -9
  86. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -23
  87. package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -20
  88. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  89. package/srv/blockchain/wallet-worker/index.js +3 -5
  90. package/srv/blockchain/wallet-worker/job-store.d.ts +15 -65
  91. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  92. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -10
  93. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -12
  94. package/srv/blockchain/wallet-worker/signers.d.ts +3 -11
  95. package/srv/blockchain/wallet-worker/signers.js +3 -6
  96. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +3 -21
  97. package/srv/blockchain/wallet-worker/wallet-worker.js +47 -54
  98. package/srv/cardano-agent-service.cds +123 -146
  99. package/srv/cardano-agent-service.js +2 -5
  100. package/srv/cardano-backend-service.cds +10 -17
  101. package/srv/cardano-backend-service.js +7 -12
  102. package/srv/cardano-indexer-service.cds +35 -37
  103. package/srv/cardano-indexer-service.d.ts +5 -1
  104. package/srv/cardano-indexer-service.js +64 -33
  105. package/srv/cardano-service.cds +56 -40
  106. package/srv/cardano-service.js +42 -69
  107. package/srv/cardano-sign-service.cds +14 -23
  108. package/srv/cardano-sign-service.js +18 -24
  109. package/srv/cardano-tx-service.cds +27 -29
  110. package/srv/cardano-tx-service.js +60 -122
  111. package/srv/cardano-worker-service.cds +109 -125
  112. package/srv/cardano-worker-service.js +21 -31
  113. package/srv/cbor/cip68.d.ts +13 -0
  114. package/srv/cbor/cip68.js +56 -0
  115. package/srv/cbor/index.d.ts +1 -0
  116. package/srv/cbor/index.js +6 -1
  117. package/srv/cbor/parse.d.ts +3 -18
  118. package/srv/cbor/parse.js +2 -7
  119. package/srv/cbor/plutus-data-json.d.ts +0 -4
  120. package/srv/server.d.ts +5 -36
  121. package/srv/server.js +30 -51
  122. package/srv/utils/agent-grants-config.d.ts +0 -18
  123. package/srv/utils/agent-grants-config.js +6 -13
  124. package/srv/utils/agent-grants.d.ts +14 -68
  125. package/srv/utils/agent-grants.js +42 -60
  126. package/srv/utils/agent-token-auth.d.ts +0 -5
  127. package/srv/utils/agent-token-auth.js +2 -5
  128. package/srv/utils/backend-request-handler.d.ts +1 -1
  129. package/srv/utils/collections.d.ts +1 -4
  130. package/srv/utils/collections.js +1 -4
  131. package/srv/utils/const.d.ts +0 -18
  132. package/srv/utils/const.js +7 -18
  133. package/srv/utils/crypto.js +3 -5
  134. package/srv/utils/db-indexes.d.ts +2 -0
  135. package/srv/utils/db-indexes.js +22 -9
  136. package/srv/utils/db-sanitize.d.ts +1 -8
  137. package/srv/utils/db-sanitize.js +3 -8
  138. package/srv/utils/epoch-slots.d.ts +1 -8
  139. package/srv/utils/epoch-slots.js +3 -8
  140. package/srv/utils/error-codes.d.ts +0 -4
  141. package/srv/utils/error-codes.js +2 -4
  142. package/srv/utils/errors.d.ts +2 -22
  143. package/srv/utils/errors.js +13 -27
  144. package/srv/utils/liveness.d.ts +0 -4
  145. package/srv/utils/liveness.js +2 -4
  146. package/srv/utils/mappers.d.ts +0 -37
  147. package/srv/utils/mappers.js +22 -39
  148. package/srv/utils/network-context.js +2 -4
  149. package/srv/utils/paging.d.ts +31 -0
  150. package/srv/utils/paging.js +43 -0
  151. package/srv/utils/pg-inline-json.js +3 -7
  152. package/srv/utils/pg-order-nulls.js +2 -5
  153. package/srv/utils/plutus-placeholders.d.ts +0 -13
  154. package/srv/utils/plutus-placeholders.js +6 -13
  155. package/srv/utils/rate-limiter.d.ts +0 -8
  156. package/srv/utils/rate-limiter.js +2 -4
  157. package/srv/utils/reference-script.d.ts +0 -18
  158. package/srv/utils/reference-script.js +8 -19
  159. package/srv/utils/service-events.d.ts +0 -4
  160. package/srv/utils/service-events.js +2 -4
  161. package/srv/utils/signing-helper.d.ts +1 -8
  162. package/srv/utils/signing-helper.js +3 -8
  163. package/srv/utils/tx-build-helper.d.ts +2 -32
  164. package/srv/utils/tx-build-helper.js +26 -40
  165. package/srv/utils/tx-request-parsers.d.ts +1 -25
  166. package/srv/utils/tx-request-parsers.js +10 -25
  167. package/srv/utils/tx-utils.d.ts +0 -8
  168. package/srv/utils/tx-utils.js +10 -13
  169. package/srv/utils/types.d.ts +2 -37
  170. package/srv/utils/validators.d.ts +0 -4
  171. package/srv/utils/validators.js +2 -4
@@ -13,10 +13,8 @@ exports.activateAgentGrants = activateAgentGrants;
13
13
  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
- /**
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.
19
- */
16
+ // Grant administration calls per principal per hour. An invalid value logs a warning
17
+ // and falls back to the default. It never disables the feature.
20
18
  function loadGrantAdminRateLimit(env = process.env) {
21
19
  const cfg = envRecord();
22
20
  const raw = cfg.adminRateLimit !== undefined ? cfg.adminRateLimit : env.AGENT_GRANT_ADMIN_RATE_LIMIT;
@@ -30,10 +28,8 @@ function loadGrantAdminRateLimit(env = process.env) {
30
28
  return n;
31
29
  }
32
30
  exports.AGENT_TOKEN_CACHE_MS_DEFAULT = 10_000;
33
- /**
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.
36
- */
31
+ // How long a resolved grant row is reused before the DB is read again. 0 disables the cache.
32
+ // This bounds how late a revoke on another replica takes effect.
37
33
  function loadTokenCacheMs(env = process.env) {
38
34
  const cfg = envRecord();
39
35
  const raw = cfg.tokenCacheMs !== undefined ? cfg.tokenCacheMs : env.AGENT_TOKEN_CACHE_MS;
@@ -88,11 +84,8 @@ function loadAgentGrantsConfig(env = process.env) {
88
84
  }
89
85
  /** Once-per-process marker on the `cds` singleton; a module-level flag would not survive a double load. */
90
86
  const ACTIVATED = Symbol.for('odatano.agentGrants.activated');
91
- /**
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.
95
- */
87
+ // Installs @odatano/cap-auth with the `x-agent-token` lane and keeps the old strategy as delegate.
88
+ // Must run before cds.server() builds middlewares. Never throws.
96
89
  function activateAgentGrants() {
97
90
  const facade = cds_1.default;
98
91
  if (facade[ACTIVATED] !== undefined)
@@ -1,10 +1,6 @@
1
- /**
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.
5
- */
6
1
  import cds, { Request } from '@sap/cds';
7
2
  import { BackendError } from './errors';
3
+ import type { CardanoAgentGrant } from '#cds-models/odatano/cardano';
8
4
  export declare const AGENT_TOKEN_HEADER = "x-agent-token";
9
5
  export declare const AGENT_TOKEN_PREFIX = "odat_";
10
6
  /** Role every token principal carries; the only role it ever has. */
@@ -16,39 +12,22 @@ export declare const GRANTS_ENTITY = "odatano.cardano.CardanoAgentGrants";
16
12
  export declare const GRANT_USAGE_ENTITY = "odatano.cardano.CardanoAgentGrantUsage";
17
13
  /** The services the hook attaches to and the transport lane opens. */
18
14
  export declare const AGENT_SERVICE_NAMES: readonly string[];
19
- /**
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.
22
- */
15
+ /** Actions an operator may allow on a grant; each call costs one budget unit. Anything else not always allowed is a 403. */
23
16
  export declare const AGENT_ALLOWLISTABLE_ACTIONS: readonly string[];
24
17
  /** Allow-listable actions that spend from a worker wallet: the grant must be pinned. */
25
18
  export declare const AGENT_WALLET_ACTIONS: ReadonlySet<string>;
26
- /**
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.
29
- */
19
+ /** Events every valid token may use without allow-list entry or budget. Row-level `$user.grantId` restrictions narrow them. */
30
20
  export declare const AGENT_ALWAYS_ALLOWED_EVENTS: ReadonlySet<string>;
31
21
  /** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
32
22
  export declare const AGENT_JOB_KINDS: readonly string[];
33
23
  /** Forget every rate-limit window, the token cache and re-read the knobs from the config (tests). */
34
24
  export declare function __resetGrantRateLimiterForTests(): void;
35
- export interface AgentGrantRow {
25
+ /** A grant row with the fields every grant has set. */
26
+ export type AgentGrantRow = Omit<CardanoAgentGrant, 'ID' | 'userId' | 'allowedActions'> & {
36
27
  ID: string;
37
28
  userId: string;
38
- agentLabel?: string | null;
39
- tokenHash?: string;
40
29
  allowedActions: string;
41
- walletId?: string | null;
42
- allowedJobKinds?: string | null;
43
- maxJobsPerDay?: number | null;
44
- jobsUsedToday?: number | null;
45
- budgetWindow?: string | null;
46
- validUntil?: string | null;
47
- isActive?: boolean;
48
- revokedAt?: string | null;
49
- createdAt?: string | null;
50
- lastUsedAt?: string | null;
51
- }
30
+ };
52
31
  /** Anything that runs a CQL statement: the primary db service or one transaction of it. */
53
32
  export type Runner = {
54
33
  run: (q: unknown) => Promise<unknown>;
@@ -73,15 +52,9 @@ export declare function __setTokenCacheMsForTests(ms: number | null): void;
73
52
  export declare function invalidateTokenCache(grantId: string): void;
74
53
  /** Entries waiting in the token cache (monitoring, tests). */
75
54
  export declare function tokenCacheSize(): number;
76
- /**
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).
79
- */
55
+ /** Authenticate a token by prefix, hash and expiry. A revoked grant answers like an unknown one. */
80
56
  export declare function resolveAgentToken(token: string, runner?: Runner): Promise<TokenResolution>;
81
- /**
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.
84
- */
57
+ /** The user a token request runs as: never the operator, so `$user` restrictions apply and every Admin gate refuses it. */
85
58
  export declare function makeAgentUser(grant: AgentGrantRow): cds.User;
86
59
  export interface IssueAgentGrantInput {
87
60
  allowedActions: string[];
@@ -123,10 +96,7 @@ export interface RotatedAgentGrant {
123
96
  /** Shown once. Never logged, never stored. */
124
97
  token: string;
125
98
  }
126
- /**
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.
129
- */
99
+ /** Replace the grant's token and keep everything else. Null when the grant is missing or revoked. */
130
100
  export declare function rotateAgentGrantToken(grantId: string, runner?: Runner): Promise<RotatedAgentGrant | null>;
131
101
  /** The editable grant fields, as a client sends them: absent = untouched, explicit null = cleared. */
132
102
  export interface UpdateAgentGrantInput {
@@ -148,10 +118,6 @@ export type UpdateAgentGrantResult = {
148
118
  code?: 'GRANT_REVOKED';
149
119
  message: string;
150
120
  };
151
- /**
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.
154
- */
155
121
  export declare function updateAgentGrant(grantId: string, input: UpdateAgentGrantInput, runner?: Runner): Promise<UpdateAgentGrantResult>;
156
122
  export declare const USAGE_WINDOW_MAX_MS: number;
157
123
  export declare const USAGE_WINDOW_DEFAULT_MS: number;
@@ -185,10 +151,7 @@ export interface AgentGrantUsage {
185
151
  jobsUsedToday: number;
186
152
  maxJobsPerDay: number | null;
187
153
  }
188
- /**
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.
191
- */
154
+ /** Admitted calls of the grant in `window` per service and action. Buffered counters are flushed first. */
192
155
  export declare function getGrantUsage(grant: AgentGrantRow, window: Extract<UsageWindow, {
193
156
  ok: true;
194
157
  }>, runner?: Runner, flushRunner?: Runner): Promise<AgentGrantUsage>;
@@ -208,31 +171,20 @@ export declare function toGrantStatus(grant: AgentGrantRow): AgentGrantStatus;
208
171
  /** Validation rejections happen before any transaction work. */
209
172
  export declare function registerAgentGrantHandlers(srv: cds.Service): void;
210
173
  export declare function attachAgentGrantEnforcement(srv: cds.Service, runner?: Runner): void;
211
- /**
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.
215
- */
216
174
  export interface BudgetRunner {
217
175
  runner: Runner;
218
176
  /** true: statements run outside the request transaction (and a refused request is refunded). */
219
177
  detached: boolean;
220
178
  }
221
179
  export declare function budgetRunnerFor(req: Request, injected?: Runner, detached?: boolean): BudgetRunner;
222
- /**
223
- * The before('*') hook: allow list, wallet pinning, daily budget, usage, lastUsedAt. No-op without a grant.
224
- * `runner` / `detached` are test seams.
225
- */
180
+ export declare function errorStatus(err: unknown): number;
181
+ /** The before('*') hook for token requests: allow list, wallet binding, daily budget and usage. */
226
182
  export declare function enforceAgentGrant(req: Request, runner?: Runner, detached?: boolean, serviceName?: string): Promise<unknown>;
227
183
  export interface BudgetCharge {
228
184
  consumed: boolean;
229
185
  /** The UTC day the unit was charged to; the refund must name the same window. */
230
186
  window: string;
231
187
  }
232
- /**
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`).
235
- */
236
188
  export declare function consumeDailyBudget(br: BudgetRunner | Runner, grant: AgentGrantRow): Promise<BudgetCharge>;
237
189
  /** Undo one consumeDailyBudget in the window it was charged to; never touches a newer day's counter. */
238
190
  export declare function refundDailyBudget(br: BudgetRunner | Runner, grant: AgentGrantRow, window: string): Promise<void>;
@@ -243,18 +195,12 @@ export declare function __setGrantUsageModeForTests(mode: UsageMode | null): voi
243
195
  export declare function __resetGrantUsageBufferForTests(): void;
244
196
  /** How many keys wait for the next flush (monitoring, tests). */
245
197
  export declare function pendingGrantUsageKeys(): number;
246
- /**
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.
249
- */
198
+ /** Write the buffered deltas per key. A failed delta goes back into the buffer for the next flush. */
250
199
  export declare function flushGrantUsage(runner?: Runner): Promise<{
251
200
  flushed: number;
252
201
  failed: number;
253
202
  }>;
254
- /**
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.
257
- */
203
+ /** Count one admitted call on (grant, UTC day, service, action). Never fails the request; returns the day counted on. */
258
204
  export declare function recordGrantUsage(br: BudgetRunner | Runner, grant: AgentGrantRow, service: string, action: string, now?: Date): Promise<string>;
259
205
  /** `refunded + 1` on the row the call was counted on; deferred mode buffers it on the same key. */
260
206
  export declare function refundGrantUsage(br: BudgetRunner | Runner, grant: AgentGrantRow, service: string, action: string, day: string): Promise<void>;
@@ -1,9 +1,6 @@
1
1
  "use strict";
2
- /**
3
- * Agent grants: scoped, budgeted bearer capabilities. The transport lane turns `x-agent-token` into the
4
- * principal `agent:<grantId>` (role `agent-grant`) before any hook runs; `attachAgentGrantEnforcement`
5
- * applies allow list, wallet pinning and daily budget; `registerAgentGrantHandlers` is the lifecycle API.
6
- */
2
+ // Agent grants: scoped, budgeted bearer tokens. A token request runs as `agent:<grantId>` with the role `agent-grant`.
3
+ // attachAgentGrantEnforcement checks allow list, wallet and budget; registerAgentGrantHandlers is the admin API.
7
4
  var __importDefault = (this && this.__importDefault) || function (mod) {
8
5
  return (mod && mod.__esModule) ? mod : { "default": mod };
9
6
  };
@@ -30,6 +27,7 @@ exports.toGrantStatus = toGrantStatus;
30
27
  exports.registerAgentGrantHandlers = registerAgentGrantHandlers;
31
28
  exports.attachAgentGrantEnforcement = attachAgentGrantEnforcement;
32
29
  exports.budgetRunnerFor = budgetRunnerFor;
30
+ exports.errorStatus = errorStatus;
33
31
  exports.enforceAgentGrant = enforceAgentGrant;
34
32
  exports.consumeDailyBudget = consumeDailyBudget;
35
33
  exports.refundDailyBudget = refundDailyBudget;
@@ -68,10 +66,7 @@ exports.AGENT_SERVICE_NAMES = [
68
66
  'CardanoAgentService',
69
67
  'CardanoBackendService',
70
68
  ];
71
- /**
72
- * Actions an operator may put on a grant's allow list; each call costs one budget unit. Anything else
73
- * not in AGENT_ALWAYS_ALLOWED_EVENTS (HSM signing, pause/resume, grant administration) is a 403.
74
- */
69
+ /** Actions an operator may allow on a grant; each call costs one budget unit. Anything else not always allowed is a 403. */
75
70
  exports.AGENT_ALLOWLISTABLE_ACTIONS = [
76
71
  // CardanoTransactionService: unsigned CBOR
77
72
  'BuildSimpleAdaTransaction',
@@ -94,10 +89,7 @@ exports.AGENT_ALLOWLISTABLE_ACTIONS = [
94
89
  ];
95
90
  /** Allow-listable actions that spend from a worker wallet: the grant must be pinned. */
96
91
  exports.AGENT_WALLET_ACTIONS = new Set(['SubmitWalletJob', 'CancelJob']);
97
- /**
98
- * Events every valid token may use without allow-list entry or budget: reads, compute-only actions,
99
- * status polling. Row-level narrowing is done by the `$user.grantId` restrictions in the CDS models.
100
- */
92
+ /** Events every valid token may use without allow-list entry or budget. Row-level `$user.grantId` restrictions narrow them. */
101
93
  exports.AGENT_ALWAYS_ALLOWED_EVENTS = new Set([
102
94
  'READ',
103
95
  // CardanoODataService: chain reads through the backends
@@ -217,10 +209,7 @@ function rememberToken(hash, grant, ttl) {
217
209
  tokenCache.set(hash, { grant, until: Date.now() + ttl });
218
210
  tokenHashOfGrant.set(grant.ID, hash);
219
211
  }
220
- /**
221
- * Authenticate a bearer token: prefix, hash lookup among active grants (revoked = unknown, non-leaking),
222
- * expiry. Runs detached from any ambient transaction; the lookup is cached (see above).
223
- */
212
+ /** Authenticate a token by prefix, hash and expiry. A revoked grant answers like an unknown one. */
224
213
  async function resolveAgentToken(token, runner = dbRunner()) {
225
214
  if (typeof token !== 'string' || !token.startsWith(exports.AGENT_TOKEN_PREFIX)) {
226
215
  return { ok: false, status: 401, message: 'invalid agent token' };
@@ -249,10 +238,7 @@ async function resolveAgentToken(token, runner = dbRunner()) {
249
238
  rememberToken(hash, grant, ttl);
250
239
  return { ok: true, grant };
251
240
  }
252
- /**
253
- * The principal a token request runs under: not the operator and without the operator's roles, so
254
- * `createdBy = $user` and `$user.grantId` restrictions narrow it and every `@requires: 'Admin'` refuses it.
255
- */
241
+ /** The user a token request runs as: never the operator, so `$user` restrictions apply and every Admin gate refuses it. */
256
242
  function makeAgentUser(grant) {
257
243
  return new cds_1.default.User({
258
244
  id: agentPrincipalId(grant.ID),
@@ -371,10 +357,7 @@ async function revokeAgentGrantById(grantId, runner = dbRunner()) {
371
357
  logger.info(`agent grant ${grantId} revoked`);
372
358
  return revoked;
373
359
  }
374
- /**
375
- * Replace the grant's token; budget, wallet, allow list and expiry survive. The old token is unknown
376
- * from the next request (another replica: after AGENT_TOKEN_CACHE_MS). Null when missing or revoked.
377
- */
360
+ /** Replace the grant's token and keep everything else. Null when the grant is missing or revoked. */
378
361
  async function rotateAgentGrantToken(grantId, runner = dbRunner()) {
379
362
  if (!grantId)
380
363
  return null;
@@ -391,10 +374,8 @@ exports.GRANT_IMMUTABLE_FIELDS = ['walletId', 'userId', 'tokenHash'];
391
374
  const GRANT_EDITABLE_FIELDS = [
392
375
  'agentLabel', 'allowedActions', 'allowedJobKinds', 'maxJobsPerDay', 'validUntil',
393
376
  ];
394
- /**
395
- * Edit an active grant: absent field = untouched, explicit null = cleared (allowedActions cannot be emptied).
396
- * The merged row passes validateGrantInput. Unknown grant 404, revoked 409 GRANT_REVOKED, invalid input 400.
397
- */
377
+ // Edit an active grant. An absent field stays, an explicit null clears it; allowedActions cannot be emptied.
378
+ // Unknown grant is 404, revoked is 409 GRANT_REVOKED, invalid input is 400.
398
379
  async function updateAgentGrant(grantId, input, runner = dbRunner()) {
399
380
  const has = (k) => Object.prototype.hasOwnProperty.call(input, k);
400
381
  const existing = (await runner.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: grantId })));
@@ -463,10 +444,7 @@ function resolveUsageWindow(since, until, now = new Date()) {
463
444
  const untilIso = new Date(toMs).toISOString();
464
445
  return { ok: true, since: sinceIso, until: untilIso, sinceDay: sinceIso.slice(0, 10), untilDay: untilIso.slice(0, 10) };
465
446
  }
466
- /**
467
- * Admitted calls of the grant in `window`, grouped by service and action. Deferred counters are flushed
468
- * first on `flushRunner` (detached autocommit), so the read on `runner` sees them without holding locks.
469
- */
447
+ /** Admitted calls of the grant in `window` per service and action. Buffered counters are flushed first. */
470
448
  async function getGrantUsage(grant, window, runner = dbRunner(), flushRunner = dbRunner()) {
471
449
  if (pendingGrantUsageKeys() > 0)
472
450
  await flushGrantUsage(flushRunner);
@@ -511,10 +489,7 @@ function toGrantStatus(grant) {
511
489
  // ---------------------------------------------------------------------------
512
490
  // CardanoAgentService handlers
513
491
  // ---------------------------------------------------------------------------
514
- /**
515
- * Prelude of the administration actions: rate limit (refusals consume the window), then no token
516
- * principal, then authentication. False after a reject.
517
- */
492
+ /** Checks before each admin action: rate limit, no token caller, authenticated. False after a reject. */
518
493
  function checkGrantAdmin(req, verb) {
519
494
  const rate = grantAdminLimiter().check((0, rate_limiter_1.principalRateKey)(req, 'grant-admin'));
520
495
  if (!rate.allowed) {
@@ -662,10 +637,28 @@ function budgetRunnerFor(req, injected, detached) {
662
637
  async function runStmt(br, statement) {
663
638
  return br.detached ? (0, tx_utils_1.runWithoutAmbientTx)(() => br.runner.run(statement)) : br.runner.run(statement);
664
639
  }
665
- /**
666
- * The before('*') hook: allow list, wallet pinning, daily budget, usage, lastUsedAt. No-op without a grant.
667
- * `runner` / `detached` are test seams.
668
- */
640
+ // HTTP status of a failed request's error, as CAP derives it. A combined error has no status:
641
+ // one shared detail status wins, any 5xx gives 500, else 400.
642
+ function errorStatus(err) {
643
+ const e = err;
644
+ const own = ownStatus(e);
645
+ if (own)
646
+ return own;
647
+ if (!Array.isArray(e?.details))
648
+ return 500;
649
+ const nested = [...new Set(e.details.map(ownStatus).filter((n) => !!n))];
650
+ if (nested.length === 1)
651
+ return nested[0];
652
+ return nested.some(n => n >= 500) ? 500 : 400;
653
+ }
654
+ function ownStatus(e) {
655
+ const status = Number(e?.status ?? e?.statusCode);
656
+ if (Number.isInteger(status) && status > 0)
657
+ return status;
658
+ const code = Number(e?.code);
659
+ return Number.isInteger(code) && code >= 400 && code < 600 ? code : undefined;
660
+ }
661
+ /** The before('*') hook for token requests: allow list, wallet binding, daily budget and usage. */
669
662
  async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown') {
670
663
  const grant = agentGrantOf(req);
671
664
  if (!grant)
@@ -725,9 +718,8 @@ async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown')
725
718
  if (br.detached) {
726
719
  const chargedWindow = charge?.window ?? null;
727
720
  req.on?.('failed', (err) => {
728
- const e = err;
729
- const status = Number(e?.status ?? e?.statusCode ?? e?.code);
730
- if (Number.isInteger(status) && status >= 400 && status < 429) {
721
+ const status = errorStatus(err);
722
+ if (status >= 400 && status < 429) {
731
723
  // Off the failing request's tick: its transaction is still rolling back when 'failed' fires,
732
724
  // and a concurrent write on a second SQLite connection would contend for the lock
733
725
  setImmediate(() => {
@@ -741,10 +733,8 @@ async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown')
741
733
  }
742
734
  await touchLastUsed(grant, br);
743
735
  }
744
- /**
745
- * Consume one unit of the daily budget with two conditional UPDATEs, so concurrent requests cannot
746
- * overspend: a compare-and-swap window reset and a bounded increment (`jobsUsedToday < max`).
747
- */
736
+ // Consume one budget unit with two conditional UPDATEs, so concurrent requests cannot overspend:
737
+ // a compare-and-swap reset of the day window, then an increment bounded by the daily maximum.
748
738
  async function consumeDailyBudget(br, grant) {
749
739
  const runner = 'runner' in br ? br : { runner: br, detached: true };
750
740
  const today = utcDay();
@@ -819,10 +809,7 @@ function bufferUsage(key, calls, refunded) {
819
809
  cds_1.default.on('shutdown', () => flushGrantUsage().catch(() => undefined));
820
810
  }
821
811
  }
822
- /**
823
- * Writes the buffered deltas per key: UPDATE, INSERT when the row is missing, one more UPDATE when a racing
824
- * writer created it. A failed delta goes back into the buffer for the next flush.
825
- */
812
+ /** Write the buffered deltas per key. A failed delta goes back into the buffer for the next flush. */
826
813
  async function flushGrantUsage(runner = dbRunner()) {
827
814
  if (usageBuffer.size === 0)
828
815
  return { flushed: 0, failed: 0 };
@@ -860,10 +847,7 @@ async function flushGrantUsage(runner = dbRunner()) {
860
847
  }
861
848
  return { flushed, failed };
862
849
  }
863
- /**
864
- * One admitted call: `calls + 1` on (grant, UTC day, service, action). Deferred mode buffers the delta;
865
- * sync mode writes UPDATE / INSERT / UPDATE awaited. Never fails the request. Returns the day counted on.
866
- */
850
+ /** Count one admitted call on (grant, UTC day, service, action). Never fails the request; returns the day counted on. */
867
851
  async function recordGrantUsage(br, grant, service, action, now = new Date()) {
868
852
  const runner = 'runner' in br ? br : { runner: br, detached: true };
869
853
  const day = utcDay(now);
@@ -900,10 +884,8 @@ async function refundGrantUsage(br, grant, service, action, day) {
900
884
  .set({ refunded: { '+=': 1 } })
901
885
  .where(key));
902
886
  }
903
- /**
904
- * lastUsedAt, at most once a minute per grant. Awaited: a fire-and-forget write on a second connection
905
- * races the handler's reads (SQLITE_BUSY_SNAPSHOT in WAL mode). A failed touch never fails the request.
906
- */
887
+ // lastUsedAt at most once a minute per grant. Awaited, since a fire-and-forget write on a second
888
+ // connection races the handler's reads on SQLite. A failed touch never fails the request.
907
889
  const lastUsedTouched = new Map();
908
890
  const LAST_USED_INTERVAL_MS = 60_000;
909
891
  async function touchLastUsed(grant, br) {
@@ -1,8 +1,3 @@
1
- /**
2
- * `x-agent-token` transport lane: a token on a service path runs as `agent:<grantId>` with
3
- * role `agent-grant` (unknown 401, expired 410); other paths fall through to the delegate.
4
- * Failed attempts are throttled per client address (20 per 15 minutes).
5
- */
6
1
  import { type TransportLane } from '@odatano/cap-auth';
7
2
  /** Test seam: pin the service paths instead of reading `cds.services`. `null` resets. */
8
3
  export declare function __setAgentServicePathsForTests(paths: string[] | null): void;
@@ -1,9 +1,6 @@
1
1
  "use strict";
2
- /**
3
- * `x-agent-token` transport lane: a token on a service path runs as `agent:<grantId>` with
4
- * role `agent-grant` (unknown 401, expired 410); other paths fall through to the delegate.
5
- * Failed attempts are throttled per client address (20 per 15 minutes).
6
- */
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.
7
4
  var __importDefault = (this && this.__importDefault) || function (mod) {
8
5
  return (mod && mod.__esModule) ? mod : { "default": mod };
9
6
  };
@@ -2,5 +2,5 @@ import cds, { Request } from '@sap/cds';
2
2
  /** Wraps a backend call and normalizes any thrown error to a BackendError subclass. */
3
3
  export declare function handleBackendRequest<T>(fn: () => Promise<T>, backendName: string): Promise<T>;
4
4
  /** Runs a service handler inside the request transaction and maps errors to OData responses. */
5
- export declare function handleRequest(req: Request, handler: (db: cds.Transaction) => Promise<unknown>): Promise<unknown>;
5
+ export declare function handleRequest<T>(req: Request, handler: (db: cds.Transaction) => Promise<T>): Promise<T>;
6
6
  //# sourceMappingURL=backend-request-handler.d.ts.map
@@ -1,8 +1,5 @@
1
1
  /** Small collection helpers shared across the blockchain layer. */
2
- /**
3
- * Split an array into fixed-size chunks; keeps CQL IN-lists below driver bind-variable limits
4
- * (SQLite: 999 on older builds, 32766 on node:sqlite).
5
- */
2
+ /** Splits an array into chunks so CQL IN-lists stay below the driver's bind-variable limit. */
6
3
  export declare function chunk<T>(arr: T[], size: number): T[][];
7
4
  /** Max bind variables per IN-list, below every supported driver's cap. */
8
5
  export declare const IN_CHUNK = 500;
@@ -3,10 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.IN_CHUNK = void 0;
5
5
  exports.chunk = chunk;
6
- /**
7
- * Split an array into fixed-size chunks; keeps CQL IN-lists below driver bind-variable limits
8
- * (SQLite: 999 on older builds, 32766 on node:sqlite).
9
- */
6
+ /** Splits an array into chunks so CQL IN-lists stay below the driver's bind-variable limit. */
10
7
  function chunk(arr, size) {
11
8
  if (size <= 0)
12
9
  throw new RangeError(`chunk size must be > 0, got ${size}`);
@@ -5,12 +5,6 @@ export declare const CARDANO_DEFAULTS: {
5
5
  /** Milliseconds per slot */
6
6
  MS_PER_SLOT: number;
7
7
  };
8
- /**
9
- * Per-network epoch geometry anchored at the Shelley transition:
10
- * `epochStartSlot(epoch) = shelleyStartSlot + (epoch - shelleyStartEpoch) * slotsPerEpoch`.
11
- * Preview epochs are 1 day; mainnet/preprod are offset by their Byron era.
12
- * `securityParam` (k): blocks the node keeps volatile, i.e. how far back ledger state can be acquired.
13
- */
14
8
  export declare const EPOCH_CONFIG_BY_NETWORK: {
15
9
  readonly mainnet: {
16
10
  readonly shelleyStartEpoch: 208;
@@ -43,10 +37,6 @@ export declare const HIGH_EXECUTION_UNITS: {
43
37
  };
44
38
  /** Relative multiplier on evaluator ExUnits; combined with the ABS_* floors below. */
45
39
  export declare const EXECUTION_UNIT_BUFFER = 1.1;
46
- /**
47
- * Absolute ExUnits floor on top of the relative multiplier: covers ScriptContext drift of validators
48
- * that iterate reference inputs and decode CBOR datums. `max_tx_ex_units` still caps the total.
49
- */
50
40
  export declare const ABS_CPU_BUFFER = 200000;
51
41
  export declare const ABS_MEM_BUFFER = 5000;
52
42
  /** Transaction building constants */
@@ -73,10 +63,6 @@ export declare const HRP: {
73
63
  export declare const MAX_JSON_SIZE = 1048576;
74
64
  /** Maximum nesting depth for JSON objects/arrays */
75
65
  export declare const MAX_DEPTH = 10;
76
- /**
77
- * Nesting depth for PlutusData JSON (redeemers, datums, script params): every constructor takes two
78
- * levels ({constructor, fields: [...]}), so protocol redeemers go past MAX_DEPTH; size stays capped.
79
- */
80
66
  export declare const PLUTUS_DATA_MAX_DEPTH = 64;
81
67
  /** Maximum number of keys in a JSON object */
82
68
  export declare const MAX_KEYS = 100;
@@ -104,10 +90,6 @@ export declare const ED25519_KEY_HASH_HEX_LENGTH = 56;
104
90
  export declare const ED25519_KEY_HASH_REGEX: RegExp;
105
91
  /** Minimum lovelace for a change output carrying native assets (2 ADA) */
106
92
  export declare const MIN_CHANGE_LOVELACE = 2000000;
107
- /**
108
- * Shelley genesis parameters per network for Buildooor's GenesisInfos (`TxBuilder.posixToSlot()`)
109
- * and `slotToPosixSeconds()`. `systemStartPosixMs` is the first Shelley slot's wall-clock time.
110
- */
111
93
  export declare const GENESIS_INFOS_BY_NETWORK: {
112
94
  readonly mainnet: {
113
95
  readonly systemStartPosixMs: 1596059091000;
@@ -8,12 +8,8 @@ exports.CARDANO_DEFAULTS = {
8
8
  /** Milliseconds per slot */
9
9
  MS_PER_SLOT: 1000,
10
10
  };
11
- /**
12
- * Per-network epoch geometry anchored at the Shelley transition:
13
- * `epochStartSlot(epoch) = shelleyStartSlot + (epoch - shelleyStartEpoch) * slotsPerEpoch`.
14
- * Preview epochs are 1 day; mainnet/preprod are offset by their Byron era.
15
- * `securityParam` (k): blocks the node keeps volatile, i.e. how far back ledger state can be acquired.
16
- */
11
+ // Epoch layout per network, counted from the first Shelley epoch and slot.
12
+ // securityParam is k, the number of recent blocks whose ledger state the node can still acquire.
17
13
  exports.EPOCH_CONFIG_BY_NETWORK = {
18
14
  mainnet: { shelleyStartEpoch: 208, shelleyStartSlot: 4_492_800, slotsPerEpoch: 432_000, securityParam: 2160 },
19
15
  preprod: { shelleyStartEpoch: 4, shelleyStartSlot: 86_400, slotsPerEpoch: 432_000, securityParam: 2160 },
@@ -31,10 +27,8 @@ exports.HIGH_EXECUTION_UNITS = {
31
27
  };
32
28
  /** Relative multiplier on evaluator ExUnits; combined with the ABS_* floors below. */
33
29
  exports.EXECUTION_UNIT_BUFFER = 1.1;
34
- /**
35
- * Absolute ExUnits floor on top of the relative multiplier: covers ScriptContext drift of validators
36
- * that iterate reference inputs and decode CBOR datums. `max_tx_ex_units` still caps the total.
37
- */
30
+ // Fixed ExUnits margin added on top of the multiplier, for validators whose cost drifts
31
+ // with the script context. The protocol's max_tx_ex_units still caps the total.
38
32
  exports.ABS_CPU_BUFFER = 200_000;
39
33
  exports.ABS_MEM_BUFFER = 5_000;
40
34
  /** Transaction building constants */
@@ -52,10 +46,7 @@ exports.HRP = {
52
46
  exports.MAX_JSON_SIZE = 1_048_576;
53
47
  /** Maximum nesting depth for JSON objects/arrays */
54
48
  exports.MAX_DEPTH = 10;
55
- /**
56
- * Nesting depth for PlutusData JSON (redeemers, datums, script params): every constructor takes two
57
- * levels ({constructor, fields: [...]}), so protocol redeemers go past MAX_DEPTH; size stays capped.
58
- */
49
+ // Higher depth limit for PlutusData JSON. Each constructor uses two JSON levels, so real redeemers exceed MAX_DEPTH.
59
50
  exports.PLUTUS_DATA_MAX_DEPTH = 64;
60
51
  /** Maximum number of keys in a JSON object */
61
52
  exports.MAX_KEYS = 100;
@@ -83,10 +74,8 @@ exports.ED25519_KEY_HASH_HEX_LENGTH = 56;
83
74
  exports.ED25519_KEY_HASH_REGEX = /^[a-f0-9]{56}$/i;
84
75
  /** Minimum lovelace for a change output carrying native assets (2 ADA) */
85
76
  exports.MIN_CHANGE_LOVELACE = 2_000_000;
86
- /**
87
- * Shelley genesis parameters per network for Buildooor's GenesisInfos (`TxBuilder.posixToSlot()`)
88
- * and `slotToPosixSeconds()`. `systemStartPosixMs` is the first Shelley slot's wall-clock time.
89
- */
77
+ // Shelley genesis values per network for slot and time conversion.
78
+ // systemStartPosixMs is the wall-clock time of the first Shelley slot.
90
79
  exports.GENESIS_INFOS_BY_NETWORK = {
91
80
  mainnet: { systemStartPosixMs: 1596059091000, slotLengthMs: 1000, startSlotNo: 4492800 }, // 2020-07-29T21:44:51Z
92
81
  preprod: { systemStartPosixMs: 1655683200000, slotLengthMs: 1000, startSlotNo: 0 },
@@ -10,10 +10,8 @@ const node_crypto_1 = __importDefault(require("node:crypto"));
10
10
  const node_os_1 = __importDefault(require("node:os"));
11
11
  const cds_1 = __importDefault(require("@sap/cds"));
12
12
  const logger = cds_1.default.log('CardanoWalletWorker');
13
- /**
14
- * AES-256-GCM for secrets at rest (wallet worker signing keys), format `iv:authTag:ciphertext` in base64.
15
- * Key derived from ENCRYPTION_KEY; production refuses to start without it.
16
- */
13
+ // AES-256-GCM for secrets at rest, stored as base64 `iv:authTag:ciphertext`.
14
+ // The key comes from ENCRYPTION_KEY. Production refuses to start without it.
17
15
  const ALGORITHM = 'aes-256-gcm';
18
16
  const IV_LENGTH = 12; // 96 bits, recommended for GCM
19
17
  const AUTH_TAG_LENGTH = 16; // 128 bits
@@ -26,7 +24,7 @@ function getEncryptionKey() {
26
24
  if (process.env.NODE_ENV === 'production') {
27
25
  throw new Error('ENCRYPTION_KEY must be set in production. Refusing to start with a fallback key.');
28
26
  }
29
- logger.warn('ENCRYPTION_KEY not set — using dev fallback key. Set ENCRYPTION_KEY for production.');
27
+ logger.warn('ENCRYPTION_KEY not set, using dev fallback key. Set ENCRYPTION_KEY for production.');
30
28
  const fallback = `odatano-core-${process.pid}-${node_os_1.default.hostname()}`;
31
29
  return node_crypto_1.default.createHash('sha256').update(fallback).digest();
32
30
  }
@@ -10,6 +10,8 @@ export interface IndexSpec {
10
10
  }
11
11
  /** Every entry answers a query the service or the crawler actually runs. */
12
12
  export declare const DB_INDEXES: readonly IndexSpec[];
13
+ /** Indexes a composite entry above replaces; dropped at start. */
14
+ export declare const DROPPED_DB_INDEXES: readonly string[];
13
15
  /** The statement for one entry; exported so tests pin the shape. */
14
16
  export declare function indexStatement(spec: IndexSpec, kind?: string): string;
15
17
  /** Anything that runs a plain SQL string: the primary db service. */