@odatano/core 2.0.0-rc.3 → 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.
Files changed (36) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +151 -0
  2. package/@cds-models/CardanoAgentService/index.js +21 -0
  3. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  4. package/@cds-models/odatano/cardano/index.d.ts +50 -0
  5. package/@cds-models/odatano/cardano/index.js +3 -0
  6. package/README.md +31 -0
  7. package/db/schema.cds +72 -0
  8. package/package.json +173 -173
  9. package/src/index.d.ts +6 -0
  10. package/src/index.js +17 -1
  11. package/src/plugin.js +33 -30
  12. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
  13. package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
  14. package/srv/blockchain/wallet-worker/build-request.js +35 -6
  15. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +32 -1
  16. package/srv/blockchain/wallet-worker/confirmation-tracker.js +91 -29
  17. package/srv/blockchain/wallet-worker/job-store.d.ts +11 -0
  18. package/srv/blockchain/wallet-worker/job-store.js +42 -9
  19. package/srv/cardano-agent-service.cds +84 -0
  20. package/srv/cardano-agent-service.d.ts +2 -0
  21. package/srv/cardano-agent-service.js +16 -0
  22. package/srv/cardano-tx-service.cds +32 -26
  23. package/srv/cardano-tx-service.js +96 -38
  24. package/srv/server.d.ts +2 -1
  25. package/srv/server.js +12 -0
  26. package/srv/utils/agent-grants-config.d.ts +48 -0
  27. package/srv/utils/agent-grants-config.js +124 -0
  28. package/srv/utils/agent-grants.d.ts +211 -0
  29. package/srv/utils/agent-grants.js +541 -0
  30. package/srv/utils/agent-token-auth.d.ts +106 -0
  31. package/srv/utils/agent-token-auth.js +239 -0
  32. package/srv/utils/rate-limiter.d.ts +57 -0
  33. package/srv/utils/rate-limiter.js +126 -0
  34. package/srv/utils/tx-request-parsers.d.ts +13 -0
  35. package/srv/utils/tx-request-parsers.js +32 -0
  36. package/srv/utils/types.d.ts +15 -0
@@ -0,0 +1,541 @@
1
+ "use strict";
2
+ /**
3
+ * Agent grants: scoped, budgeted bearer capabilities for agents.
4
+ * Design: AGENT_GRANTS_DESIGN.md. Reference: NIGHTGATE srv/sessions/agent-grants.ts.
5
+ *
6
+ * Three exports carry the feature:
7
+ * - `resolveAgentToken` + `makeAgentUser`: used by the transport lane
8
+ * (agent-token-auth.ts) to turn an `x-agent-token` header into the principal
9
+ * `agent:<grantId>` with the role `agent-grant` BEFORE any service hook runs.
10
+ * Doing the authentication at the transport (not in a before-hook) matters:
11
+ * CAP runs before-handlers in parallel, so CAP's own @requires / @restrict
12
+ * evaluation must already see the final principal.
13
+ * - `attachAgentGrantEnforcement`: the before('*') hook on all six ODATANO
14
+ * services. Allow list (403), wallet pinning (403), daily budget (429),
15
+ * lastUsedAt. Ownership needs no special code: a token's jobs are created
16
+ * with createdBy = `agent:<grantId>`, so the existing `createdBy = $user`
17
+ * gates and the `$user.grantId` row restrictions do the narrowing.
18
+ * - `registerAgentGrantHandlers`: CreateAgentGrant / RevokeAgentGrant /
19
+ * GetGrantStatus for CardanoAgentService, on top of the programmatic
20
+ * `issueAgentGrant` / `revokeAgentGrantById` that @odatano/x402 uses to sell
21
+ * grants.
22
+ *
23
+ * The token is a capability, not an identity: it never carries the operator's
24
+ * roles, so every `@requires: 'Admin'` surface refuses it by construction.
25
+ */
26
+ var __importDefault = (this && this.__importDefault) || function (mod) {
27
+ return (mod && mod.__esModule) ? mod : { "default": mod };
28
+ };
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.AgentGrantInputError = exports.AGENT_JOB_KINDS = exports.AGENT_ALWAYS_ALLOWED_EVENTS = exports.AGENT_WALLET_ACTIONS = exports.AGENT_ALLOWLISTABLE_ACTIONS = exports.AGENT_SERVICE_NAMES = exports.GRANTS_ENTITY = exports.AGENT_PRINCIPAL_PREFIX = exports.AGENT_ROLE = exports.AGENT_TOKEN_PREFIX = exports.AGENT_TOKEN_HEADER = void 0;
31
+ exports.__resetGrantRateLimiterForTests = __resetGrantRateLimiterForTests;
32
+ exports.hashAgentToken = hashAgentToken;
33
+ exports.agentPrincipalId = agentPrincipalId;
34
+ exports.parseGrantList = parseGrantList;
35
+ exports.agentGrantOf = agentGrantOf;
36
+ exports.resolveAgentToken = resolveAgentToken;
37
+ exports.makeAgentUser = makeAgentUser;
38
+ exports.validateGrantInput = validateGrantInput;
39
+ exports.issueAgentGrant = issueAgentGrant;
40
+ exports.revokeAgentGrantById = revokeAgentGrantById;
41
+ exports.toGrantStatus = toGrantStatus;
42
+ exports.registerAgentGrantHandlers = registerAgentGrantHandlers;
43
+ exports.attachAgentGrantEnforcement = attachAgentGrantEnforcement;
44
+ exports.budgetRunnerFor = budgetRunnerFor;
45
+ exports.enforceAgentGrant = enforceAgentGrant;
46
+ exports.consumeDailyBudget = consumeDailyBudget;
47
+ exports.refundDailyBudget = refundDailyBudget;
48
+ const cds_1 = __importDefault(require("@sap/cds"));
49
+ const node_crypto_1 = __importDefault(require("node:crypto"));
50
+ const tx_utils_1 = require("./tx-utils");
51
+ const rate_limiter_1 = require("./rate-limiter");
52
+ const errors_1 = require("./errors");
53
+ const error_codes_1 = require("./error-codes");
54
+ const { SELECT, INSERT, UPDATE } = cds_1.default.ql;
55
+ const logger = cds_1.default.log('AgentGrants');
56
+ exports.AGENT_TOKEN_HEADER = 'x-agent-token';
57
+ exports.AGENT_TOKEN_PREFIX = 'odat_';
58
+ const TOKEN_BYTES = 32;
59
+ /** Role every token principal carries; the only role it ever has. */
60
+ exports.AGENT_ROLE = 'agent-grant';
61
+ /** `agent:<grantId>`: the principal id a token request runs under. */
62
+ exports.AGENT_PRINCIPAL_PREFIX = 'agent:';
63
+ exports.GRANTS_ENTITY = 'odatano.cardano.CardanoAgentGrants';
64
+ /** The services the hook attaches to and the transport lane opens. */
65
+ exports.AGENT_SERVICE_NAMES = [
66
+ 'CardanoODataService',
67
+ 'CardanoTransactionService',
68
+ 'CardanoSignService',
69
+ 'CardanoWorkerService',
70
+ 'CardanoIndexerService',
71
+ 'CardanoAgentService',
72
+ ];
73
+ /**
74
+ * Actions an operator MAY put on a grant's allow list. Each call costs one
75
+ * budget unit (a build is the service an agent buys). Everything not here and
76
+ * not in AGENT_ALWAYS_ALLOWED_EVENTS is a hard 403 for token requests: HSM
77
+ * signing, pause/resume, grant administration are never grantable.
78
+ */
79
+ exports.AGENT_ALLOWLISTABLE_ACTIONS = [
80
+ // CardanoTransactionService: unsigned CBOR
81
+ 'BuildSimpleAdaTransaction',
82
+ 'BuildTransactionWithMetadata',
83
+ 'BuildMultiAssetTransaction',
84
+ 'BuildMintTransaction',
85
+ 'BuildPlutusSpendTransaction',
86
+ 'SetCollateral',
87
+ // externally signed transactions
88
+ 'CreateSigningRequest',
89
+ 'VerifySignature',
90
+ 'SubmitTransaction',
91
+ 'SubmitSignedTransaction',
92
+ 'SubmitVerifiedTransaction',
93
+ 'CheckSubmissionStatus',
94
+ // server-side wallets (need walletId on the grant)
95
+ 'SubmitWalletJob',
96
+ 'CancelJob',
97
+ ];
98
+ /** Allow-listable actions that spend from a worker wallet: the grant must be pinned. */
99
+ exports.AGENT_WALLET_ACTIONS = new Set(['SubmitWalletJob', 'CancelJob']);
100
+ /**
101
+ * Events every valid token may use without an allow-list entry and without
102
+ * consuming budget: reads, compute-only actions, status polling. `READ` covers
103
+ * every entity set; row-level narrowing is done by the `$user.grantId`
104
+ * restrictions in the CDS models, not here.
105
+ */
106
+ exports.AGENT_ALWAYS_ALLOWED_EVENTS = new Set([
107
+ 'READ',
108
+ // CardanoODataService: chain reads through the backends
109
+ 'GetNetworkInformation', 'GetBlockByHash', 'GetEpochByNumber', 'GetPoolById', 'GetDrepById',
110
+ 'GetAssetInfo', 'GetAssetHistory', 'GetAccountByStakeAddress', 'GetTransactionByHash',
111
+ 'GetMetadataByTxHash', 'GetAddressByBech32', 'GetUTxOsByAddress', 'GetUTxOsByCredential',
112
+ 'GetAssetsByAddress', 'GetLatestTransactionsByAddress', 'GetLatestBlock', 'GetLatestEpoch',
113
+ 'GetLedgerProtocolParameters', 'ParseTransactionCbor',
114
+ // CardanoTransactionService: compute-only
115
+ 'GetBuildDetails', 'GetTransactionBuildsByAddress', 'DeriveScriptAddress', 'ExtractPaymentKeyHash',
116
+ // CardanoSignService: reads and stateless verification
117
+ 'GetSigningRequest', 'GetSigningRequestsByAddress', 'VerifyDataSignature', 'GetHsmStatus',
118
+ // CardanoWorkerService / CardanoIndexerService: status
119
+ 'GetJobStatus', 'GetWorkerStatus', 'getStatus',
120
+ // CardanoAgentService: the token's own grant
121
+ 'GetGrantStatus',
122
+ ]);
123
+ /** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
124
+ exports.AGENT_JOB_KINDS = ['simpleAda', 'metadata', 'multiAsset', 'mint', 'plutusSpend', 'submitSigned'];
125
+ /** Grant administration: 10 per operator per hour (NIGHTGATE's value). */
126
+ const grantAdminRateLimiter = new rate_limiter_1.RateLimiter({ windowMs: 60 * 60 * 1000, maxRequests: 10 });
127
+ /** Forget every rate-limit window (tests). */
128
+ function __resetGrantRateLimiterForTests() {
129
+ grantAdminRateLimiter.reset();
130
+ lastUsedTouched.clear();
131
+ }
132
+ function dbRunner() {
133
+ return cds_1.default.db;
134
+ }
135
+ // ---------------------------------------------------------------------------
136
+ // Small helpers
137
+ // ---------------------------------------------------------------------------
138
+ function hashAgentToken(token) {
139
+ return node_crypto_1.default.createHash('sha256').update(token).digest('hex');
140
+ }
141
+ function agentPrincipalId(grantId) {
142
+ return `${exports.AGENT_PRINCIPAL_PREFIX}${grantId}`;
143
+ }
144
+ /** The grant's JSON list column as an array; malformed or absent = empty. */
145
+ function parseGrantList(raw) {
146
+ if (!raw)
147
+ return [];
148
+ try {
149
+ const v = JSON.parse(raw);
150
+ return Array.isArray(v) ? v.filter((x) => typeof x === 'string') : [];
151
+ }
152
+ catch {
153
+ return [];
154
+ }
155
+ }
156
+ function utcDay(now = new Date()) {
157
+ return now.toISOString().slice(0, 10);
158
+ }
159
+ function isExpired(grant, now = new Date()) {
160
+ return !!grant.validUntil && new Date(grant.validUntil).getTime() < now.getTime();
161
+ }
162
+ /** The grant a request runs under, or null for an ordinary principal. */
163
+ function agentGrantOf(req) {
164
+ const r = req;
165
+ const fromHttp = r?.http?.req?.agentGrant ?? r?._?.req?.agentGrant;
166
+ if (fromHttp)
167
+ return fromHttp;
168
+ const ctx = cds_1.default.context;
169
+ return ctx?.http?.req?.agentGrant ?? null;
170
+ }
171
+ /**
172
+ * Authenticate a bearer token: prefix, hash lookup among ACTIVE grants (a
173
+ * revoked grant is an unknown token, non-leaking), expiry. Detached from any
174
+ * ambient transaction: the lane runs before the request transaction exists,
175
+ * and on SQLite the pool holds one connection.
176
+ */
177
+ async function resolveAgentToken(token, runner = dbRunner()) {
178
+ if (typeof token !== 'string' || !token.startsWith(exports.AGENT_TOKEN_PREFIX)) {
179
+ return { ok: false, status: 401, message: 'invalid agent token' };
180
+ }
181
+ const grant = (await (0, tx_utils_1.runWithoutAmbientTx)(() => runner.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ tokenHash: hashAgentToken(token), isActive: true }))));
182
+ if (!grant)
183
+ return { ok: false, status: 401, message: 'invalid agent token' };
184
+ if (isExpired(grant))
185
+ return { ok: false, status: 410, message: 'agent grant expired' };
186
+ return { ok: true, grant };
187
+ }
188
+ /**
189
+ * The principal a token request runs under. Deliberately NOT the operator and
190
+ * WITHOUT the operator's roles: `createdBy = $user` gates then scope to jobs
191
+ * this grant created, `$user.grantId` restrictions to its own grant row, and
192
+ * every `@requires: 'Admin'` refuses it.
193
+ */
194
+ function makeAgentUser(grant) {
195
+ return new cds_1.default.User({
196
+ id: agentPrincipalId(grant.ID),
197
+ roles: [exports.AGENT_ROLE],
198
+ attr: { grantId: grant.ID, operator: grant.userId, walletId: grant.walletId ?? '' },
199
+ });
200
+ }
201
+ /** A refused grant input; carries the 400 the action answers with. */
202
+ class AgentGrantInputError extends errors_1.BackendError {
203
+ constructor(message, target) {
204
+ super(`CreateAgentGrant: ${message}`, 400, error_codes_1.ERROR_CODES.INVALID_INPUT, undefined, undefined, target);
205
+ }
206
+ }
207
+ exports.AgentGrantInputError = AgentGrantInputError;
208
+ function validateGrantInput(input, now = new Date()) {
209
+ const actions = input.allowedActions;
210
+ if (!Array.isArray(actions) || actions.length === 0) {
211
+ throw new AgentGrantInputError('allowedActions must be a non-empty array', 'allowedActions');
212
+ }
213
+ const unknown = actions.filter((a) => !exports.AGENT_ALLOWLISTABLE_ACTIONS.includes(a));
214
+ if (unknown.length > 0) {
215
+ throw new AgentGrantInputError(`allowedActions contains non-grantable entries: ${unknown.join(', ')}. Grantable: ${exports.AGENT_ALLOWLISTABLE_ACTIONS.join(', ')}`, 'allowedActions');
216
+ }
217
+ const uniqueActions = [...new Set(actions)];
218
+ const walletId = typeof input.walletId === 'string' && input.walletId.trim() ? input.walletId.trim() : null;
219
+ const wantsWallet = uniqueActions.some((a) => exports.AGENT_WALLET_ACTIONS.has(a));
220
+ if (wantsWallet && !walletId) {
221
+ throw new AgentGrantInputError('walletId is required when SubmitWalletJob or CancelJob is allowed', 'walletId');
222
+ }
223
+ if (walletId && walletId.length > 50)
224
+ throw new AgentGrantInputError('walletId must be at most 50 characters', 'walletId');
225
+ let allowedJobKinds = [];
226
+ if (input.allowedJobKinds !== undefined && input.allowedJobKinds !== null) {
227
+ if (!Array.isArray(input.allowedJobKinds))
228
+ throw new AgentGrantInputError('allowedJobKinds must be an array', 'allowedJobKinds');
229
+ const badKinds = input.allowedJobKinds.filter((k) => !exports.AGENT_JOB_KINDS.includes(k));
230
+ if (badKinds.length > 0) {
231
+ throw new AgentGrantInputError(`allowedJobKinds contains unknown kinds: ${badKinds.join(', ')}. Known: ${exports.AGENT_JOB_KINDS.join(', ')}`, 'allowedJobKinds');
232
+ }
233
+ allowedJobKinds = [...new Set(input.allowedJobKinds)];
234
+ if (allowedJobKinds.length > 0 && !wantsWallet) {
235
+ throw new AgentGrantInputError('allowedJobKinds needs SubmitWalletJob in allowedActions', 'allowedJobKinds');
236
+ }
237
+ }
238
+ let maxJobsPerDay = null;
239
+ if (input.maxJobsPerDay !== undefined && input.maxJobsPerDay !== null) {
240
+ const n = Number(input.maxJobsPerDay);
241
+ if (!Number.isInteger(n) || n < 1)
242
+ throw new AgentGrantInputError('maxJobsPerDay must be a positive integer', 'maxJobsPerDay');
243
+ maxJobsPerDay = n;
244
+ }
245
+ let validUntil = null;
246
+ if (input.validUntil) {
247
+ const t = new Date(input.validUntil);
248
+ if (Number.isNaN(t.getTime()))
249
+ throw new AgentGrantInputError('validUntil must be a valid ISO-8601 timestamp', 'validUntil');
250
+ if (t.getTime() <= now.getTime())
251
+ throw new AgentGrantInputError('validUntil must be in the future', 'validUntil');
252
+ validUntil = t.toISOString();
253
+ }
254
+ const agentLabel = typeof input.agentLabel === 'string' && input.agentLabel.trim() ? input.agentLabel.trim() : null;
255
+ if (agentLabel && agentLabel.length > 100)
256
+ throw new AgentGrantInputError('agentLabel must be at most 100 characters', 'agentLabel');
257
+ return { allowedActions: uniqueActions, walletId, allowedJobKinds, maxJobsPerDay, validUntil, agentLabel };
258
+ }
259
+ /**
260
+ * Mint a grant for `operatorId`. Validation errors surface as
261
+ * AgentGrantInputError (400). The INSERT runs on `runner`: the action passes its
262
+ * request transaction, x402 passes whatever transaction its settlement runs in.
263
+ */
264
+ async function issueAgentGrant(input, operatorId, runner = dbRunner()) {
265
+ if (!operatorId)
266
+ throw new AgentGrantInputError('an operator id is required');
267
+ const n = validateGrantInput(input);
268
+ const token = exports.AGENT_TOKEN_PREFIX + node_crypto_1.default.randomBytes(TOKEN_BYTES).toString('hex');
269
+ const grant = {
270
+ ID: cds_1.default.utils.uuid(),
271
+ userId: operatorId,
272
+ agentLabel: n.agentLabel,
273
+ tokenHash: hashAgentToken(token),
274
+ allowedActions: JSON.stringify(n.allowedActions),
275
+ walletId: n.walletId,
276
+ allowedJobKinds: n.allowedJobKinds.length > 0 ? JSON.stringify(n.allowedJobKinds) : null,
277
+ maxJobsPerDay: n.maxJobsPerDay,
278
+ jobsUsedToday: 0,
279
+ budgetWindow: null,
280
+ validUntil: n.validUntil,
281
+ isActive: true,
282
+ revokedAt: null,
283
+ createdAt: new Date().toISOString(),
284
+ lastUsedAt: null,
285
+ };
286
+ await runner.run(INSERT.into(exports.GRANTS_ENTITY).entries(grant));
287
+ // Deliberately logs the id, the label and the shape, never the token.
288
+ logger.info(`agent grant ${grant.ID} issued by ${operatorId}` +
289
+ `${n.agentLabel ? ` for '${n.agentLabel}'` : ''} (actions: ${n.allowedActions.join(', ')}` +
290
+ `${n.walletId ? `, wallet ${n.walletId}` : ''}${n.maxJobsPerDay ? `, budget ${n.maxJobsPerDay}/day` : ''}` +
291
+ `${n.validUntil ? `, until ${n.validUntil}` : ''})`);
292
+ return {
293
+ grantId: grant.ID,
294
+ token,
295
+ allowedActions: n.allowedActions,
296
+ walletId: n.walletId,
297
+ allowedJobKinds: n.allowedJobKinds,
298
+ maxJobsPerDay: n.maxJobsPerDay,
299
+ validUntil: n.validUntil,
300
+ };
301
+ }
302
+ /** Deactivate a grant; false when it does not exist or is already revoked. */
303
+ async function revokeAgentGrantById(grantId, runner = dbRunner()) {
304
+ if (!grantId)
305
+ return false;
306
+ const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY)
307
+ .set({ isActive: false, revokedAt: new Date().toISOString() })
308
+ .where({ ID: grantId, isActive: true }));
309
+ const revoked = Number(affected) > 0;
310
+ if (revoked)
311
+ logger.info(`agent grant ${grantId} revoked`);
312
+ return revoked;
313
+ }
314
+ function toGrantStatus(grant) {
315
+ return {
316
+ grantId: grant.ID,
317
+ agentLabel: grant.agentLabel ?? null,
318
+ allowedActions: parseGrantList(grant.allowedActions),
319
+ walletId: grant.walletId ?? null,
320
+ allowedJobKinds: parseGrantList(grant.allowedJobKinds),
321
+ maxJobsPerDay: grant.maxJobsPerDay ?? null,
322
+ // A counter from an earlier UTC day is spent budget of a window that is over.
323
+ jobsUsedToday: grant.budgetWindow === utcDay() ? Number(grant.jobsUsedToday ?? 0) : 0,
324
+ budgetWindow: grant.budgetWindow ?? null,
325
+ validUntil: grant.validUntil ?? null,
326
+ isActive: grant.isActive !== false,
327
+ };
328
+ }
329
+ // ---------------------------------------------------------------------------
330
+ // CardanoAgentService handlers
331
+ // ---------------------------------------------------------------------------
332
+ /** Validation rejections are thrown BEFORE any transaction work (project convention). */
333
+ function registerAgentGrantHandlers(srv) {
334
+ srv.on('CreateAgentGrant', async (req) => {
335
+ // Token requests cannot mint grants: CreateAgentGrant is neither always-allowed
336
+ // nor allow-listable (the hook 403s), and @requires: 'Admin' refuses the
337
+ // role-less agent principal anyway. Belt and braces:
338
+ if (agentGrantOf(req))
339
+ return req.reject(403, 'an agent grant cannot issue grants');
340
+ const operatorId = req.user?.id;
341
+ if (!operatorId)
342
+ return req.reject(401, 'authentication required');
343
+ const rate = grantAdminRateLimiter.check((0, rate_limiter_1.principalRateKey)(req, 'grant-admin'));
344
+ if (!rate.allowed)
345
+ return req.reject(429, `Rate limited. Retry after ${Math.ceil(rate.retryAfterMs / 1000)}s`);
346
+ const data = (req.data ?? {});
347
+ let normalized;
348
+ try {
349
+ normalized = validateGrantInput(data);
350
+ }
351
+ catch (err) {
352
+ if (err instanceof errors_1.BackendError)
353
+ return req.reject(err.statusCode, err.message, err.target);
354
+ throw err;
355
+ }
356
+ const issued = await issueAgentGrant(normalized, operatorId, cds_1.default.tx(req));
357
+ return {
358
+ grantId: issued.grantId,
359
+ token: issued.token,
360
+ allowedActions: issued.allowedActions,
361
+ walletId: issued.walletId,
362
+ allowedJobKinds: issued.allowedJobKinds,
363
+ maxJobsPerDay: issued.maxJobsPerDay,
364
+ validUntil: issued.validUntil,
365
+ };
366
+ });
367
+ srv.on('RevokeAgentGrant', async (req) => {
368
+ if (agentGrantOf(req))
369
+ return req.reject(403, 'an agent grant cannot revoke grants');
370
+ const { grantId } = (req.data ?? {});
371
+ if (!grantId)
372
+ return req.reject(400, 'grantId is required', 'grantId');
373
+ const revoked = await revokeAgentGrantById(grantId, cds_1.default.tx(req));
374
+ if (!revoked)
375
+ return req.reject(404, 'Grant not found or already revoked', 'grantId');
376
+ return true;
377
+ });
378
+ // GetGrantStatus: the calling token's own grant, read fresh so the budget
379
+ // counter is current. An operator without a token lists AgentGrants instead.
380
+ srv.on('GetGrantStatus', async (req) => {
381
+ const grant = agentGrantOf(req);
382
+ if (!grant)
383
+ return req.reject(400, 'GetGrantStatus needs an x-agent-token; operators read the AgentGrants entity');
384
+ const fresh = (await cds_1.default.tx(req).run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: grant.ID })));
385
+ return toGrantStatus(fresh ?? grant);
386
+ });
387
+ }
388
+ // ---------------------------------------------------------------------------
389
+ // Enforcement (before('*') on the six services)
390
+ // ---------------------------------------------------------------------------
391
+ function attachAgentGrantEnforcement(srv, runner) {
392
+ srv.before('*', (req) => enforceAgentGrant(req, runner));
393
+ }
394
+ function budgetRunnerFor(req, injected, detached) {
395
+ if (injected)
396
+ return { runner: injected, detached: detached ?? true };
397
+ let tx = null;
398
+ try {
399
+ tx = cds_1.default.tx(req);
400
+ }
401
+ catch {
402
+ tx = null;
403
+ }
404
+ if (tx && (tx.dbc || tx.ready))
405
+ return { runner: tx, detached: false };
406
+ return { runner: dbRunner(), detached: true };
407
+ }
408
+ async function runStmt(br, statement) {
409
+ return br.detached ? (0, tx_utils_1.runWithoutAmbientTx)(() => br.runner.run(statement)) : br.runner.run(statement);
410
+ }
411
+ /**
412
+ * Exported for unit tests; see the module doc for the ladder. Ordinary
413
+ * principals pass through untouched: this hook is a no-op without a grant.
414
+ * `runner` / `detached` are test seams; production picks them per request.
415
+ */
416
+ async function enforceAgentGrant(req, runner, detached) {
417
+ const grant = agentGrantOf(req);
418
+ if (!grant)
419
+ return;
420
+ // Defence in depth: the lane already refused inactive and expired grants, but
421
+ // a grant can be revoked between two parts of a $batch, or expire mid-flight.
422
+ if (grant.isActive === false)
423
+ return req.reject(401, 'invalid agent token');
424
+ if (isExpired(grant))
425
+ return req.reject(410, 'agent grant expired');
426
+ const br = budgetRunnerFor(req, runner, detached);
427
+ const event = String(req.event ?? '');
428
+ if (exports.AGENT_ALWAYS_ALLOWED_EVENTS.has(event)) {
429
+ await touchLastUsed(grant, br);
430
+ return;
431
+ }
432
+ const allowed = parseGrantList(grant.allowedActions);
433
+ if (!allowed.includes(event)) {
434
+ return req.reject(403, `action '${event}' is not allowed for this agent grant`);
435
+ }
436
+ const data = req.data;
437
+ if (exports.AGENT_WALLET_ACTIONS.has(event)) {
438
+ if (!grant.walletId) {
439
+ return req.reject(403, 'this agent grant has no wallet binding; issue it with walletId to queue wallet jobs');
440
+ }
441
+ if (data && typeof data === 'object') {
442
+ if (event === 'SubmitWalletJob') {
443
+ if (data.walletId !== undefined && data.walletId !== null && data.walletId !== '' && data.walletId !== grant.walletId) {
444
+ return req.reject(403, 'walletId does not match this agent grant');
445
+ }
446
+ data.walletId = grant.walletId;
447
+ const kinds = parseGrantList(grant.allowedJobKinds);
448
+ if (kinds.length > 0 && !kinds.includes(String(data.kind ?? ''))) {
449
+ return req.reject(403, `job kind '${String(data.kind ?? '')}' is not allowed for this agent grant (allowed: ${kinds.join(', ')})`);
450
+ }
451
+ }
452
+ // CancelJob: the job lookup is owner-scoped by createdBy = agent:<grantId>
453
+ // in the worker service, so a foreign job is a 404 there already.
454
+ }
455
+ }
456
+ if (grant.maxJobsPerDay !== undefined && grant.maxJobsPerDay !== null) {
457
+ const charge = await consumeDailyBudget(br, grant);
458
+ if (!charge.consumed) {
459
+ return req.reject(429, `agent grant daily budget exhausted (${grant.maxJobsPerDay}/day)`);
460
+ }
461
+ // Detached charge: a request the handler refuses as invalid (400..428)
462
+ // admitted nothing, so give the unit back — in the window it was charged
463
+ // to, not in whatever day it is when the refund runs. 429 and every 5xx
464
+ // keep it (over-count, never under-count). A charge made inside the
465
+ // request's own transaction needs none of this: its rollback undoes it.
466
+ if (br.detached) {
467
+ const chargedWindow = charge.window;
468
+ req.on?.('failed', (err) => {
469
+ const e = err;
470
+ const status = Number(e?.status ?? e?.statusCode ?? e?.code);
471
+ if (Number.isInteger(status) && status >= 400 && status < 429) {
472
+ // Off the failing request's tick: its transaction is still rolling
473
+ // back when 'failed' fires, and a write on a second connection at
474
+ // that moment is the SQLite lock contention this module must never cause.
475
+ setImmediate(() => {
476
+ void refundDailyBudget(br, grant, chargedWindow).catch((refundErr) => logger.warn(`daily budget refund for grant ${grant.ID} failed: ${String(refundErr?.message ?? refundErr)}`));
477
+ });
478
+ }
479
+ });
480
+ }
481
+ }
482
+ await touchLastUsed(grant, br);
483
+ }
484
+ /**
485
+ * Consume one unit of the grant's daily budget. Two conditional UPDATEs so
486
+ * concurrent requests cannot overspend: a window reset (compare-and-swap on
487
+ * the OLD window value) and a bounded increment (`jobsUsedToday < max`). Runs
488
+ * on the BudgetRunner the hook chose (detached by default, see budgetRunnerFor).
489
+ */
490
+ async function consumeDailyBudget(br, grant) {
491
+ const runner = 'runner' in br ? br : { runner: br, detached: true };
492
+ const today = utcDay();
493
+ const max = grant.maxJobsPerDay;
494
+ if (grant.budgetWindow !== today) {
495
+ const reset = await runStmt(runner, UPDATE.entity(exports.GRANTS_ENTITY)
496
+ .set({ budgetWindow: today, jobsUsedToday: 1 })
497
+ .where({ ID: grant.ID, budgetWindow: grant.budgetWindow ?? null }));
498
+ if (Number(reset))
499
+ return { consumed: true, window: today };
500
+ // Lost the reset race: another request already moved the window.
501
+ }
502
+ const incremented = await runStmt(runner, UPDATE.entity(exports.GRANTS_ENTITY)
503
+ .set({ jobsUsedToday: { '+=': 1 } })
504
+ .where({ ID: grant.ID, budgetWindow: today, jobsUsedToday: { '<': max } }));
505
+ return { consumed: Number(incremented) > 0, window: today };
506
+ }
507
+ /**
508
+ * Undo one consumeDailyBudget in the window it was charged to (a refused
509
+ * request created nothing). A refund that lands after midnight must not touch
510
+ * the new day's counter: the unit was spent yesterday, yesterday keeps it.
511
+ */
512
+ async function refundDailyBudget(br, grant, window) {
513
+ const runner = 'runner' in br ? br : { runner: br, detached: true };
514
+ await runStmt(runner, UPDATE.entity(exports.GRANTS_ENTITY)
515
+ .set({ jobsUsedToday: { '-=': 1 } })
516
+ .where({ ID: grant.ID, budgetWindow: window, jobsUsedToday: { '>': 0 } }));
517
+ }
518
+ /**
519
+ * lastUsedAt, at most once a minute per grant. AWAITED, like the budget
520
+ * statements: every write this hook makes must be finished before the handler
521
+ * opens the request's own transaction. A fire-and-forget write on a second
522
+ * connection races the handler's reads and, on SQLite in WAL mode, turns the
523
+ * handler's first UPSERT into "database is locked" (SQLITE_BUSY_SNAPSHOT) —
524
+ * seen live on 2026-09-05. A failed touch is logged and never fails the request.
525
+ */
526
+ const lastUsedTouched = new Map();
527
+ const LAST_USED_INTERVAL_MS = 60_000;
528
+ async function touchLastUsed(grant, br) {
529
+ const now = Date.now();
530
+ const last = lastUsedTouched.get(grant.ID) ?? 0;
531
+ if (now - last < LAST_USED_INTERVAL_MS)
532
+ return;
533
+ lastUsedTouched.set(grant.ID, now);
534
+ try {
535
+ await runStmt(br, UPDATE.entity(exports.GRANTS_ENTITY).set({ lastUsedAt: new Date(now).toISOString() }).where({ ID: grant.ID }));
536
+ }
537
+ catch (err) {
538
+ logger.debug(`lastUsedAt update for grant ${grant.ID} failed: ${String(err?.message ?? err)}`);
539
+ }
540
+ }
541
+ //# sourceMappingURL=agent-grants.js.map
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Transport authentication with lanes: CAP's configured strategy PLUS an
3
+ * `x-agent-token` lane (AGENT_GRANTS_DESIGN.md §3).
4
+ *
5
+ * CAP's auth middleware 401s a request without transport credentials before any
6
+ * service hook runs, so an agent holding only an `odat_` token could never
7
+ * reach a service. This middleware is installed as `cds.requires.auth.impl` by
8
+ * src/plugin.ts when `odatano-core.agentGrants.enabled` is set, and:
9
+ *
10
+ * - runs every registered LANE first. The built-in lane admits a request that
11
+ * carries `x-agent-token` on one of the six ODATANO service paths (exact
12
+ * segment match, no lookalike prefixes): the token is authenticated HERE
13
+ * (unknown 401, expired 410, non-leaking) and the request continues as the
14
+ * principal `agent:<grantId>` with the role `agent-grant`. The resolved grant
15
+ * rides on the express request (`req.agentGrant`) for the enforcement hook.
16
+ * Other packages (@odatano/x402) add lanes with `registerTransportLane`
17
+ * instead of fighting for the single `auth.impl` slot.
18
+ * - otherwise DELEGATES to CAP's own strategy for the configured kind
19
+ * (mocked/basic → basic-auth, jwt/xsuaa → jwt-auth, ias, dummy): behaviour
20
+ * for every request without a token is exactly what it was before.
21
+ *
22
+ * Failed token attempts are throttled per client address (20 per 15 minutes):
23
+ * one static hash lookup must not become an offline-speed guessing oracle.
24
+ */
25
+ import cds from '@sap/cds';
26
+ import type { IncomingMessage, ServerResponse } from 'node:http';
27
+ import { type AgentGrantRow } from './agent-grants';
28
+ type ExpressReq = IncomingMessage & {
29
+ headers: Record<string, string | string[] | undefined>;
30
+ originalUrl?: string;
31
+ baseUrl?: string;
32
+ path?: string;
33
+ ip?: string;
34
+ user?: unknown;
35
+ agentGrant?: AgentGrantRow;
36
+ };
37
+ type ExpressRes = ServerResponse & {
38
+ status?: (code: number) => ExpressRes;
39
+ set?: (name: string, value: string) => ExpressRes;
40
+ json?: (body: unknown) => void;
41
+ };
42
+ type Next = (err?: unknown) => void;
43
+ export type AuthMiddleware = (req: ExpressReq, res: ExpressRes, next: Next) => unknown;
44
+ /** What a lane's `authenticate` may answer. */
45
+ export type LaneOutcome =
46
+ /** The lane authenticated the request; continue as this principal. */
47
+ {
48
+ user: cds.User;
49
+ }
50
+ /** The lane already sent a response (401/410/429); stop here. */
51
+ | {
52
+ handled: true;
53
+ }
54
+ /** Not this lane's request after all; try the next lane, then the delegate. */
55
+ | null;
56
+ export interface TransportLane {
57
+ /** Unique name; registering the same name twice replaces the lane. */
58
+ name: string;
59
+ /** Cheap check on headers/path; no I/O. */
60
+ match: (req: ExpressReq) => boolean;
61
+ /** Authenticate; may respond itself. */
62
+ authenticate: (req: ExpressReq, res: ExpressRes) => Promise<LaneOutcome>;
63
+ }
64
+ /** Add (or replace) a lane. Lanes run in registration order, the built-in agent-token lane first. */
65
+ export declare function registerTransportLane(lane: TransportLane): void;
66
+ /** Registered lane names, in order (tests, diagnostics). */
67
+ export declare function transportLanes(): string[];
68
+ /** Remove every lane except the built-in one (tests). */
69
+ export declare function __resetTransportLanesForTests(): void;
70
+ /** Test seam: pin the service paths instead of reading `cds.services`. `null` resets. */
71
+ export declare function __setAgentServicePathsForTests(paths: string[] | null): void;
72
+ /** Mount paths of the six services, read from `cds.services` once they are served. */
73
+ export declare function agentServicePaths(): string[];
74
+ /** Exact segment boundary: `/odata/v4/cardano-odata` and below, never `/odata/v4/cardano-odata-evil`. */
75
+ export declare function inAgentLane(path: string, servicePaths?: string[]): boolean;
76
+ export declare const agentTokenLane: TransportLane;
77
+ interface AuthOptions {
78
+ kind?: string;
79
+ impl?: string;
80
+ /** Set by activateAgentGrants: the strategy that keeps authenticating non-token requests. */
81
+ agentGrantsDelegate?: string;
82
+ /**
83
+ * Set by activateAgentGrants when the host had its own `auth.impl` before us:
84
+ * that module (path as configured, resolved like CAP does it) is the delegate,
85
+ * whatever `kind` says. The host's gate keeps running for every non-token
86
+ * request, on every path.
87
+ */
88
+ agentGrantsDelegateImpl?: string;
89
+ [key: string]: unknown;
90
+ }
91
+ /** Load CAP's own middleware for `kind`; exported so the wrapper can be unit-tested with a stub. */
92
+ /**
93
+ * Resolve a host-configured `auth.impl` the way CAP's auth factory does
94
+ * (@sap/cds/lib/srv/middlewares/auth/index.js): as a module relative to
95
+ * cds.root, else with a `./` prefix. Exported for the unit tests.
96
+ */
97
+ export declare function resolveCustomImpl(impl: string, root?: string): string;
98
+ export declare function loadDelegate(options: AuthOptions, kind: string): AuthMiddleware;
99
+ export declare function createAgentTokenAuth(options: AuthOptions, delegate?: AuthMiddleware): AuthMiddleware;
100
+ /**
101
+ * CAP requires this module and, seeing a function with fewer than three
102
+ * parameters, calls it with the merged auth options to obtain the middleware.
103
+ */
104
+ export default function agentTokenAuthFactory(options: AuthOptions): AuthMiddleware;
105
+ export {};
106
+ //# sourceMappingURL=agent-token-auth.d.ts.map