@odatano/core 2.0.0-rc.49 → 2.0.0-rc.50
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 +6 -12
- package/@cds-models/CardanoIndexerService/index.d.ts +200 -2
- package/@cds-models/CardanoIndexerService/index.js +24 -0
- package/@cds-models/CardanoODataService/index.d.ts +49 -6
- package/@cds-models/CardanoODataService/index.js +4 -0
- package/@cds-models/CardanoSignService/index.d.ts +3 -3
- package/@cds-models/CardanoWorkerService/index.d.ts +4 -3
- package/@cds-models/index.d.ts +9 -1
- package/@cds-models/index.js +2 -1
- package/@cds-models/odatano/cardano/index.d.ts +59 -5
- package/@cds-models/odatano/cardano/index.js +6 -0
- package/README.md +29 -17
- package/db/schema.cds +117 -24
- package/db/types.cds +8 -0
- package/package.json +17 -15
- package/scripts/migrate-schema.mjs +334 -0
- package/src/index.d.ts +7 -5
- package/src/index.js +12 -10
- package/src/plugin.js +6 -7
- package/srv/blockchain/backends/blockfrost-backend.js +9 -1
- package/srv/blockchain/backends/cardano-backend.d.ts +15 -0
- package/srv/blockchain/backends/cardano-backend.js +5 -0
- package/srv/blockchain/backends/koios-backend.js +16 -10
- package/srv/blockchain/backends/ogmios-backend.d.ts +9 -3
- package/srv/blockchain/backends/ogmios-backend.js +60 -18
- package/srv/blockchain/cardano-client.d.ts +5 -4
- package/srv/blockchain/cardano-client.js +46 -13
- package/srv/blockchain/cardano-indexer.d.ts +116 -9
- package/srv/blockchain/cardano-indexer.js +436 -189
- package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
- package/srv/blockchain/crawler/account-snapshots.js +153 -0
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +23 -1
- package/srv/blockchain/crawler/asset-registry-backfill.js +91 -1
- package/srv/blockchain/crawler/certificate-backfill.d.ts +2 -0
- package/srv/blockchain/crawler/certificate-backfill.js +10 -3
- package/srv/blockchain/crawler/crawler.d.ts +15 -0
- package/srv/blockchain/crawler/crawler.js +68 -3
- package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
- package/srv/blockchain/crawler/input-asset-copies.js +171 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
- package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
- package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
- package/srv/blockchain/crawler/transaction-backfill.js +12 -8
- package/srv/blockchain/pool-metadata.d.ts +15 -0
- package/srv/blockchain/pool-metadata.js +132 -0
- package/srv/blockchain/signing/cose-verifier.d.ts +3 -1
- package/srv/blockchain/signing/cose-verifier.js +144 -56
- package/srv/blockchain/signing/hsm-signer.js +2 -1
- package/srv/blockchain/signing/submission-finalizer.d.ts +15 -4
- package/srv/blockchain/signing/submission-finalizer.js +201 -69
- package/srv/blockchain/stored-chain.js +1 -1
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +1 -3
- package/srv/blockchain/transaction-building/buildooor-tx.js +34 -54
- package/srv/blockchain/transaction-presence.d.ts +5 -0
- package/srv/blockchain/transaction-presence.js +29 -0
- package/srv/blockchain/transaction-rows.js +1 -1
- package/srv/blockchain/wallet-worker/build-request.d.ts +4 -1
- package/srv/blockchain/wallet-worker/build-request.js +25 -0
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +1 -1
- package/srv/blockchain/wallet-worker/job-store.d.ts +17 -7
- package/srv/blockchain/wallet-worker/job-store.js +0 -0
- package/srv/blockchain/wallet-worker/signers.d.ts +2 -0
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +2 -0
- package/srv/blockchain/wallet-worker/wallet-worker.js +42 -32
- package/srv/cardano-agent-service.cds +11 -12
- package/srv/cardano-agent-service.js +2 -0
- package/srv/cardano-backend-service.cds +34 -1
- package/srv/cardano-backend-service.js +20 -17
- package/srv/cardano-indexer-service.cds +153 -12
- package/srv/cardano-indexer-service.js +175 -29
- package/srv/cardano-service.cds +67 -3
- package/srv/cardano-service.js +132 -67
- package/srv/cardano-sign-service.cds +30 -20
- package/srv/cardano-sign-service.js +13 -10
- package/srv/cardano-tx-service.cds +15 -1
- package/srv/cardano-tx-service.js +4 -1
- package/srv/cardano-worker-service.cds +16 -7
- package/srv/cardano-worker-service.js +31 -22
- package/srv/cbor/parse.js +11 -34
- package/srv/config.d.ts +113 -0
- package/srv/config.js +409 -0
- package/srv/server.d.ts +9 -14
- package/srv/server.js +32 -316
- package/srv/utils/agent-access.d.ts +9 -0
- package/srv/utils/agent-access.js +67 -0
- package/srv/utils/agent-grants-config.d.ts +0 -17
- package/srv/utils/agent-grants-config.js +6 -81
- package/srv/utils/agent-grants.d.ts +6 -19
- package/srv/utils/agent-grants.js +69 -130
- package/srv/utils/const.d.ts +4 -0
- package/srv/utils/const.js +5 -1
- package/srv/utils/db-indexes.js +11 -3
- package/srv/utils/error-codes.d.ts +4 -0
- package/srv/utils/error-codes.js +4 -0
- package/srv/utils/errors.d.ts +6 -0
- package/srv/utils/errors.js +23 -1
- package/srv/utils/liveness.js +2 -5
- package/srv/utils/mappers.d.ts +5 -7
- package/srv/utils/mappers.js +22 -9
- package/srv/utils/pg-order-nulls.js +4 -3
- package/srv/utils/readiness.d.ts +12 -0
- package/srv/utils/readiness.js +29 -0
- package/srv/utils/result-numbers.d.ts +15 -0
- package/srv/utils/result-numbers.js +61 -0
- package/srv/utils/tx-request-parsers.d.ts +1 -1
- package/srv/utils/tx-request-parsers.js +3 -3
- package/srv/utils/tx-utils.d.ts +3 -0
- package/srv/utils/tx-utils.js +17 -3
- package/srv/utils/types.d.ts +16 -3
- package/scripts/migrate-txseq.mjs +0 -138
- package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +0 -13
- package/srv/blockchain/transaction-building/buildooor-fee-patch.js +0 -71
- package/srv/blockchain/transaction-building/caller-datums.d.ts +0 -15
- package/srv/blockchain/transaction-building/caller-datums.js +0 -133
- package/srv/cbor/redeemer-tag-patch.d.ts +0 -3
- package/srv/cbor/redeemer-tag-patch.js +0 -61
- package/srv/utils/legacy-service-paths.d.ts +0 -11
- package/srv/utils/legacy-service-paths.js +0 -58
|
@@ -3,85 +3,10 @@ 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_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
6
|
exports.activateAgentGrants = activateAgentGrants;
|
|
7
|
+
// Switches the agent grant feature on. src/plugin.ts calls it before any service module loads.
|
|
13
8
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
14
|
-
|
|
15
|
-
exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = 10;
|
|
16
|
-
// Grant administration calls per principal per hour. An invalid value logs a warning
|
|
17
|
-
// and falls back to the default. It never disables the feature.
|
|
18
|
-
function loadGrantAdminRateLimit(env = process.env) {
|
|
19
|
-
const cfg = envRecord();
|
|
20
|
-
const raw = cfg.adminRateLimit !== undefined ? cfg.adminRateLimit : env.AGENT_GRANT_ADMIN_RATE_LIMIT;
|
|
21
|
-
if (raw === undefined || raw === null || String(raw).trim() === '')
|
|
22
|
-
return exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT;
|
|
23
|
-
const n = Number(raw);
|
|
24
|
-
if (!Number.isInteger(n) || n < 1) {
|
|
25
|
-
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}`);
|
|
26
|
-
return exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT;
|
|
27
|
-
}
|
|
28
|
-
return n;
|
|
29
|
-
}
|
|
30
|
-
exports.AGENT_TOKEN_CACHE_MS_DEFAULT = 10_000;
|
|
31
|
-
// How long a resolved grant row is reused before the DB is read again. 0 disables the cache.
|
|
32
|
-
// This bounds how late a revoke on another replica takes effect.
|
|
33
|
-
function loadTokenCacheMs(env = process.env) {
|
|
34
|
-
const cfg = envRecord();
|
|
35
|
-
const raw = cfg.tokenCacheMs !== undefined ? cfg.tokenCacheMs : env.AGENT_TOKEN_CACHE_MS;
|
|
36
|
-
if (raw === undefined || raw === null || String(raw).trim() === '')
|
|
37
|
-
return exports.AGENT_TOKEN_CACHE_MS_DEFAULT;
|
|
38
|
-
const n = Number(raw);
|
|
39
|
-
if (!Number.isInteger(n) || n < 0) {
|
|
40
|
-
cds_1.default.log('ODATANO').warn(`AGENT_TOKEN_CACHE_MS "${String(raw)}" is not an integer >= 0; using ${exports.AGENT_TOKEN_CACHE_MS_DEFAULT}`);
|
|
41
|
-
return exports.AGENT_TOKEN_CACHE_MS_DEFAULT;
|
|
42
|
-
}
|
|
43
|
-
return n;
|
|
44
|
-
}
|
|
45
|
-
function envRecord() {
|
|
46
|
-
const requires = (cds_1.default.env?.requires ?? {});
|
|
47
|
-
const core = (requires['odatano-core'] ?? {});
|
|
48
|
-
return (core.agentGrants ?? {});
|
|
49
|
-
}
|
|
50
|
-
/** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
|
|
51
|
-
function configuredAuth() {
|
|
52
|
-
const auth = cds_1.default.env?.requires?.auth;
|
|
53
|
-
if (typeof auth === 'string')
|
|
54
|
-
return { kind: auth };
|
|
55
|
-
return (auth ?? {});
|
|
56
|
-
}
|
|
57
|
-
/** The transport middleware, recognisable in `auth.impl` so activation stays idempotent. */
|
|
58
|
-
const OUR_IMPL = 'cap-auth';
|
|
59
|
-
/** A host-configured custom `cds.requires.auth.impl` (not this package's middleware); the lane wraps it. */
|
|
60
|
-
function customAuthImpl(auth = configuredAuth()) {
|
|
61
|
-
const impl = typeof auth.impl === 'string' ? auth.impl.trim() : '';
|
|
62
|
-
if (!impl || impl.includes(OUR_IMPL))
|
|
63
|
-
return null;
|
|
64
|
-
return impl;
|
|
65
|
-
}
|
|
66
|
-
function loadAgentGrantsConfig(env = process.env) {
|
|
67
|
-
const cfg = envRecord();
|
|
68
|
-
const enabledRaw = cfg.enabled !== undefined ? cfg.enabled : env.AGENT_GRANTS_ENABLED;
|
|
69
|
-
const enabled = enabledRaw === true || String(enabledRaw ?? '').toLowerCase() === 'true';
|
|
70
|
-
const auth = configuredAuth();
|
|
71
|
-
const authKind = String(auth.kind ?? 'mocked');
|
|
72
|
-
// A host's own auth.impl becomes the delegate ("custom") unless configured otherwise.
|
|
73
|
-
const fallback = customAuthImpl(auth) ? 'custom' : authKind;
|
|
74
|
-
const delegateRaw = String(cfg.delegate ?? env.AGENT_GRANTS_DELEGATE ?? fallback);
|
|
75
|
-
// `xsuaa-auth` / `basic-auth` spellings are what CAP itself accepts as kinds.
|
|
76
|
-
const delegate = delegateRaw.replace(/-auth$/, '');
|
|
77
|
-
if (enabled && delegate !== 'custom' && !exports.AGENT_GRANTS_DELEGATES.includes(delegate)) {
|
|
78
|
-
throw new Error(`Invalid agentGrants.delegate "${delegateRaw}". Must be one of: ${exports.AGENT_GRANTS_DELEGATES.join(', ')}, custom`);
|
|
79
|
-
}
|
|
80
|
-
if (enabled && delegate === 'custom' && !customAuthImpl(auth)) {
|
|
81
|
-
throw new Error('agentGrants.delegate "custom" needs a custom cds.requires.auth.impl to delegate to');
|
|
82
|
-
}
|
|
83
|
-
return { enabled, delegate, adminRateLimit: loadGrantAdminRateLimit(env) };
|
|
84
|
-
}
|
|
9
|
+
const config_1 = require("../config");
|
|
85
10
|
/** Once-per-process marker on the `cds` singleton; a module-level flag would not survive a double load. */
|
|
86
11
|
const ACTIVATED = Symbol.for('odatano.agentGrants.activated');
|
|
87
12
|
// Installs @odatano/cap-auth with the `x-agent-token` lane and keeps the old strategy as delegate.
|
|
@@ -92,17 +17,17 @@ function activateAgentGrants() {
|
|
|
92
17
|
return facade[ACTIVATED] === true;
|
|
93
18
|
const logger = cds_1.default.log('ODATANO');
|
|
94
19
|
try {
|
|
95
|
-
const agentGrants = loadAgentGrantsConfig();
|
|
20
|
+
const agentGrants = (0, config_1.loadAgentGrantsConfig)();
|
|
96
21
|
if (!agentGrants.enabled) {
|
|
97
22
|
facade[ACTIVATED] = false;
|
|
98
23
|
return false;
|
|
99
24
|
}
|
|
100
|
-
const auth = configuredAuth();
|
|
25
|
+
const auth = (0, config_1.configuredAuth)();
|
|
101
26
|
const current = typeof auth.impl === 'string' ? auth.impl : '';
|
|
102
|
-
if (!current.includes(
|
|
27
|
+
if (!current.includes(config_1.AGENT_AUTH_IMPL)) {
|
|
103
28
|
// Host's own auth.impl stays as delegate. Absolute path: in plugin mode cds.root is the
|
|
104
29
|
// consumer app, which need not resolve this package's dependency.
|
|
105
|
-
const original = customAuthImpl(auth);
|
|
30
|
+
const original = (0, config_1.customAuthImpl)(auth);
|
|
106
31
|
cds_1.default.env.requires.auth = {
|
|
107
32
|
...auth,
|
|
108
33
|
kind: agentGrants.delegate === 'custom' ? auth.kind : agentGrants.delegate,
|
|
@@ -12,14 +12,6 @@ export declare const GRANTS_ENTITY = "odatano.cardano.CardanoAgentGrants";
|
|
|
12
12
|
export declare const GRANT_USAGE_ENTITY = "odatano.cardano.CardanoAgentGrantUsage";
|
|
13
13
|
/** The services the hook attaches to and the transport lane opens. */
|
|
14
14
|
export declare const AGENT_SERVICE_NAMES: readonly string[];
|
|
15
|
-
/** Actions an operator may allow on a grant; each call costs one budget unit. Anything else not always allowed is a 403. */
|
|
16
|
-
export declare const AGENT_ALLOWLISTABLE_ACTIONS: readonly string[];
|
|
17
|
-
/** Allow-listable actions that spend from a worker wallet: the grant must be pinned. */
|
|
18
|
-
export declare const AGENT_WALLET_ACTIONS: ReadonlySet<string>;
|
|
19
|
-
/** Events every valid token may use without allow-list entry or budget. Row-level `$user.grantId` restrictions narrow them. */
|
|
20
|
-
export declare const AGENT_ALWAYS_ALLOWED_EVENTS: ReadonlySet<string>;
|
|
21
|
-
/** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
|
|
22
|
-
export declare const AGENT_JOB_KINDS: readonly string[];
|
|
23
15
|
/** Forget every rate-limit window, the token cache and re-read the knobs from the config (tests). */
|
|
24
16
|
export declare function __resetGrantRateLimiterForTests(): void;
|
|
25
17
|
/** A grant row with the fields every grant has set. */
|
|
@@ -36,6 +28,8 @@ export declare function hashAgentToken(token: string): string;
|
|
|
36
28
|
export declare function agentPrincipalId(grantId: string): string;
|
|
37
29
|
/** The grant's JSON list column as an array; malformed or absent = empty. */
|
|
38
30
|
export declare function parseGrantList(raw: string | null | undefined): string[];
|
|
31
|
+
/** The stored allow list without names that are no longer grantable. */
|
|
32
|
+
export declare function grantedActions(grant: Pick<AgentGrantRow, 'allowedActions'>): string[];
|
|
39
33
|
/** The grant a request runs under, or null for an ordinary principal. */
|
|
40
34
|
export declare function agentGrantOf(req: unknown): AgentGrantRow | null;
|
|
41
35
|
export type TokenResolution = {
|
|
@@ -58,8 +52,6 @@ export declare function resolveAgentToken(token: string, runner?: Runner): Promi
|
|
|
58
52
|
export declare function makeAgentUser(grant: AgentGrantRow): cds.User;
|
|
59
53
|
export interface IssueAgentGrantInput {
|
|
60
54
|
allowedActions: string[];
|
|
61
|
-
walletId?: string | null;
|
|
62
|
-
allowedJobKinds?: string[] | null;
|
|
63
55
|
maxJobsPerDay?: number | null;
|
|
64
56
|
validUntil?: string | null;
|
|
65
57
|
agentLabel?: string | null;
|
|
@@ -69,8 +61,6 @@ export interface IssuedAgentGrant {
|
|
|
69
61
|
/** Shown once. Never logged, never stored. */
|
|
70
62
|
token: string;
|
|
71
63
|
allowedActions: string[];
|
|
72
|
-
walletId: string | null;
|
|
73
|
-
allowedJobKinds: string[];
|
|
74
64
|
maxJobsPerDay: number | null;
|
|
75
65
|
validUntil: string | null;
|
|
76
66
|
}
|
|
@@ -80,8 +70,6 @@ export declare class AgentGrantInputError extends BackendError {
|
|
|
80
70
|
}
|
|
81
71
|
interface NormalizedGrantInput {
|
|
82
72
|
allowedActions: string[];
|
|
83
|
-
walletId: string | null;
|
|
84
|
-
allowedJobKinds: string[];
|
|
85
73
|
maxJobsPerDay: number | null;
|
|
86
74
|
validUntil: string | null;
|
|
87
75
|
agentLabel: string | null;
|
|
@@ -102,11 +90,10 @@ export declare function rotateAgentGrantToken(grantId: string, runner?: Runner):
|
|
|
102
90
|
export interface UpdateAgentGrantInput {
|
|
103
91
|
agentLabel?: string | null;
|
|
104
92
|
allowedActions?: string[] | null;
|
|
105
|
-
allowedJobKinds?: string[] | null;
|
|
106
93
|
maxJobsPerDay?: number | null;
|
|
107
94
|
validUntil?: string | null;
|
|
108
95
|
}
|
|
109
|
-
/** Row fields a grant edit never touches
|
|
96
|
+
/** Row fields a grant edit never touches. */
|
|
110
97
|
export declare const GRANT_IMMUTABLE_FIELDS: readonly string[];
|
|
111
98
|
export type UpdateAgentGrantResult = {
|
|
112
99
|
ok: true;
|
|
@@ -159,8 +146,6 @@ export interface AgentGrantStatus {
|
|
|
159
146
|
grantId: string;
|
|
160
147
|
agentLabel: string | null;
|
|
161
148
|
allowedActions: string[];
|
|
162
|
-
walletId: string | null;
|
|
163
|
-
allowedJobKinds: string[];
|
|
164
149
|
maxJobsPerDay: number | null;
|
|
165
150
|
jobsUsedToday: number;
|
|
166
151
|
budgetWindow: string | null;
|
|
@@ -178,7 +163,7 @@ export interface BudgetRunner {
|
|
|
178
163
|
}
|
|
179
164
|
export declare function budgetRunnerFor(req: Request, injected?: Runner, detached?: boolean): BudgetRunner;
|
|
180
165
|
export declare function errorStatus(err: unknown): number;
|
|
181
|
-
/** The before('*') hook for token requests:
|
|
166
|
+
/** The before('*') hook for token requests: closed services, allow list, daily budget and usage. */
|
|
182
167
|
export declare function enforceAgentGrant(req: Request, runner?: Runner, detached?: boolean, serviceName?: string): Promise<unknown>;
|
|
183
168
|
export interface BudgetCharge {
|
|
184
169
|
consumed: boolean;
|
|
@@ -195,6 +180,8 @@ export declare function __setGrantUsageModeForTests(mode: UsageMode | null): voi
|
|
|
195
180
|
export declare function __resetGrantUsageBufferForTests(): void;
|
|
196
181
|
/** How many keys wait for the next flush (monitoring, tests). */
|
|
197
182
|
export declare function pendingGrantUsageKeys(): number;
|
|
183
|
+
/** Test seam: the day the retention last ran (null = not yet). */
|
|
184
|
+
export declare function __setGrantUsagePrunedForTests(day: string | null): void;
|
|
198
185
|
/** Write the buffered deltas per key. A failed delta goes back into the buffer for the next flush. */
|
|
199
186
|
export declare function flushGrantUsage(runner?: Runner): Promise<{
|
|
200
187
|
flushed: number;
|
|
@@ -5,11 +5,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
6
6
|
};
|
|
7
7
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
-
exports.USAGE_WINDOW_DEFAULT_MS = exports.USAGE_WINDOW_MAX_MS = exports.GRANT_IMMUTABLE_FIELDS = exports.AgentGrantInputError = exports.
|
|
8
|
+
exports.USAGE_WINDOW_DEFAULT_MS = exports.USAGE_WINDOW_MAX_MS = exports.GRANT_IMMUTABLE_FIELDS = exports.AgentGrantInputError = exports.AGENT_SERVICE_NAMES = exports.GRANT_USAGE_ENTITY = exports.GRANTS_ENTITY = exports.AGENT_PRINCIPAL_PREFIX = exports.AGENT_ROLE = exports.AGENT_TOKEN_PREFIX = exports.AGENT_TOKEN_HEADER = void 0;
|
|
9
9
|
exports.__resetGrantRateLimiterForTests = __resetGrantRateLimiterForTests;
|
|
10
10
|
exports.hashAgentToken = hashAgentToken;
|
|
11
11
|
exports.agentPrincipalId = agentPrincipalId;
|
|
12
12
|
exports.parseGrantList = parseGrantList;
|
|
13
|
+
exports.grantedActions = grantedActions;
|
|
13
14
|
exports.agentGrantOf = agentGrantOf;
|
|
14
15
|
exports.__setTokenCacheMsForTests = __setTokenCacheMsForTests;
|
|
15
16
|
exports.invalidateTokenCache = invalidateTokenCache;
|
|
@@ -34,6 +35,7 @@ exports.refundDailyBudget = refundDailyBudget;
|
|
|
34
35
|
exports.__setGrantUsageModeForTests = __setGrantUsageModeForTests;
|
|
35
36
|
exports.__resetGrantUsageBufferForTests = __resetGrantUsageBufferForTests;
|
|
36
37
|
exports.pendingGrantUsageKeys = pendingGrantUsageKeys;
|
|
38
|
+
exports.__setGrantUsagePrunedForTests = __setGrantUsagePrunedForTests;
|
|
37
39
|
exports.flushGrantUsage = flushGrantUsage;
|
|
38
40
|
exports.recordGrantUsage = recordGrantUsage;
|
|
39
41
|
exports.refundGrantUsage = refundGrantUsage;
|
|
@@ -43,8 +45,9 @@ const tx_utils_1 = require("./tx-utils");
|
|
|
43
45
|
const rate_limiter_1 = require("./rate-limiter");
|
|
44
46
|
const errors_1 = require("./errors");
|
|
45
47
|
const error_codes_1 = require("./error-codes");
|
|
46
|
-
const
|
|
47
|
-
const
|
|
48
|
+
const config_1 = require("../config");
|
|
49
|
+
const agent_access_1 = require("./agent-access");
|
|
50
|
+
const { SELECT, INSERT, UPDATE, DELETE } = cds_1.default.ql;
|
|
48
51
|
const logger = cds_1.default.log('AgentGrants');
|
|
49
52
|
exports.AGENT_TOKEN_HEADER = 'x-agent-token';
|
|
50
53
|
exports.AGENT_TOKEN_PREFIX = 'odat_';
|
|
@@ -66,59 +69,10 @@ exports.AGENT_SERVICE_NAMES = [
|
|
|
66
69
|
'CardanoAgentService',
|
|
67
70
|
'CardanoBackendService',
|
|
68
71
|
];
|
|
69
|
-
/** Actions an operator may allow on a grant; each call costs one budget unit. Anything else not always allowed is a 403. */
|
|
70
|
-
exports.AGENT_ALLOWLISTABLE_ACTIONS = [
|
|
71
|
-
// CardanoTransactionService: unsigned CBOR
|
|
72
|
-
'BuildSimpleAdaTransaction',
|
|
73
|
-
'BuildTransactionWithMetadata',
|
|
74
|
-
'BuildMultiAssetTransaction',
|
|
75
|
-
'BuildMintTransaction',
|
|
76
|
-
'BuildPlutusSpendTransaction',
|
|
77
|
-
'BuildPlutusTransaction',
|
|
78
|
-
'SetCollateral',
|
|
79
|
-
// externally signed transactions
|
|
80
|
-
'CreateSigningRequest',
|
|
81
|
-
'VerifySignature',
|
|
82
|
-
'SubmitTransaction',
|
|
83
|
-
'SubmitSignedTransaction',
|
|
84
|
-
'SubmitVerifiedTransaction',
|
|
85
|
-
'CheckSubmissionStatus',
|
|
86
|
-
// server-side wallets (need walletId on the grant)
|
|
87
|
-
'SubmitWalletJob',
|
|
88
|
-
'CancelJob',
|
|
89
|
-
];
|
|
90
|
-
/** Allow-listable actions that spend from a worker wallet: the grant must be pinned. */
|
|
91
|
-
exports.AGENT_WALLET_ACTIONS = new Set(['SubmitWalletJob', 'CancelJob']);
|
|
92
|
-
/** Events every valid token may use without allow-list entry or budget. Row-level `$user.grantId` restrictions narrow them. */
|
|
93
|
-
exports.AGENT_ALWAYS_ALLOWED_EVENTS = new Set([
|
|
94
|
-
'READ',
|
|
95
|
-
// CardanoODataService: chain reads through the backends
|
|
96
|
-
'GetNetworkInformation', 'GetBlockByHash', 'GetEpochByNumber', 'GetPoolById', 'GetDrepById',
|
|
97
|
-
'GetAssetInfo', 'GetAssetHistory', 'GetAccountByStakeAddress', 'GetTransactionByHash',
|
|
98
|
-
'GetTransactionConfirmations', 'GetMetadataByTxHash', 'GetAddressByBech32', 'GetUTxOsByAddress', 'GetUTxOsByCredential',
|
|
99
|
-
'GetAssetsByAddress', 'GetLatestTransactionsByAddress', 'GetLatestBlock', 'GetLatestEpoch',
|
|
100
|
-
'GetLedgerProtocolParameters', 'ParseTransactionCbor', 'DecodePlutusData',
|
|
101
|
-
// CardanoTransactionService: compute-only
|
|
102
|
-
'GetBuildDetails', 'GetTransactionBuildsByAddress', 'DeriveScriptAddress', 'ExtractPaymentKeyHash',
|
|
103
|
-
// CardanoSignService: reads and stateless verification
|
|
104
|
-
'GetSigningRequest', 'GetSigningRequestsByAddress', 'VerifyDataSignature', 'GetHsmStatus',
|
|
105
|
-
// CardanoWorkerService / CardanoIndexerService: status and liveness
|
|
106
|
-
'GetJobStatus', 'GetWorkerStatus', 'getStatus', 'getLiveness',
|
|
107
|
-
// CardanoAgentService: the token's own grant (GetGrantUsage is narrowed to it in enforceAgentGrant)
|
|
108
|
-
'GetGrantStatus', 'GetGrantUsage',
|
|
109
|
-
// CardanoBackendService: reads and evaluation for another ODATANO instance (submit is allow-listed)
|
|
110
|
-
'GetTransaction', 'GetTransactionsBatch', 'GetTransactionMetadata', 'GetBlock', 'GetBlockByHeight',
|
|
111
|
-
'GetNextBlocks', 'GetBlockTransactions', 'GetCurrentSlot', 'GetEpoch', 'GetAddress', 'GetAddressUtxos',
|
|
112
|
-
'GetAddressTransactions', 'GetAddressTransactionHashes', 'GetCredentialUtxos', 'IsUtxoUnspent',
|
|
113
|
-
'GetUnspentOutputs', 'GetAccount', 'GetPool', 'GetPoolIds', 'GetPools', 'GetDrep', 'GetDrepIds', 'GetDreps',
|
|
114
|
-
'GetProtocolParameters', 'EvaluateTransaction',
|
|
115
|
-
]);
|
|
116
|
-
/** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
|
|
117
|
-
exports.AGENT_JOB_KINDS = ['simpleAda', 'metadata', 'multiAsset', 'mint', 'plutusSpend', 'submitSigned'];
|
|
118
72
|
/** Grant administration limiter: `adminRateLimit` calls per principal per hour, built on first use. */
|
|
119
73
|
let grantAdminRateLimiter = null;
|
|
120
74
|
function grantAdminLimiter() {
|
|
121
|
-
grantAdminRateLimiter ??= new rate_limiter_1.RateLimiter({ windowMs: 60 * 60 * 1000, maxRequests: (0,
|
|
75
|
+
grantAdminRateLimiter ??= new rate_limiter_1.RateLimiter({ windowMs: 60 * 60 * 1000, maxRequests: (0, config_1.loadGrantAdminRateLimit)() });
|
|
122
76
|
return grantAdminRateLimiter;
|
|
123
77
|
}
|
|
124
78
|
/** Forget every rate-limit window, the token cache and re-read the knobs from the config (tests). */
|
|
@@ -154,6 +108,11 @@ function parseGrantList(raw) {
|
|
|
154
108
|
return [];
|
|
155
109
|
}
|
|
156
110
|
}
|
|
111
|
+
/** The stored allow list without names that are no longer grantable. */
|
|
112
|
+
function grantedActions(grant) {
|
|
113
|
+
const grantable = (0, agent_access_1.agentGrantableActions)();
|
|
114
|
+
return parseGrantList(grant.allowedActions).filter((a) => grantable.includes(a));
|
|
115
|
+
}
|
|
157
116
|
function utcDay(now = new Date()) {
|
|
158
117
|
return now.toISOString().slice(0, 10);
|
|
159
118
|
}
|
|
@@ -178,7 +137,7 @@ let tokenCacheGeneration = 0;
|
|
|
178
137
|
function tokenCacheTtl() {
|
|
179
138
|
if (tokenCacheOverride !== null)
|
|
180
139
|
return tokenCacheOverride;
|
|
181
|
-
tokenCacheMs ??= (0,
|
|
140
|
+
tokenCacheMs ??= (0, config_1.loadTokenCacheMs)();
|
|
182
141
|
return tokenCacheMs;
|
|
183
142
|
}
|
|
184
143
|
/** Test seam: cache lifetime in ms for injected runners too (null = config, injected runners bypass). */
|
|
@@ -242,8 +201,9 @@ async function resolveAgentToken(token, runner = dbRunner()) {
|
|
|
242
201
|
function makeAgentUser(grant) {
|
|
243
202
|
return new cds_1.default.User({
|
|
244
203
|
id: agentPrincipalId(grant.ID),
|
|
245
|
-
roles
|
|
246
|
-
|
|
204
|
+
// the service roles let a token past the model; its grant decides per operation
|
|
205
|
+
roles: [exports.AGENT_ROLE, 'Read', 'Transact', 'Sign'],
|
|
206
|
+
attr: { grantId: grant.ID, operator: grant.userId },
|
|
247
207
|
});
|
|
248
208
|
}
|
|
249
209
|
/** A refused grant input; carries the 400 the action answers with. */
|
|
@@ -259,31 +219,12 @@ function validateGrantInput(input, now = new Date(), context = 'CreateAgentGrant
|
|
|
259
219
|
if (!Array.isArray(actions) || actions.length === 0) {
|
|
260
220
|
throw fail('allowedActions must be a non-empty array', 'allowedActions');
|
|
261
221
|
}
|
|
262
|
-
const
|
|
222
|
+
const grantable = (0, agent_access_1.agentGrantableActions)();
|
|
223
|
+
const unknown = actions.filter((a) => !grantable.includes(a));
|
|
263
224
|
if (unknown.length > 0) {
|
|
264
|
-
throw fail(`allowedActions contains non-grantable entries: ${unknown.join(', ')}. Grantable: ${
|
|
225
|
+
throw fail(`allowedActions contains non-grantable entries: ${unknown.join(', ')}. Grantable: ${grantable.join(', ')}`, 'allowedActions');
|
|
265
226
|
}
|
|
266
227
|
const uniqueActions = [...new Set(actions)];
|
|
267
|
-
const walletId = typeof input.walletId === 'string' && input.walletId.trim() ? input.walletId.trim() : null;
|
|
268
|
-
const wantsWallet = uniqueActions.some((a) => exports.AGENT_WALLET_ACTIONS.has(a));
|
|
269
|
-
if (wantsWallet && !walletId) {
|
|
270
|
-
throw fail('walletId is required when SubmitWalletJob or CancelJob is allowed', 'walletId');
|
|
271
|
-
}
|
|
272
|
-
if (walletId && walletId.length > 50)
|
|
273
|
-
throw fail('walletId must be at most 50 characters', 'walletId');
|
|
274
|
-
let allowedJobKinds = [];
|
|
275
|
-
if (input.allowedJobKinds !== undefined && input.allowedJobKinds !== null) {
|
|
276
|
-
if (!Array.isArray(input.allowedJobKinds))
|
|
277
|
-
throw fail('allowedJobKinds must be an array', 'allowedJobKinds');
|
|
278
|
-
const badKinds = input.allowedJobKinds.filter((k) => !exports.AGENT_JOB_KINDS.includes(k));
|
|
279
|
-
if (badKinds.length > 0) {
|
|
280
|
-
throw fail(`allowedJobKinds contains unknown kinds: ${badKinds.join(', ')}. Known: ${exports.AGENT_JOB_KINDS.join(', ')}`, 'allowedJobKinds');
|
|
281
|
-
}
|
|
282
|
-
allowedJobKinds = [...new Set(input.allowedJobKinds)];
|
|
283
|
-
if (allowedJobKinds.length > 0 && !wantsWallet) {
|
|
284
|
-
throw fail('allowedJobKinds needs SubmitWalletJob in allowedActions', 'allowedJobKinds');
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
228
|
let maxJobsPerDay = null;
|
|
288
229
|
if (input.maxJobsPerDay !== undefined && input.maxJobsPerDay !== null) {
|
|
289
230
|
const n = Number(input.maxJobsPerDay);
|
|
@@ -303,7 +244,7 @@ function validateGrantInput(input, now = new Date(), context = 'CreateAgentGrant
|
|
|
303
244
|
const agentLabel = typeof input.agentLabel === 'string' && input.agentLabel.trim() ? input.agentLabel.trim() : null;
|
|
304
245
|
if (agentLabel && agentLabel.length > 100)
|
|
305
246
|
throw fail('agentLabel must be at most 100 characters', 'agentLabel');
|
|
306
|
-
return { allowedActions: uniqueActions,
|
|
247
|
+
return { allowedActions: uniqueActions, maxJobsPerDay, validUntil, agentLabel };
|
|
307
248
|
}
|
|
308
249
|
/** Mint a grant for `operatorId` on `runner`; validation errors surface as AgentGrantInputError (400). */
|
|
309
250
|
async function issueAgentGrant(input, operatorId, runner = dbRunner()) {
|
|
@@ -317,8 +258,6 @@ async function issueAgentGrant(input, operatorId, runner = dbRunner()) {
|
|
|
317
258
|
agentLabel: n.agentLabel,
|
|
318
259
|
tokenHash: hashAgentToken(token),
|
|
319
260
|
allowedActions: JSON.stringify(n.allowedActions),
|
|
320
|
-
walletId: n.walletId,
|
|
321
|
-
allowedJobKinds: n.allowedJobKinds.length > 0 ? JSON.stringify(n.allowedJobKinds) : null,
|
|
322
261
|
maxJobsPerDay: n.maxJobsPerDay,
|
|
323
262
|
jobsUsedToday: 0,
|
|
324
263
|
budgetWindow: null,
|
|
@@ -332,14 +271,12 @@ async function issueAgentGrant(input, operatorId, runner = dbRunner()) {
|
|
|
332
271
|
// never logs the token
|
|
333
272
|
logger.info(`agent grant ${grant.ID} issued by ${operatorId}` +
|
|
334
273
|
`${n.agentLabel ? ` for '${n.agentLabel}'` : ''} (actions: ${n.allowedActions.join(', ')}` +
|
|
335
|
-
`${n.
|
|
274
|
+
`${n.maxJobsPerDay ? `, budget ${n.maxJobsPerDay}/day` : ''}` +
|
|
336
275
|
`${n.validUntil ? `, until ${n.validUntil}` : ''})`);
|
|
337
276
|
return {
|
|
338
277
|
grantId: grant.ID,
|
|
339
278
|
token,
|
|
340
279
|
allowedActions: n.allowedActions,
|
|
341
|
-
walletId: n.walletId,
|
|
342
|
-
allowedJobKinds: n.allowedJobKinds,
|
|
343
280
|
maxJobsPerDay: n.maxJobsPerDay,
|
|
344
281
|
validUntil: n.validUntil,
|
|
345
282
|
};
|
|
@@ -369,10 +306,10 @@ async function rotateAgentGrantToken(grantId, runner = dbRunner()) {
|
|
|
369
306
|
logger.info(`agent grant ${grantId} token rotated`);
|
|
370
307
|
return { grantId, token };
|
|
371
308
|
}
|
|
372
|
-
/** Row fields a grant edit never touches
|
|
373
|
-
exports.GRANT_IMMUTABLE_FIELDS = ['
|
|
309
|
+
/** Row fields a grant edit never touches. */
|
|
310
|
+
exports.GRANT_IMMUTABLE_FIELDS = ['userId', 'tokenHash'];
|
|
374
311
|
const GRANT_EDITABLE_FIELDS = [
|
|
375
|
-
'agentLabel', 'allowedActions', '
|
|
312
|
+
'agentLabel', 'allowedActions', 'maxJobsPerDay', 'validUntil',
|
|
376
313
|
];
|
|
377
314
|
// Edit an active grant. An absent field stays, an explicit null clears it; allowedActions cannot be emptied.
|
|
378
315
|
// Unknown grant is 404, revoked is 409 GRANT_REVOKED, invalid input is 400.
|
|
@@ -385,9 +322,7 @@ async function updateAgentGrant(grantId, input, runner = dbRunner()) {
|
|
|
385
322
|
return { ok: false, status: 409, code: 'GRANT_REVOKED', message: 'Grant is revoked' };
|
|
386
323
|
// validUntil only when given: an untouched, already passed expiry is the lane's 410, not this edit's 400
|
|
387
324
|
const n = validateGrantInput({
|
|
388
|
-
allowedActions: has('allowedActions') ? input.allowedActions :
|
|
389
|
-
walletId: existing.walletId ?? null,
|
|
390
|
-
allowedJobKinds: has('allowedJobKinds') ? input.allowedJobKinds : parseGrantList(existing.allowedJobKinds),
|
|
325
|
+
allowedActions: has('allowedActions') ? input.allowedActions : grantedActions(existing),
|
|
391
326
|
maxJobsPerDay: has('maxJobsPerDay') ? input.maxJobsPerDay : existing.maxJobsPerDay,
|
|
392
327
|
validUntil: has('validUntil') ? input.validUntil : null,
|
|
393
328
|
agentLabel: has('agentLabel') ? input.agentLabel : existing.agentLabel,
|
|
@@ -395,8 +330,6 @@ async function updateAgentGrant(grantId, input, runner = dbRunner()) {
|
|
|
395
330
|
const patch = {};
|
|
396
331
|
if (has('allowedActions'))
|
|
397
332
|
patch.allowedActions = JSON.stringify(n.allowedActions);
|
|
398
|
-
if (has('allowedJobKinds'))
|
|
399
|
-
patch.allowedJobKinds = n.allowedJobKinds.length > 0 ? JSON.stringify(n.allowedJobKinds) : null;
|
|
400
333
|
if (has('maxJobsPerDay'))
|
|
401
334
|
patch.maxJobsPerDay = n.maxJobsPerDay;
|
|
402
335
|
if (has('validUntil'))
|
|
@@ -475,9 +408,7 @@ function toGrantStatus(grant) {
|
|
|
475
408
|
return {
|
|
476
409
|
grantId: grant.ID,
|
|
477
410
|
agentLabel: grant.agentLabel ?? null,
|
|
478
|
-
allowedActions:
|
|
479
|
-
walletId: grant.walletId ?? null,
|
|
480
|
-
allowedJobKinds: parseGrantList(grant.allowedJobKinds),
|
|
411
|
+
allowedActions: grantedActions(grant),
|
|
481
412
|
maxJobsPerDay: grant.maxJobsPerDay ?? null,
|
|
482
413
|
// a counter from an earlier UTC day belongs to a window that is over
|
|
483
414
|
jobsUsedToday: grant.budgetWindow === utcDay() ? Number(grant.jobsUsedToday ?? 0) : 0,
|
|
@@ -531,8 +462,6 @@ function registerAgentGrantHandlers(srv) {
|
|
|
531
462
|
grantId: issued.grantId,
|
|
532
463
|
token: issued.token,
|
|
533
464
|
allowedActions: issued.allowedActions,
|
|
534
|
-
walletId: issued.walletId,
|
|
535
|
-
allowedJobKinds: issued.allowedJobKinds,
|
|
536
465
|
maxJobsPerDay: issued.maxJobsPerDay,
|
|
537
466
|
validUntil: issued.validUntil,
|
|
538
467
|
};
|
|
@@ -567,7 +496,7 @@ function registerAgentGrantHandlers(srv) {
|
|
|
567
496
|
return req.reject(400, 'grantId is required', 'grantId');
|
|
568
497
|
const immutable = exports.GRANT_IMMUTABLE_FIELDS.filter((f) => Object.prototype.hasOwnProperty.call(data, f));
|
|
569
498
|
if (immutable.length > 0) {
|
|
570
|
-
return req.reject(400, `${immutable.join(', ')} cannot be changed
|
|
499
|
+
return req.reject(400, `${immutable.join(', ')} cannot be changed`, immutable[0]);
|
|
571
500
|
}
|
|
572
501
|
let result;
|
|
573
502
|
try {
|
|
@@ -630,7 +559,7 @@ function budgetRunnerFor(req, injected, detached) {
|
|
|
630
559
|
catch {
|
|
631
560
|
tx = null;
|
|
632
561
|
}
|
|
633
|
-
if (tx && (
|
|
562
|
+
if (tx && (0, tx_utils_1.holdsConnection)(tx))
|
|
634
563
|
return { runner: tx, detached: false };
|
|
635
564
|
return { runner: dbRunner(), detached: true };
|
|
636
565
|
}
|
|
@@ -658,7 +587,7 @@ function ownStatus(e) {
|
|
|
658
587
|
const code = Number(e?.code);
|
|
659
588
|
return Number.isInteger(code) && code >= 400 && code < 600 ? code : undefined;
|
|
660
589
|
}
|
|
661
|
-
/** The before('*') hook for token requests:
|
|
590
|
+
/** The before('*') hook for token requests: closed services, allow list, daily budget and usage. */
|
|
662
591
|
async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown') {
|
|
663
592
|
const grant = agentGrantOf(req);
|
|
664
593
|
if (!grant)
|
|
@@ -668,9 +597,13 @@ async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown')
|
|
|
668
597
|
return req.reject(401, 'invalid agent token');
|
|
669
598
|
if (isExpired(grant))
|
|
670
599
|
return req.reject(410, 'agent grant expired');
|
|
671
|
-
const br = budgetRunnerFor(req, runner, detached);
|
|
672
600
|
const event = String(req.event ?? '');
|
|
673
|
-
|
|
601
|
+
const access = (0, agent_access_1.agentAccessOf)(serviceName, event);
|
|
602
|
+
if (access === 'closed') {
|
|
603
|
+
return req.reject(403, 'worker wallets are not available to agent tokens');
|
|
604
|
+
}
|
|
605
|
+
const br = budgetRunnerFor(req, runner, detached);
|
|
606
|
+
if (access === 'read') {
|
|
674
607
|
// a token sees its own usage only; a foreign id is not found (non-leaking)
|
|
675
608
|
if (event === 'GetGrantUsage') {
|
|
676
609
|
const asked = String(req.data?.grantId ?? '');
|
|
@@ -680,29 +613,9 @@ async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown')
|
|
|
680
613
|
await touchLastUsed(grant, br);
|
|
681
614
|
return;
|
|
682
615
|
}
|
|
683
|
-
|
|
684
|
-
if (!allowed.includes(event)) {
|
|
616
|
+
if (access !== 'grant' || !grantedActions(grant).includes(event)) {
|
|
685
617
|
return req.reject(403, `action '${event}' is not allowed for this agent grant`);
|
|
686
618
|
}
|
|
687
|
-
const data = req.data;
|
|
688
|
-
if (exports.AGENT_WALLET_ACTIONS.has(event)) {
|
|
689
|
-
if (!grant.walletId) {
|
|
690
|
-
return req.reject(403, 'this agent grant has no wallet binding; issue it with walletId to queue wallet jobs');
|
|
691
|
-
}
|
|
692
|
-
if (data && typeof data === 'object') {
|
|
693
|
-
if (event === 'SubmitWalletJob') {
|
|
694
|
-
if (data.walletId !== undefined && data.walletId !== null && data.walletId !== '' && data.walletId !== grant.walletId) {
|
|
695
|
-
return req.reject(403, 'walletId does not match this agent grant');
|
|
696
|
-
}
|
|
697
|
-
data.walletId = grant.walletId;
|
|
698
|
-
const kinds = parseGrantList(grant.allowedJobKinds);
|
|
699
|
-
if (kinds.length > 0 && !kinds.includes(String(data.kind ?? ''))) {
|
|
700
|
-
return req.reject(403, `job kind '${String(data.kind ?? '')}' is not allowed for this agent grant (allowed: ${kinds.join(', ')})`);
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
// CancelJob: the worker service scopes the job lookup by createdBy = agent:<grantId>
|
|
704
|
-
}
|
|
705
|
-
}
|
|
706
619
|
let charge = null;
|
|
707
620
|
if (grant.maxJobsPerDay !== undefined && grant.maxJobsPerDay !== null) {
|
|
708
621
|
charge = await consumeDailyBudget(br, grant);
|
|
@@ -809,6 +722,30 @@ function bufferUsage(key, calls, refunded) {
|
|
|
809
722
|
cds_1.default.on('shutdown', () => flushGrantUsage().catch(() => undefined));
|
|
810
723
|
}
|
|
811
724
|
}
|
|
725
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
726
|
+
/** UTC day of the last retention run of this process. */
|
|
727
|
+
let usagePrunedOn = null;
|
|
728
|
+
/** Test seam: the day the retention last ran (null = not yet). */
|
|
729
|
+
function __setGrantUsagePrunedForTests(day) {
|
|
730
|
+
usagePrunedOn = day;
|
|
731
|
+
}
|
|
732
|
+
// Once per UTC day and process: delete the usage rows older than the retention. Never fails the caller.
|
|
733
|
+
async function pruneGrantUsage(runner, now = new Date()) {
|
|
734
|
+
const today = utcDay(now);
|
|
735
|
+
if (usagePrunedOn === today)
|
|
736
|
+
return;
|
|
737
|
+
usagePrunedOn = today;
|
|
738
|
+
const days = (0, config_1.loadGrantUsageRetentionDays)();
|
|
739
|
+
if (days === 0)
|
|
740
|
+
return;
|
|
741
|
+
const before = utcDay(new Date(now.getTime() - days * DAY_MS));
|
|
742
|
+
try {
|
|
743
|
+
await runStmt(runner, DELETE.from(exports.GRANT_USAGE_ENTITY).where({ day: { '<': before } }));
|
|
744
|
+
}
|
|
745
|
+
catch (err) {
|
|
746
|
+
logger.warn(`usage retention failed: ${String(err?.message ?? err)}`);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
812
749
|
/** Write the buffered deltas per key. A failed delta goes back into the buffer for the next flush. */
|
|
813
750
|
async function flushGrantUsage(runner = dbRunner()) {
|
|
814
751
|
if (usageBuffer.size === 0)
|
|
@@ -845,6 +782,7 @@ async function flushGrantUsage(runner = dbRunner()) {
|
|
|
845
782
|
logger.warn(`usage flush for grant ${d.grant_ID} (${d.service}.${d.action}) failed, kept for retry: ${String(err?.message ?? err)}`);
|
|
846
783
|
}
|
|
847
784
|
}
|
|
785
|
+
await pruneGrantUsage(br);
|
|
848
786
|
return { flushed, failed };
|
|
849
787
|
}
|
|
850
788
|
/** Count one admitted call on (grant, UTC day, service, action). Never fails the request; returns the day counted on. */
|
|
@@ -858,18 +796,19 @@ async function recordGrantUsage(br, grant, service, action, now = new Date()) {
|
|
|
858
796
|
}
|
|
859
797
|
const bump = () => runStmt(runner, UPDATE.entity(exports.GRANT_USAGE_ENTITY).set({ calls: { '+=': 1 } }).where(key));
|
|
860
798
|
try {
|
|
861
|
-
if (Number(await bump())
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
799
|
+
if (Number(await bump()) === 0) {
|
|
800
|
+
try {
|
|
801
|
+
await runStmt(runner, INSERT.into(exports.GRANT_USAGE_ENTITY).entries({ ...key, calls: 1, refunded: 0 }));
|
|
802
|
+
}
|
|
803
|
+
catch {
|
|
804
|
+
await bump(); // lost the insert race: the row exists now
|
|
805
|
+
}
|
|
868
806
|
}
|
|
869
807
|
}
|
|
870
808
|
catch (err) {
|
|
871
809
|
logger.warn(`usage record for grant ${grant.ID} (${service}.${action}) failed: ${String(err?.message ?? err)}`);
|
|
872
810
|
}
|
|
811
|
+
await pruneGrantUsage(runner, now);
|
|
873
812
|
return day;
|
|
874
813
|
}
|
|
875
814
|
/** `refunded + 1` on the row the call was counted on; deferred mode buffers it on the same key. */
|
package/srv/utils/const.d.ts
CHANGED
|
@@ -117,6 +117,10 @@ export declare const MAX_POSIX_MS_DIGITS = 13;
|
|
|
117
117
|
export declare const HEX_64_REGEX: RegExp;
|
|
118
118
|
/** Generic 56-character hex string: 28-byte hashes (Blake2b-224, payment credential, script hash, pool key hash) */
|
|
119
119
|
export declare const HEX_56_REGEX: RegExp;
|
|
120
|
+
/** How long a stored address, account, pool, DRep or asset answers before it is read again. */
|
|
121
|
+
export declare const DEFAULT_INDEX_TTL_MS = 3600000;
|
|
122
|
+
/** How long protocol parameters answer before the backend is asked again. */
|
|
123
|
+
export declare const PROTOCOL_PARAMS_TTL_MS: number;
|
|
120
124
|
/** Transaction hash: 64-character hex string */
|
|
121
125
|
export declare const TX_HASH_REGEX: RegExp;
|
|
122
126
|
/** Asset unit: policy ID (56 hex) + asset name (0-32 bytes = 0-64 hex, even length; total <= 120 = String(120) key column) */
|
package/srv/utils/const.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.DREP_ID_REGEX = exports.POOL_ID_REGEX = exports.ASSET_UNIT_REGEX = exports.TX_HASH_REGEX = exports.HEX_56_REGEX = exports.HEX_64_REGEX = exports.MAX_POSIX_MS_DIGITS = exports.DEFAULT_VALIDITY_END_OFFSET_MS = exports.DEFAULT_VALIDITY_START_OFFSET_MS = exports.GENESIS_INFOS_BY_NETWORK = exports.MIN_CHANGE_LOVELACE = exports.ED25519_KEY_HASH_REGEX = exports.ED25519_KEY_HASH_HEX_LENGTH = exports.MIN_FULL_ASSET_UNIT_LENGTH = exports.POLICY_ID_HEX_LENGTH = exports.DREP_ID_BYTES = exports.POOL_ID_BYTES = exports.MAX_EPOCH = exports.MAX_TX_CBOR_HEX_LENGTH = exports.BECH32_MAX_LENGTH = exports.MAX_STRING_LENGTH = exports.MAX_ARRAY_LENGTH = exports.MAX_KEYS = exports.PLUTUS_DATA_MAX_DEPTH = exports.MAX_DEPTH = exports.MAX_JSON_SIZE = exports.HRP = exports.FEE_BUFFER_LOVELACE = exports.COLLATERAL_LOVELACE = exports.ABS_MEM_BUFFER = exports.ABS_CPU_BUFFER = exports.EXECUTION_UNIT_BUFFER = exports.HIGH_EXECUTION_UNITS = exports.DEFAULT_EXECUTION_UNITS = exports.EPOCH_CONFIG_BY_NETWORK = exports.CARDANO_DEFAULTS = void 0;
|
|
3
|
+
exports.DREP_ID_REGEX = exports.POOL_ID_REGEX = exports.ASSET_UNIT_REGEX = exports.TX_HASH_REGEX = exports.PROTOCOL_PARAMS_TTL_MS = exports.DEFAULT_INDEX_TTL_MS = exports.HEX_56_REGEX = exports.HEX_64_REGEX = exports.MAX_POSIX_MS_DIGITS = exports.DEFAULT_VALIDITY_END_OFFSET_MS = exports.DEFAULT_VALIDITY_START_OFFSET_MS = exports.GENESIS_INFOS_BY_NETWORK = exports.MIN_CHANGE_LOVELACE = exports.ED25519_KEY_HASH_REGEX = exports.ED25519_KEY_HASH_HEX_LENGTH = exports.MIN_FULL_ASSET_UNIT_LENGTH = exports.POLICY_ID_HEX_LENGTH = exports.DREP_ID_BYTES = exports.POOL_ID_BYTES = exports.MAX_EPOCH = exports.MAX_TX_CBOR_HEX_LENGTH = exports.BECH32_MAX_LENGTH = exports.MAX_STRING_LENGTH = exports.MAX_ARRAY_LENGTH = exports.MAX_KEYS = exports.PLUTUS_DATA_MAX_DEPTH = exports.MAX_DEPTH = exports.MAX_JSON_SIZE = exports.HRP = exports.FEE_BUFFER_LOVELACE = exports.COLLATERAL_LOVELACE = exports.ABS_MEM_BUFFER = exports.ABS_CPU_BUFFER = exports.EXECUTION_UNIT_BUFFER = exports.HIGH_EXECUTION_UNITS = exports.DEFAULT_EXECUTION_UNITS = exports.EPOCH_CONFIG_BY_NETWORK = exports.CARDANO_DEFAULTS = void 0;
|
|
4
4
|
/** Cardano protocol constants */
|
|
5
5
|
exports.CARDANO_DEFAULTS = {
|
|
6
6
|
/** Maximum ADA supply in lovelace (45 billion ADA) */
|
|
@@ -91,6 +91,10 @@ exports.MAX_POSIX_MS_DIGITS = 13;
|
|
|
91
91
|
exports.HEX_64_REGEX = /^[a-f0-9]{64}$/;
|
|
92
92
|
/** Generic 56-character hex string: 28-byte hashes (Blake2b-224, payment credential, script hash, pool key hash) */
|
|
93
93
|
exports.HEX_56_REGEX = /^[a-f0-9]{56}$/;
|
|
94
|
+
/** How long a stored address, account, pool, DRep or asset answers before it is read again. */
|
|
95
|
+
exports.DEFAULT_INDEX_TTL_MS = 3_600_000;
|
|
96
|
+
/** How long protocol parameters answer before the backend is asked again. */
|
|
97
|
+
exports.PROTOCOL_PARAMS_TTL_MS = 5 * 60 * 1000;
|
|
94
98
|
/** Transaction hash: 64-character hex string */
|
|
95
99
|
exports.TX_HASH_REGEX = /^[a-f0-9]{64}$/;
|
|
96
100
|
/** Asset unit: policy ID (56 hex) + asset name (0-32 bytes = 0-64 hex, even length; total <= 120 = String(120) key column) */
|