@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
@@ -0,0 +1,821 @@
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`: the grant lifecycle for CardanoAgentService
19
+ * (CreateAgentGrant / UpdateAgentGrant / RotateAgentGrantToken /
20
+ * RevokeAgentGrant, GetGrantStatus / GetGrantUsage), on top of the
21
+ * programmatic `issueAgentGrant` / `updateAgentGrant` /
22
+ * `rotateAgentGrantToken` / `revokeAgentGrantById` that @odatano/x402 uses
23
+ * to sell grants. Names are this repo's PascalCase; semantics follow
24
+ * NIGHTGATE's so a gateway (ODATANO ACCESS) drives both with one code path.
25
+ *
26
+ * The token is a capability, not an identity: it never carries the operator's
27
+ * roles, so every `@requires: 'Admin'` surface refuses it by construction.
28
+ */
29
+ var __importDefault = (this && this.__importDefault) || function (mod) {
30
+ return (mod && mod.__esModule) ? mod : { "default": mod };
31
+ };
32
+ Object.defineProperty(exports, "__esModule", { value: true });
33
+ exports.USAGE_WINDOW_DEFAULT_MS = exports.USAGE_WINDOW_MAX_MS = exports.GRANT_IMMUTABLE_FIELDS = exports.AgentGrantInputError = exports.AGENT_JOB_KINDS = exports.AGENT_ALWAYS_ALLOWED_EVENTS = exports.AGENT_WALLET_ACTIONS = exports.AGENT_ALLOWLISTABLE_ACTIONS = exports.AGENT_SERVICE_NAMES = exports.GRANT_USAGE_ENTITY = exports.GRANTS_ENTITY = exports.AGENT_PRINCIPAL_PREFIX = exports.AGENT_ROLE = exports.AGENT_TOKEN_PREFIX = exports.AGENT_TOKEN_HEADER = void 0;
34
+ exports.__resetGrantRateLimiterForTests = __resetGrantRateLimiterForTests;
35
+ exports.hashAgentToken = hashAgentToken;
36
+ exports.agentPrincipalId = agentPrincipalId;
37
+ exports.parseGrantList = parseGrantList;
38
+ exports.agentGrantOf = agentGrantOf;
39
+ exports.resolveAgentToken = resolveAgentToken;
40
+ exports.makeAgentUser = makeAgentUser;
41
+ exports.validateGrantInput = validateGrantInput;
42
+ exports.issueAgentGrant = issueAgentGrant;
43
+ exports.revokeAgentGrantById = revokeAgentGrantById;
44
+ exports.rotateAgentGrantToken = rotateAgentGrantToken;
45
+ exports.updateAgentGrant = updateAgentGrant;
46
+ exports.resolveUsageWindow = resolveUsageWindow;
47
+ exports.getGrantUsage = getGrantUsage;
48
+ exports.toGrantStatus = toGrantStatus;
49
+ exports.registerAgentGrantHandlers = registerAgentGrantHandlers;
50
+ exports.attachAgentGrantEnforcement = attachAgentGrantEnforcement;
51
+ exports.budgetRunnerFor = budgetRunnerFor;
52
+ exports.enforceAgentGrant = enforceAgentGrant;
53
+ exports.consumeDailyBudget = consumeDailyBudget;
54
+ exports.refundDailyBudget = refundDailyBudget;
55
+ exports.recordGrantUsage = recordGrantUsage;
56
+ exports.refundGrantUsage = refundGrantUsage;
57
+ const cds_1 = __importDefault(require("@sap/cds"));
58
+ const node_crypto_1 = __importDefault(require("node:crypto"));
59
+ const tx_utils_1 = require("./tx-utils");
60
+ const rate_limiter_1 = require("./rate-limiter");
61
+ const errors_1 = require("./errors");
62
+ const error_codes_1 = require("./error-codes");
63
+ const agent_grants_config_1 = require("./agent-grants-config");
64
+ const { SELECT, INSERT, UPDATE } = cds_1.default.ql;
65
+ const logger = cds_1.default.log('AgentGrants');
66
+ exports.AGENT_TOKEN_HEADER = 'x-agent-token';
67
+ exports.AGENT_TOKEN_PREFIX = 'odat_';
68
+ const TOKEN_BYTES = 32;
69
+ /** Role every token principal carries; the only role it ever has. */
70
+ exports.AGENT_ROLE = 'agent-grant';
71
+ /** `agent:<grantId>`: the principal id a token request runs under. */
72
+ exports.AGENT_PRINCIPAL_PREFIX = 'agent:';
73
+ exports.GRANTS_ENTITY = 'odatano.cardano.CardanoAgentGrants';
74
+ /** Daily per-action counters of admitted calls (feeds GetGrantUsage); never exposed as an entity. */
75
+ exports.GRANT_USAGE_ENTITY = 'odatano.cardano.CardanoAgentGrantUsage';
76
+ /** The services the hook attaches to and the transport lane opens. */
77
+ exports.AGENT_SERVICE_NAMES = [
78
+ 'CardanoODataService',
79
+ 'CardanoTransactionService',
80
+ 'CardanoSignService',
81
+ 'CardanoWorkerService',
82
+ 'CardanoIndexerService',
83
+ 'CardanoAgentService',
84
+ ];
85
+ /**
86
+ * Actions an operator MAY put on a grant's allow list. Each call costs one
87
+ * budget unit (a build is the service an agent buys). Everything not here and
88
+ * not in AGENT_ALWAYS_ALLOWED_EVENTS is a hard 403 for token requests: HSM
89
+ * signing, pause/resume, grant administration are never grantable.
90
+ */
91
+ exports.AGENT_ALLOWLISTABLE_ACTIONS = [
92
+ // CardanoTransactionService: unsigned CBOR
93
+ 'BuildSimpleAdaTransaction',
94
+ 'BuildTransactionWithMetadata',
95
+ 'BuildMultiAssetTransaction',
96
+ 'BuildMintTransaction',
97
+ 'BuildPlutusSpendTransaction',
98
+ 'SetCollateral',
99
+ // externally signed transactions
100
+ 'CreateSigningRequest',
101
+ 'VerifySignature',
102
+ 'SubmitTransaction',
103
+ 'SubmitSignedTransaction',
104
+ 'SubmitVerifiedTransaction',
105
+ 'CheckSubmissionStatus',
106
+ // server-side wallets (need walletId on the grant)
107
+ 'SubmitWalletJob',
108
+ 'CancelJob',
109
+ ];
110
+ /** Allow-listable actions that spend from a worker wallet: the grant must be pinned. */
111
+ exports.AGENT_WALLET_ACTIONS = new Set(['SubmitWalletJob', 'CancelJob']);
112
+ /**
113
+ * Events every valid token may use without an allow-list entry and without
114
+ * consuming budget: reads, compute-only actions, status polling. `READ` covers
115
+ * every entity set; row-level narrowing is done by the `$user.grantId`
116
+ * restrictions in the CDS models, not here.
117
+ */
118
+ exports.AGENT_ALWAYS_ALLOWED_EVENTS = new Set([
119
+ 'READ',
120
+ // CardanoODataService: chain reads through the backends
121
+ 'GetNetworkInformation', 'GetBlockByHash', 'GetEpochByNumber', 'GetPoolById', 'GetDrepById',
122
+ 'GetAssetInfo', 'GetAssetHistory', 'GetAccountByStakeAddress', 'GetTransactionByHash',
123
+ 'GetMetadataByTxHash', 'GetAddressByBech32', 'GetUTxOsByAddress', 'GetUTxOsByCredential',
124
+ 'GetAssetsByAddress', 'GetLatestTransactionsByAddress', 'GetLatestBlock', 'GetLatestEpoch',
125
+ 'GetLedgerProtocolParameters', 'ParseTransactionCbor',
126
+ // CardanoTransactionService: compute-only
127
+ 'GetBuildDetails', 'GetTransactionBuildsByAddress', 'DeriveScriptAddress', 'ExtractPaymentKeyHash',
128
+ // CardanoSignService: reads and stateless verification
129
+ 'GetSigningRequest', 'GetSigningRequestsByAddress', 'VerifyDataSignature', 'GetHsmStatus',
130
+ // CardanoWorkerService / CardanoIndexerService: status and liveness
131
+ 'GetJobStatus', 'GetWorkerStatus', 'getStatus', 'getLiveness',
132
+ // CardanoAgentService: the token's own grant (GetGrantUsage is narrowed to it in enforceAgentGrant)
133
+ 'GetGrantStatus', 'GetGrantUsage',
134
+ ]);
135
+ /** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
136
+ exports.AGENT_JOB_KINDS = ['simpleAda', 'metadata', 'multiAsset', 'mint', 'plutusSpend', 'submitSigned'];
137
+ /**
138
+ * Grant administration (Create / Update / Rotate / Revoke): N per principal per
139
+ * hour, N from `agentGrants.adminRateLimit` / `AGENT_GRANT_ADMIN_RATE_LIMIT`
140
+ * (default 10, NIGHTGATE's `NIGHTGATE_GRANT_ADMIN_RATE_LIMIT`). Built on first
141
+ * use so the knob is read once the config is loaded, and re-read after a reset.
142
+ */
143
+ let grantAdminRateLimiter = null;
144
+ function grantAdminLimiter() {
145
+ grantAdminRateLimiter ??= new rate_limiter_1.RateLimiter({ windowMs: 60 * 60 * 1000, maxRequests: (0, agent_grants_config_1.loadGrantAdminRateLimit)() });
146
+ return grantAdminRateLimiter;
147
+ }
148
+ /** Forget every rate-limit window and re-read the limit from the config (tests). */
149
+ function __resetGrantRateLimiterForTests() {
150
+ grantAdminRateLimiter = null;
151
+ lastUsedTouched.clear();
152
+ }
153
+ function dbRunner() {
154
+ return cds_1.default.db;
155
+ }
156
+ // ---------------------------------------------------------------------------
157
+ // Small helpers
158
+ // ---------------------------------------------------------------------------
159
+ function hashAgentToken(token) {
160
+ return node_crypto_1.default.createHash('sha256').update(token).digest('hex');
161
+ }
162
+ function agentPrincipalId(grantId) {
163
+ return `${exports.AGENT_PRINCIPAL_PREFIX}${grantId}`;
164
+ }
165
+ /** The grant's JSON list column as an array; malformed or absent = empty. */
166
+ function parseGrantList(raw) {
167
+ if (!raw)
168
+ return [];
169
+ try {
170
+ const v = JSON.parse(raw);
171
+ return Array.isArray(v) ? v.filter((x) => typeof x === 'string') : [];
172
+ }
173
+ catch {
174
+ return [];
175
+ }
176
+ }
177
+ function utcDay(now = new Date()) {
178
+ return now.toISOString().slice(0, 10);
179
+ }
180
+ function isExpired(grant, now = new Date()) {
181
+ return !!grant.validUntil && new Date(grant.validUntil).getTime() < now.getTime();
182
+ }
183
+ /** The grant a request runs under, or null for an ordinary principal. */
184
+ function agentGrantOf(req) {
185
+ const r = req;
186
+ const fromHttp = r?.http?.req?.agentGrant ?? r?._?.req?.agentGrant;
187
+ if (fromHttp)
188
+ return fromHttp;
189
+ const ctx = cds_1.default.context;
190
+ return ctx?.http?.req?.agentGrant ?? null;
191
+ }
192
+ /**
193
+ * Authenticate a bearer token: prefix, hash lookup among ACTIVE grants (a
194
+ * revoked grant is an unknown token, non-leaking), expiry. Detached from any
195
+ * ambient transaction: the lane runs before the request transaction exists,
196
+ * and on SQLite the pool holds one connection.
197
+ */
198
+ async function resolveAgentToken(token, runner = dbRunner()) {
199
+ if (typeof token !== 'string' || !token.startsWith(exports.AGENT_TOKEN_PREFIX)) {
200
+ return { ok: false, status: 401, message: 'invalid agent token' };
201
+ }
202
+ const grant = (await (0, tx_utils_1.runWithoutAmbientTx)(() => runner.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ tokenHash: hashAgentToken(token), isActive: true }))));
203
+ if (!grant)
204
+ return { ok: false, status: 401, message: 'invalid agent token' };
205
+ if (isExpired(grant))
206
+ return { ok: false, status: 410, message: 'agent grant expired' };
207
+ return { ok: true, grant };
208
+ }
209
+ /**
210
+ * The principal a token request runs under. Deliberately NOT the operator and
211
+ * WITHOUT the operator's roles: `createdBy = $user` gates then scope to jobs
212
+ * this grant created, `$user.grantId` restrictions to its own grant row, and
213
+ * every `@requires: 'Admin'` refuses it.
214
+ */
215
+ function makeAgentUser(grant) {
216
+ return new cds_1.default.User({
217
+ id: agentPrincipalId(grant.ID),
218
+ roles: [exports.AGENT_ROLE],
219
+ attr: { grantId: grant.ID, operator: grant.userId, walletId: grant.walletId ?? '' },
220
+ });
221
+ }
222
+ /** A refused grant input; carries the 400 the action answers with. */
223
+ class AgentGrantInputError extends errors_1.BackendError {
224
+ constructor(message, target, context = 'CreateAgentGrant') {
225
+ super(`${context}: ${message}`, 400, error_codes_1.ERROR_CODES.INVALID_INPUT, undefined, undefined, target);
226
+ }
227
+ }
228
+ exports.AgentGrantInputError = AgentGrantInputError;
229
+ function validateGrantInput(input, now = new Date(), context = 'CreateAgentGrant') {
230
+ const fail = (message, target) => new AgentGrantInputError(message, target, context);
231
+ const actions = input.allowedActions;
232
+ if (!Array.isArray(actions) || actions.length === 0) {
233
+ throw fail('allowedActions must be a non-empty array', 'allowedActions');
234
+ }
235
+ const unknown = actions.filter((a) => !exports.AGENT_ALLOWLISTABLE_ACTIONS.includes(a));
236
+ if (unknown.length > 0) {
237
+ throw fail(`allowedActions contains non-grantable entries: ${unknown.join(', ')}. Grantable: ${exports.AGENT_ALLOWLISTABLE_ACTIONS.join(', ')}`, 'allowedActions');
238
+ }
239
+ const uniqueActions = [...new Set(actions)];
240
+ const walletId = typeof input.walletId === 'string' && input.walletId.trim() ? input.walletId.trim() : null;
241
+ const wantsWallet = uniqueActions.some((a) => exports.AGENT_WALLET_ACTIONS.has(a));
242
+ if (wantsWallet && !walletId) {
243
+ throw fail('walletId is required when SubmitWalletJob or CancelJob is allowed', 'walletId');
244
+ }
245
+ if (walletId && walletId.length > 50)
246
+ throw fail('walletId must be at most 50 characters', 'walletId');
247
+ let allowedJobKinds = [];
248
+ if (input.allowedJobKinds !== undefined && input.allowedJobKinds !== null) {
249
+ if (!Array.isArray(input.allowedJobKinds))
250
+ throw fail('allowedJobKinds must be an array', 'allowedJobKinds');
251
+ const badKinds = input.allowedJobKinds.filter((k) => !exports.AGENT_JOB_KINDS.includes(k));
252
+ if (badKinds.length > 0) {
253
+ throw fail(`allowedJobKinds contains unknown kinds: ${badKinds.join(', ')}. Known: ${exports.AGENT_JOB_KINDS.join(', ')}`, 'allowedJobKinds');
254
+ }
255
+ allowedJobKinds = [...new Set(input.allowedJobKinds)];
256
+ if (allowedJobKinds.length > 0 && !wantsWallet) {
257
+ throw fail('allowedJobKinds needs SubmitWalletJob in allowedActions', 'allowedJobKinds');
258
+ }
259
+ }
260
+ let maxJobsPerDay = null;
261
+ if (input.maxJobsPerDay !== undefined && input.maxJobsPerDay !== null) {
262
+ const n = Number(input.maxJobsPerDay);
263
+ if (!Number.isInteger(n) || n < 1)
264
+ throw fail('maxJobsPerDay must be a positive integer', 'maxJobsPerDay');
265
+ maxJobsPerDay = n;
266
+ }
267
+ let validUntil = null;
268
+ if (input.validUntil) {
269
+ const t = new Date(input.validUntil);
270
+ if (Number.isNaN(t.getTime()))
271
+ throw fail('validUntil must be a valid ISO-8601 timestamp', 'validUntil');
272
+ if (t.getTime() <= now.getTime())
273
+ throw fail('validUntil must be in the future', 'validUntil');
274
+ validUntil = t.toISOString();
275
+ }
276
+ const agentLabel = typeof input.agentLabel === 'string' && input.agentLabel.trim() ? input.agentLabel.trim() : null;
277
+ if (agentLabel && agentLabel.length > 100)
278
+ throw fail('agentLabel must be at most 100 characters', 'agentLabel');
279
+ return { allowedActions: uniqueActions, walletId, allowedJobKinds, maxJobsPerDay, validUntil, agentLabel };
280
+ }
281
+ /**
282
+ * Mint a grant for `operatorId`. Validation errors surface as
283
+ * AgentGrantInputError (400). The INSERT runs on `runner`: the action passes its
284
+ * request transaction, x402 passes whatever transaction its settlement runs in.
285
+ */
286
+ async function issueAgentGrant(input, operatorId, runner = dbRunner()) {
287
+ if (!operatorId)
288
+ throw new AgentGrantInputError('an operator id is required');
289
+ const n = validateGrantInput(input);
290
+ const token = exports.AGENT_TOKEN_PREFIX + node_crypto_1.default.randomBytes(TOKEN_BYTES).toString('hex');
291
+ const grant = {
292
+ ID: cds_1.default.utils.uuid(),
293
+ userId: operatorId,
294
+ agentLabel: n.agentLabel,
295
+ tokenHash: hashAgentToken(token),
296
+ allowedActions: JSON.stringify(n.allowedActions),
297
+ walletId: n.walletId,
298
+ allowedJobKinds: n.allowedJobKinds.length > 0 ? JSON.stringify(n.allowedJobKinds) : null,
299
+ maxJobsPerDay: n.maxJobsPerDay,
300
+ jobsUsedToday: 0,
301
+ budgetWindow: null,
302
+ validUntil: n.validUntil,
303
+ isActive: true,
304
+ revokedAt: null,
305
+ createdAt: new Date().toISOString(),
306
+ lastUsedAt: null,
307
+ };
308
+ await runner.run(INSERT.into(exports.GRANTS_ENTITY).entries(grant));
309
+ // Deliberately logs the id, the label and the shape, never the token.
310
+ logger.info(`agent grant ${grant.ID} issued by ${operatorId}` +
311
+ `${n.agentLabel ? ` for '${n.agentLabel}'` : ''} (actions: ${n.allowedActions.join(', ')}` +
312
+ `${n.walletId ? `, wallet ${n.walletId}` : ''}${n.maxJobsPerDay ? `, budget ${n.maxJobsPerDay}/day` : ''}` +
313
+ `${n.validUntil ? `, until ${n.validUntil}` : ''})`);
314
+ return {
315
+ grantId: grant.ID,
316
+ token,
317
+ allowedActions: n.allowedActions,
318
+ walletId: n.walletId,
319
+ allowedJobKinds: n.allowedJobKinds,
320
+ maxJobsPerDay: n.maxJobsPerDay,
321
+ validUntil: n.validUntil,
322
+ };
323
+ }
324
+ /** Deactivate a grant; false when it does not exist or is already revoked. */
325
+ async function revokeAgentGrantById(grantId, runner = dbRunner()) {
326
+ if (!grantId)
327
+ return false;
328
+ const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY)
329
+ .set({ isActive: false, revokedAt: new Date().toISOString() })
330
+ .where({ ID: grantId, isActive: true }));
331
+ const revoked = Number(affected) > 0;
332
+ if (revoked)
333
+ logger.info(`agent grant ${grantId} revoked`);
334
+ return revoked;
335
+ }
336
+ /**
337
+ * Replace the grant's token; the old one is an unknown token from the next
338
+ * request (the lane reads tokenHash per request, so nothing needs invalidating;
339
+ * a request in flight with the old token completes). Budget, wallet, allow
340
+ * list and expiry survive. Null when the grant does not exist or is revoked.
341
+ */
342
+ async function rotateAgentGrantToken(grantId, runner = dbRunner()) {
343
+ if (!grantId)
344
+ return null;
345
+ const token = exports.AGENT_TOKEN_PREFIX + node_crypto_1.default.randomBytes(TOKEN_BYTES).toString('hex');
346
+ const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY).set({ tokenHash: hashAgentToken(token) }).where({ ID: grantId, isActive: true }));
347
+ if (Number(affected) === 0)
348
+ return null;
349
+ logger.info(`agent grant ${grantId} token rotated`);
350
+ return { grantId, token };
351
+ }
352
+ /** Row fields a grant edit never touches; a different wallet binding is a different grant (NIGHTGATE: sessionId). */
353
+ exports.GRANT_IMMUTABLE_FIELDS = ['walletId', 'userId', 'tokenHash'];
354
+ const GRANT_EDITABLE_FIELDS = [
355
+ 'agentLabel', 'allowedActions', 'allowedJobKinds', 'maxJobsPerDay', 'validUntil',
356
+ ];
357
+ /**
358
+ * Change the given fields of an ACTIVE grant. A field absent from `input`
359
+ * keeps its value; an explicit null clears agentLabel, allowedJobKinds,
360
+ * maxJobsPerDay or validUntil (NIGHTGATE's updateAgentGrant semantics).
361
+ * allowedActions cannot be emptied. The merged row goes through
362
+ * validateGrantInput, so the cross-field rules hold: wallet actions need the
363
+ * grant's (immutable) wallet, job kinds need SubmitWalletJob, a given
364
+ * validUntil lies in the future. Lowering maxJobsPerDay below jobsUsedToday is
365
+ * allowed; the grant is simply over budget until the UTC day rolls.
366
+ *
367
+ * Validation errors surface as AgentGrantInputError (400); an unknown grant is
368
+ * 404 and a revoked one 409 GRANT_REVOKED (revoked grants are never edited;
369
+ * re-mint instead).
370
+ */
371
+ async function updateAgentGrant(grantId, input, runner = dbRunner()) {
372
+ const has = (k) => Object.prototype.hasOwnProperty.call(input, k);
373
+ const existing = (await runner.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: grantId })));
374
+ if (!existing)
375
+ return { ok: false, status: 404, message: 'Grant not found' };
376
+ if (existing.isActive === false)
377
+ return { ok: false, status: 409, code: 'GRANT_REVOKED', message: 'Grant is revoked' };
378
+ // The merged row. validUntil only when given: an untouched expiry that has
379
+ // meanwhile passed is the lane's 410, not this edit's 400.
380
+ const n = validateGrantInput({
381
+ allowedActions: has('allowedActions') ? input.allowedActions : parseGrantList(existing.allowedActions),
382
+ walletId: existing.walletId ?? null,
383
+ allowedJobKinds: has('allowedJobKinds') ? input.allowedJobKinds : parseGrantList(existing.allowedJobKinds),
384
+ maxJobsPerDay: has('maxJobsPerDay') ? input.maxJobsPerDay : existing.maxJobsPerDay,
385
+ validUntil: has('validUntil') ? input.validUntil : null,
386
+ agentLabel: has('agentLabel') ? input.agentLabel : existing.agentLabel,
387
+ }, new Date(), 'UpdateAgentGrant');
388
+ const patch = {};
389
+ if (has('allowedActions'))
390
+ patch.allowedActions = JSON.stringify(n.allowedActions);
391
+ if (has('allowedJobKinds'))
392
+ patch.allowedJobKinds = n.allowedJobKinds.length > 0 ? JSON.stringify(n.allowedJobKinds) : null;
393
+ if (has('maxJobsPerDay'))
394
+ patch.maxJobsPerDay = n.maxJobsPerDay;
395
+ if (has('validUntil'))
396
+ patch.validUntil = n.validUntil;
397
+ if (has('agentLabel'))
398
+ patch.agentLabel = n.agentLabel;
399
+ const updated = GRANT_EDITABLE_FIELDS.filter((f) => has(f));
400
+ if (updated.length === 0)
401
+ return { ok: true, grantId, updated: [] };
402
+ // Conditional on isActive: a concurrent revoke wins over the edit.
403
+ const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY).set(patch).where({ ID: grantId, isActive: true }));
404
+ if (Number(affected) === 0)
405
+ return { ok: false, status: 409, code: 'GRANT_REVOKED', message: 'Grant is revoked' };
406
+ logger.info(`agent grant ${grantId} updated (${updated.join(', ')})`);
407
+ return { ok: true, grantId, updated };
408
+ }
409
+ // ---------------------------------------------------------------------------
410
+ // Usage history (GetGrantUsage)
411
+ // ---------------------------------------------------------------------------
412
+ exports.USAGE_WINDOW_MAX_MS = 366 * 24 * 60 * 60 * 1000;
413
+ exports.USAGE_WINDOW_DEFAULT_MS = 30 * 24 * 60 * 60 * 1000;
414
+ /** ISO timestamp or undefined; `null` when the value does not parse. */
415
+ function parseTimestamp(raw) {
416
+ if (raw === undefined || raw === null || raw === '')
417
+ return undefined;
418
+ const t = new Date(String(raw));
419
+ return Number.isNaN(t.getTime()) ? null : t.toISOString();
420
+ }
421
+ /**
422
+ * since (default until - 30 days) .. until (default now), at most 366 days
423
+ * (NIGHTGATE's rules and wording). Counters are per UTC day, so the days both
424
+ * ends fall on are included whole.
425
+ */
426
+ function resolveUsageWindow(since, until, now = new Date()) {
427
+ const to = parseTimestamp(until);
428
+ const from = parseTimestamp(since);
429
+ if (to === null)
430
+ return { ok: false, message: 'until must be a valid ISO-8601 timestamp', target: 'until' };
431
+ if (from === null)
432
+ return { ok: false, message: 'since must be a valid ISO-8601 timestamp', target: 'since' };
433
+ const toMs = to ? new Date(to).getTime() : now.getTime();
434
+ const fromMs = from ? new Date(from).getTime() : toMs - exports.USAGE_WINDOW_DEFAULT_MS;
435
+ if (fromMs > toMs)
436
+ return { ok: false, message: 'since must not lie after until', target: 'since' };
437
+ if (toMs - fromMs > exports.USAGE_WINDOW_MAX_MS)
438
+ return { ok: false, message: 'the window may span at most 366 days', target: 'since' };
439
+ const sinceIso = new Date(fromMs).toISOString();
440
+ const untilIso = new Date(toMs).toISOString();
441
+ return { ok: true, since: sinceIso, until: untilIso, sinceDay: sinceIso.slice(0, 10), untilDay: untilIso.slice(0, 10) };
442
+ }
443
+ /** The grant's admitted calls in `window`, grouped by service and action (one SUM per group). */
444
+ async function getGrantUsage(grant, window, runner = dbRunner()) {
445
+ const rows = ((await runner.run(SELECT.from(exports.GRANT_USAGE_ENTITY)
446
+ .columns('service', 'action', { func: 'sum', args: [{ ref: ['calls'] }], as: 'calls' }, { func: 'sum', args: [{ ref: ['refunded'] }], as: 'refunded' })
447
+ .where({ grant_ID: grant.ID, day: { '>=': window.sinceDay } })
448
+ .and({ day: { '<=': window.untilDay } })
449
+ .groupBy('service', 'action'))) ?? []);
450
+ const calls = rows
451
+ .map((r) => {
452
+ const admitted = Number(r.calls ?? 0);
453
+ const refunded = Number(r.refunded ?? 0);
454
+ return { service: String(r.service ?? ''), action: String(r.action ?? ''), count: Math.max(admitted - refunded, 0), refunded };
455
+ })
456
+ .sort((a, b) => a.service.localeCompare(b.service) || a.action.localeCompare(b.action));
457
+ const status = toGrantStatus(grant);
458
+ return {
459
+ grantId: grant.ID,
460
+ since: window.since,
461
+ until: window.until,
462
+ calls,
463
+ total: calls.reduce((sum, c) => sum + c.count, 0),
464
+ jobsUsedToday: status.jobsUsedToday,
465
+ maxJobsPerDay: status.maxJobsPerDay,
466
+ };
467
+ }
468
+ function toGrantStatus(grant) {
469
+ return {
470
+ grantId: grant.ID,
471
+ agentLabel: grant.agentLabel ?? null,
472
+ allowedActions: parseGrantList(grant.allowedActions),
473
+ walletId: grant.walletId ?? null,
474
+ allowedJobKinds: parseGrantList(grant.allowedJobKinds),
475
+ maxJobsPerDay: grant.maxJobsPerDay ?? null,
476
+ // A counter from an earlier UTC day is spent budget of a window that is over.
477
+ jobsUsedToday: grant.budgetWindow === utcDay() ? Number(grant.jobsUsedToday ?? 0) : 0,
478
+ budgetWindow: grant.budgetWindow ?? null,
479
+ validUntil: grant.validUntil ?? null,
480
+ isActive: grant.isActive !== false,
481
+ };
482
+ }
483
+ // ---------------------------------------------------------------------------
484
+ // CardanoAgentService handlers
485
+ // ---------------------------------------------------------------------------
486
+ /**
487
+ * The common prelude of the four administration actions: the rate limit first
488
+ * (refusals consume the window, like NIGHTGATE), then the token principal
489
+ * (belt and braces: none of these is always-allowed or allow-listable, so the
490
+ * hook 403s, and @requires: 'Admin' refuses the role-less principal anyway),
491
+ * then authentication. False after a reject.
492
+ */
493
+ function checkGrantAdmin(req, verb) {
494
+ const rate = grantAdminLimiter().check((0, rate_limiter_1.principalRateKey)(req, 'grant-admin'));
495
+ if (!rate.allowed) {
496
+ req.reject(429, `Rate limited. Retry after ${Math.ceil(rate.retryAfterMs / 1000)}s`);
497
+ return false;
498
+ }
499
+ if (agentGrantOf(req)) {
500
+ req.reject(403, `an agent grant cannot ${verb} grants`);
501
+ return false;
502
+ }
503
+ if (!req.user?.id) {
504
+ req.reject(401, 'authentication required');
505
+ return false;
506
+ }
507
+ return true;
508
+ }
509
+ function userIs(req, role) {
510
+ const user = req.user;
511
+ return typeof user?.is === 'function' ? user.is(role) === true : false;
512
+ }
513
+ /** Validation rejections are thrown BEFORE any transaction work (project convention). */
514
+ function registerAgentGrantHandlers(srv) {
515
+ srv.on('CreateAgentGrant', async (req) => {
516
+ if (!checkGrantAdmin(req, 'issue'))
517
+ return;
518
+ const operatorId = String(req.user.id);
519
+ const data = (req.data ?? {});
520
+ let normalized;
521
+ try {
522
+ normalized = validateGrantInput(data);
523
+ }
524
+ catch (err) {
525
+ if (err instanceof errors_1.BackendError)
526
+ return req.reject(err.statusCode, err.message, err.target);
527
+ throw err;
528
+ }
529
+ const issued = await issueAgentGrant(normalized, operatorId, cds_1.default.tx(req));
530
+ return {
531
+ grantId: issued.grantId,
532
+ token: issued.token,
533
+ allowedActions: issued.allowedActions,
534
+ walletId: issued.walletId,
535
+ allowedJobKinds: issued.allowedJobKinds,
536
+ maxJobsPerDay: issued.maxJobsPerDay,
537
+ validUntil: issued.validUntil,
538
+ };
539
+ });
540
+ srv.on('RevokeAgentGrant', async (req) => {
541
+ if (!checkGrantAdmin(req, 'revoke'))
542
+ return;
543
+ const { grantId } = (req.data ?? {});
544
+ if (!grantId)
545
+ return req.reject(400, 'grantId is required', 'grantId');
546
+ const revoked = await revokeAgentGrantById(grantId, cds_1.default.tx(req));
547
+ if (!revoked)
548
+ return req.reject(404, 'Grant not found or already revoked', 'grantId');
549
+ return true;
550
+ });
551
+ srv.on('RotateAgentGrantToken', async (req) => {
552
+ if (!checkGrantAdmin(req, 'rotate'))
553
+ return;
554
+ const { grantId } = (req.data ?? {});
555
+ if (!grantId)
556
+ return req.reject(400, 'grantId is required', 'grantId');
557
+ const rotated = await rotateAgentGrantToken(grantId, cds_1.default.tx(req));
558
+ if (!rotated)
559
+ return req.reject(404, 'Grant not found or already revoked', 'grantId');
560
+ return rotated;
561
+ });
562
+ srv.on('UpdateAgentGrant', async (req) => {
563
+ if (!checkGrantAdmin(req, 'update'))
564
+ return;
565
+ const data = (req.data ?? {});
566
+ if (!data.grantId)
567
+ return req.reject(400, 'grantId is required', 'grantId');
568
+ const immutable = exports.GRANT_IMMUTABLE_FIELDS.filter((f) => Object.prototype.hasOwnProperty.call(data, f));
569
+ if (immutable.length > 0) {
570
+ return req.reject(400, `${immutable.join(', ')} cannot be changed; issue a new grant for a different binding`, immutable[0]);
571
+ }
572
+ let result;
573
+ try {
574
+ result = await updateAgentGrant(data.grantId, data, cds_1.default.tx(req));
575
+ }
576
+ catch (err) {
577
+ if (err instanceof errors_1.BackendError)
578
+ return req.reject(err.statusCode, err.message, err.target);
579
+ throw err;
580
+ }
581
+ if (!result.ok) {
582
+ if (result.code)
583
+ return req.reject({ status: result.status, code: result.code, message: result.message });
584
+ return req.reject(result.status, result.message, 'grantId');
585
+ }
586
+ return { grantId: result.grantId, updated: result.updated };
587
+ });
588
+ // GetGrantStatus: the calling token's own grant, read fresh so the budget
589
+ // counter is current. An operator without a token lists AgentGrants instead.
590
+ srv.on('GetGrantStatus', async (req) => {
591
+ const grant = agentGrantOf(req);
592
+ if (!grant)
593
+ return req.reject(400, 'GetGrantStatus needs an x-agent-token; operators read the AgentGrants entity');
594
+ const fresh = (await cds_1.default.tx(req).run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: grant.ID })));
595
+ return toGrantStatus(fresh ?? grant);
596
+ });
597
+ // GetGrantUsage: an Admin sees any grant (revoked ones keep their history), a
598
+ // token only its own — the hook already narrowed it (404, non-leaking).
599
+ srv.on('GetGrantUsage', async (req) => {
600
+ const data = (req.data ?? {});
601
+ if (!data.grantId)
602
+ return req.reject(400, 'grantId is required', 'grantId');
603
+ const window = resolveUsageWindow(data.since, data.until);
604
+ if (!window.ok)
605
+ return req.reject(400, window.message, window.target);
606
+ const own = agentGrantOf(req);
607
+ if (own && own.ID !== data.grantId)
608
+ return req.reject(404, 'Grant not found', 'grantId');
609
+ if (!own && !userIs(req, 'Admin'))
610
+ return req.reject(403, "GetGrantUsage needs Admin or the grant's own token");
611
+ const tx = cds_1.default.tx(req);
612
+ const grant = (await tx.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: data.grantId })));
613
+ if (!grant)
614
+ return req.reject(404, 'Grant not found', 'grantId');
615
+ return getGrantUsage(grant, window, tx);
616
+ });
617
+ }
618
+ // ---------------------------------------------------------------------------
619
+ // Enforcement (before('*') on the six services)
620
+ // ---------------------------------------------------------------------------
621
+ function attachAgentGrantEnforcement(srv, runner) {
622
+ const serviceName = String(srv.name ?? 'unknown');
623
+ srv.before('*', (req) => enforceAgentGrant(req, runner, undefined, serviceName));
624
+ }
625
+ function budgetRunnerFor(req, injected, detached) {
626
+ if (injected)
627
+ return { runner: injected, detached: detached ?? true };
628
+ let tx = null;
629
+ try {
630
+ tx = cds_1.default.tx(req);
631
+ }
632
+ catch {
633
+ tx = null;
634
+ }
635
+ if (tx && (tx.dbc || tx.ready))
636
+ return { runner: tx, detached: false };
637
+ return { runner: dbRunner(), detached: true };
638
+ }
639
+ async function runStmt(br, statement) {
640
+ return br.detached ? (0, tx_utils_1.runWithoutAmbientTx)(() => br.runner.run(statement)) : br.runner.run(statement);
641
+ }
642
+ /**
643
+ * Exported for unit tests; see the module doc for the ladder. Ordinary
644
+ * principals pass through untouched: this hook is a no-op without a grant.
645
+ * `runner` / `detached` are test seams; production picks them per request.
646
+ */
647
+ async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown') {
648
+ const grant = agentGrantOf(req);
649
+ if (!grant)
650
+ return;
651
+ // Defence in depth: the lane already refused inactive and expired grants, but
652
+ // a grant can be revoked between two parts of a $batch, or expire mid-flight.
653
+ if (grant.isActive === false)
654
+ return req.reject(401, 'invalid agent token');
655
+ if (isExpired(grant))
656
+ return req.reject(410, 'agent grant expired');
657
+ const br = budgetRunnerFor(req, runner, detached);
658
+ const event = String(req.event ?? '');
659
+ if (exports.AGENT_ALWAYS_ALLOWED_EVENTS.has(event)) {
660
+ // The handler's Admin gate alone would answer for every grant: a token sees
661
+ // its own usage only, and a foreign id is not found (non-leaking, NIGHTGATE).
662
+ if (event === 'GetGrantUsage') {
663
+ const asked = String(req.data?.grantId ?? '');
664
+ if (asked !== grant.ID)
665
+ return req.reject(404, 'Grant not found', 'grantId');
666
+ }
667
+ await touchLastUsed(grant, br);
668
+ return;
669
+ }
670
+ const allowed = parseGrantList(grant.allowedActions);
671
+ if (!allowed.includes(event)) {
672
+ return req.reject(403, `action '${event}' is not allowed for this agent grant`);
673
+ }
674
+ const data = req.data;
675
+ if (exports.AGENT_WALLET_ACTIONS.has(event)) {
676
+ if (!grant.walletId) {
677
+ return req.reject(403, 'this agent grant has no wallet binding; issue it with walletId to queue wallet jobs');
678
+ }
679
+ if (data && typeof data === 'object') {
680
+ if (event === 'SubmitWalletJob') {
681
+ if (data.walletId !== undefined && data.walletId !== null && data.walletId !== '' && data.walletId !== grant.walletId) {
682
+ return req.reject(403, 'walletId does not match this agent grant');
683
+ }
684
+ data.walletId = grant.walletId;
685
+ const kinds = parseGrantList(grant.allowedJobKinds);
686
+ if (kinds.length > 0 && !kinds.includes(String(data.kind ?? ''))) {
687
+ return req.reject(403, `job kind '${String(data.kind ?? '')}' is not allowed for this agent grant (allowed: ${kinds.join(', ')})`);
688
+ }
689
+ }
690
+ // CancelJob: the job lookup is owner-scoped by createdBy = agent:<grantId>
691
+ // in the worker service, so a foreign job is a 404 there already.
692
+ }
693
+ }
694
+ let charge = null;
695
+ if (grant.maxJobsPerDay !== undefined && grant.maxJobsPerDay !== null) {
696
+ charge = await consumeDailyBudget(br, grant);
697
+ if (!charge.consumed) {
698
+ return req.reject(429, `agent grant daily budget exhausted (${grant.maxJobsPerDay}/day)`);
699
+ }
700
+ }
701
+ // Admitted: one usage unit on (grant, day, service, action), budgeted or not.
702
+ const usageDay = await recordGrantUsage(br, grant, serviceName, event);
703
+ // Detached writes: a request the handler refuses as invalid (400..428)
704
+ // admitted nothing, so give the budget unit back — in the window it was
705
+ // charged to, not in whatever day it is when the refund runs — and mark the
706
+ // usage unit refunded. 429 and every 5xx keep both (over-count, never
707
+ // under-count). Writes made inside the request's own transaction need none
708
+ // of this: its rollback undoes them.
709
+ if (br.detached) {
710
+ const chargedWindow = charge?.window ?? null;
711
+ req.on?.('failed', (err) => {
712
+ const e = err;
713
+ const status = Number(e?.status ?? e?.statusCode ?? e?.code);
714
+ if (Number.isInteger(status) && status >= 400 && status < 429) {
715
+ // Off the failing request's tick: its transaction is still rolling
716
+ // back when 'failed' fires, and a write on a second connection at
717
+ // that moment is the SQLite lock contention this module must never cause.
718
+ setImmediate(() => {
719
+ if (chargedWindow) {
720
+ void refundDailyBudget(br, grant, chargedWindow).catch((refundErr) => logger.warn(`daily budget refund for grant ${grant.ID} failed: ${String(refundErr?.message ?? refundErr)}`));
721
+ }
722
+ void refundGrantUsage(br, grant, serviceName, event, usageDay).catch((refundErr) => logger.warn(`usage refund for grant ${grant.ID} failed: ${String(refundErr?.message ?? refundErr)}`));
723
+ });
724
+ }
725
+ });
726
+ }
727
+ await touchLastUsed(grant, br);
728
+ }
729
+ /**
730
+ * Consume one unit of the grant's daily budget. Two conditional UPDATEs so
731
+ * concurrent requests cannot overspend: a window reset (compare-and-swap on
732
+ * the OLD window value) and a bounded increment (`jobsUsedToday < max`). Runs
733
+ * on the BudgetRunner the hook chose (detached by default, see budgetRunnerFor).
734
+ */
735
+ async function consumeDailyBudget(br, grant) {
736
+ const runner = 'runner' in br ? br : { runner: br, detached: true };
737
+ const today = utcDay();
738
+ const max = grant.maxJobsPerDay;
739
+ if (grant.budgetWindow !== today) {
740
+ const reset = await runStmt(runner, UPDATE.entity(exports.GRANTS_ENTITY)
741
+ .set({ budgetWindow: today, jobsUsedToday: 1 })
742
+ .where({ ID: grant.ID, budgetWindow: grant.budgetWindow ?? null }));
743
+ if (Number(reset))
744
+ return { consumed: true, window: today };
745
+ // Lost the reset race: another request already moved the window.
746
+ }
747
+ const incremented = await runStmt(runner, UPDATE.entity(exports.GRANTS_ENTITY)
748
+ .set({ jobsUsedToday: { '+=': 1 } })
749
+ .where({ ID: grant.ID, budgetWindow: today, jobsUsedToday: { '<': max } }));
750
+ return { consumed: Number(incremented) > 0, window: today };
751
+ }
752
+ /**
753
+ * Undo one consumeDailyBudget in the window it was charged to (a refused
754
+ * request created nothing). A refund that lands after midnight must not touch
755
+ * the new day's counter: the unit was spent yesterday, yesterday keeps it.
756
+ */
757
+ async function refundDailyBudget(br, grant, window) {
758
+ const runner = 'runner' in br ? br : { runner: br, detached: true };
759
+ await runStmt(runner, UPDATE.entity(exports.GRANTS_ENTITY)
760
+ .set({ jobsUsedToday: { '-=': 1 } })
761
+ .where({ ID: grant.ID, budgetWindow: window, jobsUsedToday: { '>': 0 } }));
762
+ }
763
+ /**
764
+ * One admitted call: `calls + 1` on (grant, UTC day, service, action). A
765
+ * conditional UPDATE first (the common path), an INSERT when the row does not
766
+ * exist yet, one more UPDATE when a racing request inserted it first. Runs on
767
+ * the hook's BudgetRunner and is AWAITED like every other write of the hook
768
+ * (see touchLastUsed), but never fails the request: usage is accounting, not
769
+ * admission. Returns the day the call was counted on (the refund names it).
770
+ */
771
+ async function recordGrantUsage(br, grant, service, action, now = new Date()) {
772
+ const runner = 'runner' in br ? br : { runner: br, detached: true };
773
+ const day = utcDay(now);
774
+ const key = { grant_ID: grant.ID, day, service, action };
775
+ const bump = () => runStmt(runner, UPDATE.entity(exports.GRANT_USAGE_ENTITY).set({ calls: { '+=': 1 } }).where(key));
776
+ try {
777
+ if (Number(await bump()) > 0)
778
+ return day;
779
+ try {
780
+ await runStmt(runner, INSERT.into(exports.GRANT_USAGE_ENTITY).entries({ ...key, calls: 1, refunded: 0 }));
781
+ }
782
+ catch {
783
+ await bump(); // lost the insert race: the row exists now
784
+ }
785
+ }
786
+ catch (err) {
787
+ logger.warn(`usage record for grant ${grant.ID} (${service}.${action}) failed: ${String(err?.message ?? err)}`);
788
+ }
789
+ return day;
790
+ }
791
+ /** `refunded + 1` on the row the call was counted on: a refused request admitted nothing. */
792
+ async function refundGrantUsage(br, grant, service, action, day) {
793
+ const runner = 'runner' in br ? br : { runner: br, detached: true };
794
+ await runStmt(runner, UPDATE.entity(exports.GRANT_USAGE_ENTITY)
795
+ .set({ refunded: { '+=': 1 } })
796
+ .where({ grant_ID: grant.ID, day, service, action }));
797
+ }
798
+ /**
799
+ * lastUsedAt, at most once a minute per grant. AWAITED, like the budget
800
+ * statements: every write this hook makes must be finished before the handler
801
+ * opens the request's own transaction. A fire-and-forget write on a second
802
+ * connection races the handler's reads and, on SQLite in WAL mode, turns the
803
+ * handler's first UPSERT into "database is locked" (SQLITE_BUSY_SNAPSHOT) —
804
+ * seen live on 2026-09-05. A failed touch is logged and never fails the request.
805
+ */
806
+ const lastUsedTouched = new Map();
807
+ const LAST_USED_INTERVAL_MS = 60_000;
808
+ async function touchLastUsed(grant, br) {
809
+ const now = Date.now();
810
+ const last = lastUsedTouched.get(grant.ID) ?? 0;
811
+ if (now - last < LAST_USED_INTERVAL_MS)
812
+ return;
813
+ lastUsedTouched.set(grant.ID, now);
814
+ try {
815
+ await runStmt(br, UPDATE.entity(exports.GRANTS_ENTITY).set({ lastUsedAt: new Date(now).toISOString() }).where({ ID: grant.ID }));
816
+ }
817
+ catch (err) {
818
+ logger.debug(`lastUsedAt update for grant ${grant.ID} failed: ${String(err?.message ?? err)}`);
819
+ }
820
+ }
821
+ //# sourceMappingURL=agent-grants.js.map