@odatano/core 2.0.0-rc.5 → 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 +99 -51
- package/@cds-models/CardanoAgentService/index.js +15 -0
- package/@cds-models/CardanoBackendService/index.d.ts +347 -0
- package/@cds-models/CardanoBackendService/index.js +40 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
- package/@cds-models/CardanoIndexerService/index.js +64 -0
- package/@cds-models/CardanoODataService/index.d.ts +414 -57
- package/@cds-models/CardanoODataService/index.js +42 -0
- package/@cds-models/CardanoSignService/index.d.ts +32 -19
- package/@cds-models/CardanoSignService/index.js +3 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
- package/@cds-models/CardanoTransactionService/index.js +4 -0
- package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
- package/@cds-models/index.d.ts +101 -1
- package/@cds-models/index.js +16 -1
- package/@cds-models/odatano/cardano/index.d.ts +437 -32
- package/@cds-models/odatano/cardano/index.js +48 -0
- package/README.md +207 -167
- package/db/schema.cds +2402 -1705
- package/db/types.cds +446 -295
- package/package.json +41 -16
- package/scripts/migrate-schema.mjs +334 -0
- package/scripts/migrate-slot-leader.mjs +96 -0
- package/src/index.d.ts +20 -21
- package/src/index.js +45 -31
- package/src/plugin.js +17 -35
- package/srv/blockchain/asset-decimals.d.ts +7 -0
- package/srv/blockchain/asset-decimals.js +91 -0
- package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
- package/srv/blockchain/backends/blockfrost-backend.js +66 -172
- package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
- package/srv/blockchain/backends/cardano-backend.js +29 -5
- package/srv/blockchain/backends/koios-backend.d.ts +103 -168
- package/srv/blockchain/backends/koios-backend.js +428 -360
- package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
- package/srv/blockchain/backends/odatano-backend.js +169 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
- package/srv/blockchain/backends/ogmios-backend.js +637 -315
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
- package/srv/blockchain/cardano-client.d.ts +61 -241
- package/srv/blockchain/cardano-client.js +253 -293
- package/srv/blockchain/cardano-indexer.d.ts +282 -281
- package/srv/blockchain/cardano-indexer.js +1551 -484
- package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
- package/srv/blockchain/cardano-tx-builder.js +164 -140
- package/srv/blockchain/circuit-breaker.d.ts +1 -13
- package/srv/blockchain/circuit-breaker.js +5 -15
- package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
- package/srv/blockchain/crawler/account-snapshots.js +153 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
- package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
- package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
- package/srv/blockchain/crawler/certificate-backfill.js +162 -0
- package/srv/blockchain/crawler/crawler.d.ts +104 -81
- package/srv/blockchain/crawler/crawler.js +532 -160
- package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
- package/srv/blockchain/crawler/credential-backfill.js +124 -0
- package/srv/blockchain/crawler/hooks.d.ts +2 -17
- package/srv/blockchain/crawler/index.d.ts +1 -8
- package/srv/blockchain/crawler/index.js +31 -17
- 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/sync-state.d.ts +27 -47
- package/srv/blockchain/crawler/sync-state.js +113 -63
- package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
- package/srv/blockchain/crawler/transaction-backfill.js +278 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
- package/srv/blockchain/crawler/utxo-set-import.js +399 -0
- package/srv/blockchain/ledger-state.d.ts +62 -0
- package/srv/blockchain/ledger-state.js +419 -0
- package/srv/blockchain/pending-spends.d.ts +16 -0
- package/srv/blockchain/pending-spends.js +81 -0
- package/srv/blockchain/pool-metadata.d.ts +15 -0
- package/srv/blockchain/pool-metadata.js +132 -0
- package/srv/blockchain/request-coalescer.d.ts +2 -16
- package/srv/blockchain/request-coalescer.js +2 -16
- package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
- package/srv/blockchain/signing/cose-verifier.js +146 -70
- package/srv/blockchain/signing/external-signer.d.ts +15 -115
- package/srv/blockchain/signing/external-signer.js +17 -126
- package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
- package/srv/blockchain/signing/hsm-signer.js +28 -79
- package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
- package/srv/blockchain/signing/signature-verifier.js +70 -83
- package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
- package/srv/blockchain/signing/submission-finalizer.js +219 -86
- package/srv/blockchain/stored-chain.d.ts +20 -0
- package/srv/blockchain/stored-chain.js +237 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
- package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
- package/srv/blockchain/transaction-presence.d.ts +5 -0
- package/srv/blockchain/transaction-presence.js +29 -0
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +44 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
- package/srv/blockchain/wallet-worker/build-request.js +47 -30
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
- package/srv/blockchain/wallet-worker/index.d.ts +1 -1
- package/srv/blockchain/wallet-worker/index.js +3 -11
- package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
- package/srv/blockchain/wallet-worker/job-store.js +101 -201
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
- package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
- package/srv/blockchain/wallet-worker/signers.js +4 -12
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
- package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
- package/srv/cardano-agent-service.cds +122 -84
- package/srv/cardano-agent-service.js +4 -9
- package/srv/cardano-backend-service.cds +78 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +242 -0
- package/srv/cardano-indexer-service.cds +387 -73
- package/srv/cardano-indexer-service.d.ts +5 -1
- package/srv/cardano-indexer-service.js +532 -16
- package/srv/cardano-service.cds +424 -269
- package/srv/cardano-service.js +289 -201
- package/srv/cardano-sign-service.cds +201 -180
- package/srv/cardano-sign-service.js +71 -201
- package/srv/cardano-tx-service.cds +451 -370
- package/srv/cardano-tx-service.js +271 -289
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.cds +118 -125
- package/srv/cardano-worker-service.js +52 -61
- package/srv/cbor/cip68.d.ts +13 -0
- package/srv/cbor/cip68.js +56 -0
- package/srv/cbor/index.d.ts +3 -1
- package/srv/cbor/index.js +9 -1
- package/srv/cbor/parse.d.ts +30 -18
- package/srv/cbor/parse.js +44 -9
- package/srv/cbor/plutus-data-json.d.ts +20 -0
- package/srv/cbor/plutus-data-json.js +32 -0
- package/srv/config.d.ts +113 -0
- package/srv/config.js +409 -0
- package/srv/server.d.ts +15 -110
- package/srv/server.js +84 -404
- 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 -46
- package/srv/utils/agent-grants-config.js +17 -85
- package/srv/utils/agent-grants.d.ts +106 -122
- package/srv/utils/agent-grants.js +538 -236
- package/srv/utils/agent-token-auth.d.ts +4 -99
- package/srv/utils/agent-token-auth.js +18 -182
- package/srv/utils/backend-request-handler.d.ts +3 -17
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/collections.d.ts +3 -10
- package/srv/utils/collections.js +3 -10
- package/srv/utils/const.d.ts +23 -74
- package/srv/utils/const.js +32 -79
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +6 -21
- package/srv/utils/db-indexes.d.ts +27 -0
- package/srv/utils/db-indexes.js +120 -0
- package/srv/utils/db-sanitize.d.ts +20 -0
- package/srv/utils/db-sanitize.js +80 -0
- package/srv/utils/deep-json.d.ts +6 -0
- package/srv/utils/deep-json.js +240 -0
- package/srv/utils/epoch-slots.d.ts +13 -0
- package/srv/utils/epoch-slots.js +38 -0
- package/srv/utils/error-codes.d.ts +22 -75
- package/srv/utils/error-codes.js +23 -72
- package/srv/utils/errors.d.ts +46 -187
- package/srv/utils/errors.js +114 -230
- package/srv/utils/liveness.d.ts +12 -0
- package/srv/utils/liveness.js +35 -0
- package/srv/utils/mappers.d.ts +102 -223
- package/srv/utils/mappers.js +387 -316
- package/srv/utils/network-context.js +2 -13
- package/srv/utils/paging.d.ts +31 -0
- package/srv/utils/paging.js +43 -0
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +58 -0
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +54 -0
- package/srv/utils/plutus-placeholders.d.ts +16 -22
- package/srv/utils/plutus-placeholders.js +62 -33
- package/srv/utils/rate-limiter.d.ts +2 -21
- package/srv/utils/rate-limiter.js +5 -17
- package/srv/utils/readiness.d.ts +12 -0
- package/srv/utils/readiness.js +29 -0
- package/srv/utils/reference-script.d.ts +19 -0
- package/srv/utils/reference-script.js +84 -0
- package/srv/utils/result-numbers.d.ts +15 -0
- package/srv/utils/result-numbers.js +61 -0
- package/srv/utils/service-events.d.ts +0 -24
- package/srv/utils/service-events.js +3 -25
- package/srv/utils/signing-helper.d.ts +3 -20
- package/srv/utils/signing-helper.js +35 -64
- package/srv/utils/tx-build-helper.d.ts +10 -105
- package/srv/utils/tx-build-helper.js +81 -144
- package/srv/utils/tx-request-parsers.d.ts +82 -33
- package/srv/utils/tx-request-parsers.js +401 -49
- package/srv/utils/tx-utils.d.ts +3 -27
- package/srv/utils/tx-utils.js +32 -50
- package/srv/utils/types.d.ts +261 -191
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +22 -92
- package/srv/utils/validators.js +50 -149
|
@@ -1,57 +1,53 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
* Design: AGENT_GRANTS_DESIGN.md. Reference: NIGHTGATE srv/sessions/agent-grants.ts.
|
|
5
|
-
*
|
|
6
|
-
* Three exports carry the feature:
|
|
7
|
-
* - `resolveAgentToken` + `makeAgentUser`: used by the transport lane
|
|
8
|
-
* (agent-token-auth.ts) to turn an `x-agent-token` header into the principal
|
|
9
|
-
* `agent:<grantId>` with the role `agent-grant` BEFORE any service hook runs.
|
|
10
|
-
* Doing the authentication at the transport (not in a before-hook) matters:
|
|
11
|
-
* CAP runs before-handlers in parallel, so CAP's own @requires / @restrict
|
|
12
|
-
* evaluation must already see the final principal.
|
|
13
|
-
* - `attachAgentGrantEnforcement`: the before('*') hook on all six ODATANO
|
|
14
|
-
* services. Allow list (403), wallet pinning (403), daily budget (429),
|
|
15
|
-
* lastUsedAt. Ownership needs no special code: a token's jobs are created
|
|
16
|
-
* with createdBy = `agent:<grantId>`, so the existing `createdBy = $user`
|
|
17
|
-
* gates and the `$user.grantId` row restrictions do the narrowing.
|
|
18
|
-
* - `registerAgentGrantHandlers`: CreateAgentGrant / RevokeAgentGrant /
|
|
19
|
-
* GetGrantStatus for CardanoAgentService, on top of the programmatic
|
|
20
|
-
* `issueAgentGrant` / `revokeAgentGrantById` that @odatano/x402 uses to sell
|
|
21
|
-
* grants.
|
|
22
|
-
*
|
|
23
|
-
* The token is a capability, not an identity: it never carries the operator's
|
|
24
|
-
* roles, so every `@requires: 'Admin'` surface refuses it by construction.
|
|
25
|
-
*/
|
|
2
|
+
// Agent grants: scoped, budgeted bearer tokens. A token request runs as `agent:<grantId>` with the role `agent-grant`.
|
|
3
|
+
// attachAgentGrantEnforcement checks allow list, wallet and budget; registerAgentGrantHandlers is the admin API.
|
|
26
4
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
27
5
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
28
6
|
};
|
|
29
7
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
30
|
-
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;
|
|
31
9
|
exports.__resetGrantRateLimiterForTests = __resetGrantRateLimiterForTests;
|
|
32
10
|
exports.hashAgentToken = hashAgentToken;
|
|
33
11
|
exports.agentPrincipalId = agentPrincipalId;
|
|
34
12
|
exports.parseGrantList = parseGrantList;
|
|
13
|
+
exports.grantedActions = grantedActions;
|
|
35
14
|
exports.agentGrantOf = agentGrantOf;
|
|
15
|
+
exports.__setTokenCacheMsForTests = __setTokenCacheMsForTests;
|
|
16
|
+
exports.invalidateTokenCache = invalidateTokenCache;
|
|
17
|
+
exports.tokenCacheSize = tokenCacheSize;
|
|
36
18
|
exports.resolveAgentToken = resolveAgentToken;
|
|
37
19
|
exports.makeAgentUser = makeAgentUser;
|
|
38
20
|
exports.validateGrantInput = validateGrantInput;
|
|
39
21
|
exports.issueAgentGrant = issueAgentGrant;
|
|
40
22
|
exports.revokeAgentGrantById = revokeAgentGrantById;
|
|
23
|
+
exports.rotateAgentGrantToken = rotateAgentGrantToken;
|
|
24
|
+
exports.updateAgentGrant = updateAgentGrant;
|
|
25
|
+
exports.resolveUsageWindow = resolveUsageWindow;
|
|
26
|
+
exports.getGrantUsage = getGrantUsage;
|
|
41
27
|
exports.toGrantStatus = toGrantStatus;
|
|
42
28
|
exports.registerAgentGrantHandlers = registerAgentGrantHandlers;
|
|
43
29
|
exports.attachAgentGrantEnforcement = attachAgentGrantEnforcement;
|
|
44
30
|
exports.budgetRunnerFor = budgetRunnerFor;
|
|
31
|
+
exports.errorStatus = errorStatus;
|
|
45
32
|
exports.enforceAgentGrant = enforceAgentGrant;
|
|
46
33
|
exports.consumeDailyBudget = consumeDailyBudget;
|
|
47
34
|
exports.refundDailyBudget = refundDailyBudget;
|
|
35
|
+
exports.__setGrantUsageModeForTests = __setGrantUsageModeForTests;
|
|
36
|
+
exports.__resetGrantUsageBufferForTests = __resetGrantUsageBufferForTests;
|
|
37
|
+
exports.pendingGrantUsageKeys = pendingGrantUsageKeys;
|
|
38
|
+
exports.__setGrantUsagePrunedForTests = __setGrantUsagePrunedForTests;
|
|
39
|
+
exports.flushGrantUsage = flushGrantUsage;
|
|
40
|
+
exports.recordGrantUsage = recordGrantUsage;
|
|
41
|
+
exports.refundGrantUsage = refundGrantUsage;
|
|
48
42
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
49
43
|
const node_crypto_1 = __importDefault(require("node:crypto"));
|
|
50
44
|
const tx_utils_1 = require("./tx-utils");
|
|
51
45
|
const rate_limiter_1 = require("./rate-limiter");
|
|
52
46
|
const errors_1 = require("./errors");
|
|
53
47
|
const error_codes_1 = require("./error-codes");
|
|
54
|
-
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;
|
|
55
51
|
const logger = cds_1.default.log('AgentGrants');
|
|
56
52
|
exports.AGENT_TOKEN_HEADER = 'x-agent-token';
|
|
57
53
|
exports.AGENT_TOKEN_PREFIX = 'odat_';
|
|
@@ -61,6 +57,8 @@ exports.AGENT_ROLE = 'agent-grant';
|
|
|
61
57
|
/** `agent:<grantId>`: the principal id a token request runs under. */
|
|
62
58
|
exports.AGENT_PRINCIPAL_PREFIX = 'agent:';
|
|
63
59
|
exports.GRANTS_ENTITY = 'odatano.cardano.CardanoAgentGrants';
|
|
60
|
+
/** Daily per-action counters of admitted calls (feeds GetGrantUsage); never exposed as an entity. */
|
|
61
|
+
exports.GRANT_USAGE_ENTITY = 'odatano.cardano.CardanoAgentGrantUsage';
|
|
64
62
|
/** The services the hook attaches to and the transport lane opens. */
|
|
65
63
|
exports.AGENT_SERVICE_NAMES = [
|
|
66
64
|
'CardanoODataService',
|
|
@@ -69,65 +67,22 @@ exports.AGENT_SERVICE_NAMES = [
|
|
|
69
67
|
'CardanoWorkerService',
|
|
70
68
|
'CardanoIndexerService',
|
|
71
69
|
'CardanoAgentService',
|
|
70
|
+
'CardanoBackendService',
|
|
72
71
|
];
|
|
73
|
-
/**
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
// CardanoTransactionService: unsigned CBOR
|
|
81
|
-
'BuildSimpleAdaTransaction',
|
|
82
|
-
'BuildTransactionWithMetadata',
|
|
83
|
-
'BuildMultiAssetTransaction',
|
|
84
|
-
'BuildMintTransaction',
|
|
85
|
-
'BuildPlutusSpendTransaction',
|
|
86
|
-
'SetCollateral',
|
|
87
|
-
// externally signed transactions
|
|
88
|
-
'CreateSigningRequest',
|
|
89
|
-
'VerifySignature',
|
|
90
|
-
'SubmitTransaction',
|
|
91
|
-
'SubmitSignedTransaction',
|
|
92
|
-
'SubmitVerifiedTransaction',
|
|
93
|
-
'CheckSubmissionStatus',
|
|
94
|
-
// server-side wallets (need walletId on the grant)
|
|
95
|
-
'SubmitWalletJob',
|
|
96
|
-
'CancelJob',
|
|
97
|
-
];
|
|
98
|
-
/** Allow-listable actions that spend from a worker wallet: the grant must be pinned. */
|
|
99
|
-
exports.AGENT_WALLET_ACTIONS = new Set(['SubmitWalletJob', 'CancelJob']);
|
|
100
|
-
/**
|
|
101
|
-
* Events every valid token may use without an allow-list entry and without
|
|
102
|
-
* consuming budget: reads, compute-only actions, status polling. `READ` covers
|
|
103
|
-
* every entity set; row-level narrowing is done by the `$user.grantId`
|
|
104
|
-
* restrictions in the CDS models, not here.
|
|
105
|
-
*/
|
|
106
|
-
exports.AGENT_ALWAYS_ALLOWED_EVENTS = new Set([
|
|
107
|
-
'READ',
|
|
108
|
-
// CardanoODataService: chain reads through the backends
|
|
109
|
-
'GetNetworkInformation', 'GetBlockByHash', 'GetEpochByNumber', 'GetPoolById', 'GetDrepById',
|
|
110
|
-
'GetAssetInfo', 'GetAssetHistory', 'GetAccountByStakeAddress', 'GetTransactionByHash',
|
|
111
|
-
'GetMetadataByTxHash', 'GetAddressByBech32', 'GetUTxOsByAddress', 'GetUTxOsByCredential',
|
|
112
|
-
'GetAssetsByAddress', 'GetLatestTransactionsByAddress', 'GetLatestBlock', 'GetLatestEpoch',
|
|
113
|
-
'GetLedgerProtocolParameters', 'ParseTransactionCbor',
|
|
114
|
-
// CardanoTransactionService: compute-only
|
|
115
|
-
'GetBuildDetails', 'GetTransactionBuildsByAddress', 'DeriveScriptAddress', 'ExtractPaymentKeyHash',
|
|
116
|
-
// CardanoSignService: reads and stateless verification
|
|
117
|
-
'GetSigningRequest', 'GetSigningRequestsByAddress', 'VerifyDataSignature', 'GetHsmStatus',
|
|
118
|
-
// CardanoWorkerService / CardanoIndexerService: status
|
|
119
|
-
'GetJobStatus', 'GetWorkerStatus', 'getStatus',
|
|
120
|
-
// CardanoAgentService: the token's own grant
|
|
121
|
-
'GetGrantStatus',
|
|
122
|
-
]);
|
|
123
|
-
/** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
|
|
124
|
-
exports.AGENT_JOB_KINDS = ['simpleAda', 'metadata', 'multiAsset', 'mint', 'plutusSpend', 'submitSigned'];
|
|
125
|
-
/** Grant administration: 10 per operator per hour (NIGHTGATE's value). */
|
|
126
|
-
const grantAdminRateLimiter = new rate_limiter_1.RateLimiter({ windowMs: 60 * 60 * 1000, maxRequests: 10 });
|
|
127
|
-
/** Forget every rate-limit window (tests). */
|
|
72
|
+
/** Grant administration limiter: `adminRateLimit` calls per principal per hour, built on first use. */
|
|
73
|
+
let grantAdminRateLimiter = null;
|
|
74
|
+
function grantAdminLimiter() {
|
|
75
|
+
grantAdminRateLimiter ??= new rate_limiter_1.RateLimiter({ windowMs: 60 * 60 * 1000, maxRequests: (0, config_1.loadGrantAdminRateLimit)() });
|
|
76
|
+
return grantAdminRateLimiter;
|
|
77
|
+
}
|
|
78
|
+
/** Forget every rate-limit window, the token cache and re-read the knobs from the config (tests). */
|
|
128
79
|
function __resetGrantRateLimiterForTests() {
|
|
129
|
-
grantAdminRateLimiter
|
|
80
|
+
grantAdminRateLimiter = null;
|
|
130
81
|
lastUsedTouched.clear();
|
|
82
|
+
tokenCache.clear();
|
|
83
|
+
tokenHashOfGrant.clear();
|
|
84
|
+
tokenCacheMs = null;
|
|
85
|
+
tokenCacheOverride = null;
|
|
131
86
|
}
|
|
132
87
|
function dbRunner() {
|
|
133
88
|
return cds_1.default.db;
|
|
@@ -153,6 +108,11 @@ function parseGrantList(raw) {
|
|
|
153
108
|
return [];
|
|
154
109
|
}
|
|
155
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
|
+
}
|
|
156
116
|
function utcDay(now = new Date()) {
|
|
157
117
|
return now.toISOString().slice(0, 10);
|
|
158
118
|
}
|
|
@@ -168,99 +128,125 @@ function agentGrantOf(req) {
|
|
|
168
128
|
const ctx = cds_1.default.context;
|
|
169
129
|
return ctx?.http?.req?.agentGrant ?? null;
|
|
170
130
|
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
131
|
+
const TOKEN_CACHE_MAX = 10_000;
|
|
132
|
+
const tokenCache = new Map();
|
|
133
|
+
const tokenHashOfGrant = new Map();
|
|
134
|
+
let tokenCacheMs = null;
|
|
135
|
+
let tokenCacheOverride = null;
|
|
136
|
+
let tokenCacheGeneration = 0;
|
|
137
|
+
function tokenCacheTtl() {
|
|
138
|
+
if (tokenCacheOverride !== null)
|
|
139
|
+
return tokenCacheOverride;
|
|
140
|
+
tokenCacheMs ??= (0, config_1.loadTokenCacheMs)();
|
|
141
|
+
return tokenCacheMs;
|
|
142
|
+
}
|
|
143
|
+
/** Test seam: cache lifetime in ms for injected runners too (null = config, injected runners bypass). */
|
|
144
|
+
function __setTokenCacheMsForTests(ms) {
|
|
145
|
+
tokenCacheOverride = ms;
|
|
146
|
+
tokenCache.clear();
|
|
147
|
+
tokenHashOfGrant.clear();
|
|
148
|
+
}
|
|
149
|
+
/** Drops the cached resolution of a grant (revoke, rotate, update). */
|
|
150
|
+
function invalidateTokenCache(grantId) {
|
|
151
|
+
tokenCacheGeneration++;
|
|
152
|
+
const hash = tokenHashOfGrant.get(grantId);
|
|
153
|
+
if (hash !== undefined) {
|
|
154
|
+
tokenCache.delete(hash);
|
|
155
|
+
tokenHashOfGrant.delete(grantId);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/** Entries waiting in the token cache (monitoring, tests). */
|
|
159
|
+
function tokenCacheSize() {
|
|
160
|
+
return tokenCache.size;
|
|
161
|
+
}
|
|
162
|
+
function rememberToken(hash, grant, ttl) {
|
|
163
|
+
if (tokenCache.size >= TOKEN_CACHE_MAX) {
|
|
164
|
+
// bounded against a flood of distinct tokens
|
|
165
|
+
tokenCache.clear();
|
|
166
|
+
tokenHashOfGrant.clear();
|
|
167
|
+
}
|
|
168
|
+
tokenCache.set(hash, { grant, until: Date.now() + ttl });
|
|
169
|
+
tokenHashOfGrant.set(grant.ID, hash);
|
|
170
|
+
}
|
|
171
|
+
/** Authenticate a token by prefix, hash and expiry. A revoked grant answers like an unknown one. */
|
|
177
172
|
async function resolveAgentToken(token, runner = dbRunner()) {
|
|
178
173
|
if (typeof token !== 'string' || !token.startsWith(exports.AGENT_TOKEN_PREFIX)) {
|
|
179
174
|
return { ok: false, status: 401, message: 'invalid agent token' };
|
|
180
175
|
}
|
|
181
|
-
const
|
|
176
|
+
const hash = hashAgentToken(token);
|
|
177
|
+
const ttl = tokenCacheTtl();
|
|
178
|
+
const cacheable = ttl > 0 && (tokenCacheOverride !== null || runner === dbRunner());
|
|
179
|
+
if (cacheable) {
|
|
180
|
+
const hit = tokenCache.get(hash);
|
|
181
|
+
if (hit && hit.until > Date.now()) {
|
|
182
|
+
if (isExpired(hit.grant))
|
|
183
|
+
return { ok: false, status: 410, message: 'agent grant expired' };
|
|
184
|
+
return { ok: true, grant: hit.grant };
|
|
185
|
+
}
|
|
186
|
+
if (hit)
|
|
187
|
+
tokenCache.delete(hash);
|
|
188
|
+
}
|
|
189
|
+
const generation = tokenCacheGeneration;
|
|
190
|
+
const grant = (await (0, tx_utils_1.runWithoutAmbientTx)(() => runner.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ tokenHash: hash, isActive: true }))));
|
|
182
191
|
if (!grant)
|
|
183
192
|
return { ok: false, status: 401, message: 'invalid agent token' };
|
|
184
193
|
if (isExpired(grant))
|
|
185
194
|
return { ok: false, status: 410, message: 'agent grant expired' };
|
|
195
|
+
// not remembered when an invalidation ran while the SELECT was in flight
|
|
196
|
+
if (cacheable && generation === tokenCacheGeneration)
|
|
197
|
+
rememberToken(hash, grant, ttl);
|
|
186
198
|
return { ok: true, grant };
|
|
187
199
|
}
|
|
188
|
-
/**
|
|
189
|
-
* The principal a token request runs under. Deliberately NOT the operator and
|
|
190
|
-
* WITHOUT the operator's roles: `createdBy = $user` gates then scope to jobs
|
|
191
|
-
* this grant created, `$user.grantId` restrictions to its own grant row, and
|
|
192
|
-
* every `@requires: 'Admin'` refuses it.
|
|
193
|
-
*/
|
|
200
|
+
/** The user a token request runs as: never the operator, so `$user` restrictions apply and every Admin gate refuses it. */
|
|
194
201
|
function makeAgentUser(grant) {
|
|
195
202
|
return new cds_1.default.User({
|
|
196
203
|
id: agentPrincipalId(grant.ID),
|
|
197
|
-
roles
|
|
198
|
-
|
|
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 },
|
|
199
207
|
});
|
|
200
208
|
}
|
|
201
209
|
/** A refused grant input; carries the 400 the action answers with. */
|
|
202
210
|
class AgentGrantInputError extends errors_1.BackendError {
|
|
203
|
-
constructor(message, target) {
|
|
204
|
-
super(
|
|
211
|
+
constructor(message, target, context = 'CreateAgentGrant') {
|
|
212
|
+
super(`${context}: ${message}`, 400, error_codes_1.ERROR_CODES.INVALID_INPUT, undefined, undefined, target);
|
|
205
213
|
}
|
|
206
214
|
}
|
|
207
215
|
exports.AgentGrantInputError = AgentGrantInputError;
|
|
208
|
-
function validateGrantInput(input, now = new Date()) {
|
|
216
|
+
function validateGrantInput(input, now = new Date(), context = 'CreateAgentGrant') {
|
|
217
|
+
const fail = (message, target) => new AgentGrantInputError(message, target, context);
|
|
209
218
|
const actions = input.allowedActions;
|
|
210
219
|
if (!Array.isArray(actions) || actions.length === 0) {
|
|
211
|
-
throw
|
|
220
|
+
throw fail('allowedActions must be a non-empty array', 'allowedActions');
|
|
212
221
|
}
|
|
213
|
-
const
|
|
222
|
+
const grantable = (0, agent_access_1.agentGrantableActions)();
|
|
223
|
+
const unknown = actions.filter((a) => !grantable.includes(a));
|
|
214
224
|
if (unknown.length > 0) {
|
|
215
|
-
throw
|
|
225
|
+
throw fail(`allowedActions contains non-grantable entries: ${unknown.join(', ')}. Grantable: ${grantable.join(', ')}`, 'allowedActions');
|
|
216
226
|
}
|
|
217
227
|
const uniqueActions = [...new Set(actions)];
|
|
218
|
-
const walletId = typeof input.walletId === 'string' && input.walletId.trim() ? input.walletId.trim() : null;
|
|
219
|
-
const wantsWallet = uniqueActions.some((a) => exports.AGENT_WALLET_ACTIONS.has(a));
|
|
220
|
-
if (wantsWallet && !walletId) {
|
|
221
|
-
throw new AgentGrantInputError('walletId is required when SubmitWalletJob or CancelJob is allowed', 'walletId');
|
|
222
|
-
}
|
|
223
|
-
if (walletId && walletId.length > 50)
|
|
224
|
-
throw new AgentGrantInputError('walletId must be at most 50 characters', 'walletId');
|
|
225
|
-
let allowedJobKinds = [];
|
|
226
|
-
if (input.allowedJobKinds !== undefined && input.allowedJobKinds !== null) {
|
|
227
|
-
if (!Array.isArray(input.allowedJobKinds))
|
|
228
|
-
throw new AgentGrantInputError('allowedJobKinds must be an array', 'allowedJobKinds');
|
|
229
|
-
const badKinds = input.allowedJobKinds.filter((k) => !exports.AGENT_JOB_KINDS.includes(k));
|
|
230
|
-
if (badKinds.length > 0) {
|
|
231
|
-
throw new AgentGrantInputError(`allowedJobKinds contains unknown kinds: ${badKinds.join(', ')}. Known: ${exports.AGENT_JOB_KINDS.join(', ')}`, 'allowedJobKinds');
|
|
232
|
-
}
|
|
233
|
-
allowedJobKinds = [...new Set(input.allowedJobKinds)];
|
|
234
|
-
if (allowedJobKinds.length > 0 && !wantsWallet) {
|
|
235
|
-
throw new AgentGrantInputError('allowedJobKinds needs SubmitWalletJob in allowedActions', 'allowedJobKinds');
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
228
|
let maxJobsPerDay = null;
|
|
239
229
|
if (input.maxJobsPerDay !== undefined && input.maxJobsPerDay !== null) {
|
|
240
230
|
const n = Number(input.maxJobsPerDay);
|
|
241
231
|
if (!Number.isInteger(n) || n < 1)
|
|
242
|
-
throw
|
|
232
|
+
throw fail('maxJobsPerDay must be a positive integer', 'maxJobsPerDay');
|
|
243
233
|
maxJobsPerDay = n;
|
|
244
234
|
}
|
|
245
235
|
let validUntil = null;
|
|
246
236
|
if (input.validUntil) {
|
|
247
237
|
const t = new Date(input.validUntil);
|
|
248
238
|
if (Number.isNaN(t.getTime()))
|
|
249
|
-
throw
|
|
239
|
+
throw fail('validUntil must be a valid ISO-8601 timestamp', 'validUntil');
|
|
250
240
|
if (t.getTime() <= now.getTime())
|
|
251
|
-
throw
|
|
241
|
+
throw fail('validUntil must be in the future', 'validUntil');
|
|
252
242
|
validUntil = t.toISOString();
|
|
253
243
|
}
|
|
254
244
|
const agentLabel = typeof input.agentLabel === 'string' && input.agentLabel.trim() ? input.agentLabel.trim() : null;
|
|
255
245
|
if (agentLabel && agentLabel.length > 100)
|
|
256
|
-
throw
|
|
257
|
-
return { allowedActions: uniqueActions,
|
|
258
|
-
}
|
|
259
|
-
/**
|
|
260
|
-
* Mint a grant for `operatorId`. Validation errors surface as
|
|
261
|
-
* AgentGrantInputError (400). The INSERT runs on `runner`: the action passes its
|
|
262
|
-
* request transaction, x402 passes whatever transaction its settlement runs in.
|
|
263
|
-
*/
|
|
246
|
+
throw fail('agentLabel must be at most 100 characters', 'agentLabel');
|
|
247
|
+
return { allowedActions: uniqueActions, maxJobsPerDay, validUntil, agentLabel };
|
|
248
|
+
}
|
|
249
|
+
/** Mint a grant for `operatorId` on `runner`; validation errors surface as AgentGrantInputError (400). */
|
|
264
250
|
async function issueAgentGrant(input, operatorId, runner = dbRunner()) {
|
|
265
251
|
if (!operatorId)
|
|
266
252
|
throw new AgentGrantInputError('an operator id is required');
|
|
@@ -272,8 +258,6 @@ async function issueAgentGrant(input, operatorId, runner = dbRunner()) {
|
|
|
272
258
|
agentLabel: n.agentLabel,
|
|
273
259
|
tokenHash: hashAgentToken(token),
|
|
274
260
|
allowedActions: JSON.stringify(n.allowedActions),
|
|
275
|
-
walletId: n.walletId,
|
|
276
|
-
allowedJobKinds: n.allowedJobKinds.length > 0 ? JSON.stringify(n.allowedJobKinds) : null,
|
|
277
261
|
maxJobsPerDay: n.maxJobsPerDay,
|
|
278
262
|
jobsUsedToday: 0,
|
|
279
263
|
budgetWindow: null,
|
|
@@ -284,17 +268,15 @@ async function issueAgentGrant(input, operatorId, runner = dbRunner()) {
|
|
|
284
268
|
lastUsedAt: null,
|
|
285
269
|
};
|
|
286
270
|
await runner.run(INSERT.into(exports.GRANTS_ENTITY).entries(grant));
|
|
287
|
-
//
|
|
271
|
+
// never logs the token
|
|
288
272
|
logger.info(`agent grant ${grant.ID} issued by ${operatorId}` +
|
|
289
273
|
`${n.agentLabel ? ` for '${n.agentLabel}'` : ''} (actions: ${n.allowedActions.join(', ')}` +
|
|
290
|
-
`${n.
|
|
274
|
+
`${n.maxJobsPerDay ? `, budget ${n.maxJobsPerDay}/day` : ''}` +
|
|
291
275
|
`${n.validUntil ? `, until ${n.validUntil}` : ''})`);
|
|
292
276
|
return {
|
|
293
277
|
grantId: grant.ID,
|
|
294
278
|
token,
|
|
295
279
|
allowedActions: n.allowedActions,
|
|
296
|
-
walletId: n.walletId,
|
|
297
|
-
allowedJobKinds: n.allowedJobKinds,
|
|
298
280
|
maxJobsPerDay: n.maxJobsPerDay,
|
|
299
281
|
validUntil: n.validUntil,
|
|
300
282
|
};
|
|
@@ -307,19 +289,128 @@ async function revokeAgentGrantById(grantId, runner = dbRunner()) {
|
|
|
307
289
|
.set({ isActive: false, revokedAt: new Date().toISOString() })
|
|
308
290
|
.where({ ID: grantId, isActive: true }));
|
|
309
291
|
const revoked = Number(affected) > 0;
|
|
292
|
+
invalidateTokenCache(grantId);
|
|
310
293
|
if (revoked)
|
|
311
294
|
logger.info(`agent grant ${grantId} revoked`);
|
|
312
295
|
return revoked;
|
|
313
296
|
}
|
|
297
|
+
/** Replace the grant's token and keep everything else. Null when the grant is missing or revoked. */
|
|
298
|
+
async function rotateAgentGrantToken(grantId, runner = dbRunner()) {
|
|
299
|
+
if (!grantId)
|
|
300
|
+
return null;
|
|
301
|
+
const token = exports.AGENT_TOKEN_PREFIX + node_crypto_1.default.randomBytes(TOKEN_BYTES).toString('hex');
|
|
302
|
+
const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY).set({ tokenHash: hashAgentToken(token) }).where({ ID: grantId, isActive: true }));
|
|
303
|
+
invalidateTokenCache(grantId);
|
|
304
|
+
if (Number(affected) === 0)
|
|
305
|
+
return null;
|
|
306
|
+
logger.info(`agent grant ${grantId} token rotated`);
|
|
307
|
+
return { grantId, token };
|
|
308
|
+
}
|
|
309
|
+
/** Row fields a grant edit never touches. */
|
|
310
|
+
exports.GRANT_IMMUTABLE_FIELDS = ['userId', 'tokenHash'];
|
|
311
|
+
const GRANT_EDITABLE_FIELDS = [
|
|
312
|
+
'agentLabel', 'allowedActions', 'maxJobsPerDay', 'validUntil',
|
|
313
|
+
];
|
|
314
|
+
// Edit an active grant. An absent field stays, an explicit null clears it; allowedActions cannot be emptied.
|
|
315
|
+
// Unknown grant is 404, revoked is 409 GRANT_REVOKED, invalid input is 400.
|
|
316
|
+
async function updateAgentGrant(grantId, input, runner = dbRunner()) {
|
|
317
|
+
const has = (k) => Object.prototype.hasOwnProperty.call(input, k);
|
|
318
|
+
const existing = (await runner.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: grantId })));
|
|
319
|
+
if (!existing)
|
|
320
|
+
return { ok: false, status: 404, message: 'Grant not found' };
|
|
321
|
+
if (existing.isActive === false)
|
|
322
|
+
return { ok: false, status: 409, code: 'GRANT_REVOKED', message: 'Grant is revoked' };
|
|
323
|
+
// validUntil only when given: an untouched, already passed expiry is the lane's 410, not this edit's 400
|
|
324
|
+
const n = validateGrantInput({
|
|
325
|
+
allowedActions: has('allowedActions') ? input.allowedActions : grantedActions(existing),
|
|
326
|
+
maxJobsPerDay: has('maxJobsPerDay') ? input.maxJobsPerDay : existing.maxJobsPerDay,
|
|
327
|
+
validUntil: has('validUntil') ? input.validUntil : null,
|
|
328
|
+
agentLabel: has('agentLabel') ? input.agentLabel : existing.agentLabel,
|
|
329
|
+
}, new Date(), 'UpdateAgentGrant');
|
|
330
|
+
const patch = {};
|
|
331
|
+
if (has('allowedActions'))
|
|
332
|
+
patch.allowedActions = JSON.stringify(n.allowedActions);
|
|
333
|
+
if (has('maxJobsPerDay'))
|
|
334
|
+
patch.maxJobsPerDay = n.maxJobsPerDay;
|
|
335
|
+
if (has('validUntil'))
|
|
336
|
+
patch.validUntil = n.validUntil;
|
|
337
|
+
if (has('agentLabel'))
|
|
338
|
+
patch.agentLabel = n.agentLabel;
|
|
339
|
+
const updated = GRANT_EDITABLE_FIELDS.filter((f) => has(f));
|
|
340
|
+
if (updated.length === 0)
|
|
341
|
+
return { ok: true, grantId, updated: [] };
|
|
342
|
+
// conditional on isActive: a concurrent revoke wins
|
|
343
|
+
const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY).set(patch).where({ ID: grantId, isActive: true }));
|
|
344
|
+
invalidateTokenCache(grantId);
|
|
345
|
+
if (Number(affected) === 0)
|
|
346
|
+
return { ok: false, status: 409, code: 'GRANT_REVOKED', message: 'Grant is revoked' };
|
|
347
|
+
logger.info(`agent grant ${grantId} updated (${updated.join(', ')})`);
|
|
348
|
+
return { ok: true, grantId, updated };
|
|
349
|
+
}
|
|
350
|
+
// ---------------------------------------------------------------------------
|
|
351
|
+
// Usage history (GetGrantUsage)
|
|
352
|
+
// ---------------------------------------------------------------------------
|
|
353
|
+
exports.USAGE_WINDOW_MAX_MS = 366 * 24 * 60 * 60 * 1000;
|
|
354
|
+
exports.USAGE_WINDOW_DEFAULT_MS = 30 * 24 * 60 * 60 * 1000;
|
|
355
|
+
/** ISO timestamp or undefined; `null` when the value does not parse. */
|
|
356
|
+
function parseTimestamp(raw) {
|
|
357
|
+
if (raw === undefined || raw === null || raw === '')
|
|
358
|
+
return undefined;
|
|
359
|
+
const t = new Date(String(raw));
|
|
360
|
+
return Number.isNaN(t.getTime()) ? null : t.toISOString();
|
|
361
|
+
}
|
|
362
|
+
/** since (default until - 30 days) .. until (default now), at most 366 days; whole UTC days at both ends. */
|
|
363
|
+
function resolveUsageWindow(since, until, now = new Date()) {
|
|
364
|
+
const to = parseTimestamp(until);
|
|
365
|
+
const from = parseTimestamp(since);
|
|
366
|
+
if (to === null)
|
|
367
|
+
return { ok: false, message: 'until must be a valid ISO-8601 timestamp', target: 'until' };
|
|
368
|
+
if (from === null)
|
|
369
|
+
return { ok: false, message: 'since must be a valid ISO-8601 timestamp', target: 'since' };
|
|
370
|
+
const toMs = to ? new Date(to).getTime() : now.getTime();
|
|
371
|
+
const fromMs = from ? new Date(from).getTime() : toMs - exports.USAGE_WINDOW_DEFAULT_MS;
|
|
372
|
+
if (fromMs > toMs)
|
|
373
|
+
return { ok: false, message: 'since must not lie after until', target: 'since' };
|
|
374
|
+
if (toMs - fromMs > exports.USAGE_WINDOW_MAX_MS)
|
|
375
|
+
return { ok: false, message: 'the window may span at most 366 days', target: 'since' };
|
|
376
|
+
const sinceIso = new Date(fromMs).toISOString();
|
|
377
|
+
const untilIso = new Date(toMs).toISOString();
|
|
378
|
+
return { ok: true, since: sinceIso, until: untilIso, sinceDay: sinceIso.slice(0, 10), untilDay: untilIso.slice(0, 10) };
|
|
379
|
+
}
|
|
380
|
+
/** Admitted calls of the grant in `window` per service and action. Buffered counters are flushed first. */
|
|
381
|
+
async function getGrantUsage(grant, window, runner = dbRunner(), flushRunner = dbRunner()) {
|
|
382
|
+
if (pendingGrantUsageKeys() > 0)
|
|
383
|
+
await flushGrantUsage(flushRunner);
|
|
384
|
+
const rows = ((await runner.run(SELECT.from(exports.GRANT_USAGE_ENTITY)
|
|
385
|
+
.columns('service', 'action', { func: 'sum', args: [{ ref: ['calls'] }], as: 'calls' }, { func: 'sum', args: [{ ref: ['refunded'] }], as: 'refunded' })
|
|
386
|
+
.where({ grant_ID: grant.ID, day: { '>=': window.sinceDay } })
|
|
387
|
+
.and({ day: { '<=': window.untilDay } })
|
|
388
|
+
.groupBy('service', 'action'))) ?? []);
|
|
389
|
+
const calls = rows
|
|
390
|
+
.map((r) => {
|
|
391
|
+
const admitted = Number(r.calls ?? 0);
|
|
392
|
+
const refunded = Number(r.refunded ?? 0);
|
|
393
|
+
return { service: String(r.service ?? ''), action: String(r.action ?? ''), count: Math.max(admitted - refunded, 0), refunded };
|
|
394
|
+
})
|
|
395
|
+
.sort((a, b) => a.service.localeCompare(b.service) || a.action.localeCompare(b.action));
|
|
396
|
+
const status = toGrantStatus(grant);
|
|
397
|
+
return {
|
|
398
|
+
grantId: grant.ID,
|
|
399
|
+
since: window.since,
|
|
400
|
+
until: window.until,
|
|
401
|
+
calls,
|
|
402
|
+
total: calls.reduce((sum, c) => sum + c.count, 0),
|
|
403
|
+
jobsUsedToday: status.jobsUsedToday,
|
|
404
|
+
maxJobsPerDay: status.maxJobsPerDay,
|
|
405
|
+
};
|
|
406
|
+
}
|
|
314
407
|
function toGrantStatus(grant) {
|
|
315
408
|
return {
|
|
316
409
|
grantId: grant.ID,
|
|
317
410
|
agentLabel: grant.agentLabel ?? null,
|
|
318
|
-
allowedActions:
|
|
319
|
-
walletId: grant.walletId ?? null,
|
|
320
|
-
allowedJobKinds: parseGrantList(grant.allowedJobKinds),
|
|
411
|
+
allowedActions: grantedActions(grant),
|
|
321
412
|
maxJobsPerDay: grant.maxJobsPerDay ?? null,
|
|
322
|
-
//
|
|
413
|
+
// a counter from an earlier UTC day belongs to a window that is over
|
|
323
414
|
jobsUsedToday: grant.budgetWindow === utcDay() ? Number(grant.jobsUsedToday ?? 0) : 0,
|
|
324
415
|
budgetWindow: grant.budgetWindow ?? null,
|
|
325
416
|
validUntil: grant.validUntil ?? null,
|
|
@@ -329,20 +420,33 @@ function toGrantStatus(grant) {
|
|
|
329
420
|
// ---------------------------------------------------------------------------
|
|
330
421
|
// CardanoAgentService handlers
|
|
331
422
|
// ---------------------------------------------------------------------------
|
|
332
|
-
/**
|
|
423
|
+
/** Checks before each admin action: rate limit, no token caller, authenticated. False after a reject. */
|
|
424
|
+
function checkGrantAdmin(req, verb) {
|
|
425
|
+
const rate = grantAdminLimiter().check((0, rate_limiter_1.principalRateKey)(req, 'grant-admin'));
|
|
426
|
+
if (!rate.allowed) {
|
|
427
|
+
req.reject(429, `Rate limited. Retry after ${Math.ceil(rate.retryAfterMs / 1000)}s`);
|
|
428
|
+
return false;
|
|
429
|
+
}
|
|
430
|
+
if (agentGrantOf(req)) {
|
|
431
|
+
req.reject(403, `an agent grant cannot ${verb} grants`);
|
|
432
|
+
return false;
|
|
433
|
+
}
|
|
434
|
+
if (!req.user?.id) {
|
|
435
|
+
req.reject(401, 'authentication required');
|
|
436
|
+
return false;
|
|
437
|
+
}
|
|
438
|
+
return true;
|
|
439
|
+
}
|
|
440
|
+
function userIs(req, role) {
|
|
441
|
+
const user = req.user;
|
|
442
|
+
return typeof user?.is === 'function' ? user.is(role) === true : false;
|
|
443
|
+
}
|
|
444
|
+
/** Validation rejections happen before any transaction work. */
|
|
333
445
|
function registerAgentGrantHandlers(srv) {
|
|
334
446
|
srv.on('CreateAgentGrant', async (req) => {
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
if (agentGrantOf(req))
|
|
339
|
-
return req.reject(403, 'an agent grant cannot issue grants');
|
|
340
|
-
const operatorId = req.user?.id;
|
|
341
|
-
if (!operatorId)
|
|
342
|
-
return req.reject(401, 'authentication required');
|
|
343
|
-
const rate = grantAdminRateLimiter.check((0, rate_limiter_1.principalRateKey)(req, 'grant-admin'));
|
|
344
|
-
if (!rate.allowed)
|
|
345
|
-
return req.reject(429, `Rate limited. Retry after ${Math.ceil(rate.retryAfterMs / 1000)}s`);
|
|
447
|
+
if (!checkGrantAdmin(req, 'issue'))
|
|
448
|
+
return;
|
|
449
|
+
const operatorId = String(req.user.id);
|
|
346
450
|
const data = (req.data ?? {});
|
|
347
451
|
let normalized;
|
|
348
452
|
try {
|
|
@@ -358,15 +462,13 @@ function registerAgentGrantHandlers(srv) {
|
|
|
358
462
|
grantId: issued.grantId,
|
|
359
463
|
token: issued.token,
|
|
360
464
|
allowedActions: issued.allowedActions,
|
|
361
|
-
walletId: issued.walletId,
|
|
362
|
-
allowedJobKinds: issued.allowedJobKinds,
|
|
363
465
|
maxJobsPerDay: issued.maxJobsPerDay,
|
|
364
466
|
validUntil: issued.validUntil,
|
|
365
467
|
};
|
|
366
468
|
});
|
|
367
469
|
srv.on('RevokeAgentGrant', async (req) => {
|
|
368
|
-
if (
|
|
369
|
-
return
|
|
470
|
+
if (!checkGrantAdmin(req, 'revoke'))
|
|
471
|
+
return;
|
|
370
472
|
const { grantId } = (req.data ?? {});
|
|
371
473
|
if (!grantId)
|
|
372
474
|
return req.reject(400, 'grantId is required', 'grantId');
|
|
@@ -375,8 +477,44 @@ function registerAgentGrantHandlers(srv) {
|
|
|
375
477
|
return req.reject(404, 'Grant not found or already revoked', 'grantId');
|
|
376
478
|
return true;
|
|
377
479
|
});
|
|
378
|
-
|
|
379
|
-
|
|
480
|
+
srv.on('RotateAgentGrantToken', async (req) => {
|
|
481
|
+
if (!checkGrantAdmin(req, 'rotate'))
|
|
482
|
+
return;
|
|
483
|
+
const { grantId } = (req.data ?? {});
|
|
484
|
+
if (!grantId)
|
|
485
|
+
return req.reject(400, 'grantId is required', 'grantId');
|
|
486
|
+
const rotated = await rotateAgentGrantToken(grantId, cds_1.default.tx(req));
|
|
487
|
+
if (!rotated)
|
|
488
|
+
return req.reject(404, 'Grant not found or already revoked', 'grantId');
|
|
489
|
+
return rotated;
|
|
490
|
+
});
|
|
491
|
+
srv.on('UpdateAgentGrant', async (req) => {
|
|
492
|
+
if (!checkGrantAdmin(req, 'update'))
|
|
493
|
+
return;
|
|
494
|
+
const data = (req.data ?? {});
|
|
495
|
+
if (!data.grantId)
|
|
496
|
+
return req.reject(400, 'grantId is required', 'grantId');
|
|
497
|
+
const immutable = exports.GRANT_IMMUTABLE_FIELDS.filter((f) => Object.prototype.hasOwnProperty.call(data, f));
|
|
498
|
+
if (immutable.length > 0) {
|
|
499
|
+
return req.reject(400, `${immutable.join(', ')} cannot be changed`, immutable[0]);
|
|
500
|
+
}
|
|
501
|
+
let result;
|
|
502
|
+
try {
|
|
503
|
+
result = await updateAgentGrant(data.grantId, data, cds_1.default.tx(req));
|
|
504
|
+
}
|
|
505
|
+
catch (err) {
|
|
506
|
+
if (err instanceof errors_1.BackendError)
|
|
507
|
+
return req.reject(err.statusCode, err.message, err.target);
|
|
508
|
+
throw err;
|
|
509
|
+
}
|
|
510
|
+
if (!result.ok) {
|
|
511
|
+
if (result.code)
|
|
512
|
+
return req.reject({ status: result.status, code: result.code, message: result.message });
|
|
513
|
+
return req.reject(result.status, result.message, 'grantId');
|
|
514
|
+
}
|
|
515
|
+
return { grantId: result.grantId, updated: result.updated };
|
|
516
|
+
});
|
|
517
|
+
// The calling token's own grant, read fresh so the budget counter is current
|
|
380
518
|
srv.on('GetGrantStatus', async (req) => {
|
|
381
519
|
const grant = agentGrantOf(req);
|
|
382
520
|
if (!grant)
|
|
@@ -384,12 +522,32 @@ function registerAgentGrantHandlers(srv) {
|
|
|
384
522
|
const fresh = (await cds_1.default.tx(req).run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: grant.ID })));
|
|
385
523
|
return toGrantStatus(fresh ?? grant);
|
|
386
524
|
});
|
|
525
|
+
// Admin sees any grant (revoked ones keep their history), a token only its own (404 otherwise)
|
|
526
|
+
srv.on('GetGrantUsage', async (req) => {
|
|
527
|
+
const data = (req.data ?? {});
|
|
528
|
+
if (!data.grantId)
|
|
529
|
+
return req.reject(400, 'grantId is required', 'grantId');
|
|
530
|
+
const window = resolveUsageWindow(data.since, data.until);
|
|
531
|
+
if (!window.ok)
|
|
532
|
+
return req.reject(400, window.message, window.target);
|
|
533
|
+
const own = agentGrantOf(req);
|
|
534
|
+
if (own && own.ID !== data.grantId)
|
|
535
|
+
return req.reject(404, 'Grant not found', 'grantId');
|
|
536
|
+
if (!own && !userIs(req, 'Admin'))
|
|
537
|
+
return req.reject(403, "GetGrantUsage needs Admin or the grant's own token");
|
|
538
|
+
const tx = cds_1.default.tx(req);
|
|
539
|
+
const grant = (await tx.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: data.grantId })));
|
|
540
|
+
if (!grant)
|
|
541
|
+
return req.reject(404, 'Grant not found', 'grantId');
|
|
542
|
+
return getGrantUsage(grant, window, tx, dbRunner());
|
|
543
|
+
});
|
|
387
544
|
}
|
|
388
545
|
// ---------------------------------------------------------------------------
|
|
389
546
|
// Enforcement (before('*') on the six services)
|
|
390
547
|
// ---------------------------------------------------------------------------
|
|
391
548
|
function attachAgentGrantEnforcement(srv, runner) {
|
|
392
|
-
|
|
549
|
+
const serviceName = String(srv.name ?? 'unknown');
|
|
550
|
+
srv.before('*', (req) => enforceAgentGrant(req, runner, undefined, serviceName));
|
|
393
551
|
}
|
|
394
552
|
function budgetRunnerFor(req, injected, detached) {
|
|
395
553
|
if (injected)
|
|
@@ -401,92 +559,95 @@ function budgetRunnerFor(req, injected, detached) {
|
|
|
401
559
|
catch {
|
|
402
560
|
tx = null;
|
|
403
561
|
}
|
|
404
|
-
if (tx && (
|
|
562
|
+
if (tx && (0, tx_utils_1.holdsConnection)(tx))
|
|
405
563
|
return { runner: tx, detached: false };
|
|
406
564
|
return { runner: dbRunner(), detached: true };
|
|
407
565
|
}
|
|
408
566
|
async function runStmt(br, statement) {
|
|
409
567
|
return br.detached ? (0, tx_utils_1.runWithoutAmbientTx)(() => br.runner.run(statement)) : br.runner.run(statement);
|
|
410
568
|
}
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
569
|
+
// HTTP status of a failed request's error, as CAP derives it. A combined error has no status:
|
|
570
|
+
// one shared detail status wins, any 5xx gives 500, else 400.
|
|
571
|
+
function errorStatus(err) {
|
|
572
|
+
const e = err;
|
|
573
|
+
const own = ownStatus(e);
|
|
574
|
+
if (own)
|
|
575
|
+
return own;
|
|
576
|
+
if (!Array.isArray(e?.details))
|
|
577
|
+
return 500;
|
|
578
|
+
const nested = [...new Set(e.details.map(ownStatus).filter((n) => !!n))];
|
|
579
|
+
if (nested.length === 1)
|
|
580
|
+
return nested[0];
|
|
581
|
+
return nested.some(n => n >= 500) ? 500 : 400;
|
|
582
|
+
}
|
|
583
|
+
function ownStatus(e) {
|
|
584
|
+
const status = Number(e?.status ?? e?.statusCode);
|
|
585
|
+
if (Number.isInteger(status) && status > 0)
|
|
586
|
+
return status;
|
|
587
|
+
const code = Number(e?.code);
|
|
588
|
+
return Number.isInteger(code) && code >= 400 && code < 600 ? code : undefined;
|
|
589
|
+
}
|
|
590
|
+
/** The before('*') hook for token requests: closed services, allow list, daily budget and usage. */
|
|
591
|
+
async function enforceAgentGrant(req, runner, detached, serviceName = 'unknown') {
|
|
417
592
|
const grant = agentGrantOf(req);
|
|
418
593
|
if (!grant)
|
|
419
594
|
return;
|
|
420
|
-
//
|
|
421
|
-
// a grant can be revoked between two parts of a $batch, or expire mid-flight.
|
|
595
|
+
// A grant can be revoked between two parts of a $batch, or expire mid-flight
|
|
422
596
|
if (grant.isActive === false)
|
|
423
597
|
return req.reject(401, 'invalid agent token');
|
|
424
598
|
if (isExpired(grant))
|
|
425
599
|
return req.reject(410, 'agent grant expired');
|
|
426
|
-
const br = budgetRunnerFor(req, runner, detached);
|
|
427
600
|
const event = String(req.event ?? '');
|
|
428
|
-
|
|
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') {
|
|
607
|
+
// a token sees its own usage only; a foreign id is not found (non-leaking)
|
|
608
|
+
if (event === 'GetGrantUsage') {
|
|
609
|
+
const asked = String(req.data?.grantId ?? '');
|
|
610
|
+
if (asked !== grant.ID)
|
|
611
|
+
return req.reject(404, 'Grant not found', 'grantId');
|
|
612
|
+
}
|
|
429
613
|
await touchLastUsed(grant, br);
|
|
430
614
|
return;
|
|
431
615
|
}
|
|
432
|
-
|
|
433
|
-
if (!allowed.includes(event)) {
|
|
616
|
+
if (access !== 'grant' || !grantedActions(grant).includes(event)) {
|
|
434
617
|
return req.reject(403, `action '${event}' is not allowed for this agent grant`);
|
|
435
618
|
}
|
|
436
|
-
|
|
437
|
-
if (exports.AGENT_WALLET_ACTIONS.has(event)) {
|
|
438
|
-
if (!grant.walletId) {
|
|
439
|
-
return req.reject(403, 'this agent grant has no wallet binding; issue it with walletId to queue wallet jobs');
|
|
440
|
-
}
|
|
441
|
-
if (data && typeof data === 'object') {
|
|
442
|
-
if (event === 'SubmitWalletJob') {
|
|
443
|
-
if (data.walletId !== undefined && data.walletId !== null && data.walletId !== '' && data.walletId !== grant.walletId) {
|
|
444
|
-
return req.reject(403, 'walletId does not match this agent grant');
|
|
445
|
-
}
|
|
446
|
-
data.walletId = grant.walletId;
|
|
447
|
-
const kinds = parseGrantList(grant.allowedJobKinds);
|
|
448
|
-
if (kinds.length > 0 && !kinds.includes(String(data.kind ?? ''))) {
|
|
449
|
-
return req.reject(403, `job kind '${String(data.kind ?? '')}' is not allowed for this agent grant (allowed: ${kinds.join(', ')})`);
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
// CancelJob: the job lookup is owner-scoped by createdBy = agent:<grantId>
|
|
453
|
-
// in the worker service, so a foreign job is a 404 there already.
|
|
454
|
-
}
|
|
455
|
-
}
|
|
619
|
+
let charge = null;
|
|
456
620
|
if (grant.maxJobsPerDay !== undefined && grant.maxJobsPerDay !== null) {
|
|
457
|
-
|
|
621
|
+
charge = await consumeDailyBudget(br, grant);
|
|
458
622
|
if (!charge.consumed) {
|
|
459
623
|
return req.reject(429, `agent grant daily budget exhausted (${grant.maxJobsPerDay}/day)`);
|
|
460
624
|
}
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
625
|
+
}
|
|
626
|
+
// one usage unit on (grant, day, service, action), budgeted or not
|
|
627
|
+
const usageDay = await recordGrantUsage(br, grant, serviceName, event);
|
|
628
|
+
// Detached writes: a request refused as invalid (400..428) admitted nothing, so refund the budget unit
|
|
629
|
+
// in the window it was charged to and mark the usage unit refunded; 429 and 5xx keep both.
|
|
630
|
+
// Writes inside the request's own transaction are undone by its rollback.
|
|
631
|
+
if (br.detached) {
|
|
632
|
+
const chargedWindow = charge?.window ?? null;
|
|
633
|
+
req.on?.('failed', (err) => {
|
|
634
|
+
const status = errorStatus(err);
|
|
635
|
+
if (status >= 400 && status < 429) {
|
|
636
|
+
// Off the failing request's tick: its transaction is still rolling back when 'failed' fires,
|
|
637
|
+
// and a concurrent write on a second SQLite connection would contend for the lock
|
|
638
|
+
setImmediate(() => {
|
|
639
|
+
if (chargedWindow) {
|
|
476
640
|
void refundDailyBudget(br, grant, chargedWindow).catch((refundErr) => logger.warn(`daily budget refund for grant ${grant.ID} failed: ${String(refundErr?.message ?? refundErr)}`));
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
641
|
+
}
|
|
642
|
+
void refundGrantUsage(br, grant, serviceName, event, usageDay).catch((refundErr) => logger.warn(`usage refund for grant ${grant.ID} failed: ${String(refundErr?.message ?? refundErr)}`));
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
});
|
|
481
646
|
}
|
|
482
647
|
await touchLastUsed(grant, br);
|
|
483
648
|
}
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
* concurrent requests cannot overspend: a window reset (compare-and-swap on
|
|
487
|
-
* the OLD window value) and a bounded increment (`jobsUsedToday < max`). Runs
|
|
488
|
-
* on the BudgetRunner the hook chose (detached by default, see budgetRunnerFor).
|
|
489
|
-
*/
|
|
649
|
+
// Consume one budget unit with two conditional UPDATEs, so concurrent requests cannot overspend:
|
|
650
|
+
// a compare-and-swap reset of the day window, then an increment bounded by the daily maximum.
|
|
490
651
|
async function consumeDailyBudget(br, grant) {
|
|
491
652
|
const runner = 'runner' in br ? br : { runner: br, detached: true };
|
|
492
653
|
const today = utcDay();
|
|
@@ -497,32 +658,173 @@ async function consumeDailyBudget(br, grant) {
|
|
|
497
658
|
.where({ ID: grant.ID, budgetWindow: grant.budgetWindow ?? null }));
|
|
498
659
|
if (Number(reset))
|
|
499
660
|
return { consumed: true, window: today };
|
|
500
|
-
//
|
|
661
|
+
// lost the reset race: another request already moved the window
|
|
501
662
|
}
|
|
502
663
|
const incremented = await runStmt(runner, UPDATE.entity(exports.GRANTS_ENTITY)
|
|
503
664
|
.set({ jobsUsedToday: { '+=': 1 } })
|
|
504
665
|
.where({ ID: grant.ID, budgetWindow: today, jobsUsedToday: { '<': max } }));
|
|
505
666
|
return { consumed: Number(incremented) > 0, window: today };
|
|
506
667
|
}
|
|
507
|
-
/**
|
|
508
|
-
* Undo one consumeDailyBudget in the window it was charged to (a refused
|
|
509
|
-
* request created nothing). A refund that lands after midnight must not touch
|
|
510
|
-
* the new day's counter: the unit was spent yesterday, yesterday keeps it.
|
|
511
|
-
*/
|
|
668
|
+
/** Undo one consumeDailyBudget in the window it was charged to; never touches a newer day's counter. */
|
|
512
669
|
async function refundDailyBudget(br, grant, window) {
|
|
513
670
|
const runner = 'runner' in br ? br : { runner: br, detached: true };
|
|
514
671
|
await runStmt(runner, UPDATE.entity(exports.GRANTS_ENTITY)
|
|
515
672
|
.set({ jobsUsedToday: { '-=': 1 } })
|
|
516
673
|
.where({ ID: grant.ID, budgetWindow: window, jobsUsedToday: { '>': 0 } }));
|
|
517
674
|
}
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
675
|
+
const USAGE_FLUSH_INTERVAL_MS = 1000;
|
|
676
|
+
const usageBuffer = new Map();
|
|
677
|
+
let usageFlushTimer = null;
|
|
678
|
+
let usageModeOverride = null;
|
|
679
|
+
let usageShutdownHooked = false;
|
|
680
|
+
/** Deferred on the databases whose writers do not block readers; sync everywhere else (SQLite, tests). */
|
|
681
|
+
function usageMode() {
|
|
682
|
+
if (usageModeOverride)
|
|
683
|
+
return usageModeOverride;
|
|
684
|
+
const kind = String(cds_1.default.db?.kind ?? '');
|
|
685
|
+
return kind === 'postgres' || kind === 'hana' ? 'deferred' : 'sync';
|
|
686
|
+
}
|
|
687
|
+
/** Test seam: force a mode (null = derive from cds.db.kind). */
|
|
688
|
+
function __setGrantUsageModeForTests(mode) {
|
|
689
|
+
usageModeOverride = mode;
|
|
690
|
+
}
|
|
691
|
+
/** Test seam: forget buffered deltas and the pending timer. */
|
|
692
|
+
function __resetGrantUsageBufferForTests() {
|
|
693
|
+
usageBuffer.clear();
|
|
694
|
+
if (usageFlushTimer) {
|
|
695
|
+
clearTimeout(usageFlushTimer);
|
|
696
|
+
usageFlushTimer = null;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
/** How many keys wait for the next flush (monitoring, tests). */
|
|
700
|
+
function pendingGrantUsageKeys() {
|
|
701
|
+
return usageBuffer.size;
|
|
702
|
+
}
|
|
703
|
+
function bufferUsage(key, calls, refunded) {
|
|
704
|
+
const k = `${key.grant_ID}|${key.day}|${key.service}|${key.action}`;
|
|
705
|
+
const d = usageBuffer.get(k);
|
|
706
|
+
if (d) {
|
|
707
|
+
d.calls += calls;
|
|
708
|
+
d.refunded += refunded;
|
|
709
|
+
}
|
|
710
|
+
else
|
|
711
|
+
usageBuffer.set(k, { ...key, calls, refunded });
|
|
712
|
+
// under a test override the tests flush explicitly; no timer may race them
|
|
713
|
+
if (!usageFlushTimer && !usageModeOverride) {
|
|
714
|
+
usageFlushTimer = setTimeout(() => {
|
|
715
|
+
usageFlushTimer = null;
|
|
716
|
+
void flushGrantUsage().catch((err) => logger.warn(`usage flush failed: ${String(err?.message ?? err)}`));
|
|
717
|
+
}, USAGE_FLUSH_INTERVAL_MS);
|
|
718
|
+
usageFlushTimer.unref?.();
|
|
719
|
+
}
|
|
720
|
+
if (!usageShutdownHooked) {
|
|
721
|
+
usageShutdownHooked = true;
|
|
722
|
+
cds_1.default.on('shutdown', () => flushGrantUsage().catch(() => undefined));
|
|
723
|
+
}
|
|
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
|
+
}
|
|
749
|
+
/** Write the buffered deltas per key. A failed delta goes back into the buffer for the next flush. */
|
|
750
|
+
async function flushGrantUsage(runner = dbRunner()) {
|
|
751
|
+
if (usageBuffer.size === 0)
|
|
752
|
+
return { flushed: 0, failed: 0 };
|
|
753
|
+
if (!runner) {
|
|
754
|
+
// no database service yet: keep the deltas
|
|
755
|
+
logger.debug('usage flush skipped: no database service');
|
|
756
|
+
return { flushed: 0, failed: usageBuffer.size };
|
|
757
|
+
}
|
|
758
|
+
const batch = [...usageBuffer.values()];
|
|
759
|
+
usageBuffer.clear();
|
|
760
|
+
const br = { runner, detached: true };
|
|
761
|
+
let flushed = 0;
|
|
762
|
+
let failed = 0;
|
|
763
|
+
for (const d of batch) {
|
|
764
|
+
const key = { grant_ID: d.grant_ID, day: d.day, service: d.service, action: d.action };
|
|
765
|
+
const bump = () => runStmt(br, UPDATE.entity(exports.GRANT_USAGE_ENTITY).set({ calls: { '+=': d.calls }, refunded: { '+=': d.refunded } }).where(key));
|
|
766
|
+
try {
|
|
767
|
+
if (Number(await bump()) === 0) {
|
|
768
|
+
try {
|
|
769
|
+
await runStmt(br, INSERT.into(exports.GRANT_USAGE_ENTITY).entries({ ...key, calls: d.calls, refunded: d.refunded }));
|
|
770
|
+
}
|
|
771
|
+
catch (insertErr) {
|
|
772
|
+
// lost the insert race (row exists now); if it is still missing, the INSERT itself failed
|
|
773
|
+
if (Number(await bump()) === 0)
|
|
774
|
+
throw insertErr;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
flushed++;
|
|
778
|
+
}
|
|
779
|
+
catch (err) {
|
|
780
|
+
failed++;
|
|
781
|
+
bufferUsage(key, d.calls, d.refunded); // retried on the next flush
|
|
782
|
+
logger.warn(`usage flush for grant ${d.grant_ID} (${d.service}.${d.action}) failed, kept for retry: ${String(err?.message ?? err)}`);
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
await pruneGrantUsage(br);
|
|
786
|
+
return { flushed, failed };
|
|
787
|
+
}
|
|
788
|
+
/** Count one admitted call on (grant, UTC day, service, action). Never fails the request; returns the day counted on. */
|
|
789
|
+
async function recordGrantUsage(br, grant, service, action, now = new Date()) {
|
|
790
|
+
const runner = 'runner' in br ? br : { runner: br, detached: true };
|
|
791
|
+
const day = utcDay(now);
|
|
792
|
+
const key = { grant_ID: grant.ID, day, service, action };
|
|
793
|
+
if (runner.detached && usageMode() === 'deferred') {
|
|
794
|
+
bufferUsage(key, 1, 0);
|
|
795
|
+
return day;
|
|
796
|
+
}
|
|
797
|
+
const bump = () => runStmt(runner, UPDATE.entity(exports.GRANT_USAGE_ENTITY).set({ calls: { '+=': 1 } }).where(key));
|
|
798
|
+
try {
|
|
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
|
+
}
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
catch (err) {
|
|
809
|
+
logger.warn(`usage record for grant ${grant.ID} (${service}.${action}) failed: ${String(err?.message ?? err)}`);
|
|
810
|
+
}
|
|
811
|
+
await pruneGrantUsage(runner, now);
|
|
812
|
+
return day;
|
|
813
|
+
}
|
|
814
|
+
/** `refunded + 1` on the row the call was counted on; deferred mode buffers it on the same key. */
|
|
815
|
+
async function refundGrantUsage(br, grant, service, action, day) {
|
|
816
|
+
const runner = 'runner' in br ? br : { runner: br, detached: true };
|
|
817
|
+
const key = { grant_ID: grant.ID, day, service, action };
|
|
818
|
+
if (runner.detached && usageMode() === 'deferred') {
|
|
819
|
+
bufferUsage(key, 0, 1);
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
await runStmt(runner, UPDATE.entity(exports.GRANT_USAGE_ENTITY)
|
|
823
|
+
.set({ refunded: { '+=': 1 } })
|
|
824
|
+
.where(key));
|
|
825
|
+
}
|
|
826
|
+
// lastUsedAt at most once a minute per grant. Awaited, since a fire-and-forget write on a second
|
|
827
|
+
// connection races the handler's reads on SQLite. A failed touch never fails the request.
|
|
526
828
|
const lastUsedTouched = new Map();
|
|
527
829
|
const LAST_USED_INTERVAL_MS = 60_000;
|
|
528
830
|
async function touchLastUsed(grant, br) {
|