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

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.
@@ -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,84 @@
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 / RevokeAgentGrant: Admin-only administration. The token is
10
+ * returned ONCE from CreateAgentGrant and stored as SHA-256 only.
11
+ * - AgentGrants: Admin-only projection (no token hash). A request carrying a token
12
+ * runs as the principal `agent:<grantId>` with the role `agent-grant` and sees
13
+ * exactly its own row through the row-level restriction below.
14
+ * - GetGrantStatus: token self-service — what am I allowed to do, how much budget
15
+ * is left, when do I expire. What an MCP tool needs to describe itself honestly.
16
+ *
17
+ * A token request never inherits the operator's roles: `@requires: 'Admin'` on the
18
+ * two actions, on PauseWorker / ResumeWorker / pauseCrawler / resumeCrawler and on
19
+ * every other Admin surface therefore refuses it by construction. The allow list,
20
+ * wallet pinning and daily budget are enforced by a before('*') hook on all six
21
+ * ODATANO services (srv/utils/agent-grants.ts). The `x-agent-token` header only
22
+ * reaches the services when cds.requires.odatano-core.agentGrants.enabled is set
23
+ * (srv/utils/agent-token-auth.ts).
24
+ */
25
+ @requires: 'authenticated-user'
26
+ service CardanoAgentService @(impl: './cardano-agent-service') {
27
+
28
+ @readonly
29
+ @title : 'Agent Grants'
30
+ @description: 'Issued grants (token hash excluded). Admins see all, a token sees its own row.'
31
+ @restrict : [
32
+ { grant: 'READ', to: 'Admin' },
33
+ { grant: 'READ', to: 'agent-grant', where: 'ID = $user.grantId' }
34
+ ]
35
+ entity AgentGrants as projection on db.CardanoAgentGrants excluding { tokenHash };
36
+
37
+ @title : 'Grant Status'
38
+ type GrantStatus {
39
+ grantId : UUID;
40
+ agentLabel : String(100);
41
+ allowedActions : many String;
42
+ walletId : String(50);
43
+ allowedJobKinds : many String;
44
+ maxJobsPerDay : Integer;
45
+ jobsUsedToday : Integer;
46
+ budgetWindow : String(10);
47
+ validUntil : Timestamp;
48
+ isActive : Boolean;
49
+ }
50
+
51
+ @title : 'Issued Grant'
52
+ type IssuedGrant {
53
+ grantId : UUID;
54
+ token : String; // shown once, never stored
55
+ allowedActions : many String;
56
+ walletId : String(50);
57
+ allowedJobKinds : many String;
58
+ maxJobsPerDay : Integer;
59
+ validUntil : Timestamp;
60
+ }
61
+
62
+ @title : 'Get Grant Status'
63
+ @description: 'The calling token''s own grant: allow list, wallet, remaining daily budget, expiry. 400 without a token — an operator lists AgentGrants instead.'
64
+ function GetGrantStatus() returns GrantStatus;
65
+
66
+ @title : 'Create Agent Grant'
67
+ @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.'
68
+ @requires : 'Admin'
69
+ action CreateAgentGrant(
70
+ @title: 'Allowed Actions' allowedActions : many String,
71
+ @title: 'Wallet Id' walletId : String(50),
72
+ @title: 'Allowed Job Kinds' allowedJobKinds : many String,
73
+ @title: 'Max Jobs Per Day' maxJobsPerDay : Integer,
74
+ @title: 'Valid Until' validUntil : Timestamp,
75
+ @title: 'Agent Label' agentLabel : String(100)
76
+ ) returns IssuedGrant;
77
+
78
+ @title : 'Revoke Agent Grant'
79
+ @description: 'Deactivate a grant. Admin only. Its token becomes an unknown token immediately.'
80
+ @requires : 'Admin'
81
+ action RevokeAgentGrant(
82
+ @title: 'Grant Id' grantId : UUID
83
+ ) returns Boolean;
84
+ }
@@ -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
package/srv/server.d.ts CHANGED
@@ -13,6 +13,8 @@ interface AppContext {
13
13
  cardanoIndexer: CardanoIndexer;
14
14
  cardanoTxBuilder: CardanoTransactionBuilder;
15
15
  }
16
+ /** Agent-grant feature switch (AGENT_GRANTS_DESIGN.md); lives in its own module so src/plugin.ts can read it at load. */
17
+ export { loadAgentGrantsConfig, activateAgentGrants } from './utils/agent-grants-config';
16
18
  /**
17
19
  * Get the application context (must be called after bootstrap)
18
20
  * @throws {ProviderUnavailableError} 503 when uninitialized — request handlers using
@@ -125,5 +127,4 @@ export declare function startWalletWorkerIfConfigured(): Promise<void>;
125
127
  * Non-fatal, mirrors startCrawlerIfConfigured/startWalletWorkerIfConfigured.
126
128
  */
127
129
  export declare function redriveInterruptedSubmissionsIfConfigured(): Promise<void>;
128
- export {};
129
130
  //# sourceMappingURL=server.d.ts.map
package/srv/server.js CHANGED
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.activateAgentGrants = exports.loadAgentGrantsConfig = void 0;
6
7
  exports.getAppContext = getAppContext;
7
8
  exports.getCardanoIndexer = getCardanoIndexer;
8
9
  exports.getCardanoClient = getCardanoClient;
@@ -28,6 +29,7 @@ const errors_1 = require("./utils/errors");
28
29
  const network_context_1 = require("./utils/network-context");
29
30
  const crawler_1 = require("./blockchain/crawler");
30
31
  const wallet_worker_1 = require("./blockchain/wallet-worker");
32
+ const agent_grants_config_1 = require("./utils/agent-grants-config");
31
33
  const process_1 = require("process");
32
34
  const logger = cds_1.default.log('ODATANO');
33
35
  const VALID_NETWORKS = ['mainnet', 'preview', 'preprod'];
@@ -91,6 +93,16 @@ async function initializeAppContext(config, protocolParams, hsmConfig) {
91
93
  cardanoTxBuilder,
92
94
  };
93
95
  }
96
+ /** Agent-grant feature switch (AGENT_GRANTS_DESIGN.md); lives in its own module so src/plugin.ts can read it at load. */
97
+ var agent_grants_config_2 = require("./utils/agent-grants-config");
98
+ Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get: function () { return agent_grants_config_2.loadAgentGrantsConfig; } });
99
+ Object.defineProperty(exports, "activateAgentGrants", { enumerable: true, get: function () { return agent_grants_config_2.activateAgentGrants; } });
100
+ // Standalone mode (`cds serve` / `cds watch` in this project): CAP loads
101
+ // cds-plugin.js only from dependencies, so src/plugin.ts never runs here and
102
+ // agent grants would stay off regardless of AGENT_GRANTS_ENABLED. bin/serve.js
103
+ // imports this file before cds.server() instantiates the middlewares, so the
104
+ // auth impl can still be swapped. Idempotent: a no-op after the plugin's call.
105
+ (0, agent_grants_config_1.activateAgentGrants)();
94
106
  /**
95
107
  * Get the application context (must be called after bootstrap)
96
108
  * @throws {ProviderUnavailableError} 503 when uninitialized — request handlers using
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Agent-grant feature switch. Read from `cds.requires.odatano-core.agentGrants`
3
+ * first, then from the environment; kept in its own tiny module because
4
+ * src/plugin.ts reads it at plugin load, before any blockchain module may be
5
+ * required.
6
+ *
7
+ * cds: "odatano-core": { "agentGrants": { "enabled": true, "delegate": "mocked" } }
8
+ * env: AGENT_GRANTS_ENABLED=true AGENT_GRANTS_DELEGATE=mocked|basic|jwt|xsuaa|ias|dummy
9
+ *
10
+ * `delegate` names the CAP auth strategy that keeps authenticating every
11
+ * request WITHOUT an `x-agent-token` header (the transport lane only adds the
12
+ * token path next to it). Default: the configured `cds.requires.auth.kind`.
13
+ */
14
+ export interface AgentGrantsConfig {
15
+ enabled: boolean;
16
+ /** CAP auth kind the transport middleware delegates to for non-token requests. */
17
+ delegate: string;
18
+ }
19
+ export declare const AGENT_GRANTS_DELEGATES: readonly string[];
20
+ /** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
21
+ export declare function configuredAuth(): Record<string, unknown>;
22
+ /**
23
+ * A custom `cds.requires.auth.impl` the host configured before us (anything
24
+ * that is not this package's middleware). It keeps authenticating every
25
+ * non-token request: the lane wraps it instead of replacing it.
26
+ */
27
+ export declare function customAuthImpl(auth?: Record<string, unknown>): string | null;
28
+ export declare function loadAgentGrantsConfig(env?: Record<string, string | undefined>): AgentGrantsConfig;
29
+ /**
30
+ * Switch agent grants on for this process when configured. Called from BOTH
31
+ * entry points, because CAP loads `cds-plugin.js` only from a project's
32
+ * dependencies, never from the project itself:
33
+ * - src/plugin.ts at plugin load (consumer app), and
34
+ * - srv/server.ts at module load (standalone `cds serve` / `cds watch`, where
35
+ * bin/serve.js imports the local server.js BEFORE cds.server() builds its
36
+ * middlewares — the last moment `cds.requires.auth.impl` can still change).
37
+ *
38
+ * When enabled:
39
+ * - the transport auth becomes srv/utils/agent-token-auth, which admits the
40
+ * `x-agent-token` header on the six service paths and delegates every other
41
+ * request to the strategy that was configured before (kept as the delegate);
42
+ * - each of the six services gets the enforcement hook once it is served.
43
+ *
44
+ * Never throws: a misconfiguration is logged and the feature stays off, so a
45
+ * host app never fails to start because of it. Returns whether grants are on.
46
+ */
47
+ export declare function activateAgentGrants(): boolean;
48
+ //# sourceMappingURL=agent-grants-config.d.ts.map
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.AGENT_GRANTS_DELEGATES = void 0;
7
+ exports.configuredAuth = configuredAuth;
8
+ exports.customAuthImpl = customAuthImpl;
9
+ exports.loadAgentGrantsConfig = loadAgentGrantsConfig;
10
+ exports.activateAgentGrants = activateAgentGrants;
11
+ const cds_1 = __importDefault(require("@sap/cds"));
12
+ const path_1 = __importDefault(require("path"));
13
+ exports.AGENT_GRANTS_DELEGATES = ['mocked', 'basic', 'jwt', 'xsuaa', 'ias', 'dummy'];
14
+ function envRecord() {
15
+ const requires = (cds_1.default.env?.requires ?? {});
16
+ const core = (requires['odatano-core'] ?? {});
17
+ return (core.agentGrants ?? {});
18
+ }
19
+ /** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
20
+ function configuredAuth() {
21
+ const auth = cds_1.default.env?.requires?.auth;
22
+ if (typeof auth === 'string')
23
+ return { kind: auth };
24
+ return (auth ?? {});
25
+ }
26
+ /** Our own middleware module, recognisable in `auth.impl` so activation stays idempotent. */
27
+ const OUR_IMPL = 'agent-token-auth';
28
+ /**
29
+ * A custom `cds.requires.auth.impl` the host configured before us (anything
30
+ * that is not this package's middleware). It keeps authenticating every
31
+ * non-token request: the lane wraps it instead of replacing it.
32
+ */
33
+ function customAuthImpl(auth = configuredAuth()) {
34
+ const impl = typeof auth.impl === 'string' ? auth.impl.trim() : '';
35
+ if (!impl || impl.includes(OUR_IMPL))
36
+ return null;
37
+ return impl;
38
+ }
39
+ function loadAgentGrantsConfig(env = process.env) {
40
+ const cfg = envRecord();
41
+ const enabledRaw = cfg.enabled !== undefined ? cfg.enabled : env.AGENT_GRANTS_ENABLED;
42
+ const enabled = enabledRaw === true || String(enabledRaw ?? '').toLowerCase() === 'true';
43
+ const auth = configuredAuth();
44
+ const authKind = String(auth.kind ?? 'mocked');
45
+ // A host with its own auth.impl keeps it as the delegate ("custom") unless
46
+ // an explicit delegate says otherwise.
47
+ const fallback = customAuthImpl(auth) ? 'custom' : authKind;
48
+ const delegateRaw = String(cfg.delegate ?? env.AGENT_GRANTS_DELEGATE ?? fallback);
49
+ // `xsuaa-auth` / `basic-auth` spellings are what CAP itself accepts as kinds.
50
+ const delegate = delegateRaw.replace(/-auth$/, '');
51
+ if (enabled && delegate !== 'custom' && !exports.AGENT_GRANTS_DELEGATES.includes(delegate)) {
52
+ throw new Error(`Invalid agentGrants.delegate "${delegateRaw}". Must be one of: ${exports.AGENT_GRANTS_DELEGATES.join(', ')}, custom`);
53
+ }
54
+ if (enabled && delegate === 'custom' && !customAuthImpl(auth)) {
55
+ throw new Error('agentGrants.delegate "custom" needs a custom cds.requires.auth.impl to delegate to');
56
+ }
57
+ return { enabled, delegate };
58
+ }
59
+ /**
60
+ * Marker on the shared `cds` facade: the activation below must run exactly once
61
+ * per process even though this module can be loaded twice (natively by CAP /
62
+ * src/plugin.ts and again through a test runner's transform). A module-level
63
+ * flag would not survive that; the `cds` singleton does.
64
+ */
65
+ const ACTIVATED = Symbol.for('odatano.agentGrants.activated');
66
+ /**
67
+ * Switch agent grants on for this process when configured. Called from BOTH
68
+ * entry points, because CAP loads `cds-plugin.js` only from a project's
69
+ * dependencies, never from the project itself:
70
+ * - src/plugin.ts at plugin load (consumer app), and
71
+ * - srv/server.ts at module load (standalone `cds serve` / `cds watch`, where
72
+ * bin/serve.js imports the local server.js BEFORE cds.server() builds its
73
+ * middlewares — the last moment `cds.requires.auth.impl` can still change).
74
+ *
75
+ * When enabled:
76
+ * - the transport auth becomes srv/utils/agent-token-auth, which admits the
77
+ * `x-agent-token` header on the six service paths and delegates every other
78
+ * request to the strategy that was configured before (kept as the delegate);
79
+ * - each of the six services gets the enforcement hook once it is served.
80
+ *
81
+ * Never throws: a misconfiguration is logged and the feature stays off, so a
82
+ * host app never fails to start because of it. Returns whether grants are on.
83
+ */
84
+ function activateAgentGrants() {
85
+ const facade = cds_1.default;
86
+ if (facade[ACTIVATED] !== undefined)
87
+ return facade[ACTIVATED] === true;
88
+ const logger = cds_1.default.log('ODATANO');
89
+ try {
90
+ const agentGrants = loadAgentGrantsConfig();
91
+ if (!agentGrants.enabled) {
92
+ facade[ACTIVATED] = false;
93
+ return false;
94
+ }
95
+ const auth = configuredAuth();
96
+ const current = typeof auth.impl === 'string' ? auth.impl : '';
97
+ if (!current.includes(OUR_IMPL)) {
98
+ // A host's own auth.impl is preserved as the delegate: the lane only adds
99
+ // the token path in front of it, it never replaces the host's gate.
100
+ const original = customAuthImpl(auth);
101
+ cds_1.default.env.requires.auth = {
102
+ ...auth,
103
+ kind: auth.kind ?? agentGrants.delegate,
104
+ impl: path_1.default.join(__dirname, OUR_IMPL),
105
+ agentGrantsDelegate: agentGrants.delegate,
106
+ ...(original ? { agentGrantsDelegateImpl: original } : {})
107
+ };
108
+ }
109
+ cds_1.default.on('serving', (srv) => {
110
+ const { AGENT_SERVICE_NAMES, attachAgentGrantEnforcement } = require('./agent-grants');
111
+ if (AGENT_SERVICE_NAMES.includes(srv.name))
112
+ attachAgentGrantEnforcement(srv);
113
+ });
114
+ facade[ACTIVATED] = true;
115
+ logger.info(`Agent grants enabled (transport delegate: ${agentGrants.delegate})`);
116
+ return true;
117
+ }
118
+ catch (err) {
119
+ facade[ACTIVATED] = false;
120
+ logger.error('Agent grants not enabled:', err instanceof Error ? err.message : err);
121
+ return false;
122
+ }
123
+ }
124
+ //# sourceMappingURL=agent-grants-config.js.map