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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,211 @@
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`: CreateAgentGrant / RevokeAgentGrant /
18
+ * GetGrantStatus for CardanoAgentService, on top of the programmatic
19
+ * `issueAgentGrant` / `revokeAgentGrantById` that @odatano/x402 uses to sell
20
+ * grants.
21
+ *
22
+ * The token is a capability, not an identity: it never carries the operator's
23
+ * roles, so every `@requires: 'Admin'` surface refuses it by construction.
24
+ */
25
+ import cds, { Request } from '@sap/cds';
26
+ import { BackendError } from './errors';
27
+ export declare const AGENT_TOKEN_HEADER = "x-agent-token";
28
+ export declare const AGENT_TOKEN_PREFIX = "odat_";
29
+ /** Role every token principal carries; the only role it ever has. */
30
+ export declare const AGENT_ROLE = "agent-grant";
31
+ /** `agent:<grantId>`: the principal id a token request runs under. */
32
+ export declare const AGENT_PRINCIPAL_PREFIX = "agent:";
33
+ export declare const GRANTS_ENTITY = "odatano.cardano.CardanoAgentGrants";
34
+ /** The services the hook attaches to and the transport lane opens. */
35
+ export declare const AGENT_SERVICE_NAMES: readonly string[];
36
+ /**
37
+ * Actions an operator MAY put on a grant's allow list. Each call costs one
38
+ * budget unit (a build is the service an agent buys). Everything not here and
39
+ * not in AGENT_ALWAYS_ALLOWED_EVENTS is a hard 403 for token requests: HSM
40
+ * signing, pause/resume, grant administration are never grantable.
41
+ */
42
+ export declare const AGENT_ALLOWLISTABLE_ACTIONS: readonly string[];
43
+ /** Allow-listable actions that spend from a worker wallet: the grant must be pinned. */
44
+ export declare const AGENT_WALLET_ACTIONS: ReadonlySet<string>;
45
+ /**
46
+ * Events every valid token may use without an allow-list entry and without
47
+ * consuming budget: reads, compute-only actions, status polling. `READ` covers
48
+ * every entity set; row-level narrowing is done by the `$user.grantId`
49
+ * restrictions in the CDS models, not here.
50
+ */
51
+ export declare const AGENT_ALWAYS_ALLOWED_EVENTS: ReadonlySet<string>;
52
+ /** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
53
+ export declare const AGENT_JOB_KINDS: readonly string[];
54
+ /** Forget every rate-limit window (tests). */
55
+ export declare function __resetGrantRateLimiterForTests(): void;
56
+ export interface AgentGrantRow {
57
+ ID: string;
58
+ userId: string;
59
+ agentLabel?: string | null;
60
+ tokenHash?: string;
61
+ allowedActions: string;
62
+ walletId?: string | null;
63
+ allowedJobKinds?: string | null;
64
+ maxJobsPerDay?: number | null;
65
+ jobsUsedToday?: number | null;
66
+ budgetWindow?: string | null;
67
+ validUntil?: string | null;
68
+ isActive?: boolean;
69
+ revokedAt?: string | null;
70
+ createdAt?: string | null;
71
+ lastUsedAt?: string | null;
72
+ }
73
+ /** Anything that runs a CQL statement: the primary db service or one transaction of it. */
74
+ export type Runner = {
75
+ run: (q: unknown) => Promise<unknown>;
76
+ };
77
+ export declare function hashAgentToken(token: string): string;
78
+ export declare function agentPrincipalId(grantId: string): string;
79
+ /** The grant's JSON list column as an array; malformed or absent = empty. */
80
+ export declare function parseGrantList(raw: string | null | undefined): string[];
81
+ /** The grant a request runs under, or null for an ordinary principal. */
82
+ export declare function agentGrantOf(req: unknown): AgentGrantRow | null;
83
+ export type TokenResolution = {
84
+ ok: true;
85
+ grant: AgentGrantRow;
86
+ } | {
87
+ ok: false;
88
+ status: 401 | 410;
89
+ message: string;
90
+ };
91
+ /**
92
+ * Authenticate a bearer token: prefix, hash lookup among ACTIVE grants (a
93
+ * revoked grant is an unknown token, non-leaking), expiry. Detached from any
94
+ * ambient transaction: the lane runs before the request transaction exists,
95
+ * and on SQLite the pool holds one connection.
96
+ */
97
+ export declare function resolveAgentToken(token: string, runner?: Runner): Promise<TokenResolution>;
98
+ /**
99
+ * The principal a token request runs under. Deliberately NOT the operator and
100
+ * WITHOUT the operator's roles: `createdBy = $user` gates then scope to jobs
101
+ * this grant created, `$user.grantId` restrictions to its own grant row, and
102
+ * every `@requires: 'Admin'` refuses it.
103
+ */
104
+ export declare function makeAgentUser(grant: AgentGrantRow): cds.User;
105
+ export interface IssueAgentGrantInput {
106
+ allowedActions: string[];
107
+ walletId?: string | null;
108
+ allowedJobKinds?: string[] | null;
109
+ maxJobsPerDay?: number | null;
110
+ validUntil?: string | null;
111
+ agentLabel?: string | null;
112
+ }
113
+ export interface IssuedAgentGrant {
114
+ grantId: string;
115
+ /** Shown once. Never logged, never stored. */
116
+ token: string;
117
+ allowedActions: string[];
118
+ walletId: string | null;
119
+ allowedJobKinds: string[];
120
+ maxJobsPerDay: number | null;
121
+ validUntil: string | null;
122
+ }
123
+ /** A refused grant input; carries the 400 the action answers with. */
124
+ export declare class AgentGrantInputError extends BackendError {
125
+ constructor(message: string, target?: string);
126
+ }
127
+ interface NormalizedGrantInput {
128
+ allowedActions: string[];
129
+ walletId: string | null;
130
+ allowedJobKinds: string[];
131
+ maxJobsPerDay: number | null;
132
+ validUntil: string | null;
133
+ agentLabel: string | null;
134
+ }
135
+ export declare function validateGrantInput(input: IssueAgentGrantInput, now?: Date): NormalizedGrantInput;
136
+ /**
137
+ * Mint a grant for `operatorId`. Validation errors surface as
138
+ * AgentGrantInputError (400). The INSERT runs on `runner`: the action passes its
139
+ * request transaction, x402 passes whatever transaction its settlement runs in.
140
+ */
141
+ export declare function issueAgentGrant(input: IssueAgentGrantInput, operatorId: string, runner?: Runner): Promise<IssuedAgentGrant>;
142
+ /** Deactivate a grant; false when it does not exist or is already revoked. */
143
+ export declare function revokeAgentGrantById(grantId: string, runner?: Runner): Promise<boolean>;
144
+ export interface AgentGrantStatus {
145
+ grantId: string;
146
+ agentLabel: string | null;
147
+ allowedActions: string[];
148
+ walletId: string | null;
149
+ allowedJobKinds: string[];
150
+ maxJobsPerDay: number | null;
151
+ jobsUsedToday: number;
152
+ budgetWindow: string | null;
153
+ validUntil: string | null;
154
+ isActive: boolean;
155
+ }
156
+ export declare function toGrantStatus(grant: AgentGrantRow): AgentGrantStatus;
157
+ /** Validation rejections are thrown BEFORE any transaction work (project convention). */
158
+ export declare function registerAgentGrantHandlers(srv: cds.Service): void;
159
+ export declare function attachAgentGrantEnforcement(srv: cds.Service, runner?: Runner): void;
160
+ /**
161
+ * Exported for unit tests; see the module doc for the ladder. Ordinary
162
+ * principals pass through untouched: this hook is a no-op without a grant.
163
+ */
164
+ /**
165
+ * Where the hook's own writes go.
166
+ *
167
+ * Default: DETACHED from the request transaction (`runWithoutAmbientTx`), so
168
+ * the spend sticks even when the request later fails and no write lock is held
169
+ * across the handler's backend round trips.
170
+ *
171
+ * Exception: a request that already sits inside an open transaction — the
172
+ * second and later parts of a `$batch` changeset (atomicity group) — owns the
173
+ * pooled connection. On SQLite the pool has one connection, so a detached
174
+ * statement would wait for it until the changeset commits, which waits for
175
+ * this hook: a deadlock. Such a request rides its own transaction instead; the
176
+ * changeset's rollback is then the refund, and no `failed` listener is needed.
177
+ * `ready` is set the moment CAP begins the transaction, `dbc` once the
178
+ * connection is acquired; either means "already open".
179
+ */
180
+ export interface BudgetRunner {
181
+ runner: Runner;
182
+ /** true: statements run outside the request transaction (and a refused request is refunded). */
183
+ detached: boolean;
184
+ }
185
+ export declare function budgetRunnerFor(req: Request, injected?: Runner, detached?: boolean): BudgetRunner;
186
+ /**
187
+ * Exported for unit tests; see the module doc for the ladder. Ordinary
188
+ * principals pass through untouched: this hook is a no-op without a grant.
189
+ * `runner` / `detached` are test seams; production picks them per request.
190
+ */
191
+ export declare function enforceAgentGrant(req: Request, runner?: Runner, detached?: boolean): Promise<unknown>;
192
+ export interface BudgetCharge {
193
+ consumed: boolean;
194
+ /** The UTC day the unit was charged to; the refund must name the same window. */
195
+ window: string;
196
+ }
197
+ /**
198
+ * Consume one unit of the grant's daily budget. Two conditional UPDATEs so
199
+ * concurrent requests cannot overspend: a window reset (compare-and-swap on
200
+ * the OLD window value) and a bounded increment (`jobsUsedToday < max`). Runs
201
+ * on the BudgetRunner the hook chose (detached by default, see budgetRunnerFor).
202
+ */
203
+ export declare function consumeDailyBudget(br: BudgetRunner | Runner, grant: AgentGrantRow): Promise<BudgetCharge>;
204
+ /**
205
+ * Undo one consumeDailyBudget in the window it was charged to (a refused
206
+ * request created nothing). A refund that lands after midnight must not touch
207
+ * the new day's counter: the unit was spent yesterday, yesterday keeps it.
208
+ */
209
+ export declare function refundDailyBudget(br: BudgetRunner | Runner, grant: AgentGrantRow, window: string): Promise<void>;
210
+ export {};
211
+ //# sourceMappingURL=agent-grants.d.ts.map