@odatano/core 2.0.0-rc.4 → 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.
Files changed (35) 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 +28 -0
  4. package/@cds-models/CardanoIndexerService/index.js +4 -0
  5. package/@cds-models/odatano/cardano/index.d.ts +86 -0
  6. package/@cds-models/odatano/cardano/index.js +6 -0
  7. package/README.md +53 -3
  8. package/db/schema.cds +105 -0
  9. package/package.json +4 -3
  10. package/src/index.d.ts +6 -0
  11. package/src/index.js +21 -1
  12. package/src/plugin.js +33 -30
  13. package/srv/blockchain/backends/ogmios-backend.d.ts +23 -3
  14. package/srv/blockchain/backends/ogmios-backend.js +72 -5
  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 +150 -0
  20. package/srv/cardano-agent-service.d.ts +2 -0
  21. package/srv/cardano-agent-service.js +16 -0
  22. package/srv/cardano-indexer-service.cds +20 -0
  23. package/srv/cardano-indexer-service.js +3 -0
  24. package/srv/server.d.ts +2 -1
  25. package/srv/server.js +12 -0
  26. package/srv/utils/agent-grants-config.d.ts +64 -0
  27. package/srv/utils/agent-grants-config.js +144 -0
  28. package/srv/utils/agent-grants.d.ts +314 -0
  29. package/srv/utils/agent-grants.js +821 -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/liveness.d.ts +23 -0
  33. package/srv/utils/liveness.js +49 -0
  34. package/srv/utils/rate-limiter.d.ts +57 -0
  35. package/srv/utils/rate-limiter.js +126 -0
@@ -0,0 +1,314 @@
1
+ /**
2
+ * Agent grants: scoped, budgeted bearer capabilities for agents.
3
+ * Design: AGENT_GRANTS_DESIGN.md. Reference: NIGHTGATE srv/sessions/agent-grants.ts.
4
+ *
5
+ * Three exports carry the feature:
6
+ * - `resolveAgentToken` + `makeAgentUser`: used by the transport lane
7
+ * (agent-token-auth.ts) to turn an `x-agent-token` header into the principal
8
+ * `agent:<grantId>` with the role `agent-grant` BEFORE any service hook runs.
9
+ * Doing the authentication at the transport (not in a before-hook) matters:
10
+ * CAP runs before-handlers in parallel, so CAP's own @requires / @restrict
11
+ * evaluation must already see the final principal.
12
+ * - `attachAgentGrantEnforcement`: the before('*') hook on all six ODATANO
13
+ * services. Allow list (403), wallet pinning (403), daily budget (429),
14
+ * lastUsedAt. Ownership needs no special code: a token's jobs are created
15
+ * with createdBy = `agent:<grantId>`, so the existing `createdBy = $user`
16
+ * gates and the `$user.grantId` row restrictions do the narrowing.
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.
24
+ *
25
+ * The token is a capability, not an identity: it never carries the operator's
26
+ * roles, so every `@requires: 'Admin'` surface refuses it by construction.
27
+ */
28
+ import cds, { Request } from '@sap/cds';
29
+ import { BackendError } from './errors';
30
+ export declare const AGENT_TOKEN_HEADER = "x-agent-token";
31
+ export declare const AGENT_TOKEN_PREFIX = "odat_";
32
+ /** Role every token principal carries; the only role it ever has. */
33
+ export declare const AGENT_ROLE = "agent-grant";
34
+ /** `agent:<grantId>`: the principal id a token request runs under. */
35
+ export declare const AGENT_PRINCIPAL_PREFIX = "agent:";
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";
39
+ /** The services the hook attaches to and the transport lane opens. */
40
+ export declare const AGENT_SERVICE_NAMES: readonly string[];
41
+ /**
42
+ * Actions an operator MAY put on a grant's allow list. Each call costs one
43
+ * budget unit (a build is the service an agent buys). Everything not here and
44
+ * not in AGENT_ALWAYS_ALLOWED_EVENTS is a hard 403 for token requests: HSM
45
+ * signing, pause/resume, grant administration are never grantable.
46
+ */
47
+ export declare const AGENT_ALLOWLISTABLE_ACTIONS: readonly string[];
48
+ /** Allow-listable actions that spend from a worker wallet: the grant must be pinned. */
49
+ export declare const AGENT_WALLET_ACTIONS: ReadonlySet<string>;
50
+ /**
51
+ * Events every valid token may use without an allow-list entry and without
52
+ * consuming budget: reads, compute-only actions, status polling. `READ` covers
53
+ * every entity set; row-level narrowing is done by the `$user.grantId`
54
+ * restrictions in the CDS models, not here.
55
+ */
56
+ export declare const AGENT_ALWAYS_ALLOWED_EVENTS: ReadonlySet<string>;
57
+ /** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
58
+ export declare const AGENT_JOB_KINDS: readonly string[];
59
+ /** Forget every rate-limit window and re-read the limit from the config (tests). */
60
+ export declare function __resetGrantRateLimiterForTests(): void;
61
+ export interface AgentGrantRow {
62
+ ID: string;
63
+ userId: string;
64
+ agentLabel?: string | null;
65
+ tokenHash?: string;
66
+ allowedActions: string;
67
+ walletId?: string | null;
68
+ allowedJobKinds?: string | null;
69
+ maxJobsPerDay?: number | null;
70
+ jobsUsedToday?: number | null;
71
+ budgetWindow?: string | null;
72
+ validUntil?: string | null;
73
+ isActive?: boolean;
74
+ revokedAt?: string | null;
75
+ createdAt?: string | null;
76
+ lastUsedAt?: string | null;
77
+ }
78
+ /** Anything that runs a CQL statement: the primary db service or one transaction of it. */
79
+ export type Runner = {
80
+ run: (q: unknown) => Promise<unknown>;
81
+ };
82
+ export declare function hashAgentToken(token: string): string;
83
+ export declare function agentPrincipalId(grantId: string): string;
84
+ /** The grant's JSON list column as an array; malformed or absent = empty. */
85
+ export declare function parseGrantList(raw: string | null | undefined): string[];
86
+ /** The grant a request runs under, or null for an ordinary principal. */
87
+ export declare function agentGrantOf(req: unknown): AgentGrantRow | null;
88
+ export type TokenResolution = {
89
+ ok: true;
90
+ grant: AgentGrantRow;
91
+ } | {
92
+ ok: false;
93
+ status: 401 | 410;
94
+ message: string;
95
+ };
96
+ /**
97
+ * Authenticate a bearer token: prefix, hash lookup among ACTIVE grants (a
98
+ * revoked grant is an unknown token, non-leaking), expiry. Detached from any
99
+ * ambient transaction: the lane runs before the request transaction exists,
100
+ * and on SQLite the pool holds one connection.
101
+ */
102
+ export declare function resolveAgentToken(token: string, runner?: Runner): Promise<TokenResolution>;
103
+ /**
104
+ * The principal a token request runs under. Deliberately NOT the operator and
105
+ * WITHOUT the operator's roles: `createdBy = $user` gates then scope to jobs
106
+ * this grant created, `$user.grantId` restrictions to its own grant row, and
107
+ * every `@requires: 'Admin'` refuses it.
108
+ */
109
+ export declare function makeAgentUser(grant: AgentGrantRow): cds.User;
110
+ export interface IssueAgentGrantInput {
111
+ allowedActions: string[];
112
+ walletId?: string | null;
113
+ allowedJobKinds?: string[] | null;
114
+ maxJobsPerDay?: number | null;
115
+ validUntil?: string | null;
116
+ agentLabel?: string | null;
117
+ }
118
+ export interface IssuedAgentGrant {
119
+ grantId: string;
120
+ /** Shown once. Never logged, never stored. */
121
+ token: string;
122
+ allowedActions: string[];
123
+ walletId: string | null;
124
+ allowedJobKinds: string[];
125
+ maxJobsPerDay: number | null;
126
+ validUntil: string | null;
127
+ }
128
+ /** A refused grant input; carries the 400 the action answers with. */
129
+ export declare class AgentGrantInputError extends BackendError {
130
+ constructor(message: string, target?: string, context?: string);
131
+ }
132
+ interface NormalizedGrantInput {
133
+ allowedActions: string[];
134
+ walletId: string | null;
135
+ allowedJobKinds: string[];
136
+ maxJobsPerDay: number | null;
137
+ validUntil: string | null;
138
+ agentLabel: string | null;
139
+ }
140
+ export declare function validateGrantInput(input: IssueAgentGrantInput, now?: Date, context?: string): NormalizedGrantInput;
141
+ /**
142
+ * Mint a grant for `operatorId`. Validation errors surface as
143
+ * AgentGrantInputError (400). The INSERT runs on `runner`: the action passes its
144
+ * request transaction, x402 passes whatever transaction its settlement runs in.
145
+ */
146
+ export declare function issueAgentGrant(input: IssueAgentGrantInput, operatorId: string, runner?: Runner): Promise<IssuedAgentGrant>;
147
+ /** Deactivate a grant; false when it does not exist or is already revoked. */
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>;
236
+ export interface AgentGrantStatus {
237
+ grantId: string;
238
+ agentLabel: string | null;
239
+ allowedActions: string[];
240
+ walletId: string | null;
241
+ allowedJobKinds: string[];
242
+ maxJobsPerDay: number | null;
243
+ jobsUsedToday: number;
244
+ budgetWindow: string | null;
245
+ validUntil: string | null;
246
+ isActive: boolean;
247
+ }
248
+ export declare function toGrantStatus(grant: AgentGrantRow): AgentGrantStatus;
249
+ /** Validation rejections are thrown BEFORE any transaction work (project convention). */
250
+ export declare function registerAgentGrantHandlers(srv: cds.Service): void;
251
+ export declare function attachAgentGrantEnforcement(srv: cds.Service, runner?: Runner): void;
252
+ /**
253
+ * Exported for unit tests; see the module doc for the ladder. Ordinary
254
+ * principals pass through untouched: this hook is a no-op without a grant.
255
+ */
256
+ /**
257
+ * Where the hook's own writes go.
258
+ *
259
+ * Default: DETACHED from the request transaction (`runWithoutAmbientTx`), so
260
+ * the spend sticks even when the request later fails and no write lock is held
261
+ * across the handler's backend round trips.
262
+ *
263
+ * Exception: a request that already sits inside an open transaction — the
264
+ * second and later parts of a `$batch` changeset (atomicity group) — owns the
265
+ * pooled connection. On SQLite the pool has one connection, so a detached
266
+ * statement would wait for it until the changeset commits, which waits for
267
+ * this hook: a deadlock. Such a request rides its own transaction instead; the
268
+ * changeset's rollback is then the refund, and no `failed` listener is needed.
269
+ * `ready` is set the moment CAP begins the transaction, `dbc` once the
270
+ * connection is acquired; either means "already open".
271
+ */
272
+ export interface BudgetRunner {
273
+ runner: Runner;
274
+ /** true: statements run outside the request transaction (and a refused request is refunded). */
275
+ detached: boolean;
276
+ }
277
+ export declare function budgetRunnerFor(req: Request, injected?: Runner, detached?: boolean): BudgetRunner;
278
+ /**
279
+ * Exported for unit tests; see the module doc for the ladder. Ordinary
280
+ * principals pass through untouched: this hook is a no-op without a grant.
281
+ * `runner` / `detached` are test seams; production picks them per request.
282
+ */
283
+ export declare function enforceAgentGrant(req: Request, runner?: Runner, detached?: boolean, serviceName?: string): Promise<unknown>;
284
+ export interface BudgetCharge {
285
+ consumed: boolean;
286
+ /** The UTC day the unit was charged to; the refund must name the same window. */
287
+ window: string;
288
+ }
289
+ /**
290
+ * Consume one unit of the grant's daily budget. Two conditional UPDATEs so
291
+ * concurrent requests cannot overspend: a window reset (compare-and-swap on
292
+ * the OLD window value) and a bounded increment (`jobsUsedToday < max`). Runs
293
+ * on the BudgetRunner the hook chose (detached by default, see budgetRunnerFor).
294
+ */
295
+ export declare function consumeDailyBudget(br: BudgetRunner | Runner, grant: AgentGrantRow): Promise<BudgetCharge>;
296
+ /**
297
+ * Undo one consumeDailyBudget in the window it was charged to (a refused
298
+ * request created nothing). A refund that lands after midnight must not touch
299
+ * the new day's counter: the unit was spent yesterday, yesterday keeps it.
300
+ */
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>;
313
+ export {};
314
+ //# sourceMappingURL=agent-grants.d.ts.map