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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +151 -0
  2. package/@cds-models/CardanoAgentService/index.js +21 -0
  3. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  4. package/@cds-models/odatano/cardano/index.d.ts +50 -0
  5. package/@cds-models/odatano/cardano/index.js +3 -0
  6. package/README.md +31 -0
  7. package/db/schema.cds +72 -0
  8. package/package.json +173 -173
  9. package/src/index.d.ts +6 -0
  10. package/src/index.js +17 -1
  11. package/src/plugin.js +33 -30
  12. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
  13. package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
  14. package/srv/blockchain/wallet-worker/build-request.js +35 -6
  15. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +32 -1
  16. package/srv/blockchain/wallet-worker/confirmation-tracker.js +91 -29
  17. package/srv/blockchain/wallet-worker/job-store.d.ts +11 -0
  18. package/srv/blockchain/wallet-worker/job-store.js +42 -9
  19. package/srv/cardano-agent-service.cds +84 -0
  20. package/srv/cardano-agent-service.d.ts +2 -0
  21. package/srv/cardano-agent-service.js +16 -0
  22. package/srv/cardano-tx-service.cds +32 -26
  23. package/srv/cardano-tx-service.js +96 -38
  24. package/srv/server.d.ts +2 -1
  25. package/srv/server.js +12 -0
  26. package/srv/utils/agent-grants-config.d.ts +48 -0
  27. package/srv/utils/agent-grants-config.js +124 -0
  28. package/srv/utils/agent-grants.d.ts +211 -0
  29. package/srv/utils/agent-grants.js +541 -0
  30. package/srv/utils/agent-token-auth.d.ts +106 -0
  31. package/srv/utils/agent-token-auth.js +239 -0
  32. package/srv/utils/rate-limiter.d.ts +57 -0
  33. package/srv/utils/rate-limiter.js +126 -0
  34. package/srv/utils/tx-request-parsers.d.ts +13 -0
  35. package/srv/utils/tx-request-parsers.js +32 -0
  36. package/srv/utils/types.d.ts +15 -0
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.AGENT_GRANTS_DELEGATES = void 0;
7
+ exports.configuredAuth = configuredAuth;
8
+ exports.customAuthImpl = customAuthImpl;
9
+ exports.loadAgentGrantsConfig = loadAgentGrantsConfig;
10
+ exports.activateAgentGrants = activateAgentGrants;
11
+ const cds_1 = __importDefault(require("@sap/cds"));
12
+ const path_1 = __importDefault(require("path"));
13
+ exports.AGENT_GRANTS_DELEGATES = ['mocked', 'basic', 'jwt', 'xsuaa', 'ias', 'dummy'];
14
+ function envRecord() {
15
+ const requires = (cds_1.default.env?.requires ?? {});
16
+ const core = (requires['odatano-core'] ?? {});
17
+ return (core.agentGrants ?? {});
18
+ }
19
+ /** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
20
+ function configuredAuth() {
21
+ const auth = cds_1.default.env?.requires?.auth;
22
+ if (typeof auth === 'string')
23
+ return { kind: auth };
24
+ return (auth ?? {});
25
+ }
26
+ /** Our own middleware module, recognisable in `auth.impl` so activation stays idempotent. */
27
+ const OUR_IMPL = 'agent-token-auth';
28
+ /**
29
+ * A custom `cds.requires.auth.impl` the host configured before us (anything
30
+ * that is not this package's middleware). It keeps authenticating every
31
+ * non-token request: the lane wraps it instead of replacing it.
32
+ */
33
+ function customAuthImpl(auth = configuredAuth()) {
34
+ const impl = typeof auth.impl === 'string' ? auth.impl.trim() : '';
35
+ if (!impl || impl.includes(OUR_IMPL))
36
+ return null;
37
+ return impl;
38
+ }
39
+ function loadAgentGrantsConfig(env = process.env) {
40
+ const cfg = envRecord();
41
+ const enabledRaw = cfg.enabled !== undefined ? cfg.enabled : env.AGENT_GRANTS_ENABLED;
42
+ const enabled = enabledRaw === true || String(enabledRaw ?? '').toLowerCase() === 'true';
43
+ const auth = configuredAuth();
44
+ const authKind = String(auth.kind ?? 'mocked');
45
+ // A host with its own auth.impl keeps it as the delegate ("custom") unless
46
+ // an explicit delegate says otherwise.
47
+ const fallback = customAuthImpl(auth) ? 'custom' : authKind;
48
+ const delegateRaw = String(cfg.delegate ?? env.AGENT_GRANTS_DELEGATE ?? fallback);
49
+ // `xsuaa-auth` / `basic-auth` spellings are what CAP itself accepts as kinds.
50
+ const delegate = delegateRaw.replace(/-auth$/, '');
51
+ if (enabled && delegate !== 'custom' && !exports.AGENT_GRANTS_DELEGATES.includes(delegate)) {
52
+ throw new Error(`Invalid agentGrants.delegate "${delegateRaw}". Must be one of: ${exports.AGENT_GRANTS_DELEGATES.join(', ')}, custom`);
53
+ }
54
+ if (enabled && delegate === 'custom' && !customAuthImpl(auth)) {
55
+ throw new Error('agentGrants.delegate "custom" needs a custom cds.requires.auth.impl to delegate to');
56
+ }
57
+ return { enabled, delegate };
58
+ }
59
+ /**
60
+ * Marker on the shared `cds` facade: the activation below must run exactly once
61
+ * per process even though this module can be loaded twice (natively by CAP /
62
+ * src/plugin.ts and again through a test runner's transform). A module-level
63
+ * flag would not survive that; the `cds` singleton does.
64
+ */
65
+ const ACTIVATED = Symbol.for('odatano.agentGrants.activated');
66
+ /**
67
+ * Switch agent grants on for this process when configured. Called from BOTH
68
+ * entry points, because CAP loads `cds-plugin.js` only from a project's
69
+ * dependencies, never from the project itself:
70
+ * - src/plugin.ts at plugin load (consumer app), and
71
+ * - srv/server.ts at module load (standalone `cds serve` / `cds watch`, where
72
+ * bin/serve.js imports the local server.js BEFORE cds.server() builds its
73
+ * middlewares — the last moment `cds.requires.auth.impl` can still change).
74
+ *
75
+ * When enabled:
76
+ * - the transport auth becomes srv/utils/agent-token-auth, which admits the
77
+ * `x-agent-token` header on the six service paths and delegates every other
78
+ * request to the strategy that was configured before (kept as the delegate);
79
+ * - each of the six services gets the enforcement hook once it is served.
80
+ *
81
+ * Never throws: a misconfiguration is logged and the feature stays off, so a
82
+ * host app never fails to start because of it. Returns whether grants are on.
83
+ */
84
+ function activateAgentGrants() {
85
+ const facade = cds_1.default;
86
+ if (facade[ACTIVATED] !== undefined)
87
+ return facade[ACTIVATED] === true;
88
+ const logger = cds_1.default.log('ODATANO');
89
+ try {
90
+ const agentGrants = loadAgentGrantsConfig();
91
+ if (!agentGrants.enabled) {
92
+ facade[ACTIVATED] = false;
93
+ return false;
94
+ }
95
+ const auth = configuredAuth();
96
+ const current = typeof auth.impl === 'string' ? auth.impl : '';
97
+ if (!current.includes(OUR_IMPL)) {
98
+ // A host's own auth.impl is preserved as the delegate: the lane only adds
99
+ // the token path in front of it, it never replaces the host's gate.
100
+ const original = customAuthImpl(auth);
101
+ cds_1.default.env.requires.auth = {
102
+ ...auth,
103
+ kind: auth.kind ?? agentGrants.delegate,
104
+ impl: path_1.default.join(__dirname, OUR_IMPL),
105
+ agentGrantsDelegate: agentGrants.delegate,
106
+ ...(original ? { agentGrantsDelegateImpl: original } : {})
107
+ };
108
+ }
109
+ cds_1.default.on('serving', (srv) => {
110
+ const { AGENT_SERVICE_NAMES, attachAgentGrantEnforcement } = require('./agent-grants');
111
+ if (AGENT_SERVICE_NAMES.includes(srv.name))
112
+ attachAgentGrantEnforcement(srv);
113
+ });
114
+ facade[ACTIVATED] = true;
115
+ logger.info(`Agent grants enabled (transport delegate: ${agentGrants.delegate})`);
116
+ return true;
117
+ }
118
+ catch (err) {
119
+ facade[ACTIVATED] = false;
120
+ logger.error('Agent grants not enabled:', err instanceof Error ? err.message : err);
121
+ return false;
122
+ }
123
+ }
124
+ //# sourceMappingURL=agent-grants-config.js.map
@@ -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