@odatano/core 2.0.0-rc.2 → 2.0.0-rc.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/@cds-models/CardanoAgentService/index.d.ts +251 -0
- package/@cds-models/CardanoAgentService/index.js +36 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +139 -2
- package/@cds-models/CardanoIndexerService/index.js +18 -0
- package/@cds-models/CardanoODataService/index.d.ts +224 -0
- package/@cds-models/CardanoODataService/index.js +27 -0
- package/@cds-models/CardanoSignService/index.d.ts +5 -2
- package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
- package/@cds-models/odatano/cardano/index.d.ts +316 -0
- package/@cds-models/odatano/cardano/index.js +33 -0
- package/README.md +195 -136
- package/db/schema.cds +2121 -1633
- package/package.json +179 -173
- package/src/index.d.ts +10 -10
- package/src/index.js +24 -14
- package/src/plugin.js +39 -52
- package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
- package/srv/blockchain/backends/blockfrost-backend.js +45 -158
- package/srv/blockchain/backends/cardano-backend.d.ts +78 -158
- package/srv/blockchain/backends/cardano-backend.js +14 -5
- package/srv/blockchain/backends/koios-backend.d.ts +126 -60
- package/srv/blockchain/backends/koios-backend.js +292 -202
- package/srv/blockchain/backends/ogmios-backend.d.ts +59 -96
- package/srv/blockchain/backends/ogmios-backend.js +241 -153
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
- package/srv/blockchain/cardano-client.d.ts +50 -205
- package/srv/blockchain/cardano-client.js +80 -224
- package/srv/blockchain/cardano-indexer.d.ts +146 -244
- package/srv/blockchain/cardano-indexer.js +442 -285
- package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
- package/srv/blockchain/cardano-tx-builder.js +21 -107
- package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
- package/srv/blockchain/crawler/certificate-backfill.js +150 -0
- package/srv/blockchain/crawler/crawler.d.ts +121 -53
- package/srv/blockchain/crawler/crawler.js +402 -82
- package/srv/blockchain/crawler/hooks.d.ts +3 -14
- package/srv/blockchain/crawler/index.d.ts +5 -0
- package/srv/blockchain/crawler/index.js +35 -7
- package/srv/blockchain/crawler/sync-state.d.ts +44 -28
- package/srv/blockchain/crawler/sync-state.js +115 -43
- package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
- package/srv/blockchain/crawler/utxo-set-import.js +269 -0
- package/srv/blockchain/ledger-state.d.ts +80 -0
- package/srv/blockchain/ledger-state.js +383 -0
- package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
- package/srv/blockchain/signing/cose-verifier.js +6 -12
- package/srv/blockchain/signing/external-signer.d.ts +16 -113
- package/srv/blockchain/signing/external-signer.js +19 -122
- package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
- package/srv/blockchain/signing/hsm-signer.js +23 -63
- package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
- package/srv/blockchain/signing/signature-verifier.js +13 -54
- package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
- package/srv/blockchain/signing/submission-finalizer.js +16 -48
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
- package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
- package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
- package/srv/blockchain/wallet-worker/build-request.js +39 -23
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
- package/srv/blockchain/wallet-worker/index.js +2 -8
- package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
- package/srv/blockchain/wallet-worker/job-store.js +0 -0
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
- package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
- package/srv/blockchain/wallet-worker/signers.js +3 -8
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
- package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
- package/srv/cardano-agent-service.cds +146 -0
- package/srv/cardano-agent-service.d.ts +2 -0
- package/srv/cardano-agent-service.js +12 -0
- package/srv/cardano-indexer-service.cds +164 -73
- package/srv/cardano-indexer-service.js +156 -11
- package/srv/cardano-service.cds +45 -0
- package/srv/cardano-service.js +38 -96
- package/srv/cardano-sign-service.cds +200 -180
- package/srv/cardano-sign-service.js +55 -173
- package/srv/cardano-tx-service.cds +32 -26
- package/srv/cardano-tx-service.js +133 -195
- package/srv/cardano-worker-service.js +7 -15
- package/srv/server.d.ts +28 -86
- package/srv/server.js +95 -128
- package/srv/utils/agent-grants-config.d.ts +37 -0
- package/srv/utils/agent-grants-config.js +138 -0
- package/srv/utils/agent-grants.d.ts +262 -0
- package/srv/utils/agent-grants.js +914 -0
- package/srv/utils/agent-token-auth.d.ts +16 -0
- package/srv/utils/agent-token-auth.js +78 -0
- package/srv/utils/backend-request-handler.d.ts +2 -16
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/collections.d.ts +4 -8
- package/srv/utils/collections.js +4 -8
- package/srv/utils/const.d.ts +19 -68
- package/srv/utils/const.js +20 -69
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +5 -18
- package/srv/utils/db-indexes.d.ts +25 -0
- package/srv/utils/db-indexes.js +89 -0
- package/srv/utils/db-sanitize.d.ts +27 -0
- package/srv/utils/db-sanitize.js +85 -0
- package/srv/utils/error-codes.d.ts +18 -73
- package/srv/utils/error-codes.js +17 -70
- package/srv/utils/errors.d.ts +34 -178
- package/srv/utils/errors.js +55 -217
- package/srv/utils/liveness.d.ts +16 -0
- package/srv/utils/liveness.js +41 -0
- package/srv/utils/mappers.d.ts +82 -210
- package/srv/utils/mappers.js +272 -293
- package/srv/utils/network-context.js +2 -11
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +57 -0
- package/srv/utils/plutus-placeholders.d.ts +6 -18
- package/srv/utils/plutus-placeholders.js +6 -20
- package/srv/utils/rate-limiter.d.ts +46 -0
- package/srv/utils/rate-limiter.js +116 -0
- package/srv/utils/service-events.d.ts +2 -22
- package/srv/utils/service-events.js +3 -23
- package/srv/utils/signing-helper.d.ts +3 -18
- package/srv/utils/signing-helper.js +10 -32
- package/srv/utils/tx-build-helper.d.ts +18 -92
- package/srv/utils/tx-build-helper.js +32 -123
- package/srv/utils/tx-request-parsers.d.ts +14 -20
- package/srv/utils/tx-request-parsers.js +33 -20
- package/srv/utils/tx-utils.d.ts +4 -23
- package/srv/utils/tx-utils.js +12 -41
- package/srv/utils/types.d.ts +112 -169
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +19 -89
- package/srv/utils/validators.js +31 -138
|
@@ -3,17 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.setActiveNetwork = setActiveNetwork;
|
|
4
4
|
exports.getActiveNetwork = getActiveNetwork;
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* This is a deliberately tiny *leaf* module: it has no runtime dependencies (the
|
|
9
|
-
* `Network` import is type-only and erased at compile), so leaf utilities such as
|
|
10
|
-
* `validators.ts` can read the configured network WITHOUT importing `server.ts`
|
|
11
|
-
* — which would otherwise drag the whole server → indexer graph (and its
|
|
12
|
-
* module-load `cds.ql` access) into every consumer.
|
|
13
|
-
*
|
|
14
|
-
* Set during bootstrap by `initializeAppContext` and cleared on shutdown. Reads
|
|
15
|
-
* before bootstrap return `null`; callers treat that as "not ready" rather than
|
|
16
|
-
* throwing (e.g. network-aware validators return `false`).
|
|
6
|
+
* Dependency-free holder for the active network, so leaf utilities (validators) can read it
|
|
7
|
+
* without importing `server.ts`. Set by `initializeAppContext`, `null` before bootstrap.
|
|
17
8
|
*/
|
|
18
9
|
let active = null;
|
|
19
10
|
/** Record the active network. Pass `null` to clear (shutdown/reset). */
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
interface OrderTerm {
|
|
2
|
+
nulls?: string;
|
|
3
|
+
element?: {
|
|
4
|
+
key?: boolean;
|
|
5
|
+
notNull?: boolean;
|
|
6
|
+
'@cds.valid.from'?: boolean;
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
/** Strips the null placement from the rendered terms whose column cannot be NULL. */
|
|
10
|
+
export declare function stripNullsForNotNull(orderBy: OrderTerm[], rendered: string[]): string[];
|
|
11
|
+
/** Wraps the driver's `_orderBy` once; returns false when the driver or the hook is missing. */
|
|
12
|
+
export declare function installPostgresOrderNulls(): boolean;
|
|
13
|
+
export {};
|
|
14
|
+
//# sourceMappingURL=pg-order-nulls.d.ts.map
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.stripNullsForNotNull = stripNullsForNotNull;
|
|
7
|
+
exports.installPostgresOrderNulls = installPostgresOrderNulls;
|
|
8
|
+
/**
|
|
9
|
+
* ORDER BY on PostgreSQL: drop the NULLS clause for columns that cannot be NULL.
|
|
10
|
+
* @cap-js/postgres renders `ASC NULLS FIRST` / `DESC NULLS LAST`, the opposite of a btree index's
|
|
11
|
+
* placement, so `$top` reads sorted the whole table; key, `not null` and `@cds.valid.from` columns are exempt.
|
|
12
|
+
*/
|
|
13
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
14
|
+
const logger = cds_1.default.log('PgOrderNulls');
|
|
15
|
+
const INSTALLED = Symbol.for('odatano.pgOrderNulls');
|
|
16
|
+
/** Strips the null placement from the rendered terms whose column cannot be NULL. */
|
|
17
|
+
function stripNullsForNotNull(orderBy, rendered) {
|
|
18
|
+
return rendered.map((sql, i) => {
|
|
19
|
+
const c = orderBy[i];
|
|
20
|
+
if (!c || c.nulls)
|
|
21
|
+
return sql;
|
|
22
|
+
const el = c.element;
|
|
23
|
+
if (el && (el.key === true || el.notNull === true || el['@cds.valid.from'] === true))
|
|
24
|
+
return sql.replace(/ NULLS (FIRST|LAST)$/, '');
|
|
25
|
+
return sql;
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/** Wraps the driver's `_orderBy` once; returns false when the driver or the hook is missing. */
|
|
29
|
+
function installPostgresOrderNulls() {
|
|
30
|
+
let PostgresService;
|
|
31
|
+
try {
|
|
32
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
33
|
+
PostgresService = require('@cap-js/postgres/lib/PostgresService');
|
|
34
|
+
}
|
|
35
|
+
catch (err) {
|
|
36
|
+
// No loadable Postgres driver: silent unless the database is Postgres.
|
|
37
|
+
const dbKind = String((cds_1.default.env?.requires?.db)?.kind ?? '');
|
|
38
|
+
if (dbKind === 'postgres')
|
|
39
|
+
logger.warn(`@cap-js/postgres/lib/PostgresService not loadable, ORDER BY keeps the NULLS clause: ${String(err?.message ?? err)}`);
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
const proto = PostgresService.CQN2SQL?.prototype;
|
|
43
|
+
const orig = proto?._orderBy;
|
|
44
|
+
if (!proto || typeof orig !== 'function') {
|
|
45
|
+
logger.warn('@cap-js/postgres has no _orderBy hook; ORDER BY keeps the NULLS clause (indexes will not serve ordered reads)');
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
if (proto[INSTALLED])
|
|
49
|
+
return true;
|
|
50
|
+
proto._orderBy = function (orderBy, ...rest) {
|
|
51
|
+
return stripNullsForNotNull(orderBy, orig.call(this, orderBy, ...rest));
|
|
52
|
+
};
|
|
53
|
+
proto[INSTALLED] = true;
|
|
54
|
+
logger.info('ORDER BY on Postgres: NULLS clause dropped for key and NOT NULL columns');
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=pg-order-nulls.js.map
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import type { JSONValue } from './types';
|
|
2
2
|
/**
|
|
3
|
-
* PlutusData-JSON input-index placeholder
|
|
4
|
-
*
|
|
5
|
-
* The placeholder must be the entire `int` field value — partial matches are ignored.
|
|
3
|
+
* PlutusData-JSON input-index placeholder `__INPUT_IDX:<64-hex txHash>#<outputIndex>__`; must be the
|
|
4
|
+
* entire `int` field value. Hash case-insensitive, normalized to lowercase at the use site.
|
|
6
5
|
*/
|
|
7
6
|
export declare const INPUT_IDX_REGEX: RegExp;
|
|
8
7
|
/** Minimal UTxO reference shape used by the placeholder resolver. */
|
|
@@ -11,25 +10,14 @@ export interface InputRef {
|
|
|
11
10
|
outputIndex: number;
|
|
12
11
|
}
|
|
13
12
|
export interface ResolveContext {
|
|
14
|
-
/** Inputs in their final, post-sort order
|
|
13
|
+
/** Inputs in their final, post-sort order; the array index is the resolved placeholder value. */
|
|
15
14
|
sortedInputs: InputRef[];
|
|
16
15
|
}
|
|
17
|
-
/**
|
|
18
|
-
* Replicates Buildooor's input sort: lexicographic on the txHash bytes, tie-break by outputIndex asc.
|
|
19
|
-
* This mirrors the Cardano ledger CBOR-set ordering used by Buildooor.
|
|
20
|
-
* Verified against node_modules/@harmoniclabs/buildooor/dist/TxBuilder/TxBuilder.js:772.
|
|
21
|
-
*/
|
|
16
|
+
/** Replicates Buildooor's input sort (ledger CBOR-set order): txHash bytes, then outputIndex asc. */
|
|
22
17
|
export declare function sortInputsLikeBuildooor<T extends InputRef>(refs: T[]): T[];
|
|
23
18
|
/**
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
* Placeholders are only recognised inside an `int` field. Strings elsewhere (e.g. `bytes`)
|
|
28
|
-
* are left untouched — hex payloads may legitimately contain `__` sequences.
|
|
29
|
-
*
|
|
30
|
-
* Throws TransactionValidationError if a placeholder references a UTxO ref that is not present
|
|
31
|
-
* in `ctx.sortedInputs`. The exact placeholder string is included in the message so consumers
|
|
32
|
-
* can diagnose missing forceInputs / script UTxOs.
|
|
19
|
+
* Replaces `{int: "__INPUT_IDX:<hash>#<idx>__"}` leaves with the input's sorted position. Only `int`
|
|
20
|
+
* fields are inspected (`bytes` may legitimately contain `__`); an unknown ref throws TransactionValidationError.
|
|
33
21
|
*/
|
|
34
22
|
export declare function resolveIndexPlaceholders(node: JSONValue, ctx: ResolveContext): JSONValue;
|
|
35
23
|
//# sourceMappingURL=plutus-placeholders.d.ts.map
|
|
@@ -5,19 +5,12 @@ exports.sortInputsLikeBuildooor = sortInputsLikeBuildooor;
|
|
|
5
5
|
exports.resolveIndexPlaceholders = resolveIndexPlaceholders;
|
|
6
6
|
const errors_1 = require("./errors");
|
|
7
7
|
/**
|
|
8
|
-
* PlutusData-JSON input-index placeholder
|
|
9
|
-
*
|
|
10
|
-
* The placeholder must be the entire `int` field value — partial matches are ignored.
|
|
8
|
+
* PlutusData-JSON input-index placeholder `__INPUT_IDX:<64-hex txHash>#<outputIndex>__`; must be the
|
|
9
|
+
* entire `int` field value. Hash case-insensitive, normalized to lowercase at the use site.
|
|
11
10
|
*/
|
|
12
|
-
// case-insensitive: tx hashes are conventionally lowercase, but accept either
|
|
13
|
-
// case and normalize the captured hash to lowercase at the use site
|
|
14
11
|
exports.INPUT_IDX_REGEX = /^__INPUT_IDX:([0-9a-fA-F]{64})#(\d+)__$/;
|
|
15
12
|
const MAX_WALK_DEPTH = 64;
|
|
16
|
-
/**
|
|
17
|
-
* Replicates Buildooor's input sort: lexicographic on the txHash bytes, tie-break by outputIndex asc.
|
|
18
|
-
* This mirrors the Cardano ledger CBOR-set ordering used by Buildooor.
|
|
19
|
-
* Verified against node_modules/@harmoniclabs/buildooor/dist/TxBuilder/TxBuilder.js:772.
|
|
20
|
-
*/
|
|
13
|
+
/** Replicates Buildooor's input sort (ledger CBOR-set order): txHash bytes, then outputIndex asc. */
|
|
21
14
|
function sortInputsLikeBuildooor(refs) {
|
|
22
15
|
const copy = refs.slice();
|
|
23
16
|
copy.sort((a, b) => {
|
|
@@ -31,15 +24,8 @@ function sortInputsLikeBuildooor(refs) {
|
|
|
31
24
|
return copy;
|
|
32
25
|
}
|
|
33
26
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
* Placeholders are only recognised inside an `int` field. Strings elsewhere (e.g. `bytes`)
|
|
38
|
-
* are left untouched — hex payloads may legitimately contain `__` sequences.
|
|
39
|
-
*
|
|
40
|
-
* Throws TransactionValidationError if a placeholder references a UTxO ref that is not present
|
|
41
|
-
* in `ctx.sortedInputs`. The exact placeholder string is included in the message so consumers
|
|
42
|
-
* can diagnose missing forceInputs / script UTxOs.
|
|
27
|
+
* Replaces `{int: "__INPUT_IDX:<hash>#<idx>__"}` leaves with the input's sorted position. Only `int`
|
|
28
|
+
* fields are inspected (`bytes` may legitimately contain `__`); an unknown ref throws TransactionValidationError.
|
|
43
29
|
*/
|
|
44
30
|
function resolveIndexPlaceholders(node, ctx) {
|
|
45
31
|
return walk(node, ctx, 0);
|
|
@@ -59,7 +45,7 @@ function walk(node, ctx, depth) {
|
|
|
59
45
|
const match = exports.INPUT_IDX_REGEX.exec(value);
|
|
60
46
|
if (match) {
|
|
61
47
|
const [, rawTxHash, idxStr] = match;
|
|
62
|
-
const txHash = rawTxHash.toLowerCase(); //
|
|
48
|
+
const txHash = rawTxHash.toLowerCase(); // input refs are validated lowercase
|
|
63
49
|
const outputIndex = Number(idxStr);
|
|
64
50
|
const pos = ctx.sortedInputs.findIndex(ref => ref.txHash === txHash && ref.outputIndex === outputIndex);
|
|
65
51
|
if (pos === -1) {
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** In-memory sliding-window rate limiter (grant administration, failed agent-token attempts). No DB. */
|
|
2
|
+
export interface RateLimiterOptions {
|
|
3
|
+
windowMs: number;
|
|
4
|
+
maxRequests: number;
|
|
5
|
+
/** Max tracked keys (default 10 000). */
|
|
6
|
+
maxKeys?: number;
|
|
7
|
+
/** Stale-key sweep interval (default 60 000 ms). */
|
|
8
|
+
sweepIntervalMs?: number;
|
|
9
|
+
/**
|
|
10
|
+
* Max distinct keys one group (key up to its first ':', the principal) may hold (default 64),
|
|
11
|
+
* so one caller's made-up scopes cannot evict other callers' windows.
|
|
12
|
+
*/
|
|
13
|
+
maxKeysPerGroup?: number;
|
|
14
|
+
}
|
|
15
|
+
export interface RateCheckResult {
|
|
16
|
+
allowed: boolean;
|
|
17
|
+
retryAfterMs: number;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Rate-limit key `principal:scope` for a CAP request; the principal is the user, else the client
|
|
21
|
+
* address (last resort: batch parts and proxies hide it). No ':' in the principal, it is the group.
|
|
22
|
+
*/
|
|
23
|
+
export declare function principalRateKey(req: unknown, scope: string): string;
|
|
24
|
+
export declare class RateLimiter {
|
|
25
|
+
private readonly windowMs;
|
|
26
|
+
private readonly maxRequests;
|
|
27
|
+
private readonly maxKeys;
|
|
28
|
+
private readonly maxKeysPerGroup;
|
|
29
|
+
private readonly groupCounts;
|
|
30
|
+
private readonly hits;
|
|
31
|
+
private readonly sweepTimer;
|
|
32
|
+
constructor(opts: RateLimiterOptions);
|
|
33
|
+
check(key: string): RateCheckResult;
|
|
34
|
+
/** Would ONE more hit fit? Records nothing. */
|
|
35
|
+
peek(key: string): RateCheckResult;
|
|
36
|
+
/** Forget every key (tests). */
|
|
37
|
+
reset(): void;
|
|
38
|
+
/** Consume `count` slots atomically: all fit and are recorded, or none are. */
|
|
39
|
+
checkMany(key: string, count: number): RateCheckResult;
|
|
40
|
+
private dropKey;
|
|
41
|
+
/** Remove keys with no hits within the current window. */
|
|
42
|
+
private sweep;
|
|
43
|
+
/** Stop the background sweep timer. */
|
|
44
|
+
destroy(): void;
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=rate-limiter.d.ts.map
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/** In-memory sliding-window rate limiter (grant administration, failed agent-token attempts). No DB. */
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.RateLimiter = void 0;
|
|
5
|
+
exports.principalRateKey = principalRateKey;
|
|
6
|
+
/** The group a key belongs to: everything before the first ':' (the principal). */
|
|
7
|
+
function groupOf(key) {
|
|
8
|
+
const i = key.indexOf(':');
|
|
9
|
+
return i < 0 ? key : key.slice(0, i);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Rate-limit key `principal:scope` for a CAP request; the principal is the user, else the client
|
|
13
|
+
* address (last resort: batch parts and proxies hide it). No ':' in the principal, it is the group.
|
|
14
|
+
*/
|
|
15
|
+
function principalRateKey(req, scope) {
|
|
16
|
+
const r = req;
|
|
17
|
+
const user = r?.user?.id;
|
|
18
|
+
const ip = r?._?.req?.ip ?? r?.http?.req?.ip ?? r?.ip;
|
|
19
|
+
const principal = user ? `user=${String(user)}`
|
|
20
|
+
: ip ? `ip=${String(ip).replace(/:/g, '.')}`
|
|
21
|
+
: 'anonymous';
|
|
22
|
+
return `${principal}:${scope}`;
|
|
23
|
+
}
|
|
24
|
+
class RateLimiter {
|
|
25
|
+
windowMs;
|
|
26
|
+
maxRequests;
|
|
27
|
+
maxKeys;
|
|
28
|
+
maxKeysPerGroup;
|
|
29
|
+
groupCounts = new Map();
|
|
30
|
+
hits = new Map();
|
|
31
|
+
sweepTimer;
|
|
32
|
+
constructor(opts) {
|
|
33
|
+
this.windowMs = opts.windowMs;
|
|
34
|
+
this.maxRequests = opts.maxRequests;
|
|
35
|
+
this.maxKeys = opts.maxKeys || 10_000;
|
|
36
|
+
this.maxKeysPerGroup = opts.maxKeysPerGroup || 64;
|
|
37
|
+
this.sweepTimer = setInterval(() => this.sweep(), opts.sweepIntervalMs || 60_000);
|
|
38
|
+
if (typeof this.sweepTimer.unref === 'function')
|
|
39
|
+
this.sweepTimer.unref();
|
|
40
|
+
}
|
|
41
|
+
check(key) {
|
|
42
|
+
return this.checkMany(key, 1);
|
|
43
|
+
}
|
|
44
|
+
/** Would ONE more hit fit? Records nothing. */
|
|
45
|
+
peek(key) {
|
|
46
|
+
const now = Date.now();
|
|
47
|
+
const inWindow = (this.hits.get(key) ?? []).filter((t) => t > now - this.windowMs);
|
|
48
|
+
if (inWindow.length < this.maxRequests)
|
|
49
|
+
return { allowed: true, retryAfterMs: 0 };
|
|
50
|
+
const oldest = Math.min(...inWindow);
|
|
51
|
+
return { allowed: false, retryAfterMs: Math.max(oldest + this.windowMs - now, 0) };
|
|
52
|
+
}
|
|
53
|
+
/** Forget every key (tests). */
|
|
54
|
+
reset() {
|
|
55
|
+
this.hits.clear();
|
|
56
|
+
this.groupCounts.clear();
|
|
57
|
+
}
|
|
58
|
+
/** Consume `count` slots atomically: all fit and are recorded, or none are. */
|
|
59
|
+
checkMany(key, count) {
|
|
60
|
+
if (count <= 0)
|
|
61
|
+
return { allowed: true, retryAfterMs: 0 };
|
|
62
|
+
const now = Date.now();
|
|
63
|
+
const windowStart = now - this.windowMs;
|
|
64
|
+
if (!this.hits.has(key)) {
|
|
65
|
+
const group = groupOf(key);
|
|
66
|
+
if ((this.groupCounts.get(group) ?? 0) >= this.maxKeysPerGroup) {
|
|
67
|
+
return { allowed: false, retryAfterMs: this.windowMs };
|
|
68
|
+
}
|
|
69
|
+
// At capacity a new key evicts the least recently used one (insertion-ordered map, re-inserted per hit).
|
|
70
|
+
if (this.hits.size >= this.maxKeys) {
|
|
71
|
+
const oldest = this.hits.keys().next().value;
|
|
72
|
+
if (oldest !== undefined)
|
|
73
|
+
this.dropKey(oldest);
|
|
74
|
+
}
|
|
75
|
+
this.groupCounts.set(group, (this.groupCounts.get(group) ?? 0) + 1);
|
|
76
|
+
}
|
|
77
|
+
let timestamps = this.hits.get(key) || [];
|
|
78
|
+
timestamps = timestamps.filter((t) => t > windowStart);
|
|
79
|
+
this.hits.delete(key); // re-insert below = most recently used
|
|
80
|
+
if (timestamps.length + count > this.maxRequests) {
|
|
81
|
+
timestamps.sort((a, b) => a - b);
|
|
82
|
+
const oldestInWindow = timestamps[0];
|
|
83
|
+
const retryAfterMs = oldestInWindow === undefined ? this.windowMs : oldestInWindow + this.windowMs - now;
|
|
84
|
+
this.hits.set(key, timestamps);
|
|
85
|
+
return { allowed: false, retryAfterMs: Math.max(retryAfterMs, 0) };
|
|
86
|
+
}
|
|
87
|
+
for (let i = 0; i < count; i++)
|
|
88
|
+
timestamps.push(now);
|
|
89
|
+
this.hits.set(key, timestamps);
|
|
90
|
+
return { allowed: true, retryAfterMs: 0 };
|
|
91
|
+
}
|
|
92
|
+
dropKey(key) {
|
|
93
|
+
if (!this.hits.delete(key))
|
|
94
|
+
return;
|
|
95
|
+
const group = groupOf(key);
|
|
96
|
+
const n = (this.groupCounts.get(group) ?? 1) - 1;
|
|
97
|
+
if (n <= 0)
|
|
98
|
+
this.groupCounts.delete(group);
|
|
99
|
+
else
|
|
100
|
+
this.groupCounts.set(group, n);
|
|
101
|
+
}
|
|
102
|
+
/** Remove keys with no hits within the current window. */
|
|
103
|
+
sweep() {
|
|
104
|
+
const windowStart = Date.now() - this.windowMs;
|
|
105
|
+
for (const [key, timestamps] of this.hits) {
|
|
106
|
+
if (!timestamps.some((t) => t > windowStart))
|
|
107
|
+
this.dropKey(key);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/** Stop the background sweep timer. */
|
|
111
|
+
destroy() {
|
|
112
|
+
clearInterval(this.sweepTimer);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
exports.RateLimiter = RateLimiter;
|
|
116
|
+
//# sourceMappingURL=rate-limiter.js.map
|
|
@@ -1,26 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* const worker = await cds.connect.to('CardanoWorkerService');
|
|
6
|
-
* worker.on('jobConfirmed', ({ data }) => …);
|
|
7
|
-
*
|
|
8
|
-
* ODATANO ships as a CAP plugin, so a consumer runs in the SAME process — these
|
|
9
|
-
* events therefore need no broker and no `cds.requires.messaging`. Configuring a
|
|
10
|
-
* messaging service later routes the very same emits through it (with the CAP
|
|
11
|
-
* outbox) without a change here.
|
|
12
|
-
*
|
|
13
|
-
* Three properties this helper guarantees, because every caller is a background
|
|
14
|
-
* loop that must not be disturbed by an observer:
|
|
15
|
-
* - **Never throws.** A missing service, a rejected emit or a broken subscriber
|
|
16
|
-
* is logged and swallowed; the crawler/worker carries on.
|
|
17
|
-
* - **Never blocks.** Emission is fire-and-forget; a slow subscriber cannot stall
|
|
18
|
-
* block ingestion.
|
|
19
|
-
* - **Silent when unserved.** In unit tests and before CAP's `served` phase the
|
|
20
|
-
* service simply does not exist yet — that is normal, not an error.
|
|
21
|
-
*
|
|
22
|
-
* Call sites must emit AFTER their transaction commits: an event that names data
|
|
23
|
-
* a subscriber cannot read yet is worse than no event.
|
|
2
|
+
* Emits a declared CAP service event in-process (no broker needed). Never throws, never blocks,
|
|
3
|
+
* silent when the service is not served yet. Callers must emit AFTER their transaction commits.
|
|
24
4
|
*/
|
|
25
5
|
export declare function emitServiceEvent(serviceName: string, event: string, data: Record<string, unknown>): void;
|
|
26
6
|
//# sourceMappingURL=service-events.d.ts.map
|
|
@@ -7,33 +7,13 @@ exports.emitServiceEvent = emitServiceEvent;
|
|
|
7
7
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
8
8
|
const logger = cds_1.default.log('ServiceEvents');
|
|
9
9
|
/**
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* const worker = await cds.connect.to('CardanoWorkerService');
|
|
14
|
-
* worker.on('jobConfirmed', ({ data }) => …);
|
|
15
|
-
*
|
|
16
|
-
* ODATANO ships as a CAP plugin, so a consumer runs in the SAME process — these
|
|
17
|
-
* events therefore need no broker and no `cds.requires.messaging`. Configuring a
|
|
18
|
-
* messaging service later routes the very same emits through it (with the CAP
|
|
19
|
-
* outbox) without a change here.
|
|
20
|
-
*
|
|
21
|
-
* Three properties this helper guarantees, because every caller is a background
|
|
22
|
-
* loop that must not be disturbed by an observer:
|
|
23
|
-
* - **Never throws.** A missing service, a rejected emit or a broken subscriber
|
|
24
|
-
* is logged and swallowed; the crawler/worker carries on.
|
|
25
|
-
* - **Never blocks.** Emission is fire-and-forget; a slow subscriber cannot stall
|
|
26
|
-
* block ingestion.
|
|
27
|
-
* - **Silent when unserved.** In unit tests and before CAP's `served` phase the
|
|
28
|
-
* service simply does not exist yet — that is normal, not an error.
|
|
29
|
-
*
|
|
30
|
-
* Call sites must emit AFTER their transaction commits: an event that names data
|
|
31
|
-
* a subscriber cannot read yet is worse than no event.
|
|
10
|
+
* Emits a declared CAP service event in-process (no broker needed). Never throws, never blocks,
|
|
11
|
+
* silent when the service is not served yet. Callers must emit AFTER their transaction commits.
|
|
32
12
|
*/
|
|
33
13
|
function emitServiceEvent(serviceName, event, data) {
|
|
34
14
|
const srv = cds_1.default.services?.[serviceName];
|
|
35
15
|
if (!srv?.emit)
|
|
36
|
-
return; // not served
|
|
16
|
+
return; // not served yet
|
|
37
17
|
try {
|
|
38
18
|
void Promise.resolve(srv.emit(event, data)).catch((err) => {
|
|
39
19
|
logger.warn(`${serviceName}.${event} subscriber failed (ignored):`, err);
|
|
@@ -1,23 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Combine an unsigned
|
|
3
|
-
*
|
|
4
|
-
* CIP-30 signTx() returns only the witness set, not a complete signed transaction.
|
|
5
|
-
* This function combines the original unsigned transaction with the witness set
|
|
6
|
-
* to create a complete signed transaction that can be submitted to the network.
|
|
7
|
-
*
|
|
8
|
-
* @param unsignedTxCbor - The unsigned transaction CBOR (hex)
|
|
9
|
-
* @param witnessSetCbor - The witness set CBOR from CIP-30 signTx() (hex)
|
|
10
|
-
* @returns Complete signed transaction CBOR (hex)
|
|
2
|
+
* Combine an unsigned tx with the witness set a CIP-30 `signTx()` returns into a submittable signed tx.
|
|
3
|
+
* @returns complete signed transaction CBOR (hex)
|
|
11
4
|
*/
|
|
12
5
|
export declare function combineTransactionWithWitnesses(unsignedTxCbor: string, witnessSetCbor: string): string;
|
|
13
|
-
/**
|
|
14
|
-
* Check if a CBOR string is a witness set (vs a full transaction)
|
|
15
|
-
*
|
|
16
|
-
* CIP-30 returns witness sets, not full transactions.
|
|
17
|
-
* This helps detect when we need to call combineTransactionWithWitnesses.
|
|
18
|
-
*
|
|
19
|
-
* @param cborHex - CBOR hex string
|
|
20
|
-
* @returns true if it's a witness set, false if it's a full transaction
|
|
21
|
-
*/
|
|
6
|
+
/** True when the CBOR is a CIP-30 witness set (map) rather than a full transaction (array). */
|
|
22
7
|
export declare function isWitnessSetCbor(cborHex: string): boolean;
|
|
23
8
|
//# sourceMappingURL=signing-helper.d.ts.map
|
|
@@ -11,19 +11,12 @@ const uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
|
|
|
11
11
|
const errors_1 = require("./errors");
|
|
12
12
|
const logger = cds_1.default.log('SigningHelper');
|
|
13
13
|
/**
|
|
14
|
-
* Combine an unsigned
|
|
15
|
-
*
|
|
16
|
-
* CIP-30 signTx() returns only the witness set, not a complete signed transaction.
|
|
17
|
-
* This function combines the original unsigned transaction with the witness set
|
|
18
|
-
* to create a complete signed transaction that can be submitted to the network.
|
|
19
|
-
*
|
|
20
|
-
* @param unsignedTxCbor - The unsigned transaction CBOR (hex)
|
|
21
|
-
* @param witnessSetCbor - The witness set CBOR from CIP-30 signTx() (hex)
|
|
22
|
-
* @returns Complete signed transaction CBOR (hex)
|
|
14
|
+
* Combine an unsigned tx with the witness set a CIP-30 `signTx()` returns into a submittable signed tx.
|
|
15
|
+
* @returns complete signed transaction CBOR (hex)
|
|
23
16
|
*/
|
|
24
17
|
function combineTransactionWithWitnesses(unsignedTxCbor, witnessSetCbor) {
|
|
25
18
|
try {
|
|
26
|
-
//
|
|
19
|
+
// Raw CBOR level: no Cardano type validation, preserves all encoding metadata
|
|
27
20
|
const txObj = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(unsignedTxCbor));
|
|
28
21
|
if (!(txObj instanceof cbor_1.CborArray) || txObj.array.length < 2) {
|
|
29
22
|
throw new errors_1.TransactionValidationError('Invalid transaction CBOR structure');
|
|
@@ -33,19 +26,18 @@ function combineTransactionWithWitnesses(unsignedTxCbor, witnessSetCbor) {
|
|
|
33
26
|
const origWs = txObj.array[1];
|
|
34
27
|
let witnessCount = 0;
|
|
35
28
|
if (origWs instanceof cbor_1.CborMap && walletWsObj instanceof cbor_1.CborMap) {
|
|
36
|
-
//
|
|
29
|
+
// Wallet's VKey witnesses (map key 0)
|
|
37
30
|
const walletVkeyEntry = walletWsObj.map.find(e => e.k instanceof cbor_1.CborUInt && Number(e.k.num) === 0);
|
|
38
31
|
if (walletVkeyEntry) {
|
|
39
|
-
//
|
|
40
|
-
// remove any existing key 0, then add wallet's key 0 (VKey witnesses)
|
|
32
|
+
// Keep original entries (redeemers, datums, scripts at keys 3-7), replace key 0 with the wallet's
|
|
41
33
|
const mergedEntries = origWs.map
|
|
42
34
|
.filter(e => !(e.k instanceof cbor_1.CborUInt && Number(e.k.num) === 0))
|
|
43
35
|
.concat([walletVkeyEntry]);
|
|
44
|
-
//
|
|
36
|
+
// New witness set map preserving the original's encoding style
|
|
45
37
|
txObj.array[1] = new cbor_1.CborMap(mergedEntries, {
|
|
46
38
|
indefinite: origWs.indefinite,
|
|
47
39
|
});
|
|
48
|
-
//
|
|
40
|
+
// VKey witnesses: CborArray, or CborTag(258, CborArray) in Conway
|
|
49
41
|
const vkeyValue = walletVkeyEntry.v;
|
|
50
42
|
if (vkeyValue instanceof cbor_1.CborArray) {
|
|
51
43
|
witnessCount = vkeyValue.array.length;
|
|
@@ -61,11 +53,8 @@ function combineTransactionWithWitnesses(unsignedTxCbor, witnessSetCbor) {
|
|
|
61
53
|
else {
|
|
62
54
|
throw new errors_1.TransactionValidationError('Witness set must be CBOR map per Cardano spec');
|
|
63
55
|
}
|
|
64
|
-
//
|
|
65
|
-
//
|
|
66
|
-
// matches now that the witness set changed). The INNER element subCborRefs are
|
|
67
|
-
// deliberately kept: that byte-preserves the body (array[0]), so the tx body hash
|
|
68
|
-
// the witnesses signed stays identical.
|
|
56
|
+
// New outer CborArray so the encoder cannot reuse the stale outer subCborRef; the inner
|
|
57
|
+
// subCborRefs are kept so the body bytes (and thus the signed body hash) stay identical.
|
|
69
58
|
const signedTxCbor = (0, uint8array_utils_1.toHex)(cbor_1.Cbor.encode(new cbor_1.CborArray(txObj.array, { indefinite: txObj.indefinite })));
|
|
70
59
|
logger.info({
|
|
71
60
|
unsignedTxLength: unsignedTxCbor.length,
|
|
@@ -81,26 +70,15 @@ function combineTransactionWithWitnesses(unsignedTxCbor, witnessSetCbor) {
|
|
|
81
70
|
throw new errors_1.TransactionValidationError(`Failed to combine transaction with witnesses: ${msg}`);
|
|
82
71
|
}
|
|
83
72
|
}
|
|
84
|
-
/**
|
|
85
|
-
* Check if a CBOR string is a witness set (vs a full transaction)
|
|
86
|
-
*
|
|
87
|
-
* CIP-30 returns witness sets, not full transactions.
|
|
88
|
-
* This helps detect when we need to call combineTransactionWithWitnesses.
|
|
89
|
-
*
|
|
90
|
-
* @param cborHex - CBOR hex string
|
|
91
|
-
* @returns true if it's a witness set, false if it's a full transaction
|
|
92
|
-
*/
|
|
73
|
+
/** True when the CBOR is a CIP-30 witness set (map) rather than a full transaction (array). */
|
|
93
74
|
function isWitnessSetCbor(cborHex) {
|
|
94
75
|
try {
|
|
95
76
|
const obj = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(cborHex));
|
|
96
|
-
// A full transaction is a CBOR array ([body, witness_set, is_valid, aux_data]);
|
|
97
|
-
// a CIP-30 witness set is a CBOR map. The two shapes are unambiguous.
|
|
98
77
|
if (obj instanceof cbor_1.CborArray)
|
|
99
78
|
return false;
|
|
100
79
|
return obj instanceof cbor_1.CborMap;
|
|
101
80
|
}
|
|
102
81
|
catch {
|
|
103
|
-
// Invalid / unparseable CBOR
|
|
104
82
|
return false;
|
|
105
83
|
}
|
|
106
84
|
}
|