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

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.
@@ -6,16 +6,24 @@ using {odatano.cardano as db} from '../db/schema';
6
6
  * Agent grants: scoped, budgeted bearer capabilities an Admin hands to an agent
7
7
  * instead of a full user (see AGENT_GRANTS_DESIGN.md).
8
8
  *
9
- * - CreateAgentGrant / RevokeAgentGrant: Admin-only administration. The token is
10
- * returned ONCE from CreateAgentGrant and stored as SHA-256 only.
9
+ * - CreateAgentGrant / UpdateAgentGrant / RotateAgentGrantToken / RevokeAgentGrant:
10
+ * Admin-only administration, rate limited per principal per hour
11
+ * (AGENT_GRANT_ADMIN_RATE_LIMIT, default 10). The token is returned ONCE from
12
+ * CreateAgentGrant and RotateAgentGrantToken and stored as SHA-256 only.
11
13
  * - AgentGrants: Admin-only projection (no token hash). A request carrying a token
12
14
  * runs as the principal `agent:<grantId>` with the role `agent-grant` and sees
13
15
  * exactly its own row through the row-level restriction below.
14
16
  * - GetGrantStatus: token self-service — what am I allowed to do, how much budget
15
17
  * is left, when do I expire. What an MCP tool needs to describe itself honestly.
18
+ * - GetGrantUsage: admitted calls per service and action over a window — an Admin
19
+ * for any grant, a token for its own (a partner usage view, ledger reconciliation).
20
+ *
21
+ * Names are this repo's PascalCase; semantics mirror NIGHTGATE's agent grants
22
+ * (createAgentGrant / updateAgentGrant / rotateAgentGrantToken / revokeAgentGrant /
23
+ * getGrantUsage), so a gateway drives both products with one code path.
16
24
  *
17
25
  * A token request never inherits the operator's roles: `@requires: 'Admin'` on the
18
- * two actions, on PauseWorker / ResumeWorker / pauseCrawler / resumeCrawler and on
26
+ * four actions, on PauseWorker / ResumeWorker / pauseCrawler / resumeCrawler and on
19
27
  * every other Admin surface therefore refuses it by construction. The allow list,
20
28
  * wallet pinning and daily budget are enforced by a before('*') hook on all six
21
29
  * ODATANO services (srv/utils/agent-grants.ts). The `x-agent-token` header only
@@ -81,4 +89,62 @@ service CardanoAgentService @(impl: './cardano-agent-service') {
81
89
  action RevokeAgentGrant(
82
90
  @title: 'Grant Id' grantId : UUID
83
91
  ) returns Boolean;
92
+
93
+ @title : 'Rotated Grant'
94
+ type RotatedGrant {
95
+ grantId : UUID;
96
+ token : String; // shown once, never stored
97
+ }
98
+
99
+ @title : 'Rotate Agent Grant Token'
100
+ @description: 'Replace the grant token; the old token is unknown from the next request. Budget, wallet, allow list and expiry survive. Admin only. 404 when the grant does not exist or is revoked.'
101
+ @requires : 'Admin'
102
+ action RotateAgentGrantToken(
103
+ @title: 'Grant Id' grantId : UUID
104
+ ) returns RotatedGrant;
105
+
106
+ @title : 'Updated Grant'
107
+ type UpdatedGrant {
108
+ grantId : UUID;
109
+ updated : many String; // parameter names that were applied
110
+ }
111
+
112
+ @title : 'Update Agent Grant'
113
+ @description: 'Change label, allow list, job kinds, daily budget or expiry of an active grant. An absent parameter stays as it is; an explicit null clears agentLabel, allowedJobKinds, maxJobsPerDay or validUntil. allowedActions cannot be emptied; the wallet binding is immutable (issue a new grant). Admin only. 404 unknown grant, 409 GRANT_REVOKED.'
114
+ @requires : 'Admin'
115
+ action UpdateAgentGrant(
116
+ @title: 'Grant Id' grantId : UUID,
117
+ @title: 'Agent Label' agentLabel : String(100),
118
+ @title: 'Allowed Actions' allowedActions : many String,
119
+ @title: 'Allowed Job Kinds' allowedJobKinds : many String,
120
+ @title: 'Max Jobs Per Day' maxJobsPerDay : Integer,
121
+ @title: 'Valid Until' validUntil : Timestamp
122
+ ) returns UpdatedGrant;
123
+
124
+ @title : 'Grant Usage Call'
125
+ type GrantUsageCall {
126
+ service : String(60); // CardanoTransactionService, CardanoSignService, ...
127
+ action : String(100); // BuildSimpleAdaTransaction, SubmitTransaction, ...
128
+ count : Integer; // admitted and kept (budget charged and not refunded)
129
+ refunded : Integer; // admitted, then refunded because the handler refused the input
130
+ }
131
+
132
+ @title : 'Grant Usage'
133
+ type GrantUsage {
134
+ grantId : UUID;
135
+ since : Timestamp;
136
+ until : Timestamp;
137
+ calls : many GrantUsageCall;
138
+ total : Integer;
139
+ jobsUsedToday : Integer;
140
+ maxJobsPerDay : Integer;
141
+ }
142
+
143
+ @title : 'Get Grant Usage'
144
+ @description: 'Admitted calls under a grant between since (default until - 30 days) and until (default now), at most 366 days, per UTC day, grouped by service and action. An Admin sees any grant (revoked ones keep their history); a token sees only its own.'
145
+ function GetGrantUsage(
146
+ @title: 'Grant Id' grantId : UUID,
147
+ @title: 'Since' since : Timestamp,
148
+ @title: 'Until' until : Timestamp
149
+ ) returns GrantUsage;
84
150
  }
@@ -61,6 +61,26 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
61
61
 
62
62
  function getStatus() returns CrawlerStatus;
63
63
 
64
+ @title : 'Liveness'
65
+ type Liveness {
66
+ status : String; // 'alive'
67
+ timestamp : Timestamp;
68
+ uptime : Integer; // seconds since process start
69
+ version : String; // @odatano/core version
70
+ network : String; // configured network
71
+ }
72
+
73
+ // Public override (see VerifyDataSignature in cardano-sign-service.cds): a
74
+ // liveness probe carries no credentials. 200 as long as the process answers —
75
+ // no backend or DB probe, no secrets, no backend names, no API key state. That
76
+ // stays with getStatus and the backend health entities, which remain
77
+ // authenticated. Mirrors NIGHTGATE's `/api/v1/indexer/getLiveness()`, so a
78
+ // gateway probes both products the same way.
79
+ @title : 'Get Liveness'
80
+ @description: 'Unauthenticated liveness probe: 200 while the process answers. Docker HEALTHCHECK and upstream probes use this instead of the service document.'
81
+ @requires : 'any'
82
+ function getLiveness() returns Liveness;
83
+
64
84
  @title : 'Pause Crawler'
65
85
  @description: 'Stop the crawler (closes the chain-sync stream). Resume continues from the cursor.'
66
86
  @requires : 'Admin'
@@ -9,6 +9,7 @@ const errors_1 = require("./utils/errors");
9
9
  const crawler_1 = require("./blockchain/crawler");
10
10
  const sync_state_1 = require("./blockchain/crawler/sync-state");
11
11
  const server_1 = require("./server");
12
+ const liveness_1 = require("./utils/liveness");
12
13
  const logger = cds_1.default.log('CardanoIndexerService');
13
14
  /**
14
15
  * CardanoIndexerService handlers — thin control/observability surface over the crawler
@@ -16,6 +17,8 @@ const logger = cds_1.default.log('CardanoIndexerService');
16
17
  * cursor and starts/stops the crawler.
17
18
  */
18
19
  module.exports = (srv) => {
20
+ // getLiveness — unauthenticated probe (@requires: 'any'); no handleRequest, no app context.
21
+ srv.on('getLiveness', async () => (0, liveness_1.buildLiveness)());
19
22
  // getStatus — live run state + sync progress (numeric fields as strings, CAP-10 aligned)
20
23
  srv.on('getStatus', async (req) => {
21
24
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
@@ -4,19 +4,35 @@
4
4
  * src/plugin.ts reads it at plugin load, before any blockchain module may be
5
5
  * required.
6
6
  *
7
- * cds: "odatano-core": { "agentGrants": { "enabled": true, "delegate": "mocked" } }
7
+ * cds: "odatano-core": { "agentGrants": { "enabled": true, "delegate": "mocked", "adminRateLimit": 10 } }
8
8
  * env: AGENT_GRANTS_ENABLED=true AGENT_GRANTS_DELEGATE=mocked|basic|jwt|xsuaa|ias|dummy
9
+ * AGENT_GRANT_ADMIN_RATE_LIMIT=10
9
10
  *
10
11
  * `delegate` names the CAP auth strategy that keeps authenticating every
11
12
  * request WITHOUT an `x-agent-token` header (the transport lane only adds the
12
13
  * token path next to it). Default: the configured `cds.requires.auth.kind`.
14
+ *
15
+ * `adminRateLimit` is the number of grant-administration calls
16
+ * (CreateAgentGrant, UpdateAgentGrant, RotateAgentGrantToken, RevokeAgentGrant)
17
+ * one principal may make per hour; NIGHTGATE's `NIGHTGATE_GRANT_ADMIN_RATE_LIMIT`.
18
+ * A gateway that mints for everybody (ODATANO ACCESS) raises it.
13
19
  */
14
20
  export interface AgentGrantsConfig {
15
21
  enabled: boolean;
16
22
  /** CAP auth kind the transport middleware delegates to for non-token requests. */
17
23
  delegate: string;
24
+ /** Grant administration calls per principal per hour (integer >= 1). */
25
+ adminRateLimit: number;
18
26
  }
19
27
  export declare const AGENT_GRANTS_DELEGATES: readonly string[];
28
+ export declare const AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = 10;
29
+ /**
30
+ * The admin rate limit: `agentGrants.adminRateLimit`, then
31
+ * `AGENT_GRANT_ADMIN_RATE_LIMIT`, default 10. An unusable value (not an
32
+ * integer, below 1) is logged once and falls back to the default — a typo in
33
+ * this knob must not switch the whole feature off, unlike a wrong delegate.
34
+ */
35
+ export declare function loadGrantAdminRateLimit(env?: Record<string, string | undefined>): number;
20
36
  /** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
21
37
  export declare function configuredAuth(): Record<string, unknown>;
22
38
  /**
@@ -3,7 +3,8 @@ 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.AGENT_GRANTS_DELEGATES = void 0;
6
+ exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = exports.AGENT_GRANTS_DELEGATES = void 0;
7
+ exports.loadGrantAdminRateLimit = loadGrantAdminRateLimit;
7
8
  exports.configuredAuth = configuredAuth;
8
9
  exports.customAuthImpl = customAuthImpl;
9
10
  exports.loadAgentGrantsConfig = loadAgentGrantsConfig;
@@ -11,6 +12,25 @@ exports.activateAgentGrants = activateAgentGrants;
11
12
  const cds_1 = __importDefault(require("@sap/cds"));
12
13
  const path_1 = __importDefault(require("path"));
13
14
  exports.AGENT_GRANTS_DELEGATES = ['mocked', 'basic', 'jwt', 'xsuaa', 'ias', 'dummy'];
15
+ exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = 10;
16
+ /**
17
+ * The admin rate limit: `agentGrants.adminRateLimit`, then
18
+ * `AGENT_GRANT_ADMIN_RATE_LIMIT`, default 10. An unusable value (not an
19
+ * integer, below 1) is logged once and falls back to the default — a typo in
20
+ * this knob must not switch the whole feature off, unlike a wrong delegate.
21
+ */
22
+ function loadGrantAdminRateLimit(env = process.env) {
23
+ const cfg = envRecord();
24
+ const raw = cfg.adminRateLimit !== undefined ? cfg.adminRateLimit : env.AGENT_GRANT_ADMIN_RATE_LIMIT;
25
+ if (raw === undefined || raw === null || String(raw).trim() === '')
26
+ return exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT;
27
+ const n = Number(raw);
28
+ if (!Number.isInteger(n) || n < 1) {
29
+ cds_1.default.log('ODATANO').warn(`AGENT_GRANT_ADMIN_RATE_LIMIT "${String(raw)}" is not an integer >= 1; using ${exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT}`);
30
+ return exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT;
31
+ }
32
+ return n;
33
+ }
14
34
  function envRecord() {
15
35
  const requires = (cds_1.default.env?.requires ?? {});
16
36
  const core = (requires['odatano-core'] ?? {});
@@ -54,7 +74,7 @@ function loadAgentGrantsConfig(env = process.env) {
54
74
  if (enabled && delegate === 'custom' && !customAuthImpl(auth)) {
55
75
  throw new Error('agentGrants.delegate "custom" needs a custom cds.requires.auth.impl to delegate to');
56
76
  }
57
- return { enabled, delegate };
77
+ return { enabled, delegate, adminRateLimit: loadGrantAdminRateLimit(env) };
58
78
  }
59
79
  /**
60
80
  * Marker on the shared `cds` facade: the activation below must run exactly once
@@ -14,10 +14,13 @@
14
14
  * lastUsedAt. Ownership needs no special code: a token's jobs are created
15
15
  * with createdBy = `agent:<grantId>`, so the existing `createdBy = $user`
16
16
  * gates and the `$user.grantId` row restrictions do the narrowing.
17
- * - `registerAgentGrantHandlers`: CreateAgentGrant / RevokeAgentGrant /
18
- * GetGrantStatus for CardanoAgentService, on top of the programmatic
19
- * `issueAgentGrant` / `revokeAgentGrantById` that @odatano/x402 uses to sell
20
- * grants.
17
+ * - `registerAgentGrantHandlers`: the grant lifecycle for CardanoAgentService
18
+ * (CreateAgentGrant / UpdateAgentGrant / RotateAgentGrantToken /
19
+ * RevokeAgentGrant, GetGrantStatus / GetGrantUsage), on top of the
20
+ * programmatic `issueAgentGrant` / `updateAgentGrant` /
21
+ * `rotateAgentGrantToken` / `revokeAgentGrantById` that @odatano/x402 uses
22
+ * to sell grants. Names are this repo's PascalCase; semantics follow
23
+ * NIGHTGATE's so a gateway (ODATANO ACCESS) drives both with one code path.
21
24
  *
22
25
  * The token is a capability, not an identity: it never carries the operator's
23
26
  * roles, so every `@requires: 'Admin'` surface refuses it by construction.
@@ -31,6 +34,8 @@ export declare const AGENT_ROLE = "agent-grant";
31
34
  /** `agent:<grantId>`: the principal id a token request runs under. */
32
35
  export declare const AGENT_PRINCIPAL_PREFIX = "agent:";
33
36
  export declare const GRANTS_ENTITY = "odatano.cardano.CardanoAgentGrants";
37
+ /** Daily per-action counters of admitted calls (feeds GetGrantUsage); never exposed as an entity. */
38
+ export declare const GRANT_USAGE_ENTITY = "odatano.cardano.CardanoAgentGrantUsage";
34
39
  /** The services the hook attaches to and the transport lane opens. */
35
40
  export declare const AGENT_SERVICE_NAMES: readonly string[];
36
41
  /**
@@ -51,7 +56,7 @@ export declare const AGENT_WALLET_ACTIONS: ReadonlySet<string>;
51
56
  export declare const AGENT_ALWAYS_ALLOWED_EVENTS: ReadonlySet<string>;
52
57
  /** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
53
58
  export declare const AGENT_JOB_KINDS: readonly string[];
54
- /** Forget every rate-limit window (tests). */
59
+ /** Forget every rate-limit window and re-read the limit from the config (tests). */
55
60
  export declare function __resetGrantRateLimiterForTests(): void;
56
61
  export interface AgentGrantRow {
57
62
  ID: string;
@@ -122,7 +127,7 @@ export interface IssuedAgentGrant {
122
127
  }
123
128
  /** A refused grant input; carries the 400 the action answers with. */
124
129
  export declare class AgentGrantInputError extends BackendError {
125
- constructor(message: string, target?: string);
130
+ constructor(message: string, target?: string, context?: string);
126
131
  }
127
132
  interface NormalizedGrantInput {
128
133
  allowedActions: string[];
@@ -132,7 +137,7 @@ interface NormalizedGrantInput {
132
137
  validUntil: string | null;
133
138
  agentLabel: string | null;
134
139
  }
135
- export declare function validateGrantInput(input: IssueAgentGrantInput, now?: Date): NormalizedGrantInput;
140
+ export declare function validateGrantInput(input: IssueAgentGrantInput, now?: Date, context?: string): NormalizedGrantInput;
136
141
  /**
137
142
  * Mint a grant for `operatorId`. Validation errors surface as
138
143
  * AgentGrantInputError (400). The INSERT runs on `runner`: the action passes its
@@ -141,6 +146,93 @@ export declare function validateGrantInput(input: IssueAgentGrantInput, now?: Da
141
146
  export declare function issueAgentGrant(input: IssueAgentGrantInput, operatorId: string, runner?: Runner): Promise<IssuedAgentGrant>;
142
147
  /** Deactivate a grant; false when it does not exist or is already revoked. */
143
148
  export declare function revokeAgentGrantById(grantId: string, runner?: Runner): Promise<boolean>;
149
+ export interface RotatedAgentGrant {
150
+ grantId: string;
151
+ /** Shown once. Never logged, never stored. */
152
+ token: string;
153
+ }
154
+ /**
155
+ * Replace the grant's token; the old one is an unknown token from the next
156
+ * request (the lane reads tokenHash per request, so nothing needs invalidating;
157
+ * a request in flight with the old token completes). Budget, wallet, allow
158
+ * list and expiry survive. Null when the grant does not exist or is revoked.
159
+ */
160
+ export declare function rotateAgentGrantToken(grantId: string, runner?: Runner): Promise<RotatedAgentGrant | null>;
161
+ /** The editable grant fields, as a client sends them: absent = untouched, explicit null = cleared. */
162
+ export interface UpdateAgentGrantInput {
163
+ agentLabel?: string | null;
164
+ allowedActions?: string[] | null;
165
+ allowedJobKinds?: string[] | null;
166
+ maxJobsPerDay?: number | null;
167
+ validUntil?: string | null;
168
+ }
169
+ /** Row fields a grant edit never touches; a different wallet binding is a different grant (NIGHTGATE: sessionId). */
170
+ export declare const GRANT_IMMUTABLE_FIELDS: readonly string[];
171
+ export type UpdateAgentGrantResult = {
172
+ ok: true;
173
+ grantId: string;
174
+ updated: string[];
175
+ } | {
176
+ ok: false;
177
+ status: 404 | 409;
178
+ code?: 'GRANT_REVOKED';
179
+ message: string;
180
+ };
181
+ /**
182
+ * Change the given fields of an ACTIVE grant. A field absent from `input`
183
+ * keeps its value; an explicit null clears agentLabel, allowedJobKinds,
184
+ * maxJobsPerDay or validUntil (NIGHTGATE's updateAgentGrant semantics).
185
+ * allowedActions cannot be emptied. The merged row goes through
186
+ * validateGrantInput, so the cross-field rules hold: wallet actions need the
187
+ * grant's (immutable) wallet, job kinds need SubmitWalletJob, a given
188
+ * validUntil lies in the future. Lowering maxJobsPerDay below jobsUsedToday is
189
+ * allowed; the grant is simply over budget until the UTC day rolls.
190
+ *
191
+ * Validation errors surface as AgentGrantInputError (400); an unknown grant is
192
+ * 404 and a revoked one 409 GRANT_REVOKED (revoked grants are never edited;
193
+ * re-mint instead).
194
+ */
195
+ export declare function updateAgentGrant(grantId: string, input: UpdateAgentGrantInput, runner?: Runner): Promise<UpdateAgentGrantResult>;
196
+ export declare const USAGE_WINDOW_MAX_MS: number;
197
+ export declare const USAGE_WINDOW_DEFAULT_MS: number;
198
+ export type UsageWindow = {
199
+ ok: true;
200
+ since: string;
201
+ until: string;
202
+ sinceDay: string;
203
+ untilDay: string;
204
+ } | {
205
+ ok: false;
206
+ message: string;
207
+ target: string;
208
+ };
209
+ /**
210
+ * since (default until - 30 days) .. until (default now), at most 366 days
211
+ * (NIGHTGATE's rules and wording). Counters are per UTC day, so the days both
212
+ * ends fall on are included whole.
213
+ */
214
+ export declare function resolveUsageWindow(since: unknown, until: unknown, now?: Date): UsageWindow;
215
+ export interface GrantUsageCall {
216
+ service: string;
217
+ action: string;
218
+ /** Admitted and kept (budget charged and not refunded). */
219
+ count: number;
220
+ /** Admitted, then refunded because the handler refused the input. */
221
+ refunded: number;
222
+ }
223
+ export interface AgentGrantUsage {
224
+ grantId: string;
225
+ since: string;
226
+ until: string;
227
+ calls: GrantUsageCall[];
228
+ total: number;
229
+ jobsUsedToday: number;
230
+ maxJobsPerDay: number | null;
231
+ }
232
+ /** The grant's admitted calls in `window`, grouped by service and action (one SUM per group). */
233
+ export declare function getGrantUsage(grant: AgentGrantRow, window: Extract<UsageWindow, {
234
+ ok: true;
235
+ }>, runner?: Runner): Promise<AgentGrantUsage>;
144
236
  export interface AgentGrantStatus {
145
237
  grantId: string;
146
238
  agentLabel: string | null;
@@ -188,7 +280,7 @@ export declare function budgetRunnerFor(req: Request, injected?: Runner, detache
188
280
  * principals pass through untouched: this hook is a no-op without a grant.
189
281
  * `runner` / `detached` are test seams; production picks them per request.
190
282
  */
191
- export declare function enforceAgentGrant(req: Request, runner?: Runner, detached?: boolean): Promise<unknown>;
283
+ export declare function enforceAgentGrant(req: Request, runner?: Runner, detached?: boolean, serviceName?: string): Promise<unknown>;
192
284
  export interface BudgetCharge {
193
285
  consumed: boolean;
194
286
  /** The UTC day the unit was charged to; the refund must name the same window. */
@@ -207,5 +299,16 @@ export declare function consumeDailyBudget(br: BudgetRunner | Runner, grant: Age
207
299
  * the new day's counter: the unit was spent yesterday, yesterday keeps it.
208
300
  */
209
301
  export declare function refundDailyBudget(br: BudgetRunner | Runner, grant: AgentGrantRow, window: string): Promise<void>;
302
+ /**
303
+ * One admitted call: `calls + 1` on (grant, UTC day, service, action). A
304
+ * conditional UPDATE first (the common path), an INSERT when the row does not
305
+ * exist yet, one more UPDATE when a racing request inserted it first. Runs on
306
+ * the hook's BudgetRunner and is AWAITED like every other write of the hook
307
+ * (see touchLastUsed), but never fails the request: usage is accounting, not
308
+ * admission. Returns the day the call was counted on (the refund names it).
309
+ */
310
+ export declare function recordGrantUsage(br: BudgetRunner | Runner, grant: AgentGrantRow, service: string, action: string, now?: Date): Promise<string>;
311
+ /** `refunded + 1` on the row the call was counted on: a refused request admitted nothing. */
312
+ export declare function refundGrantUsage(br: BudgetRunner | Runner, grant: AgentGrantRow, service: string, action: string, day: string): Promise<void>;
210
313
  export {};
211
314
  //# sourceMappingURL=agent-grants.d.ts.map