@odatano/core 2.0.0-rc.2 → 2.0.0-rc.20
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.
- package/@cds-models/CardanoAgentService/index.d.ts +251 -0
- package/@cds-models/CardanoAgentService/index.js +36 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +139 -2
- package/@cds-models/CardanoIndexerService/index.js +18 -0
- package/@cds-models/CardanoODataService/index.d.ts +224 -0
- package/@cds-models/CardanoODataService/index.js +27 -0
- package/@cds-models/CardanoSignService/index.d.ts +5 -2
- package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
- package/@cds-models/odatano/cardano/index.d.ts +316 -0
- package/@cds-models/odatano/cardano/index.js +33 -0
- package/README.md +195 -136
- package/db/schema.cds +2121 -1633
- package/package.json +179 -173
- package/src/index.d.ts +10 -10
- package/src/index.js +24 -14
- package/src/plugin.js +39 -52
- package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
- package/srv/blockchain/backends/blockfrost-backend.js +45 -158
- package/srv/blockchain/backends/cardano-backend.d.ts +78 -158
- package/srv/blockchain/backends/cardano-backend.js +14 -5
- package/srv/blockchain/backends/koios-backend.d.ts +126 -60
- package/srv/blockchain/backends/koios-backend.js +292 -202
- package/srv/blockchain/backends/ogmios-backend.d.ts +59 -96
- package/srv/blockchain/backends/ogmios-backend.js +241 -153
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
- package/srv/blockchain/cardano-client.d.ts +50 -205
- package/srv/blockchain/cardano-client.js +80 -224
- package/srv/blockchain/cardano-indexer.d.ts +146 -244
- package/srv/blockchain/cardano-indexer.js +442 -285
- package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
- package/srv/blockchain/cardano-tx-builder.js +21 -107
- package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
- package/srv/blockchain/crawler/certificate-backfill.js +150 -0
- package/srv/blockchain/crawler/crawler.d.ts +121 -53
- package/srv/blockchain/crawler/crawler.js +402 -82
- package/srv/blockchain/crawler/hooks.d.ts +3 -14
- package/srv/blockchain/crawler/index.d.ts +5 -0
- package/srv/blockchain/crawler/index.js +35 -7
- package/srv/blockchain/crawler/sync-state.d.ts +44 -28
- package/srv/blockchain/crawler/sync-state.js +115 -43
- package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
- package/srv/blockchain/crawler/utxo-set-import.js +269 -0
- package/srv/blockchain/ledger-state.d.ts +80 -0
- package/srv/blockchain/ledger-state.js +383 -0
- package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
- package/srv/blockchain/signing/cose-verifier.js +6 -12
- package/srv/blockchain/signing/external-signer.d.ts +16 -113
- package/srv/blockchain/signing/external-signer.js +19 -122
- package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
- package/srv/blockchain/signing/hsm-signer.js +23 -63
- package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
- package/srv/blockchain/signing/signature-verifier.js +13 -54
- package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
- package/srv/blockchain/signing/submission-finalizer.js +16 -48
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
- package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
- package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
- package/srv/blockchain/wallet-worker/build-request.js +39 -23
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
- package/srv/blockchain/wallet-worker/index.js +2 -8
- package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
- package/srv/blockchain/wallet-worker/job-store.js +0 -0
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
- package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
- package/srv/blockchain/wallet-worker/signers.js +3 -8
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
- package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
- package/srv/cardano-agent-service.cds +146 -0
- package/srv/cardano-agent-service.d.ts +2 -0
- package/srv/cardano-agent-service.js +12 -0
- package/srv/cardano-indexer-service.cds +164 -73
- package/srv/cardano-indexer-service.js +156 -11
- package/srv/cardano-service.cds +45 -0
- package/srv/cardano-service.js +38 -96
- package/srv/cardano-sign-service.cds +200 -180
- package/srv/cardano-sign-service.js +55 -173
- package/srv/cardano-tx-service.cds +32 -26
- package/srv/cardano-tx-service.js +133 -195
- package/srv/cardano-worker-service.js +7 -15
- package/srv/server.d.ts +28 -86
- package/srv/server.js +95 -128
- package/srv/utils/agent-grants-config.d.ts +37 -0
- package/srv/utils/agent-grants-config.js +138 -0
- package/srv/utils/agent-grants.d.ts +262 -0
- package/srv/utils/agent-grants.js +914 -0
- package/srv/utils/agent-token-auth.d.ts +16 -0
- package/srv/utils/agent-token-auth.js +78 -0
- package/srv/utils/backend-request-handler.d.ts +2 -16
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/collections.d.ts +4 -8
- package/srv/utils/collections.js +4 -8
- package/srv/utils/const.d.ts +19 -68
- package/srv/utils/const.js +20 -69
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +5 -18
- package/srv/utils/db-indexes.d.ts +25 -0
- package/srv/utils/db-indexes.js +89 -0
- package/srv/utils/db-sanitize.d.ts +27 -0
- package/srv/utils/db-sanitize.js +85 -0
- package/srv/utils/error-codes.d.ts +18 -73
- package/srv/utils/error-codes.js +17 -70
- package/srv/utils/errors.d.ts +34 -178
- package/srv/utils/errors.js +55 -217
- package/srv/utils/liveness.d.ts +16 -0
- package/srv/utils/liveness.js +41 -0
- package/srv/utils/mappers.d.ts +82 -210
- package/srv/utils/mappers.js +272 -293
- package/srv/utils/network-context.js +2 -11
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +57 -0
- package/srv/utils/plutus-placeholders.d.ts +6 -18
- package/srv/utils/plutus-placeholders.js +6 -20
- package/srv/utils/rate-limiter.d.ts +46 -0
- package/srv/utils/rate-limiter.js +116 -0
- package/srv/utils/service-events.d.ts +2 -22
- package/srv/utils/service-events.js +3 -23
- package/srv/utils/signing-helper.d.ts +3 -18
- package/srv/utils/signing-helper.js +10 -32
- package/srv/utils/tx-build-helper.d.ts +18 -92
- package/srv/utils/tx-build-helper.js +32 -123
- package/srv/utils/tx-request-parsers.d.ts +14 -20
- package/srv/utils/tx-request-parsers.js +33 -20
- package/srv/utils/tx-utils.d.ts +4 -23
- package/srv/utils/tx-utils.js +12 -41
- package/srv/utils/types.d.ts +112 -169
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +19 -89
- package/srv/utils/validators.js +31 -138
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent-grant feature switch from `cds.requires.odatano-core.agentGrants`, else the environment
|
|
3
|
+
* (AGENT_GRANTS_ENABLED, AGENT_GRANTS_DELEGATE, AGENT_GRANT_ADMIN_RATE_LIMIT). Own module because
|
|
4
|
+
* src/plugin.ts reads it at plugin load, before any blockchain module is required.
|
|
5
|
+
*/
|
|
6
|
+
export interface AgentGrantsConfig {
|
|
7
|
+
enabled: boolean;
|
|
8
|
+
/** CAP auth kind the transport middleware delegates to for non-token requests. */
|
|
9
|
+
delegate: string;
|
|
10
|
+
/** Grant administration calls per principal per hour (integer >= 1). */
|
|
11
|
+
adminRateLimit: number;
|
|
12
|
+
}
|
|
13
|
+
export declare const AGENT_GRANTS_DELEGATES: readonly string[];
|
|
14
|
+
export declare const AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = 10;
|
|
15
|
+
/**
|
|
16
|
+
* Grant-administration calls per principal per hour: `agentGrants.adminRateLimit`, then
|
|
17
|
+
* `AGENT_GRANT_ADMIN_RATE_LIMIT`, default 10. An unusable value is logged and falls back, never disables the feature.
|
|
18
|
+
*/
|
|
19
|
+
export declare function loadGrantAdminRateLimit(env?: Record<string, string | undefined>): number;
|
|
20
|
+
export declare const AGENT_TOKEN_CACHE_MS_DEFAULT = 10000;
|
|
21
|
+
/**
|
|
22
|
+
* How long the transport lane reuses a resolved grant row before re-reading the DB: `agentGrants.tokenCacheMs`,
|
|
23
|
+
* then `AGENT_TOKEN_CACHE_MS`, default 10 s, 0 disables. Bounds how late a revoke on another replica takes effect.
|
|
24
|
+
*/
|
|
25
|
+
export declare function loadTokenCacheMs(env?: Record<string, string | undefined>): number;
|
|
26
|
+
/** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
|
|
27
|
+
export declare function configuredAuth(): Record<string, unknown>;
|
|
28
|
+
/** A host-configured custom `cds.requires.auth.impl` (not this package's middleware); the lane wraps it. */
|
|
29
|
+
export declare function customAuthImpl(auth?: Record<string, unknown>): string | null;
|
|
30
|
+
export declare function loadAgentGrantsConfig(env?: Record<string, string | undefined>): AgentGrantsConfig;
|
|
31
|
+
/**
|
|
32
|
+
* Switch agent grants on when configured: installs @odatano/cap-auth with the `x-agent-token` lane
|
|
33
|
+
* (previous strategy kept as delegate) and attaches the enforcement hook to each service on `serving`.
|
|
34
|
+
* Called from src/plugin.ts and srv/server.ts, before cds.server() builds middlewares. Never throws.
|
|
35
|
+
*/
|
|
36
|
+
export declare function activateAgentGrants(): boolean;
|
|
37
|
+
//# sourceMappingURL=agent-grants-config.d.ts.map
|
|
@@ -0,0 +1,138 @@
|
|
|
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_TOKEN_CACHE_MS_DEFAULT = exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = exports.AGENT_GRANTS_DELEGATES = void 0;
|
|
7
|
+
exports.loadGrantAdminRateLimit = loadGrantAdminRateLimit;
|
|
8
|
+
exports.loadTokenCacheMs = loadTokenCacheMs;
|
|
9
|
+
exports.configuredAuth = configuredAuth;
|
|
10
|
+
exports.customAuthImpl = customAuthImpl;
|
|
11
|
+
exports.loadAgentGrantsConfig = loadAgentGrantsConfig;
|
|
12
|
+
exports.activateAgentGrants = activateAgentGrants;
|
|
13
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
14
|
+
exports.AGENT_GRANTS_DELEGATES = ['mocked', 'basic', 'jwt', 'xsuaa', 'ias', 'dummy'];
|
|
15
|
+
exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = 10;
|
|
16
|
+
/**
|
|
17
|
+
* Grant-administration calls per principal per hour: `agentGrants.adminRateLimit`, then
|
|
18
|
+
* `AGENT_GRANT_ADMIN_RATE_LIMIT`, default 10. An unusable value is logged and falls back, never disables the feature.
|
|
19
|
+
*/
|
|
20
|
+
function loadGrantAdminRateLimit(env = process.env) {
|
|
21
|
+
const cfg = envRecord();
|
|
22
|
+
const raw = cfg.adminRateLimit !== undefined ? cfg.adminRateLimit : env.AGENT_GRANT_ADMIN_RATE_LIMIT;
|
|
23
|
+
if (raw === undefined || raw === null || String(raw).trim() === '')
|
|
24
|
+
return exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT;
|
|
25
|
+
const n = Number(raw);
|
|
26
|
+
if (!Number.isInteger(n) || n < 1) {
|
|
27
|
+
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}`);
|
|
28
|
+
return exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT;
|
|
29
|
+
}
|
|
30
|
+
return n;
|
|
31
|
+
}
|
|
32
|
+
exports.AGENT_TOKEN_CACHE_MS_DEFAULT = 10_000;
|
|
33
|
+
/**
|
|
34
|
+
* How long the transport lane reuses a resolved grant row before re-reading the DB: `agentGrants.tokenCacheMs`,
|
|
35
|
+
* then `AGENT_TOKEN_CACHE_MS`, default 10 s, 0 disables. Bounds how late a revoke on another replica takes effect.
|
|
36
|
+
*/
|
|
37
|
+
function loadTokenCacheMs(env = process.env) {
|
|
38
|
+
const cfg = envRecord();
|
|
39
|
+
const raw = cfg.tokenCacheMs !== undefined ? cfg.tokenCacheMs : env.AGENT_TOKEN_CACHE_MS;
|
|
40
|
+
if (raw === undefined || raw === null || String(raw).trim() === '')
|
|
41
|
+
return exports.AGENT_TOKEN_CACHE_MS_DEFAULT;
|
|
42
|
+
const n = Number(raw);
|
|
43
|
+
if (!Number.isInteger(n) || n < 0) {
|
|
44
|
+
cds_1.default.log('ODATANO').warn(`AGENT_TOKEN_CACHE_MS "${String(raw)}" is not an integer >= 0; using ${exports.AGENT_TOKEN_CACHE_MS_DEFAULT}`);
|
|
45
|
+
return exports.AGENT_TOKEN_CACHE_MS_DEFAULT;
|
|
46
|
+
}
|
|
47
|
+
return n;
|
|
48
|
+
}
|
|
49
|
+
function envRecord() {
|
|
50
|
+
const requires = (cds_1.default.env?.requires ?? {});
|
|
51
|
+
const core = (requires['odatano-core'] ?? {});
|
|
52
|
+
return (core.agentGrants ?? {});
|
|
53
|
+
}
|
|
54
|
+
/** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
|
|
55
|
+
function configuredAuth() {
|
|
56
|
+
const auth = cds_1.default.env?.requires?.auth;
|
|
57
|
+
if (typeof auth === 'string')
|
|
58
|
+
return { kind: auth };
|
|
59
|
+
return (auth ?? {});
|
|
60
|
+
}
|
|
61
|
+
/** The transport middleware, recognisable in `auth.impl` so activation stays idempotent. */
|
|
62
|
+
const OUR_IMPL = 'cap-auth';
|
|
63
|
+
/** A host-configured custom `cds.requires.auth.impl` (not this package's middleware); the lane wraps it. */
|
|
64
|
+
function customAuthImpl(auth = configuredAuth()) {
|
|
65
|
+
const impl = typeof auth.impl === 'string' ? auth.impl.trim() : '';
|
|
66
|
+
if (!impl || impl.includes(OUR_IMPL))
|
|
67
|
+
return null;
|
|
68
|
+
return impl;
|
|
69
|
+
}
|
|
70
|
+
function loadAgentGrantsConfig(env = process.env) {
|
|
71
|
+
const cfg = envRecord();
|
|
72
|
+
const enabledRaw = cfg.enabled !== undefined ? cfg.enabled : env.AGENT_GRANTS_ENABLED;
|
|
73
|
+
const enabled = enabledRaw === true || String(enabledRaw ?? '').toLowerCase() === 'true';
|
|
74
|
+
const auth = configuredAuth();
|
|
75
|
+
const authKind = String(auth.kind ?? 'mocked');
|
|
76
|
+
// A host's own auth.impl becomes the delegate ("custom") unless configured otherwise.
|
|
77
|
+
const fallback = customAuthImpl(auth) ? 'custom' : authKind;
|
|
78
|
+
const delegateRaw = String(cfg.delegate ?? env.AGENT_GRANTS_DELEGATE ?? fallback);
|
|
79
|
+
// `xsuaa-auth` / `basic-auth` spellings are what CAP itself accepts as kinds.
|
|
80
|
+
const delegate = delegateRaw.replace(/-auth$/, '');
|
|
81
|
+
if (enabled && delegate !== 'custom' && !exports.AGENT_GRANTS_DELEGATES.includes(delegate)) {
|
|
82
|
+
throw new Error(`Invalid agentGrants.delegate "${delegateRaw}". Must be one of: ${exports.AGENT_GRANTS_DELEGATES.join(', ')}, custom`);
|
|
83
|
+
}
|
|
84
|
+
if (enabled && delegate === 'custom' && !customAuthImpl(auth)) {
|
|
85
|
+
throw new Error('agentGrants.delegate "custom" needs a custom cds.requires.auth.impl to delegate to');
|
|
86
|
+
}
|
|
87
|
+
return { enabled, delegate, adminRateLimit: loadGrantAdminRateLimit(env) };
|
|
88
|
+
}
|
|
89
|
+
/** Once-per-process marker on the `cds` singleton; a module-level flag would not survive a double load. */
|
|
90
|
+
const ACTIVATED = Symbol.for('odatano.agentGrants.activated');
|
|
91
|
+
/**
|
|
92
|
+
* Switch agent grants on when configured: installs @odatano/cap-auth with the `x-agent-token` lane
|
|
93
|
+
* (previous strategy kept as delegate) and attaches the enforcement hook to each service on `serving`.
|
|
94
|
+
* Called from src/plugin.ts and srv/server.ts, before cds.server() builds middlewares. Never throws.
|
|
95
|
+
*/
|
|
96
|
+
function activateAgentGrants() {
|
|
97
|
+
const facade = cds_1.default;
|
|
98
|
+
if (facade[ACTIVATED] !== undefined)
|
|
99
|
+
return facade[ACTIVATED] === true;
|
|
100
|
+
const logger = cds_1.default.log('ODATANO');
|
|
101
|
+
try {
|
|
102
|
+
const agentGrants = loadAgentGrantsConfig();
|
|
103
|
+
if (!agentGrants.enabled) {
|
|
104
|
+
facade[ACTIVATED] = false;
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
const auth = configuredAuth();
|
|
108
|
+
const current = typeof auth.impl === 'string' ? auth.impl : '';
|
|
109
|
+
if (!current.includes(OUR_IMPL)) {
|
|
110
|
+
// Host's own auth.impl stays as delegate. Absolute path: in plugin mode cds.root is the
|
|
111
|
+
// consumer app, which need not resolve this package's dependency.
|
|
112
|
+
const original = customAuthImpl(auth);
|
|
113
|
+
cds_1.default.env.requires.auth = {
|
|
114
|
+
...auth,
|
|
115
|
+
kind: agentGrants.delegate === 'custom' ? auth.kind : agentGrants.delegate,
|
|
116
|
+
impl: require.resolve('@odatano/cap-auth'),
|
|
117
|
+
...(original ? { delegateImpl: original } : {})
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
const { registerTransportLane } = require('@odatano/cap-auth');
|
|
121
|
+
const { agentTokenLane } = require('./agent-token-auth');
|
|
122
|
+
registerTransportLane(agentTokenLane);
|
|
123
|
+
cds_1.default.on('serving', (srv) => {
|
|
124
|
+
const { AGENT_SERVICE_NAMES, attachAgentGrantEnforcement } = require('./agent-grants');
|
|
125
|
+
if (AGENT_SERVICE_NAMES.includes(srv.name))
|
|
126
|
+
attachAgentGrantEnforcement(srv);
|
|
127
|
+
});
|
|
128
|
+
facade[ACTIVATED] = true;
|
|
129
|
+
logger.info(`Agent grants enabled (transport delegate: ${agentGrants.delegate})`);
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
catch (err) {
|
|
133
|
+
facade[ACTIVATED] = false;
|
|
134
|
+
logger.error('Agent grants not enabled:', err instanceof Error ? err.message : err);
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
//# sourceMappingURL=agent-grants-config.js.map
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent grants: scoped, budgeted bearer capabilities. The transport lane turns `x-agent-token` into the
|
|
3
|
+
* principal `agent:<grantId>` (role `agent-grant`) before any hook runs; `attachAgentGrantEnforcement`
|
|
4
|
+
* applies allow list, wallet pinning and daily budget; `registerAgentGrantHandlers` is the lifecycle API.
|
|
5
|
+
*/
|
|
6
|
+
import cds, { Request } from '@sap/cds';
|
|
7
|
+
import { BackendError } from './errors';
|
|
8
|
+
export declare const AGENT_TOKEN_HEADER = "x-agent-token";
|
|
9
|
+
export declare const AGENT_TOKEN_PREFIX = "odat_";
|
|
10
|
+
/** Role every token principal carries; the only role it ever has. */
|
|
11
|
+
export declare const AGENT_ROLE = "agent-grant";
|
|
12
|
+
/** `agent:<grantId>`: the principal id a token request runs under. */
|
|
13
|
+
export declare const AGENT_PRINCIPAL_PREFIX = "agent:";
|
|
14
|
+
export declare const GRANTS_ENTITY = "odatano.cardano.CardanoAgentGrants";
|
|
15
|
+
/** Daily per-action counters of admitted calls (feeds GetGrantUsage); never exposed as an entity. */
|
|
16
|
+
export declare const GRANT_USAGE_ENTITY = "odatano.cardano.CardanoAgentGrantUsage";
|
|
17
|
+
/** The services the hook attaches to and the transport lane opens. */
|
|
18
|
+
export declare const AGENT_SERVICE_NAMES: readonly string[];
|
|
19
|
+
/**
|
|
20
|
+
* Actions an operator may put on a grant's allow list; each call costs one budget unit. Anything else
|
|
21
|
+
* not in AGENT_ALWAYS_ALLOWED_EVENTS (HSM signing, pause/resume, grant administration) is a 403.
|
|
22
|
+
*/
|
|
23
|
+
export declare const AGENT_ALLOWLISTABLE_ACTIONS: readonly string[];
|
|
24
|
+
/** Allow-listable actions that spend from a worker wallet: the grant must be pinned. */
|
|
25
|
+
export declare const AGENT_WALLET_ACTIONS: ReadonlySet<string>;
|
|
26
|
+
/**
|
|
27
|
+
* Events every valid token may use without allow-list entry or budget: reads, compute-only actions,
|
|
28
|
+
* status polling. Row-level narrowing is done by the `$user.grantId` restrictions in the CDS models.
|
|
29
|
+
*/
|
|
30
|
+
export declare const AGENT_ALWAYS_ALLOWED_EVENTS: ReadonlySet<string>;
|
|
31
|
+
/** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
|
|
32
|
+
export declare const AGENT_JOB_KINDS: readonly string[];
|
|
33
|
+
/** Forget every rate-limit window, the token cache and re-read the knobs from the config (tests). */
|
|
34
|
+
export declare function __resetGrantRateLimiterForTests(): void;
|
|
35
|
+
export interface AgentGrantRow {
|
|
36
|
+
ID: string;
|
|
37
|
+
userId: string;
|
|
38
|
+
agentLabel?: string | null;
|
|
39
|
+
tokenHash?: string;
|
|
40
|
+
allowedActions: string;
|
|
41
|
+
walletId?: string | null;
|
|
42
|
+
allowedJobKinds?: string | null;
|
|
43
|
+
maxJobsPerDay?: number | null;
|
|
44
|
+
jobsUsedToday?: number | null;
|
|
45
|
+
budgetWindow?: string | null;
|
|
46
|
+
validUntil?: string | null;
|
|
47
|
+
isActive?: boolean;
|
|
48
|
+
revokedAt?: string | null;
|
|
49
|
+
createdAt?: string | null;
|
|
50
|
+
lastUsedAt?: string | null;
|
|
51
|
+
}
|
|
52
|
+
/** Anything that runs a CQL statement: the primary db service or one transaction of it. */
|
|
53
|
+
export type Runner = {
|
|
54
|
+
run: (q: unknown) => Promise<unknown>;
|
|
55
|
+
};
|
|
56
|
+
export declare function hashAgentToken(token: string): string;
|
|
57
|
+
export declare function agentPrincipalId(grantId: string): string;
|
|
58
|
+
/** The grant's JSON list column as an array; malformed or absent = empty. */
|
|
59
|
+
export declare function parseGrantList(raw: string | null | undefined): string[];
|
|
60
|
+
/** The grant a request runs under, or null for an ordinary principal. */
|
|
61
|
+
export declare function agentGrantOf(req: unknown): AgentGrantRow | null;
|
|
62
|
+
export type TokenResolution = {
|
|
63
|
+
ok: true;
|
|
64
|
+
grant: AgentGrantRow;
|
|
65
|
+
} | {
|
|
66
|
+
ok: false;
|
|
67
|
+
status: 401 | 410;
|
|
68
|
+
message: string;
|
|
69
|
+
};
|
|
70
|
+
/** Test seam: cache lifetime in ms for injected runners too (null = config, injected runners bypass). */
|
|
71
|
+
export declare function __setTokenCacheMsForTests(ms: number | null): void;
|
|
72
|
+
/** Drops the cached resolution of a grant (revoke, rotate, update). */
|
|
73
|
+
export declare function invalidateTokenCache(grantId: string): void;
|
|
74
|
+
/** Entries waiting in the token cache (monitoring, tests). */
|
|
75
|
+
export declare function tokenCacheSize(): number;
|
|
76
|
+
/**
|
|
77
|
+
* Authenticate a bearer token: prefix, hash lookup among active grants (revoked = unknown, non-leaking),
|
|
78
|
+
* expiry. Runs detached from any ambient transaction; the lookup is cached (see above).
|
|
79
|
+
*/
|
|
80
|
+
export declare function resolveAgentToken(token: string, runner?: Runner): Promise<TokenResolution>;
|
|
81
|
+
/**
|
|
82
|
+
* The principal a token request runs under: not the operator and without the operator's roles, so
|
|
83
|
+
* `createdBy = $user` and `$user.grantId` restrictions narrow it and every `@requires: 'Admin'` refuses it.
|
|
84
|
+
*/
|
|
85
|
+
export declare function makeAgentUser(grant: AgentGrantRow): cds.User;
|
|
86
|
+
export interface IssueAgentGrantInput {
|
|
87
|
+
allowedActions: string[];
|
|
88
|
+
walletId?: string | null;
|
|
89
|
+
allowedJobKinds?: string[] | null;
|
|
90
|
+
maxJobsPerDay?: number | null;
|
|
91
|
+
validUntil?: string | null;
|
|
92
|
+
agentLabel?: string | null;
|
|
93
|
+
}
|
|
94
|
+
export interface IssuedAgentGrant {
|
|
95
|
+
grantId: string;
|
|
96
|
+
/** Shown once. Never logged, never stored. */
|
|
97
|
+
token: string;
|
|
98
|
+
allowedActions: string[];
|
|
99
|
+
walletId: string | null;
|
|
100
|
+
allowedJobKinds: string[];
|
|
101
|
+
maxJobsPerDay: number | null;
|
|
102
|
+
validUntil: string | null;
|
|
103
|
+
}
|
|
104
|
+
/** A refused grant input; carries the 400 the action answers with. */
|
|
105
|
+
export declare class AgentGrantInputError extends BackendError {
|
|
106
|
+
constructor(message: string, target?: string, context?: string);
|
|
107
|
+
}
|
|
108
|
+
interface NormalizedGrantInput {
|
|
109
|
+
allowedActions: string[];
|
|
110
|
+
walletId: string | null;
|
|
111
|
+
allowedJobKinds: string[];
|
|
112
|
+
maxJobsPerDay: number | null;
|
|
113
|
+
validUntil: string | null;
|
|
114
|
+
agentLabel: string | null;
|
|
115
|
+
}
|
|
116
|
+
export declare function validateGrantInput(input: IssueAgentGrantInput, now?: Date, context?: string): NormalizedGrantInput;
|
|
117
|
+
/** Mint a grant for `operatorId` on `runner`; validation errors surface as AgentGrantInputError (400). */
|
|
118
|
+
export declare function issueAgentGrant(input: IssueAgentGrantInput, operatorId: string, runner?: Runner): Promise<IssuedAgentGrant>;
|
|
119
|
+
/** Deactivate a grant; false when it does not exist or is already revoked. */
|
|
120
|
+
export declare function revokeAgentGrantById(grantId: string, runner?: Runner): Promise<boolean>;
|
|
121
|
+
export interface RotatedAgentGrant {
|
|
122
|
+
grantId: string;
|
|
123
|
+
/** Shown once. Never logged, never stored. */
|
|
124
|
+
token: string;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Replace the grant's token; budget, wallet, allow list and expiry survive. The old token is unknown
|
|
128
|
+
* from the next request (another replica: after AGENT_TOKEN_CACHE_MS). Null when missing or revoked.
|
|
129
|
+
*/
|
|
130
|
+
export declare function rotateAgentGrantToken(grantId: string, runner?: Runner): Promise<RotatedAgentGrant | null>;
|
|
131
|
+
/** The editable grant fields, as a client sends them: absent = untouched, explicit null = cleared. */
|
|
132
|
+
export interface UpdateAgentGrantInput {
|
|
133
|
+
agentLabel?: string | null;
|
|
134
|
+
allowedActions?: string[] | null;
|
|
135
|
+
allowedJobKinds?: string[] | null;
|
|
136
|
+
maxJobsPerDay?: number | null;
|
|
137
|
+
validUntil?: string | null;
|
|
138
|
+
}
|
|
139
|
+
/** Row fields a grant edit never touches; a different wallet binding is a different grant. */
|
|
140
|
+
export declare const GRANT_IMMUTABLE_FIELDS: readonly string[];
|
|
141
|
+
export type UpdateAgentGrantResult = {
|
|
142
|
+
ok: true;
|
|
143
|
+
grantId: string;
|
|
144
|
+
updated: string[];
|
|
145
|
+
} | {
|
|
146
|
+
ok: false;
|
|
147
|
+
status: 404 | 409;
|
|
148
|
+
code?: 'GRANT_REVOKED';
|
|
149
|
+
message: string;
|
|
150
|
+
};
|
|
151
|
+
/**
|
|
152
|
+
* Edit an active grant: absent field = untouched, explicit null = cleared (allowedActions cannot be emptied).
|
|
153
|
+
* The merged row passes validateGrantInput. Unknown grant 404, revoked 409 GRANT_REVOKED, invalid input 400.
|
|
154
|
+
*/
|
|
155
|
+
export declare function updateAgentGrant(grantId: string, input: UpdateAgentGrantInput, runner?: Runner): Promise<UpdateAgentGrantResult>;
|
|
156
|
+
export declare const USAGE_WINDOW_MAX_MS: number;
|
|
157
|
+
export declare const USAGE_WINDOW_DEFAULT_MS: number;
|
|
158
|
+
export type UsageWindow = {
|
|
159
|
+
ok: true;
|
|
160
|
+
since: string;
|
|
161
|
+
until: string;
|
|
162
|
+
sinceDay: string;
|
|
163
|
+
untilDay: string;
|
|
164
|
+
} | {
|
|
165
|
+
ok: false;
|
|
166
|
+
message: string;
|
|
167
|
+
target: string;
|
|
168
|
+
};
|
|
169
|
+
/** since (default until - 30 days) .. until (default now), at most 366 days; whole UTC days at both ends. */
|
|
170
|
+
export declare function resolveUsageWindow(since: unknown, until: unknown, now?: Date): UsageWindow;
|
|
171
|
+
export interface GrantUsageCall {
|
|
172
|
+
service: string;
|
|
173
|
+
action: string;
|
|
174
|
+
/** Admitted and kept (budget charged and not refunded). */
|
|
175
|
+
count: number;
|
|
176
|
+
/** Admitted, then refunded because the handler refused the input. */
|
|
177
|
+
refunded: number;
|
|
178
|
+
}
|
|
179
|
+
export interface AgentGrantUsage {
|
|
180
|
+
grantId: string;
|
|
181
|
+
since: string;
|
|
182
|
+
until: string;
|
|
183
|
+
calls: GrantUsageCall[];
|
|
184
|
+
total: number;
|
|
185
|
+
jobsUsedToday: number;
|
|
186
|
+
maxJobsPerDay: number | null;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Admitted calls of the grant in `window`, grouped by service and action. Deferred counters are flushed
|
|
190
|
+
* first on `flushRunner` (detached autocommit), so the read on `runner` sees them without holding locks.
|
|
191
|
+
*/
|
|
192
|
+
export declare function getGrantUsage(grant: AgentGrantRow, window: Extract<UsageWindow, {
|
|
193
|
+
ok: true;
|
|
194
|
+
}>, runner?: Runner, flushRunner?: Runner): Promise<AgentGrantUsage>;
|
|
195
|
+
export interface AgentGrantStatus {
|
|
196
|
+
grantId: string;
|
|
197
|
+
agentLabel: string | null;
|
|
198
|
+
allowedActions: string[];
|
|
199
|
+
walletId: string | null;
|
|
200
|
+
allowedJobKinds: string[];
|
|
201
|
+
maxJobsPerDay: number | null;
|
|
202
|
+
jobsUsedToday: number;
|
|
203
|
+
budgetWindow: string | null;
|
|
204
|
+
validUntil: string | null;
|
|
205
|
+
isActive: boolean;
|
|
206
|
+
}
|
|
207
|
+
export declare function toGrantStatus(grant: AgentGrantRow): AgentGrantStatus;
|
|
208
|
+
/** Validation rejections happen before any transaction work. */
|
|
209
|
+
export declare function registerAgentGrantHandlers(srv: cds.Service): void;
|
|
210
|
+
export declare function attachAgentGrantEnforcement(srv: cds.Service, runner?: Runner): void;
|
|
211
|
+
/**
|
|
212
|
+
* Where the hook's writes go: detached from the request transaction by default (the spend sticks, no lock
|
|
213
|
+
* across backend round trips). A request already inside an open transaction (`$batch` changeset parts,
|
|
214
|
+
* `ready` or `dbc` set) rides its own, since a detached statement would deadlock on SQLite's single connection.
|
|
215
|
+
*/
|
|
216
|
+
export interface BudgetRunner {
|
|
217
|
+
runner: Runner;
|
|
218
|
+
/** true: statements run outside the request transaction (and a refused request is refunded). */
|
|
219
|
+
detached: boolean;
|
|
220
|
+
}
|
|
221
|
+
export declare function budgetRunnerFor(req: Request, injected?: Runner, detached?: boolean): BudgetRunner;
|
|
222
|
+
/**
|
|
223
|
+
* The before('*') hook: allow list, wallet pinning, daily budget, usage, lastUsedAt. No-op without a grant.
|
|
224
|
+
* `runner` / `detached` are test seams.
|
|
225
|
+
*/
|
|
226
|
+
export declare function enforceAgentGrant(req: Request, runner?: Runner, detached?: boolean, serviceName?: string): Promise<unknown>;
|
|
227
|
+
export interface BudgetCharge {
|
|
228
|
+
consumed: boolean;
|
|
229
|
+
/** The UTC day the unit was charged to; the refund must name the same window. */
|
|
230
|
+
window: string;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Consume one unit of the daily budget with two conditional UPDATEs, so concurrent requests cannot
|
|
234
|
+
* overspend: a compare-and-swap window reset and a bounded increment (`jobsUsedToday < max`).
|
|
235
|
+
*/
|
|
236
|
+
export declare function consumeDailyBudget(br: BudgetRunner | Runner, grant: AgentGrantRow): Promise<BudgetCharge>;
|
|
237
|
+
/** Undo one consumeDailyBudget in the window it was charged to; never touches a newer day's counter. */
|
|
238
|
+
export declare function refundDailyBudget(br: BudgetRunner | Runner, grant: AgentGrantRow, window: string): Promise<void>;
|
|
239
|
+
type UsageMode = 'sync' | 'deferred';
|
|
240
|
+
/** Test seam: force a mode (null = derive from cds.db.kind). */
|
|
241
|
+
export declare function __setGrantUsageModeForTests(mode: UsageMode | null): void;
|
|
242
|
+
/** Test seam: forget buffered deltas and the pending timer. */
|
|
243
|
+
export declare function __resetGrantUsageBufferForTests(): void;
|
|
244
|
+
/** How many keys wait for the next flush (monitoring, tests). */
|
|
245
|
+
export declare function pendingGrantUsageKeys(): number;
|
|
246
|
+
/**
|
|
247
|
+
* Writes the buffered deltas per key: UPDATE, INSERT when the row is missing, one more UPDATE when a racing
|
|
248
|
+
* writer created it. A failed delta goes back into the buffer for the next flush.
|
|
249
|
+
*/
|
|
250
|
+
export declare function flushGrantUsage(runner?: Runner): Promise<{
|
|
251
|
+
flushed: number;
|
|
252
|
+
failed: number;
|
|
253
|
+
}>;
|
|
254
|
+
/**
|
|
255
|
+
* One admitted call: `calls + 1` on (grant, UTC day, service, action). Deferred mode buffers the delta;
|
|
256
|
+
* sync mode writes UPDATE / INSERT / UPDATE awaited. Never fails the request. Returns the day counted on.
|
|
257
|
+
*/
|
|
258
|
+
export declare function recordGrantUsage(br: BudgetRunner | Runner, grant: AgentGrantRow, service: string, action: string, now?: Date): Promise<string>;
|
|
259
|
+
/** `refunded + 1` on the row the call was counted on; deferred mode buffers it on the same key. */
|
|
260
|
+
export declare function refundGrantUsage(br: BudgetRunner | Runner, grant: AgentGrantRow, service: string, action: string, day: string): Promise<void>;
|
|
261
|
+
export {};
|
|
262
|
+
//# sourceMappingURL=agent-grants.d.ts.map
|