@odatano/core 2.0.0-rc.1 → 2.0.0-rc.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +255 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +37 -2
  4. package/@cds-models/CardanoIndexerService/index.js +4 -0
  5. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  6. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  7. package/@cds-models/odatano/cardano/index.d.ts +86 -0
  8. package/@cds-models/odatano/cardano/index.js +6 -0
  9. package/README.md +62 -4
  10. package/db/schema.cds +105 -0
  11. package/package.json +9 -3
  12. package/src/index.d.ts +6 -0
  13. package/src/index.js +21 -1
  14. package/src/plugin.js +33 -30
  15. package/srv/blockchain/backends/blockfrost-backend.js +1 -10
  16. package/srv/blockchain/backends/koios-backend.js +1 -10
  17. package/srv/blockchain/backends/ogmios-backend.d.ts +29 -4
  18. package/srv/blockchain/backends/ogmios-backend.js +96 -7
  19. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +77 -0
  20. package/srv/blockchain/backends/ogmios-frame-guard.js +181 -0
  21. package/srv/blockchain/cardano-indexer.d.ts +18 -0
  22. package/srv/blockchain/cardano-indexer.js +58 -3
  23. package/srv/blockchain/crawler/crawler.d.ts +55 -0
  24. package/srv/blockchain/crawler/crawler.js +153 -3
  25. package/srv/blockchain/crawler/index.d.ts +9 -0
  26. package/srv/blockchain/crawler/index.js +37 -4
  27. package/srv/blockchain/crawler/sync-state.d.ts +13 -1
  28. package/srv/blockchain/crawler/sync-state.js +24 -2
  29. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
  30. package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
  31. package/srv/blockchain/wallet-worker/build-request.js +35 -6
  32. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +32 -1
  33. package/srv/blockchain/wallet-worker/confirmation-tracker.js +91 -29
  34. package/srv/blockchain/wallet-worker/job-store.d.ts +11 -0
  35. package/srv/blockchain/wallet-worker/job-store.js +42 -9
  36. package/srv/cardano-agent-service.cds +150 -0
  37. package/srv/cardano-agent-service.d.ts +2 -0
  38. package/srv/cardano-agent-service.js +16 -0
  39. package/srv/cardano-indexer-service.cds +36 -3
  40. package/srv/cardano-indexer-service.js +3 -0
  41. package/srv/cardano-service.js +57 -3
  42. package/srv/cardano-sign-service.cds +200 -180
  43. package/srv/cardano-tx-service.cds +32 -26
  44. package/srv/cardano-tx-service.js +96 -38
  45. package/srv/cardano-worker-service.cds +125 -125
  46. package/srv/server.d.ts +2 -1
  47. package/srv/server.js +18 -34
  48. package/srv/utils/agent-grants-config.d.ts +65 -0
  49. package/srv/utils/agent-grants-config.js +148 -0
  50. package/srv/utils/agent-grants.d.ts +314 -0
  51. package/srv/utils/agent-grants.js +821 -0
  52. package/srv/utils/agent-token-auth.d.ts +19 -0
  53. package/srv/utils/agent-token-auth.js +81 -0
  54. package/srv/utils/db-sanitize.d.ts +40 -0
  55. package/srv/utils/db-sanitize.js +98 -0
  56. package/srv/utils/errors.d.ts +18 -0
  57. package/srv/utils/errors.js +24 -1
  58. package/srv/utils/liveness.d.ts +23 -0
  59. package/srv/utils/liveness.js +49 -0
  60. package/srv/utils/mappers.d.ts +27 -0
  61. package/srv/utils/mappers.js +67 -7
  62. package/srv/utils/rate-limiter.d.ts +57 -0
  63. package/srv/utils/rate-limiter.js +126 -0
  64. package/srv/utils/tx-request-parsers.d.ts +13 -0
  65. package/srv/utils/tx-request-parsers.js +32 -0
  66. package/srv/utils/types.d.ts +34 -0
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The `x-agent-token` transport lane for `@odatano/cap-auth`: a token on one
3
+ * of the ODATANO service paths is authenticated here (unknown 401, expired
4
+ * 410, non-leaking) and the request continues as `agent:<grantId>` with the
5
+ * role `agent-grant`; the grant rides on the express request for the
6
+ * enforcement hook. A token on any other path is left to the delegate.
7
+ * Failed attempts are throttled per client address (20 per 15 minutes).
8
+ */
9
+ import { type TransportLane } from '@odatano/cap-auth';
10
+ /** Test seam: pin the service paths instead of reading `cds.services`. `null` resets. */
11
+ export declare function __setAgentServicePathsForTests(paths: string[] | null): void;
12
+ /** Forget throttle state and the path cache (tests). */
13
+ export declare function __resetAgentTokenLaneForTests(): void;
14
+ /** Mount paths of the six services, read from `cds.services` once they are served. */
15
+ export declare function agentServicePaths(): string[];
16
+ /** Exact segment boundary: `/odata/v4/cardano-odata` and below, never `/odata/v4/cardano-odata-evil`. */
17
+ export declare function inAgentLane(path: string, servicePaths?: string[]): boolean;
18
+ export declare const agentTokenLane: TransportLane;
19
+ //# sourceMappingURL=agent-token-auth.d.ts.map
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ /**
3
+ * The `x-agent-token` transport lane for `@odatano/cap-auth`: a token on one
4
+ * of the ODATANO service paths is authenticated here (unknown 401, expired
5
+ * 410, non-leaking) and the request continues as `agent:<grantId>` with the
6
+ * role `agent-grant`; the grant rides on the express request for the
7
+ * enforcement hook. A token on any other path is left to the delegate.
8
+ * Failed attempts are throttled per client address (20 per 15 minutes).
9
+ */
10
+ var __importDefault = (this && this.__importDefault) || function (mod) {
11
+ return (mod && mod.__esModule) ? mod : { "default": mod };
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.agentTokenLane = void 0;
15
+ exports.__setAgentServicePathsForTests = __setAgentServicePathsForTests;
16
+ exports.__resetAgentTokenLaneForTests = __resetAgentTokenLaneForTests;
17
+ exports.agentServicePaths = agentServicePaths;
18
+ exports.inAgentLane = inAgentLane;
19
+ const cds_1 = __importDefault(require("@sap/cds"));
20
+ const cap_auth_1 = require("@odatano/cap-auth");
21
+ const agent_grants_1 = require("./agent-grants");
22
+ const rate_limiter_1 = require("./rate-limiter");
23
+ const tokenFailures = new rate_limiter_1.RateLimiter({ windowMs: 15 * 60 * 1000, maxRequests: 20, maxKeys: 10_000 });
24
+ let servicePathsCache = null;
25
+ let servicePathsPinned = false;
26
+ /** Test seam: pin the service paths instead of reading `cds.services`. `null` resets. */
27
+ function __setAgentServicePathsForTests(paths) {
28
+ servicePathsCache = paths;
29
+ servicePathsPinned = paths !== null;
30
+ }
31
+ /** Forget throttle state and the path cache (tests). */
32
+ function __resetAgentTokenLaneForTests() {
33
+ tokenFailures.reset();
34
+ servicePathsCache = null;
35
+ servicePathsPinned = false;
36
+ }
37
+ /** Mount paths of the six services, read from `cds.services` once they are served. */
38
+ function agentServicePaths() {
39
+ if (servicePathsPinned && servicePathsCache)
40
+ return servicePathsCache;
41
+ if (servicePathsCache && servicePathsCache.length === agent_grants_1.AGENT_SERVICE_NAMES.length)
42
+ return servicePathsCache;
43
+ const services = cds_1.default.services ?? {};
44
+ const paths = Object.values(services)
45
+ .filter((s) => s && agent_grants_1.AGENT_SERVICE_NAMES.includes(String(s.name)) && typeof s.path === 'string')
46
+ .map((s) => String(s.path).replace(/\/+$/, ''));
47
+ servicePathsCache = paths;
48
+ return paths;
49
+ }
50
+ /** Exact segment boundary: `/odata/v4/cardano-odata` and below, never `/odata/v4/cardano-odata-evil`. */
51
+ function inAgentLane(path, servicePaths = agentServicePaths()) {
52
+ const bare = path.split('?')[0];
53
+ return servicePaths.some((p) => (0, cap_auth_1.inLaneOf)(bare, p));
54
+ }
55
+ function clientKey(req) {
56
+ const ip = req.ip ?? req.socket?.remoteAddress ?? 'unknown';
57
+ return `ip=${String(ip).replace(/:/g, '.')}:agent-token`;
58
+ }
59
+ exports.agentTokenLane = {
60
+ name: 'agent-token',
61
+ match: (req) => typeof req.headers?.[agent_grants_1.AGENT_TOKEN_HEADER] === 'string' && req.headers[agent_grants_1.AGENT_TOKEN_HEADER].length > 0,
62
+ authenticate: async (req, res) => {
63
+ const token = req.headers[agent_grants_1.AGENT_TOKEN_HEADER];
64
+ if (!inAgentLane((0, cap_auth_1.requestPath)(req)))
65
+ return { next: true };
66
+ const key = clientKey(req);
67
+ const locked = tokenFailures.peek(key);
68
+ if (!locked.allowed)
69
+ return (0, cap_auth_1.respondError)(res, 429, 'Too many failed agent token attempts', locked.retryAfterMs);
70
+ const resolution = await (0, agent_grants_1.resolveAgentToken)(token);
71
+ if (!resolution.ok) {
72
+ const failed = tokenFailures.check(key);
73
+ if (!failed.allowed)
74
+ return (0, cap_auth_1.respondError)(res, 429, 'Too many failed agent token attempts', failed.retryAfterMs);
75
+ return (0, cap_auth_1.respondError)(res, resolution.status, resolution.message);
76
+ }
77
+ req.agentGrant = resolution.grant;
78
+ return { user: (0, agent_grants_1.makeAgentUser)(resolution.grant) };
79
+ },
80
+ };
81
+ //# sourceMappingURL=agent-token-auth.js.map
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Last line of defence before writes to PostgreSQL.
3
+ *
4
+ * PostgreSQL cannot store U+0000 in `text`, and @cap-js/postgres passes bulk
5
+ * INSERT/UPSERT rows as one JSON document whose parser rejects the escape
6
+ * sequence for NUL ("unsupported Unicode escape sequence"). A single decoded
7
+ * string with a NUL character therefore fails the whole write — a crawled block
8
+ * or a lazily indexed request alike. Mappers avoid producing such strings (see
9
+ * decodeAssetName); installDbSanitizer() guarantees it for every row this plugin
10
+ * writes, whatever the source (provider JSON such as Koios' asset_name_ascii or
11
+ * pool metadata included), by hooking the database service once per process.
12
+ */
13
+ /** Remove U+0000 from every string value of the row (nested plain objects included). Returns the same row when nothing changed. */
14
+ export declare function stripNulStrings<T>(row: T): T;
15
+ /** Sanitise a row array for the database; cheap when nothing needs changing. */
16
+ export declare function sanitizeRows<T>(rows: T[]): T[];
17
+ /** The slice of a db-service request the sanitizer looks at (structural, so tests can fake it). */
18
+ export interface DbWriteRequest {
19
+ query?: unknown;
20
+ target?: {
21
+ name?: string;
22
+ } | null;
23
+ }
24
+ /**
25
+ * `before` handler for the database service: strips U+0000 from the rows of an
26
+ * INSERT / UPSERT / UPDATE against one of this plugin's entities, in place.
27
+ */
28
+ export declare function sanitizeDbRequest(req: DbWriteRequest): void;
29
+ interface HookableService {
30
+ before(event: string | string[], handler: (req: DbWriteRequest) => void): unknown;
31
+ }
32
+ /**
33
+ * Hook the sanitizer into the database service (idempotent per service instance).
34
+ * Called from the app-context bootstrap; a missing/unconnected db is a no-op so
35
+ * unit tests and early programmatic initialize() calls never fail here.
36
+ * @returns true when the hook was installed by this call
37
+ */
38
+ export declare function installDbSanitizer(db?: HookableService | undefined): boolean;
39
+ export {};
40
+ //# sourceMappingURL=db-sanitize.d.ts.map
@@ -0,0 +1,98 @@
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.stripNulStrings = stripNulStrings;
7
+ exports.sanitizeRows = sanitizeRows;
8
+ exports.sanitizeDbRequest = sanitizeDbRequest;
9
+ exports.installDbSanitizer = installDbSanitizer;
10
+ const cds_1 = __importDefault(require("@sap/cds"));
11
+ /**
12
+ * Last line of defence before writes to PostgreSQL.
13
+ *
14
+ * PostgreSQL cannot store U+0000 in `text`, and @cap-js/postgres passes bulk
15
+ * INSERT/UPSERT rows as one JSON document whose parser rejects the escape
16
+ * sequence for NUL ("unsupported Unicode escape sequence"). A single decoded
17
+ * string with a NUL character therefore fails the whole write — a crawled block
18
+ * or a lazily indexed request alike. Mappers avoid producing such strings (see
19
+ * decodeAssetName); installDbSanitizer() guarantees it for every row this plugin
20
+ * writes, whatever the source (provider JSON such as Koios' asset_name_ascii or
21
+ * pool metadata included), by hooking the database service once per process.
22
+ */
23
+ /** Remove U+0000 from every string value of the row (nested plain objects included). Returns the same row when nothing changed. */
24
+ function stripNulStrings(row) {
25
+ if (typeof row === 'string')
26
+ return (row.includes('\u0000') ? row.replaceAll('\u0000', '') : row);
27
+ if (row === null || typeof row !== 'object' || Buffer.isBuffer(row))
28
+ return row;
29
+ if (Array.isArray(row)) {
30
+ let out = null;
31
+ for (let i = 0; i < row.length; i++) {
32
+ const v = stripNulStrings(row[i]);
33
+ if (v !== row[i]) {
34
+ out ??= [...row];
35
+ out[i] = v;
36
+ }
37
+ }
38
+ return (out ?? row);
39
+ }
40
+ let out = null;
41
+ for (const [k, v] of Object.entries(row)) {
42
+ const nv = stripNulStrings(v);
43
+ if (nv !== v) {
44
+ out ??= { ...row };
45
+ out[k] = nv;
46
+ }
47
+ }
48
+ return (out ?? row);
49
+ }
50
+ /** Sanitise a row array for the database; cheap when nothing needs changing. */
51
+ function sanitizeRows(rows) {
52
+ let out = null;
53
+ for (let i = 0; i < rows.length; i++) {
54
+ const r = stripNulStrings(rows[i]);
55
+ if (r !== rows[i]) {
56
+ out ??= [...rows];
57
+ out[i] = r;
58
+ }
59
+ }
60
+ return out ?? rows;
61
+ }
62
+ /** Only this plugin's entities are rewritten — a consumer's own data is never touched. */
63
+ const OWN_NAMESPACE = 'odatano.cardano.';
64
+ /**
65
+ * `before` handler for the database service: strips U+0000 from the rows of an
66
+ * INSERT / UPSERT / UPDATE against one of this plugin's entities, in place.
67
+ */
68
+ function sanitizeDbRequest(req) {
69
+ if (!req.target?.name?.startsWith(OWN_NAMESPACE))
70
+ return;
71
+ const q = req.query;
72
+ if (!q || typeof q !== 'object')
73
+ return;
74
+ const ins = q.INSERT;
75
+ if (ins && Array.isArray(ins.entries))
76
+ ins.entries = sanitizeRows(ins.entries);
77
+ const ups = q.UPSERT;
78
+ if (ups && Array.isArray(ups.entries))
79
+ ups.entries = sanitizeRows(ups.entries);
80
+ const upd = q.UPDATE;
81
+ if (upd?.data && typeof upd.data === 'object')
82
+ upd.data = stripNulStrings(upd.data);
83
+ }
84
+ const installed = new WeakSet();
85
+ /**
86
+ * Hook the sanitizer into the database service (idempotent per service instance).
87
+ * Called from the app-context bootstrap; a missing/unconnected db is a no-op so
88
+ * unit tests and early programmatic initialize() calls never fail here.
89
+ * @returns true when the hook was installed by this call
90
+ */
91
+ function installDbSanitizer(db = cds_1.default.db) {
92
+ if (!db || typeof db.before !== 'function' || installed.has(db))
93
+ return false;
94
+ db.before(['CREATE', 'UPSERT', 'UPDATE'], sanitizeDbRequest);
95
+ installed.add(db);
96
+ return true;
97
+ }
98
+ //# sourceMappingURL=db-sanitize.js.map
@@ -222,6 +222,24 @@ export declare class HsmError extends BackendError {
222
222
  export declare class ConfigError extends Error {
223
223
  constructor(message: string);
224
224
  }
225
+ /**
226
+ * ChainSyncFrameError - Ogmios delivered a frame the client cannot turn into an object.
227
+ *
228
+ * Raised by the frame guard (see `backends/ogmios-frame-guard.ts`) once the client's parser
229
+ * and the depth-safe fallback have both failed. The block is named so `lastError` points at
230
+ * it instead of leaving an empty status behind, and so the crawler can take that one block
231
+ * through the paginating backend instead of waiting on a stream that will never deliver it.
232
+ */
233
+ export declare class ChainSyncFrameError extends BackendError {
234
+ readonly height: number | null;
235
+ readonly id: string | null;
236
+ /** Constructor
237
+ * @param height block height the frame belonged to, when it could be read off the raw text
238
+ * @param id block hash, when readable
239
+ * @param reason why the frame could not be parsed
240
+ */
241
+ constructor(height: number | null, id: string | null, reason: string);
242
+ }
225
243
  /**
226
244
  * BackendInitError - Error initializing a specific backend
227
245
  * Captures backend name and original error
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AllBackendsInitFailedError = exports.BackendInitError = exports.ConfigError = exports.HsmError = exports.AllBackendsFailedError = exports.RateLimitError = exports.ProviderUnavailableError = exports.MixedAssetsError = exports.InsufficientFundsError = exports.TransactionAlreadySubmittedError = exports.ScriptValidationError = exports.TransactionValidationError = exports.NotFoundError = exports.BackendError = void 0;
3
+ exports.AllBackendsInitFailedError = exports.BackendInitError = exports.ChainSyncFrameError = exports.ConfigError = exports.HsmError = exports.AllBackendsFailedError = exports.RateLimitError = exports.ProviderUnavailableError = exports.MixedAssetsError = exports.InsufficientFundsError = exports.TransactionAlreadySubmittedError = exports.ScriptValidationError = exports.TransactionValidationError = exports.NotFoundError = exports.BackendError = void 0;
4
4
  exports.isNotFoundOnAllBackends = isNotFoundOnAllBackends;
5
5
  exports.isPostgrestServerErrorCode = isPostgrestServerErrorCode;
6
6
  exports.getErrorStatus = getErrorStatus;
@@ -442,6 +442,29 @@ class ConfigError extends Error {
442
442
  }
443
443
  }
444
444
  exports.ConfigError = ConfigError;
445
+ /**
446
+ * ChainSyncFrameError - Ogmios delivered a frame the client cannot turn into an object.
447
+ *
448
+ * Raised by the frame guard (see `backends/ogmios-frame-guard.ts`) once the client's parser
449
+ * and the depth-safe fallback have both failed. The block is named so `lastError` points at
450
+ * it instead of leaving an empty status behind, and so the crawler can take that one block
451
+ * through the paginating backend instead of waiting on a stream that will never deliver it.
452
+ */
453
+ class ChainSyncFrameError extends BackendError {
454
+ height;
455
+ id;
456
+ /** Constructor
457
+ * @param height block height the frame belonged to, when it could be read off the raw text
458
+ * @param id block hash, when readable
459
+ * @param reason why the frame could not be parsed
460
+ */
461
+ constructor(height, id, reason) {
462
+ super(`Ogmios chain-sync frame for block ${height ?? '?'} ${id ?? ''} could not be parsed: ${reason}`, 503, error_codes_1.ERROR_CODES.PROVIDER_UNAVAILABLE, 'ogmios');
463
+ this.height = height;
464
+ this.id = id;
465
+ }
466
+ }
467
+ exports.ChainSyncFrameError = ChainSyncFrameError;
445
468
  /**
446
469
  * BackendInitError - Error initializing a specific backend
447
470
  * Captures backend name and original error
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Liveness body for CardanoIndexerService.getLiveness() (unauthenticated,
3
+ * `@requires: 'any'`): process facts only. Never touches the app context, the
4
+ * backends or the DB, so it answers while those are still initializing or have
5
+ * failed — that is what a liveness probe is for; readiness stays with
6
+ * getStatus and the backend health entities, which remain authenticated.
7
+ *
8
+ * No secrets, no backend names, no API key state. Mirrors NIGHTGATE's
9
+ * `/api/v1/indexer/getLiveness()` (status 'alive', timestamp, uptime), plus the
10
+ * package version and the configured network.
11
+ */
12
+ export interface Liveness {
13
+ status: 'alive';
14
+ timestamp: string;
15
+ /** Seconds since the process started. */
16
+ uptime: number;
17
+ /** @odatano/core version; '' when package.json is not where the in-place build puts it. */
18
+ version: string;
19
+ /** Configured network (cds.requires.odatano-core.network, NETWORK, default preview). */
20
+ network: string;
21
+ }
22
+ export declare function buildLiveness(now?: Date): Liveness;
23
+ //# sourceMappingURL=liveness.d.ts.map
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ /**
3
+ * Liveness body for CardanoIndexerService.getLiveness() (unauthenticated,
4
+ * `@requires: 'any'`): process facts only. Never touches the app context, the
5
+ * backends or the DB, so it answers while those are still initializing or have
6
+ * failed — that is what a liveness probe is for; readiness stays with
7
+ * getStatus and the backend health entities, which remain authenticated.
8
+ *
9
+ * No secrets, no backend names, no API key state. Mirrors NIGHTGATE's
10
+ * `/api/v1/indexer/getLiveness()` (status 'alive', timestamp, uptime), plus the
11
+ * package version and the configured network.
12
+ */
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.buildLiveness = buildLiveness;
18
+ const cds_1 = __importDefault(require("@sap/cds"));
19
+ const path_1 = __importDefault(require("path"));
20
+ const processStartedAt = Date.now();
21
+ let cachedVersion = null;
22
+ function packageVersion() {
23
+ if (cachedVersion !== null)
24
+ return cachedVersion;
25
+ try {
26
+ // srv/utils → package root; the build compiles in place, so this holds in
27
+ // standalone and plugin mode alike.
28
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
29
+ const pkg = require(path_1.default.resolve(__dirname, '..', '..', 'package.json'));
30
+ cachedVersion = String(pkg.version ?? '');
31
+ }
32
+ catch {
33
+ cachedVersion = '';
34
+ }
35
+ return cachedVersion;
36
+ }
37
+ function buildLiveness(now = new Date()) {
38
+ const requires = (cds_1.default.env?.requires ?? {});
39
+ const core = (requires['odatano-core'] ?? {});
40
+ const network = String(core.network || process.env.NETWORK || 'preview');
41
+ return {
42
+ status: 'alive',
43
+ timestamp: now.toISOString(),
44
+ uptime: Math.max(0, Math.floor((now.getTime() - processStartedAt) / 1000)),
45
+ version: packageVersion(),
46
+ network,
47
+ };
48
+ }
49
+ //# sourceMappingURL=liveness.js.map
@@ -118,6 +118,19 @@ export declare function mapEpoch(providerEpochData: EpochProviderData): EpochRow
118
118
  * @returns {TransactionMetadataRow[]} mapped transaction metadata rows
119
119
  */
120
120
  export declare function mapTransactionMetadata(providerLabels: MetadataLabelTxProviderData[]): TransactionMetadataRow[];
121
+ /**
122
+ * Metadata labels are uint64, the `TransactionMetadata.id` key is Integer64 (int64).
123
+ * Labels >= 2^63 are mapped through two's complement (BigInt.asIntN) so they stay
124
+ * unique and in range – preprod tx ee4f7c88… carries label 17802948329108123211,
125
+ * which PostgreSQL rejected as "out of range for type bigint" and halted the
126
+ * crawler. Beyond 2^53 the value is passed as a decimal string so that no
127
+ * precision is lost on the way to the database (CAP accepts strings for
128
+ * Integer64); `label` always keeps the original text.
129
+ *
130
+ * @returns the int64 key, or null when the label is not a non-negative integer
131
+ * (the caller skips the row — a NaN key would fail the whole bulk write)
132
+ */
133
+ export declare function metadataIdFor(label: string | number): number | string | null;
121
134
  /**
122
135
  * Map Pool Data
123
136
  * Converts provider pool data into PoolRow format
@@ -243,6 +256,20 @@ export declare function mapAddressTransactionBuild(addr: string, buildId: string
243
256
  * @returns Object with all cost model values as number arrays in canonical order
244
257
  */
245
258
  export declare function normalizeCostModels(raw: Record<string, unknown>): Record<string, number[]>;
259
+ /**
260
+ * Decode an asset name (hex bytes) into its display string.
261
+ *
262
+ * Asset names are arbitrary bytes. When they are not valid UTF-8, or when they
263
+ * contain U+0000, the hex form is returned unchanged: PostgreSQL rejects NUL in
264
+ * `text` and in the JSON documents @cap-js/postgres uses for bulk INSERT/UPSERT
265
+ * ("unsupported Unicode escape sequence"), which halted the crawler on preprod
266
+ * block 4281919 (asset name ending in 0x00). SQLite accepted the same bytes
267
+ * silently. `assetNameHex` always keeps the exact bytes, so nothing is lost.
268
+ *
269
+ * @param hex - asset name as hex string
270
+ * @returns UTF-8 text, or the hex string when the bytes are not clean text
271
+ */
272
+ export declare function decodeAssetName(hex: string): string;
246
273
  /**
247
274
  * Compute CIP-14 asset fingerprint from policyId and assetName.
248
275
  * Algorithm: bech32_encode("asset", blake2b_160(policyId_bytes + assetName_bytes))
@@ -17,6 +17,7 @@ exports.mapNetworkInfo = mapNetworkInfo;
17
17
  exports.mapBlock = mapBlock;
18
18
  exports.mapEpoch = mapEpoch;
19
19
  exports.mapTransactionMetadata = mapTransactionMetadata;
20
+ exports.metadataIdFor = metadataIdFor;
20
21
  exports.mapPool = mapPool;
21
22
  exports.mapAsset = mapAsset;
22
23
  exports.mapAssetHistory = mapAssetHistory;
@@ -31,9 +32,11 @@ exports.mapTransactionSubmission = mapTransactionSubmission;
31
32
  exports.mapAddressSigningRequest = mapAddressSigningRequest;
32
33
  exports.mapAddressTransactionBuild = mapAddressTransactionBuild;
33
34
  exports.normalizeCostModels = normalizeCostModels;
35
+ exports.decodeAssetName = decodeAssetName;
34
36
  exports.computeCip14Fingerprint = computeCip14Fingerprint;
35
37
  exports.scriptHashToEnterpriseAddress = scriptHashToEnterpriseAddress;
36
38
  const cds_1 = __importDefault(require("@sap/cds"));
39
+ const node_util_1 = require("node:util");
37
40
  const blake2b_1 = __importDefault(require("blake2b"));
38
41
  const bech32_1 = require("bech32");
39
42
  const client_1 = require("@cardano-ogmios/client");
@@ -462,14 +465,16 @@ function mapEpoch(providerEpochData) {
462
465
  function mapTransactionMetadata(providerLabels) {
463
466
  const rows = [];
464
467
  for (const lbl of providerLabels) {
465
- const numericId = Number(lbl.label);
466
- // Metadata labels are uint64; the exact value is kept in the `label` string.
467
- // The numeric `id` key (now Integer64) is exact up to 2^53 — warn beyond that.
468
- if (!Number.isSafeInteger(numericId)) {
469
- logger.warn(`Metadata label ${lbl.label} exceeds safe-integer range — numeric id key may lose precision (string label is exact)`);
468
+ const id = metadataIdFor(lbl.label);
469
+ if (id === null) {
470
+ // A NaN key would fail the whole bulk write (PostgreSQL: "invalid input syntax
471
+ // for type bigint") and, in the crawler, count towards the poison-block latch.
472
+ logger.warn(`Metadata label ${JSON.stringify(lbl.label)} of tx ${lbl.txHash} is not a uint64 — row skipped`);
473
+ continue;
470
474
  }
471
475
  rows.push({
472
- id: numericId,
476
+ // uint64 label → int64 key, exact (see metadataIdFor); `label` keeps the original string
477
+ id: id,
473
478
  tx_hash: lbl.txHash,
474
479
  label: lbl.label.toString(),
475
480
  // Ogmios' parser deliberately exposes numeric metadata as native bigint.
@@ -480,6 +485,35 @@ function mapTransactionMetadata(providerLabels) {
480
485
  }
481
486
  return rows;
482
487
  }
488
+ /**
489
+ * Metadata labels are uint64, the `TransactionMetadata.id` key is Integer64 (int64).
490
+ * Labels >= 2^63 are mapped through two's complement (BigInt.asIntN) so they stay
491
+ * unique and in range – preprod tx ee4f7c88… carries label 17802948329108123211,
492
+ * which PostgreSQL rejected as "out of range for type bigint" and halted the
493
+ * crawler. Beyond 2^53 the value is passed as a decimal string so that no
494
+ * precision is lost on the way to the database (CAP accepts strings for
495
+ * Integer64); `label` always keeps the original text.
496
+ *
497
+ * @returns the int64 key, or null when the label is not a non-negative integer
498
+ * (the caller skips the row — a NaN key would fail the whole bulk write)
499
+ */
500
+ function metadataIdFor(label) {
501
+ let big;
502
+ if (typeof label === 'number') {
503
+ if (!Number.isFinite(label))
504
+ return null;
505
+ big = BigInt(Math.trunc(label));
506
+ }
507
+ else {
508
+ const text = String(label).trim();
509
+ if (!/^\d+$/.test(text))
510
+ return null;
511
+ big = BigInt(text);
512
+ }
513
+ const wrapped = BigInt.asIntN(64, big);
514
+ const safe = wrapped >= BigInt(Number.MIN_SAFE_INTEGER) && wrapped <= BigInt(Number.MAX_SAFE_INTEGER);
515
+ return safe ? Number(wrapped) : wrapped.toString();
516
+ }
483
517
  /**
484
518
  * Map Pool Data
485
519
  * Converts provider pool data into PoolRow format
@@ -849,9 +883,35 @@ function normalizeCostModels(raw) {
849
883
  * @returns {string} UTF-8 string or original hex if conversion fails
850
884
  */
851
885
  function hexToUtf8(hex) {
886
+ return decodeAssetName(hex);
887
+ }
888
+ // ignoreBOM: a leading U+FEFF is part of the asset name's bytes and must survive the
889
+ // round trip (Buffer.toString('utf8') kept it; TextDecoder's default drops it).
890
+ const strictUtf8 = new node_util_1.TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
891
+ /**
892
+ * Decode an asset name (hex bytes) into its display string.
893
+ *
894
+ * Asset names are arbitrary bytes. When they are not valid UTF-8, or when they
895
+ * contain U+0000, the hex form is returned unchanged: PostgreSQL rejects NUL in
896
+ * `text` and in the JSON documents @cap-js/postgres uses for bulk INSERT/UPSERT
897
+ * ("unsupported Unicode escape sequence"), which halted the crawler on preprod
898
+ * block 4281919 (asset name ending in 0x00). SQLite accepted the same bytes
899
+ * silently. `assetNameHex` always keeps the exact bytes, so nothing is lost.
900
+ *
901
+ * @param hex - asset name as hex string
902
+ * @returns UTF-8 text, or the hex string when the bytes are not clean text
903
+ */
904
+ function decodeAssetName(hex) {
852
905
  if (!hex)
853
906
  return hex;
854
- return Buffer.from(hex, 'hex').toString('utf8');
907
+ let text;
908
+ try {
909
+ text = strictUtf8.decode(Buffer.from(hex, 'hex'));
910
+ }
911
+ catch {
912
+ return hex;
913
+ }
914
+ return text.includes('\u0000') ? hex : text;
855
915
  }
856
916
  /**
857
917
  * Parse asset unit (policyId + assetNameHex) into components.
@@ -0,0 +1,57 @@
1
+ /**
2
+ * In-memory sliding-window rate limiter, ported from NIGHTGATE
3
+ * (srv/utils/rate-limiter.ts). Used for grant administration and for failed
4
+ * agent-token attempts; nothing here touches the database.
5
+ */
6
+ export interface RateLimiterOptions {
7
+ windowMs: number;
8
+ maxRequests: number;
9
+ /** Max tracked keys (default 10 000). */
10
+ maxKeys?: number;
11
+ /** Stale-key sweep interval (default 60 000 ms). */
12
+ sweepIntervalMs?: number;
13
+ /**
14
+ * Max distinct keys ONE group may hold (default 64). The group is the key up
15
+ * to its first ':' (the principal in `principal:scope` keys). Bounds what a
16
+ * single caller can do to the shared table: without it, made-up scopes under
17
+ * one principal evicted every other caller's window.
18
+ */
19
+ maxKeysPerGroup?: number;
20
+ }
21
+ export interface RateCheckResult {
22
+ allowed: boolean;
23
+ retryAfterMs: number;
24
+ }
25
+ /**
26
+ * Rate-limit key for a CAP request: the principal (user, else client address)
27
+ * plus the scope. Batch parts carry no address and a proxy hides the real one,
28
+ * so the address is the last resort only. The principal is the limiter's GROUP
29
+ * (see maxKeysPerGroup), hence no ':' in it.
30
+ */
31
+ export declare function principalRateKey(req: unknown, scope: string): string;
32
+ export declare class RateLimiter {
33
+ private readonly windowMs;
34
+ private readonly maxRequests;
35
+ private readonly maxKeys;
36
+ private readonly maxKeysPerGroup;
37
+ private readonly groupCounts;
38
+ private readonly hits;
39
+ private readonly sweepTimer;
40
+ constructor(opts: RateLimiterOptions);
41
+ check(key: string): RateCheckResult;
42
+ /** Would ONE more hit fit? Records nothing. */
43
+ peek(key: string): RateCheckResult;
44
+ /** Forget every key (tests). */
45
+ reset(): void;
46
+ /**
47
+ * Consume `count` slots atomically: either ALL fit into the window and are
48
+ * recorded, or NONE are (a rejected caller has consumed nothing).
49
+ */
50
+ checkMany(key: string, count: number): RateCheckResult;
51
+ private dropKey;
52
+ /** Remove keys with no hits within the current window. */
53
+ private sweep;
54
+ /** Stop the background sweep timer. */
55
+ destroy(): void;
56
+ }
57
+ //# sourceMappingURL=rate-limiter.d.ts.map