@odatano/core 2.0.0-rc.1 → 2.0.0-rc.10

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 (61) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +255 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +37 -2
  4. package/@cds-models/CardanoIndexerService/index.js +4 -0
  5. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  6. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  7. package/@cds-models/odatano/cardano/index.d.ts +86 -0
  8. package/@cds-models/odatano/cardano/index.js +6 -0
  9. package/README.md +62 -4
  10. package/db/schema.cds +105 -0
  11. package/package.json +9 -3
  12. package/src/index.d.ts +6 -0
  13. package/src/index.js +21 -1
  14. package/src/plugin.js +33 -30
  15. package/srv/blockchain/backends/blockfrost-backend.js +1 -10
  16. package/srv/blockchain/backends/koios-backend.js +1 -10
  17. package/srv/blockchain/backends/ogmios-backend.d.ts +23 -3
  18. package/srv/blockchain/backends/ogmios-backend.js +72 -5
  19. package/srv/blockchain/cardano-indexer.js +3 -1
  20. package/srv/blockchain/crawler/crawler.d.ts +25 -0
  21. package/srv/blockchain/crawler/crawler.js +68 -1
  22. package/srv/blockchain/crawler/index.d.ts +9 -0
  23. package/srv/blockchain/crawler/index.js +37 -4
  24. package/srv/blockchain/crawler/sync-state.d.ts +13 -1
  25. package/srv/blockchain/crawler/sync-state.js +24 -2
  26. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
  27. package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
  28. package/srv/blockchain/wallet-worker/build-request.js +35 -6
  29. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +32 -1
  30. package/srv/blockchain/wallet-worker/confirmation-tracker.js +91 -29
  31. package/srv/blockchain/wallet-worker/job-store.d.ts +11 -0
  32. package/srv/blockchain/wallet-worker/job-store.js +42 -9
  33. package/srv/cardano-agent-service.cds +150 -0
  34. package/srv/cardano-agent-service.d.ts +2 -0
  35. package/srv/cardano-agent-service.js +16 -0
  36. package/srv/cardano-indexer-service.cds +36 -3
  37. package/srv/cardano-indexer-service.js +3 -0
  38. package/srv/cardano-service.js +57 -3
  39. package/srv/cardano-sign-service.cds +200 -180
  40. package/srv/cardano-tx-service.cds +32 -26
  41. package/srv/cardano-tx-service.js +96 -38
  42. package/srv/cardano-worker-service.cds +125 -125
  43. package/srv/server.d.ts +2 -1
  44. package/srv/server.js +18 -34
  45. package/srv/utils/agent-grants-config.d.ts +65 -0
  46. package/srv/utils/agent-grants-config.js +148 -0
  47. package/srv/utils/agent-grants.d.ts +314 -0
  48. package/srv/utils/agent-grants.js +821 -0
  49. package/srv/utils/agent-token-auth.d.ts +19 -0
  50. package/srv/utils/agent-token-auth.js +81 -0
  51. package/srv/utils/db-sanitize.d.ts +40 -0
  52. package/srv/utils/db-sanitize.js +98 -0
  53. package/srv/utils/liveness.d.ts +23 -0
  54. package/srv/utils/liveness.js +49 -0
  55. package/srv/utils/mappers.d.ts +27 -0
  56. package/srv/utils/mappers.js +67 -7
  57. package/srv/utils/rate-limiter.d.ts +57 -0
  58. package/srv/utils/rate-limiter.js +126 -0
  59. package/srv/utils/tx-request-parsers.d.ts +13 -0
  60. package/srv/utils/tx-request-parsers.js +32 -0
  61. package/srv/utils/types.d.ts +15 -0
@@ -18,6 +18,8 @@ class ConfirmationTracker {
18
18
  running = false;
19
19
  polling = false;
20
20
  lastKnownTipHeight = null;
21
+ /** Polling round counter; see TrackedJob.seenRound. */
22
+ round = 0;
21
23
  constructor(deps) {
22
24
  this.deps = deps;
23
25
  }
@@ -103,29 +105,38 @@ class ConfirmationTracker {
103
105
  for (const job of this.pending.values()) {
104
106
  if (job.foundSlot != null && job.foundSlot > event.forkSlot) {
105
107
  logger.warn(`Job ${job.jobId}: confirmation point (slot ${job.foundSlot}) rolled back past fork ${event.forkSlot} — re-watching`);
106
- job.foundSlot = null;
107
- job.foundHeight = null;
108
- try {
109
- await cds_1.default.tx((tx) => (0, job_store_1.clearConfirmationPoint)(tx, job.jobId));
110
- }
111
- catch (err) {
112
- logger.warn(`Job ${job.jobId}: failed to clear confirmation point:`, err);
108
+ await this.forgetInclusion(job);
109
+ }
110
+ }
111
+ }
112
+ /**
113
+ * The recorded inclusion is gone (a reorg the crawler reported, or a polling
114
+ * re-check that no longer finds the tx): back to watching, and optionally
115
+ * re-submit the SAME signed CBOR — never a rebuild, that is the double-spend
116
+ * guard. "Already known" means the tx survived into the new chain's mempool;
117
+ * that is success, not an error.
118
+ */
119
+ async forgetInclusion(job) {
120
+ job.foundSlot = null;
121
+ job.foundHeight = null;
122
+ job.seenRound = undefined;
123
+ try {
124
+ await cds_1.default.tx((tx) => (0, job_store_1.clearConfirmationPoint)(tx, job.jobId));
125
+ }
126
+ catch (err) {
127
+ logger.warn(`Job ${job.jobId}: failed to clear confirmation point:`, err);
128
+ }
129
+ if (this.deps.options.resubmitOnRollback && job.signedTxCbor) {
130
+ try {
131
+ await this.deps.client.submitTransaction(job.signedTxCbor);
132
+ logger.info(`Job ${job.jobId}: re-submitted original signed tx after rollback`);
133
+ }
134
+ catch (err) {
135
+ if (err instanceof errors_1.TransactionAlreadySubmittedError) {
136
+ logger.debug(`Job ${job.jobId}: tx already known after rollback — nothing to do`);
113
137
  }
114
- if (this.deps.options.resubmitOnRollback && job.signedTxCbor) {
115
- // SAME signed CBOR only — never a rebuild. "Already known" means the tx
116
- // survived into the new chain's mempool; that is success, not an error.
117
- try {
118
- await this.deps.client.submitTransaction(job.signedTxCbor);
119
- logger.info(`Job ${job.jobId}: re-submitted original signed tx after rollback`);
120
- }
121
- catch (err) {
122
- if (err instanceof errors_1.TransactionAlreadySubmittedError) {
123
- logger.debug(`Job ${job.jobId}: tx already known after rollback — nothing to do`);
124
- }
125
- else {
126
- logger.warn(`Job ${job.jobId}: rollback re-submit failed (polling continues to watch):`, err);
127
- }
128
- }
138
+ else {
139
+ logger.warn(`Job ${job.jobId}: rollback re-submit failed (polling continues to watch):`, err);
129
140
  }
130
141
  }
131
142
  }
@@ -136,6 +147,7 @@ class ConfirmationTracker {
136
147
  if (!this.running || this.polling || this.pending.size === 0)
137
148
  return;
138
149
  this.polling = true;
150
+ this.round++;
139
151
  try {
140
152
  // Tip first — also serves the depth check for hook-found entries when the
141
153
  // crawler is off.
@@ -156,6 +168,7 @@ class ConfirmationTracker {
156
168
  const tx = await this.deps.client.getTransaction(job.txHash);
157
169
  job.foundSlot = tx.slot ?? null;
158
170
  job.foundHeight = tx.blockHeight ?? null;
171
+ job.seenRound = this.round;
159
172
  await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
160
173
  logger.info(`Job ${job.jobId}: tx ${job.txHash} found on-chain at height ${job.foundHeight} (polling)`);
161
174
  }
@@ -175,31 +188,73 @@ class ConfirmationTracker {
175
188
  }
176
189
  }
177
190
  }
178
- await this.confirmMature();
191
+ // Polling has no reorg signal, so an inclusion recorded in an EARLIER
192
+ // round is re-checked before it counts (see stillIncluded).
193
+ await this.confirmMature(true);
179
194
  }
180
195
  finally {
181
196
  this.polling = false;
182
197
  }
183
198
  }
184
199
  // ---- Shared -----------------------------------------------------------------
185
- /** Confirm every found job whose depth requirement is met by the known tip. */
186
- async confirmMature() {
200
+ /**
201
+ * Confirm every found job whose depth requirement is met by the known tip.
202
+ * `revalidate` (polling path): an inclusion not seen in THIS round is looked
203
+ * up again first — the crawler's reorg events are the only rollback signal,
204
+ * and with the crawler off there is none, so a tx that was found at height N
205
+ * and then rolled back would otherwise be confirmed on the tip alone.
206
+ */
207
+ async confirmMature(revalidate = false) {
187
208
  const tip = this.lastKnownTipHeight;
188
209
  if (tip == null)
189
210
  return;
190
211
  for (const job of [...this.pending.values()]) {
191
212
  if (job.foundHeight == null)
192
213
  continue;
193
- const confirmations = tip - job.foundHeight + 1;
194
- if (confirmations >= this.deps.options.confirmationDepth) {
195
- await this.finalize(job, 'confirmed');
214
+ if (tip - job.foundHeight + 1 < this.deps.options.confirmationDepth)
215
+ continue;
216
+ if (revalidate && job.seenRound !== this.round && !(await this.stillIncluded(job, tip)))
217
+ continue;
218
+ await this.finalize(job, 'confirmed');
219
+ }
220
+ }
221
+ /**
222
+ * Is the tx still on-chain, and still deep enough? Re-reads it; a tx that
223
+ * moved to another block (re-included after a rollback) gets its new point
224
+ * and is judged at the new height; one that is gone is forgotten (back to
225
+ * watching, optional same-CBOR re-submit) and the tip is re-learned next
226
+ * round, because the pre-rollback tip may overstate the depth.
227
+ */
228
+ async stillIncluded(job, tip) {
229
+ try {
230
+ const tx = await this.deps.client.getTransaction(job.txHash);
231
+ const height = tx.blockHeight ?? null;
232
+ job.seenRound = this.round;
233
+ if (height != null && height !== job.foundHeight) {
234
+ logger.warn(`Job ${job.jobId}: tx ${job.txHash} moved from height ${job.foundHeight} to ${height} — re-anchoring`);
235
+ job.foundHeight = height;
236
+ job.foundSlot = tx.slot ?? null;
237
+ await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
238
+ return tip - height + 1 >= this.deps.options.confirmationDepth;
239
+ }
240
+ return true;
241
+ }
242
+ catch (err) {
243
+ if ((0, errors_1.isNotFoundOnAllBackends)(err)) {
244
+ logger.warn(`Job ${job.jobId}: tx ${job.txHash} no longer on-chain (was at height ${job.foundHeight}) — rollback without a crawler signal, re-watching`);
245
+ this.lastKnownTipHeight = null;
246
+ await this.forgetInclusion(job);
247
+ return false;
196
248
  }
249
+ logger.debug(`Job ${job.jobId}: inclusion re-check failed (transient, next round retries):`, err);
250
+ return false;
197
251
  }
198
252
  }
199
253
  async finalize(job, outcome, errorCode, err) {
254
+ let transitioned = false;
200
255
  try {
201
256
  await cds_1.default.tx(async (tx) => {
202
- const transitioned = outcome === 'confirmed'
257
+ transitioned = outcome === 'confirmed'
203
258
  ? await (0, job_store_1.markConfirmed)(tx, job.jobId)
204
259
  : await (0, job_store_1.markFailed)(tx, job.jobId, errorCode ?? 'FAILED', err ?? new Error('unknown'));
205
260
  if (transitioned) {
@@ -212,6 +267,13 @@ class ConfirmationTracker {
212
267
  return; // keep tracking — the next poll round retries the transition
213
268
  }
214
269
  this.pending.delete(job.jobId);
270
+ if (!transitioned) {
271
+ // Somebody else (another tracker instance, a reconciliation pass, a
272
+ // cancel) reached the terminal state first. The job is done either way,
273
+ // but the stats bump and the terminal event belong to the winner only.
274
+ logger.debug(`Job ${job.jobId}: ${outcome} transition already applied elsewhere — no event from this tracker`);
275
+ return;
276
+ }
215
277
  logger.info(`Job ${job.jobId}: ${outcome}${outcome === 'failed' ? ` (${errorCode})` : ''}`);
216
278
  this.deps.onFinal?.({
217
279
  jobId: job.jobId,
@@ -103,6 +103,17 @@ export interface InsertJobResult {
103
103
  /** True when an idempotent retry matched an existing non-failed job. */
104
104
  deduplicated: boolean;
105
105
  }
106
+ /** The job that currently owns an idempotency key, or null when it is free. */
107
+ /**
108
+ * The stored claim for a caller's idempotency key, SCOPED TO THE PRINCIPAL that
109
+ * submits. Two agents (two grants, two users) may both use `order-1` on the
110
+ * same wallet: each must get its own job, never a "deduplicated" answer that
111
+ * hands one the other's job id. A key from an owner-less caller (privileged
112
+ * test context) stays as-is; an owned key becomes a hash of owner + key, which
113
+ * fits the String(100) column whatever the owner id's length and never collides
114
+ * with a plain key. The caller-visible `idempotencyKey` column keeps the raw key.
115
+ */
116
+ export declare function dedupKeyFor(owner: string | null | undefined, idempotencyKey: string): string;
106
117
  /**
107
118
  * Insert a job row ON THE CALLER'S transaction (NIGHTGATE lesson 1 — see module
108
119
  * docs). Idempotency: an active-or-successful row with the same (walletId, kind,
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.runWithoutAmbientTx = exports.WALLET_JOB_KINDS = exports.JOB_ERROR_CODES = exports.WORKER_LEASE_TTL_MS = void 0;
7
+ exports.dedupKeyFor = dedupKeyFor;
7
8
  exports.insertJob = insertJob;
8
9
  exports.getJobById = getJobById;
9
10
  exports.findDueJobs = findDueJobs;
@@ -160,6 +161,21 @@ function isUniqueViolation(err) {
160
161
  return text.includes('unique constraint') || text.includes('duplicate key');
161
162
  }
162
163
  /** The job that currently owns an idempotency key, or null when it is free. */
164
+ /**
165
+ * The stored claim for a caller's idempotency key, SCOPED TO THE PRINCIPAL that
166
+ * submits. Two agents (two grants, two users) may both use `order-1` on the
167
+ * same wallet: each must get its own job, never a "deduplicated" answer that
168
+ * hands one the other's job id. A key from an owner-less caller (privileged
169
+ * test context) stays as-is; an owned key becomes a hash of owner + key, which
170
+ * fits the String(100) column whatever the owner id's length and never collides
171
+ * with a plain key. The caller-visible `idempotencyKey` column keeps the raw key.
172
+ */
173
+ function dedupKeyFor(owner, idempotencyKey) {
174
+ const scope = owner?.trim() ?? '';
175
+ if (!scope)
176
+ return idempotencyKey;
177
+ return `o:${(0, node_crypto_1.createHash)('sha256').update(`${scope}${idempotencyKey}`).digest('hex').slice(0, 48)}`;
178
+ }
163
179
  async function readDedupHolder(db, walletId, kind, dedupKey) {
164
180
  const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).where({ walletId, kind, dedupKey }));
165
181
  return row ? toJobRow(row) : null;
@@ -185,10 +201,12 @@ async function readDedupHolder(db, walletId, kind, dedupKey) {
185
201
  */
186
202
  async function insertJob(db, args) {
187
203
  const idempotencyKey = args.idempotencyKey ?? null;
188
- if (idempotencyKey) {
204
+ // The claim is per principal: the same key from another owner is another job.
205
+ const claim = idempotencyKey ? dedupKeyFor(args.createdBy, idempotencyKey) : null;
206
+ if (claim) {
189
207
  // Fast path: an owner exists (by construction it is non-terminal). Terminal
190
208
  // jobs release their claim, so they never show up here.
191
- const holder = await readDedupHolder(db, args.walletId, args.kind, idempotencyKey);
209
+ const holder = await readDedupHolder(db, args.walletId, args.kind, claim);
192
210
  if (holder) {
193
211
  if (holder.status !== 'failed' && holder.status !== 'cancelled') {
194
212
  return { jobId: holder.ID, status: holder.status, deduplicated: true };
@@ -208,7 +226,7 @@ async function insertJob(db, args) {
208
226
  idempotencyKey,
209
227
  // No key → the row's own ID: unique by construction, so keyless jobs never
210
228
  // contend for the constraint.
211
- dedupKey: idempotencyKey ?? jobId,
229
+ dedupKey: claim ?? jobId,
212
230
  request: args.request,
213
231
  priority: args.priority ?? 100,
214
232
  notBefore: args.notBefore ?? null,
@@ -223,9 +241,9 @@ async function insertJob(db, args) {
223
241
  catch (err) {
224
242
  // Lost the race: another transaction committed the same key first. Its job is
225
243
  // the one and only job for this key — hand it back instead of paying twice.
226
- if (!idempotencyKey || !isUniqueViolation(err))
244
+ if (!claim || !isUniqueViolation(err))
227
245
  throw err;
228
- const winner = await readDedupHolder(db, args.walletId, args.kind, idempotencyKey);
246
+ const winner = await readDedupHolder(db, args.walletId, args.kind, claim);
229
247
  if (!winner)
230
248
  throw err; // constraint fired for some other reason — do not mask it
231
249
  logger.info(`Concurrent submission for idempotency key "${idempotencyKey}" — returning job ${winner.ID}`);
@@ -285,14 +303,29 @@ async function findOrphanedSubmittingJob(db, walletId, now = new Date()) {
285
303
  async function releaseDedupClaim(db, jobId) {
286
304
  await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs).set({ dedupKey: jobId }).where({ ID: jobId }));
287
305
  }
306
+ /**
307
+ * Move a job from one of `fromStatuses` to `set.status` and report whether THIS
308
+ * call did it. The guard is the conditional UPDATE; the answer is its affected
309
+ * row count (every @cap-js adapter returns a number). A second caller that
310
+ * finds the row already in the target state gets `false`: the transition, the
311
+ * wallet-stats bump and the terminal event belong to the first one only.
312
+ * Two trackers confirming the same job used to count it twice.
313
+ *
314
+ * Fallback for an adapter that returns something that is not a count: read
315
+ * the row back, and accept the target state only if the row was NOT already
316
+ * there before this call (checked with a pre-read in that branch).
317
+ */
288
318
  async function guardedTransition(db, jobId, fromStatuses, set) {
289
- await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
319
+ const affected = await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
290
320
  .set(set)
291
321
  .where({ ID: jobId, status: { in: fromStatuses } }));
292
- // Read-back verification: CAP adapters differ in affected-row return shapes,
293
- // SELECT is consistent everywhere (same pattern as the crawler lease).
322
+ const n = typeof affected === 'number' ? affected : Number(affected);
323
+ if (Number.isFinite(n))
324
+ return n > 0;
325
+ // Unknown return shape: the row is in the target state AND that state is not
326
+ // one it could have been in before (the guard excludes it) means we moved it.
294
327
  const row = await getJobById(db, jobId);
295
- return row?.status === set.status;
328
+ return row?.status === set.status && !fromStatuses.includes(set.status);
296
329
  }
297
330
  /** pending → building. Increments the attempt counter. Returns false when lost. */
298
331
  async function markBuilding(db, jobId, attempt) {
@@ -0,0 +1,150 @@
1
+ using {odatano.cardano as db} from '../db/schema';
2
+
3
+ /**
4
+ * Cardano Agent Service (v2.0)
5
+ *
6
+ * Agent grants: scoped, budgeted bearer capabilities an Admin hands to an agent
7
+ * instead of a full user (see AGENT_GRANTS_DESIGN.md).
8
+ *
9
+ * - CreateAgentGrant / UpdateAgentGrant / RotateAgentGrantToken / RevokeAgentGrant:
10
+ * Admin-only administration, rate limited per principal per hour
11
+ * (AGENT_GRANT_ADMIN_RATE_LIMIT, default 10). The token is returned ONCE from
12
+ * CreateAgentGrant and RotateAgentGrantToken and stored as SHA-256 only.
13
+ * - AgentGrants: Admin-only projection (no token hash). A request carrying a token
14
+ * runs as the principal `agent:<grantId>` with the role `agent-grant` and sees
15
+ * exactly its own row through the row-level restriction below.
16
+ * - GetGrantStatus: token self-service — what am I allowed to do, how much budget
17
+ * is left, when do I expire. What an MCP tool needs to describe itself honestly.
18
+ * - GetGrantUsage: admitted calls per service and action over a window — an Admin
19
+ * for any grant, a token for its own (a partner usage view, ledger reconciliation).
20
+ *
21
+ * Names are this repo's PascalCase; semantics mirror NIGHTGATE's agent grants
22
+ * (createAgentGrant / updateAgentGrant / rotateAgentGrantToken / revokeAgentGrant /
23
+ * getGrantUsage), so a gateway drives both products with one code path.
24
+ *
25
+ * A token request never inherits the operator's roles: `@requires: 'Admin'` on the
26
+ * four actions, on PauseWorker / ResumeWorker / pauseCrawler / resumeCrawler and on
27
+ * every other Admin surface therefore refuses it by construction. The allow list,
28
+ * wallet pinning and daily budget are enforced by a before('*') hook on all six
29
+ * ODATANO services (srv/utils/agent-grants.ts). The `x-agent-token` header only
30
+ * reaches the services when cds.requires.odatano-core.agentGrants.enabled is set
31
+ * (srv/utils/agent-token-auth.ts).
32
+ */
33
+ @requires: 'authenticated-user'
34
+ service CardanoAgentService @(impl: './cardano-agent-service') {
35
+
36
+ @readonly
37
+ @title : 'Agent Grants'
38
+ @description: 'Issued grants (token hash excluded). Admins see all, a token sees its own row.'
39
+ @restrict : [
40
+ { grant: 'READ', to: 'Admin' },
41
+ { grant: 'READ', to: 'agent-grant', where: 'ID = $user.grantId' }
42
+ ]
43
+ entity AgentGrants as projection on db.CardanoAgentGrants excluding { tokenHash };
44
+
45
+ @title : 'Grant Status'
46
+ type GrantStatus {
47
+ grantId : UUID;
48
+ agentLabel : String(100);
49
+ allowedActions : many String;
50
+ walletId : String(50);
51
+ allowedJobKinds : many String;
52
+ maxJobsPerDay : Integer;
53
+ jobsUsedToday : Integer;
54
+ budgetWindow : String(10);
55
+ validUntil : Timestamp;
56
+ isActive : Boolean;
57
+ }
58
+
59
+ @title : 'Issued Grant'
60
+ type IssuedGrant {
61
+ grantId : UUID;
62
+ token : String; // shown once, never stored
63
+ allowedActions : many String;
64
+ walletId : String(50);
65
+ allowedJobKinds : many String;
66
+ maxJobsPerDay : Integer;
67
+ validUntil : Timestamp;
68
+ }
69
+
70
+ @title : 'Get Grant Status'
71
+ @description: 'The calling token''s own grant: allow list, wallet, remaining daily budget, expiry. 400 without a token — an operator lists AgentGrants instead.'
72
+ function GetGrantStatus() returns GrantStatus;
73
+
74
+ @title : 'Create Agent Grant'
75
+ @description: 'Issue a scoped bearer token for an agent. Admin only. The token is returned once and stored as SHA-256. allowedActions must be a non-empty subset of the grantable set; walletId is required when SubmitWalletJob or CancelJob is allowed.'
76
+ @requires : 'Admin'
77
+ action CreateAgentGrant(
78
+ @title: 'Allowed Actions' allowedActions : many String,
79
+ @title: 'Wallet Id' walletId : String(50),
80
+ @title: 'Allowed Job Kinds' allowedJobKinds : many String,
81
+ @title: 'Max Jobs Per Day' maxJobsPerDay : Integer,
82
+ @title: 'Valid Until' validUntil : Timestamp,
83
+ @title: 'Agent Label' agentLabel : String(100)
84
+ ) returns IssuedGrant;
85
+
86
+ @title : 'Revoke Agent Grant'
87
+ @description: 'Deactivate a grant. Admin only. Its token becomes an unknown token immediately.'
88
+ @requires : 'Admin'
89
+ action RevokeAgentGrant(
90
+ @title: 'Grant Id' grantId : UUID
91
+ ) returns Boolean;
92
+
93
+ @title : 'Rotated Grant'
94
+ type RotatedGrant {
95
+ grantId : UUID;
96
+ token : String; // shown once, never stored
97
+ }
98
+
99
+ @title : 'Rotate Agent Grant Token'
100
+ @description: 'Replace the grant token; the old token is unknown from the next request. Budget, wallet, allow list and expiry survive. Admin only. 404 when the grant does not exist or is revoked.'
101
+ @requires : 'Admin'
102
+ action RotateAgentGrantToken(
103
+ @title: 'Grant Id' grantId : UUID
104
+ ) returns RotatedGrant;
105
+
106
+ @title : 'Updated Grant'
107
+ type UpdatedGrant {
108
+ grantId : UUID;
109
+ updated : many String; // parameter names that were applied
110
+ }
111
+
112
+ @title : 'Update Agent Grant'
113
+ @description: 'Change label, allow list, job kinds, daily budget or expiry of an active grant. An absent parameter stays as it is; an explicit null clears agentLabel, allowedJobKinds, maxJobsPerDay or validUntil. allowedActions cannot be emptied; the wallet binding is immutable (issue a new grant). Admin only. 404 unknown grant, 409 GRANT_REVOKED.'
114
+ @requires : 'Admin'
115
+ action UpdateAgentGrant(
116
+ @title: 'Grant Id' grantId : UUID,
117
+ @title: 'Agent Label' agentLabel : String(100),
118
+ @title: 'Allowed Actions' allowedActions : many String,
119
+ @title: 'Allowed Job Kinds' allowedJobKinds : many String,
120
+ @title: 'Max Jobs Per Day' maxJobsPerDay : Integer,
121
+ @title: 'Valid Until' validUntil : Timestamp
122
+ ) returns UpdatedGrant;
123
+
124
+ @title : 'Grant Usage Call'
125
+ type GrantUsageCall {
126
+ service : String(60); // CardanoTransactionService, CardanoSignService, ...
127
+ action : String(100); // BuildSimpleAdaTransaction, SubmitTransaction, ...
128
+ count : Integer; // admitted and kept (budget charged and not refunded)
129
+ refunded : Integer; // admitted, then refunded because the handler refused the input
130
+ }
131
+
132
+ @title : 'Grant Usage'
133
+ type GrantUsage {
134
+ grantId : UUID;
135
+ since : Timestamp;
136
+ until : Timestamp;
137
+ calls : many GrantUsageCall;
138
+ total : Integer;
139
+ jobsUsedToday : Integer;
140
+ maxJobsPerDay : Integer;
141
+ }
142
+
143
+ @title : 'Get Grant Usage'
144
+ @description: 'Admitted calls under a grant between since (default until - 30 days) and until (default now), at most 366 days, per UTC day, grouped by service and action. An Admin sees any grant (revoked ones keep their history); a token sees only its own.'
145
+ function GetGrantUsage(
146
+ @title: 'Grant Id' grantId : UUID,
147
+ @title: 'Since' since : Timestamp,
148
+ @title: 'Until' until : Timestamp
149
+ ) returns GrantUsage;
150
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=cardano-agent-service.d.ts.map
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const agent_grants_1 = require("./utils/agent-grants");
4
+ /**
5
+ * CardanoAgentService handlers — grant administration (Admin) and token
6
+ * self-service. Everything lives in srv/utils/agent-grants.ts so the
7
+ * programmatic API (`issueAgentGrant`, used by @odatano/x402 to sell grants) and
8
+ * the OData actions share one code path.
9
+ *
10
+ * The enforcement hook for token requests is attached to all six services from
11
+ * src/plugin.ts (cds.on('serving')), not here.
12
+ */
13
+ module.exports = (srv) => {
14
+ (0, agent_grants_1.registerAgentGrantHandlers)(srv);
15
+ };
16
+ //# sourceMappingURL=cardano-agent-service.js.map
@@ -8,18 +8,31 @@ using {odatano.cardano as db} from '../db/schema';
8
8
  * - status function + pause/resume actions delegating to the crawler singleton
9
9
  *
10
10
  * Security note: see CardanoODataService (cardano-service.cds) for the rationale on
11
- * service-level auth. pause/resume are operational actions — gate behind a dedicated
12
- * Admin scope. Read-only status and audit data remain available to authenticated users.
11
+ * auth. pause/resume are operational actions — gate behind a dedicated Admin scope.
12
+ * Read-only status and audit data remain available to authenticated users.
13
+ *
14
+ * Deliberately NO service-level @requires: CAP checks a service-level requirement
15
+ * on every request BEFORE the operation's own annotation, so an operation-level
16
+ * `@requires: 'any'` can never open a single function on an otherwise
17
+ * authenticated service (anonymous callers get the 401 challenge first). The
18
+ * requirement therefore sits on each element, and getLiveness() alone is 'any' —
19
+ * the same layout as NIGHTGATE's indexer service.
13
20
  */
14
- @requires: 'authenticated-user'
21
+ // Service-level 'any' on purpose: CAP authorizes the service BEFORE the operation and
22
+ // treats a service without a service-level @requires as authenticated-user under
23
+ // NODE_ENV=production, which would 401 the anonymous operation below despite its own
24
+ // 'any'. Every element carries its requirement; the service itself refuses nothing.
25
+ @requires: 'any'
15
26
  service CardanoIndexerService @(impl: './cardano-indexer-service') {
16
27
 
17
28
  @readonly
29
+ @requires : 'authenticated-user'
18
30
  @title : 'Sync State'
19
31
  @description: 'Singleton crawl cursor — pre-sync progress, tip lag, status, errors'
20
32
  entity SyncState as projection on db.CardanoSyncState;
21
33
 
22
34
  @readonly
35
+ @requires : 'authenticated-user'
23
36
  @title : 'Reorg Log'
24
37
  @description: 'Audit trail of chain rollbacks handled by the crawler'
25
38
  entity ReorgLog as projection on db.CardanoReorgLog;
@@ -59,8 +72,28 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
59
72
  blocksRolledBack : Integer;
60
73
  }
61
74
 
75
+ @requires : 'authenticated-user'
62
76
  function getStatus() returns CrawlerStatus;
63
77
 
78
+ @title : 'Liveness'
79
+ type Liveness {
80
+ status : String; // 'alive'
81
+ timestamp : Timestamp;
82
+ uptime : Integer; // seconds since process start
83
+ version : String; // @odatano/core version
84
+ network : String; // configured network
85
+ }
86
+
87
+ // Anonymous on purpose: a liveness probe carries no credentials. 200 as long
88
+ // as the process answers — no backend or DB probe, no secrets, no backend
89
+ // names, no API key state. Readiness stays with getStatus and the worker
90
+ // status, which remain authenticated. Mirrors NIGHTGATE's
91
+ // `/api/v1/indexer/getLiveness()`, so a gateway probes both products the same way.
92
+ @title : 'Get Liveness'
93
+ @description: 'Unauthenticated liveness probe: 200 while the process answers. Docker HEALTHCHECK and upstream probes use this instead of the service document.'
94
+ @requires : 'any'
95
+ function getLiveness() returns Liveness;
96
+
64
97
  @title : 'Pause Crawler'
65
98
  @description: 'Stop the crawler (closes the chain-sync stream). Resume continues from the cursor.'
66
99
  @requires : 'Admin'
@@ -9,6 +9,7 @@ const errors_1 = require("./utils/errors");
9
9
  const crawler_1 = require("./blockchain/crawler");
10
10
  const sync_state_1 = require("./blockchain/crawler/sync-state");
11
11
  const server_1 = require("./server");
12
+ const liveness_1 = require("./utils/liveness");
12
13
  const logger = cds_1.default.log('CardanoIndexerService');
13
14
  /**
14
15
  * CardanoIndexerService handlers — thin control/observability surface over the crawler
@@ -16,6 +17,8 @@ const logger = cds_1.default.log('CardanoIndexerService');
16
17
  * cursor and starts/stops the crawler.
17
18
  */
18
19
  module.exports = (srv) => {
20
+ // getLiveness — unauthenticated probe (@requires: 'any'); no handleRequest, no app context.
21
+ srv.on('getLiveness', async () => (0, liveness_1.buildLiveness)());
19
22
  // getStatus — live run state + sync progress (numeric fields as strings, CAP-10 aligned)
20
23
  srv.on('getStatus', async (req) => {
21
24
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
@@ -11,9 +11,52 @@ const backend_request_handler_1 = require("./utils/backend-request-handler");
11
11
  const cbor_1 = require("./cbor");
12
12
  const { SELECT } = cds_1.default.ql;
13
13
  const logger = cds_1.default.log(`CardanoService`);
14
+ /**
15
+ * Upper bound of the temporal window opened by {@link widenTemporalWindow}.
16
+ * Generous on purpose: it only has to outlast the slowest index-on-miss (chained
17
+ * backend timeouts of several calls) within ONE request.
18
+ */
19
+ const TEMPORAL_WINDOW_SLACK_MS = 60 * 60 * 1000;
20
+ /**
21
+ * Let this request see temporal slices that IT writes during index-on-miss.
22
+ *
23
+ * CAP filters temporal entities (Pools, Assets, Dreps, Addresses, Accounts, …)
24
+ * with `validFrom < $valid.to AND validTo > $valid.from`. The DB session reads
25
+ * both bounds from the request's `_` bag (`VALID-FROM` / `VALID-TO`) when the
26
+ * transaction begins (HANA) or on first use (sqlite) and otherwise defaults to
27
+ * `now` / `now + 1ms` — a window that is closed long before the backend fetch
28
+ * returns, so a slice stamped after the fetch would be invisible to the
29
+ * `req.query` re-read that honours `$expand` / `$select` (KNOWN_ISSUES #13).
30
+ *
31
+ * Only the UPPER bound is moved. No slice is ever future-dated (every mapper
32
+ * stamps `validFrom = now`), so the only additional rows this admits are the
33
+ * ones this very request writes; expired rows stay hidden (`validTo >
34
+ * $valid.from` is untouched). Explicit `sap-valid-*` query options are left
35
+ * alone. Must run before the handler's first DB statement.
36
+ */
37
+ function widenTemporalWindow(req) {
38
+ const q = req.http?.req?.query;
39
+ if (q && (q['sap-valid-at'] || q['sap-valid-from'] || q['sap-valid-to']))
40
+ return;
41
+ const now = Date.now();
42
+ const from = new Date(now).toISOString();
43
+ const to = new Date(now + TEMPORAL_WINDOW_SLACK_MS).toISOString();
44
+ // The DB session context is built from the context the transaction was opened
45
+ // with — `req` for our `cds.tx(req)`, the root context if a generic handler got
46
+ // there first — so stamp both bags.
47
+ const r = req;
48
+ for (const bag of new Set([r._, r.context?._])) {
49
+ if (!bag)
50
+ continue;
51
+ bag['VALID-FROM'] = from;
52
+ bag['VALID-TO'] = to;
53
+ }
54
+ }
14
55
  /**
15
56
  * Factory: READ handler with index-on-miss behavior.
16
- * If a key is provided, checks cache first; indexes if missing.
57
+ * If a key is provided, checks cache first; indexes if missing — then runs the
58
+ * client's own query so `$expand` / `$select` are honoured on the keyed branch
59
+ * too (KNOWN_ISSUES #13: returning the bare row silently dropped them).
17
60
  * If no key, passes through to generic req.query.
18
61
  */
19
62
  function indexOnMissRead(entity, reqKeyField, validate, indexFn, options) {
@@ -27,11 +70,22 @@ function indexOnMissRead(entity, reqKeyField, validate, indexFn, options) {
27
70
  (0, errors_1.rejectInvalid)(req, dbKey, errMsg, reqKeyField);
28
71
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
29
72
  if (key !== undefined && key !== null) {
73
+ widenTemporalWindow(req); // before the first DB statement — see doc comment
30
74
  // CAP temporal aspect auto-filters expired records (validTo < now → not returned)
31
75
  const existing = await db.run(SELECT.one.from(entity).where({ [dbKey]: key }));
76
+ // Populate the row (+ compositions) on a miss, then let CAP run the client's
77
+ // query — one extra SELECT per keyed read, but $expand/$select (and the
78
+ // temporal filter of the projection) apply exactly as on the un-keyed path.
32
79
  if (!existing)
33
- return await indexFn(db, key);
34
- return existing;
80
+ await indexFn(db, key);
81
+ // The client's query is the ONLY authority on what comes back. Falling back
82
+ // to `existing` (or the indexer's return value) when it matches nothing
83
+ // answers a request the client never made — a second key that does not
84
+ // match, or an excluding $filter, would get a sibling row with a 200
85
+ // instead of a 404 (KNOWN_ISSUES #15). Non-temporal entities always see
86
+ // their fresh rows here; temporal ones rely on widenTemporalWindow above,
87
+ // and if that ever stops working the failure is a loud 404 covered by
88
+ // test/integration/keyed-read-expand.test.ts, not silently wrong data.
35
89
  }
36
90
  return db.run(req.query);
37
91
  });