@lidofinance/api-rpc-proxy 0.0.0-stage → 1.0.0

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/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # @lidofinance/api-rpc-proxy
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Building blocks for a Fastify JSON-RPC proxy: method/address allowlisting, per-IP rate limiting,
4
+ chain health probing and prom-client metrics. Extracted from
5
+ [lido-consolidation-ui](https://github.com/lidofinance/lido-consolidation-ui)'s `server/`.
6
+
7
+ ## Installation
8
+
9
+ `yarn add @lidofinance/api-rpc-proxy`
10
+
11
+ ## Getting started
12
+
13
+ `registerRpcProxyRoutes` wires up `/health`, `/metrics` and `/rpc` on a Fastify instance. Everything
14
+ app-specific — allowed contract addresses, chain ids, RPC provider URLs — is passed in by the caller;
15
+ the package has no opinion on where those come from.
16
+
17
+ ```ts
18
+ import Fastify from 'fastify'
19
+ import { createRpcProxyMetrics, registerRpcProxyRoutes } from '@lidofinance/api-rpc-proxy'
20
+
21
+ const metrics = createRpcProxyMetrics({ prefix: 'my_app_' })
22
+
23
+ const app = Fastify()
24
+
25
+ registerRpcProxyRoutes(app, {
26
+ providers: { '1': ['https://mainnet.example/rpc'] },
27
+ defaultChain: '1',
28
+ fetchRPC: metrics.fetchRPC,
29
+ metrics,
30
+ validation: {
31
+ allowedRPCMethods: ['eth_call', 'eth_getLogs', 'eth_chainId'],
32
+ allowedCallAddresses: { 1: ['0x...'] },
33
+ allowedLogsAddresses: { 1: ['0x...'] },
34
+ blockEmptyAddressGetLogs: true,
35
+ maxBatchCount: 20,
36
+ maxResponseSize: 1_000_000,
37
+ },
38
+ rateLimit: { max: 300, windowSec: 60 },
39
+ })
40
+
41
+ await app.listen({ port: 3002 })
42
+ ```
43
+
44
+ ## What's included
45
+
46
+ - `rpcFactory` — validates and forwards JSON-RPC requests, streaming the upstream response back.
47
+ - `createRateLimitHook` — fixed-window per-IP rate limiter as a Fastify preHandler.
48
+ - `probeChains` — probes every configured RPC URL per chain, healthy if at least one responds.
49
+ - `createRpcProxyMetrics` — prom-client counters/histograms/gauge for requests, blocks and chain
50
+ reachability, plus a metrics-tracked `fetchRPC` (via `@lidofinance/api-rpc`).
51
+ - `registerRpcProxyRoutes` — wires the above into `/health`, `/metrics`, `/rpc` on a Fastify app.
52
+
53
+ Anything app-specific — which contracts are callable, CSP reporting, the actual `fastify()` bootstrap —
54
+ stays in the consuming app.
package/README.mdx ADDED
@@ -0,0 +1,4 @@
1
+ import { MarkdownWrapper } from '../../../.storybook/components/markdownWrapper.tsx'
2
+ import ReadmeContent from './README.md?raw'
3
+
4
+ <MarkdownWrapper>{ReadmeContent}</MarkdownWrapper>
package/dist/index.cjs ADDED
@@ -0,0 +1,558 @@
1
+ var $jf5wi$nodestream = require("node:stream");
2
+ var $jf5wi$nodestreampromises = require("node:stream/promises");
3
+ var $jf5wi$lidofinancerpc = require("@lidofinance/rpc");
4
+ var $jf5wi$memorycache = require("memory-cache");
5
+ var $jf5wi$nodenet = require("node:net");
6
+ var $jf5wi$lidofinanceapirpc = require("@lidofinance/api-rpc");
7
+ var $jf5wi$promclient = require("prom-client");
8
+ var $jf5wi$lidofinanceapimetrics = require("@lidofinance/api-metrics");
9
+
10
+ function $parcel$exportWildcard(dest, source) {
11
+ Object.keys(source).forEach(function(key) {
12
+ if (key === 'default' || key === '__esModule' || dest.hasOwnProperty(key)) {
13
+ return;
14
+ }
15
+
16
+ Object.defineProperty(dest, key, {
17
+ enumerable: true,
18
+ get: function get() {
19
+ return source[key];
20
+ }
21
+ });
22
+ });
23
+
24
+ return dest;
25
+ }
26
+ function $parcel$export(e, n, v, s) {
27
+ Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
28
+ }
29
+
30
+ $parcel$export(module.exports, "rpcFactory", () => $c36759493dc2a380$export$9bfcc39f106ad871);
31
+ $parcel$export(module.exports, "baseRequestValidationFactory", () => $fc26c06bc08587fb$export$564dd6c0fb12e680);
32
+ $parcel$export(module.exports, "ethCallValidationFactory", () => $fc26c06bc08587fb$export$b724143801441d66);
33
+ $parcel$export(module.exports, "ethGetLogsValidationFactory", () => $fc26c06bc08587fb$export$5d8ee2232a9cb21a);
34
+ $parcel$export(module.exports, "rpcMethodsValidationFactory", () => $fc26c06bc08587fb$export$bd57dbd3bc9a1cc6);
35
+ $parcel$export(module.exports, "shouldValidateRpcMethod", () => $fc26c06bc08587fb$export$e67f820dcb2fefda);
36
+ $parcel$export(module.exports, "streamMaxSizeValidationFactory", () => $fc26c06bc08587fb$export$7c5a2292697deb4b);
37
+ $parcel$export(module.exports, "createRateLimitHook", () => $ed77a7c0d430b773$export$d4d313c44e137fbd);
38
+ $parcel$export(module.exports, "FixedWindowStore", () => $1837de1d3fa59747$export$50407732e532e273);
39
+ $parcel$export(module.exports, "getClientIp", () => $b79779073d6c1ff6$export$a136460b3a4d9dd1);
40
+ $parcel$export(module.exports, "normalizeIp", () => $b79779073d6c1ff6$export$d72b6c2c9b6e498);
41
+ $parcel$export(module.exports, "RATE_LIMIT_ERROR_MESSAGE", () => $d664e7ff5c5c06af$export$cc8ff9baf1a1960);
42
+ $parcel$export(module.exports, "RATE_LIMIT_HEADERS", () => $d664e7ff5c5c06af$export$a063967512de3ebf);
43
+ $parcel$export(module.exports, "probeChains", () => $197799e10b2d45f5$export$b1f76e97540655f3);
44
+ $parcel$export(module.exports, "createRpcProxyMetrics", () => $325c7c1d154acf14$export$b3e9bcd4083b83c6);
45
+ $parcel$export(module.exports, "registerRpcProxyRoutes", () => $91c84f984aa4e6af$export$be56850439a72159);
46
+ // RPC proxy factory adapted from the @lidofinance/next-api-wrapper rpcFactory pattern
47
+ // (https://github.com/lidofinance/lido-frontend-template).
48
+ // Changes from the original:
49
+ // - Ported from Next.js API routes to Fastify request handlers
50
+ // - Added per-chain contract-address allowlist (eth_call / eth_getLogs restriction)
51
+ // - Integrated @lidofinance/api-rpc trackedFetchRpcFactory for prom-client metrics
52
+
53
+
54
+
55
+ var $50baca306c9e1fc2$exports = {};
56
+
57
+ $parcel$export($50baca306c9e1fc2$exports, "DEFAULT_API_ERROR_MESSAGE", () => $50baca306c9e1fc2$export$c982278a0ddc4dbe);
58
+ $parcel$export($50baca306c9e1fc2$exports, "HEALTHY_RPC_SERVICES_ARE_OVER", () => $50baca306c9e1fc2$export$56a189db5508cdcb);
59
+ $parcel$export($50baca306c9e1fc2$exports, "ClientError", () => $50baca306c9e1fc2$export$bb8c263ad32caa8);
60
+ $parcel$export($50baca306c9e1fc2$exports, "UnsupportedChainIdError", () => $50baca306c9e1fc2$export$fc97cac2ba066ec7);
61
+ $parcel$export($50baca306c9e1fc2$exports, "UnsupportedHTTPMethodError", () => $50baca306c9e1fc2$export$2dfa2d8949b43fdc);
62
+ $parcel$export($50baca306c9e1fc2$exports, "InvalidRequestError", () => $50baca306c9e1fc2$export$2adbfa76b71ba748);
63
+ $parcel$export($50baca306c9e1fc2$exports, "SizeTooLargeError", () => $50baca306c9e1fc2$export$e224c1080d950012);
64
+ const $50baca306c9e1fc2$export$c982278a0ddc4dbe = "Something went wrong. Sorry, try again later :(";
65
+ const $50baca306c9e1fc2$export$56a189db5508cdcb = "Healthy RPC services are over!";
66
+ class $50baca306c9e1fc2$export$bb8c263ad32caa8 extends Error {
67
+ }
68
+ class $50baca306c9e1fc2$export$fc97cac2ba066ec7 extends $50baca306c9e1fc2$export$bb8c263ad32caa8 {
69
+ constructor(message){
70
+ super(message || "Unsupported chainId");
71
+ }
72
+ }
73
+ class $50baca306c9e1fc2$export$2dfa2d8949b43fdc extends $50baca306c9e1fc2$export$bb8c263ad32caa8 {
74
+ constructor(message){
75
+ super(message || "Unsupported HTTP method");
76
+ }
77
+ }
78
+ class $50baca306c9e1fc2$export$2adbfa76b71ba748 extends $50baca306c9e1fc2$export$bb8c263ad32caa8 {
79
+ constructor(message){
80
+ super(message || "Invalid Request");
81
+ }
82
+ }
83
+ class $50baca306c9e1fc2$export$e224c1080d950012 extends $50baca306c9e1fc2$export$bb8c263ad32caa8 {
84
+ constructor(message){
85
+ super(message || "Response size too large");
86
+ }
87
+ }
88
+
89
+
90
+
91
+
92
+
93
+ // BigInt(0), not a 0n literal — this file is type-checked under the repo's shared
94
+ // root tsconfig (target es5) whenever a sibling package without its own tsconfig
95
+ // runs `tsc`, and BigInt literal syntax requires an ES2020+ target to parse.
96
+ const $fc26c06bc08587fb$var$zeroBN = BigInt(0);
97
+ const $fc26c06bc08587fb$export$564dd6c0fb12e680 = (defaultChain, providers, maxBatchSize)=>{
98
+ return (req)=>{
99
+ const rawChainId = Array.isArray(req.query.chainId) ? req.query.chainId[0] : req.query.chainId;
100
+ const chainId = Number(rawChainId || defaultChain);
101
+ if (providers[chainId] == null) throw new (0, $50baca306c9e1fc2$export$fc97cac2ba066ec7)();
102
+ const requests = Array.isArray(req.body) ? req.body : [
103
+ req.body
104
+ ];
105
+ if (typeof maxBatchSize === "number" && requests.length > maxBatchSize) throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`Too many batched requests`);
106
+ return {
107
+ chainId: chainId,
108
+ requests: requests
109
+ };
110
+ };
111
+ };
112
+ const $fc26c06bc08587fb$export$bd57dbd3bc9a1cc6 = (allowedMethods)=>{
113
+ const methodsMap = new Set(allowedMethods ?? []);
114
+ return (request, context)=>{
115
+ const method = request.method;
116
+ if (typeof method !== "string") throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method isn't string`);
117
+ if (allowedMethods && !methodsMap.has(request.method)) {
118
+ context.rpcRequestBlocked.inc({
119
+ reason: "method not allowed"
120
+ });
121
+ throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method ${method} not allowed`);
122
+ }
123
+ };
124
+ };
125
+ const $fc26c06bc08587fb$export$b724143801441d66 = (allowedAddress)=>{
126
+ const allowedCallAddressMap = $fc26c06bc08587fb$var$createAllowedAddressMap(allowedAddress);
127
+ return (request, { chainId: chainId, rpcRequestBlocked: rpcRequestBlocked })=>{
128
+ const { params: params } = request;
129
+ // Explicitly reject any request whose first param is not a well-formed tx object.
130
+ // Using an early-return guard keeps the "address allowed?" check unconditionally
131
+ // reachable and prevents future edits to the condition from accidentally creating
132
+ // a path that forwards an unvalidated eth_call.
133
+ const txObject = Array.isArray(params) ? params[0] : undefined;
134
+ if (txObject == null || typeof txObject !== "object" || !("to" in txObject) || typeof txObject.to !== "string") throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method eth_call is invalid`);
135
+ const toAddress = txObject.to;
136
+ if (!allowedCallAddressMap[chainId]?.has(toAddress.toLowerCase())) {
137
+ rpcRequestBlocked.inc({
138
+ reason: "address not allowed for eth_call"
139
+ });
140
+ throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`Address not allowed for eth_call`);
141
+ }
142
+ };
143
+ };
144
+ const $fc26c06bc08587fb$export$5d8ee2232a9cb21a = (allowedAddress, blockEmptyAddressGetLogs, maxBlockRange, currentBlockTTL = 60000)=>{
145
+ const allowedAddressMap = $fc26c06bc08587fb$var$createAllowedAddressMap(allowedAddress ?? {});
146
+ const maxBlockRangeBN = maxBlockRange ? BigInt(maxBlockRange) : $fc26c06bc08587fb$var$zeroBN;
147
+ const currentBlock = new (0, $jf5wi$memorycache.Cache)();
148
+ return async (request, { chainId: chainId, rpcRequestBlocked: rpcRequestBlocked, requestRPC: requestRPC })=>{
149
+ try {
150
+ const params = request.params[0];
151
+ const fromBlock = params.fromBlock;
152
+ const toBlock = params.toBlock ?? "latest";
153
+ if (blockEmptyAddressGetLogs || allowedAddress) {
154
+ const address = params.address;
155
+ if (blockEmptyAddressGetLogs && !address) throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method eth_getLogs address is invalid`);
156
+ const addresses = Array.isArray(address) ? address : [
157
+ address
158
+ ];
159
+ if (blockEmptyAddressGetLogs && addresses.length === 0) throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method eth_getLogs address is invalid`);
160
+ if (allowedAddress && addresses.some((eventAddress)=>typeof eventAddress !== "string" || !allowedAddressMap[chainId]?.has(eventAddress.toLowerCase()))) {
161
+ rpcRequestBlocked.inc({
162
+ reason: "address not allowed for eth_getLogs"
163
+ });
164
+ throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`Address not allowed for eth_getLogs`);
165
+ }
166
+ }
167
+ if (maxBlockRange) {
168
+ if (fromBlock === "earliest") throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method eth_getLogs fromBlock is invalid`);
169
+ if (fromBlock.startsWith("0x")) {
170
+ const normalizedFromBlock = BigInt(fromBlock);
171
+ let normalizedToBlock;
172
+ if (toBlock.startsWith("0x")) normalizedToBlock = BigInt(toBlock);
173
+ else {
174
+ const cached = currentBlock.get(chainId);
175
+ if (cached) normalizedToBlock = cached;
176
+ else {
177
+ normalizedToBlock = await requestRPC(chainId, {
178
+ id: 1,
179
+ jsonrpc: "2.0",
180
+ method: "eth_blockNumber"
181
+ }).then((res)=>res.json()).then((res)=>BigInt(res.result));
182
+ currentBlock.put(chainId, normalizedToBlock, currentBlockTTL);
183
+ }
184
+ }
185
+ const range = normalizedToBlock - normalizedFromBlock;
186
+ if (range < $fc26c06bc08587fb$var$zeroBN || range > maxBlockRangeBN) {
187
+ rpcRequestBlocked.inc({
188
+ reason: "eth_getLogs range is invalid"
189
+ });
190
+ throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method eth_getLogs range is invalid`);
191
+ }
192
+ }
193
+ }
194
+ } catch (error) {
195
+ if (error instanceof (0, $50baca306c9e1fc2$export$bb8c263ad32caa8)) throw error;
196
+ throw new (0, $50baca306c9e1fc2$export$2adbfa76b71ba748)(`RPC method eth_getLogs is invalid`);
197
+ }
198
+ };
199
+ };
200
+ const $fc26c06bc08587fb$export$7c5a2292697deb4b = (MAX_SIZE)=>(context)=>{
201
+ let bytesWritten = 0;
202
+ return new (0, $jf5wi$nodestream.Transform)({
203
+ transform (chunk, _encoding, callback) {
204
+ bytesWritten += chunk.length;
205
+ if (bytesWritten > MAX_SIZE) {
206
+ context.rpcRequestBlocked.inc({
207
+ reason: "response too large"
208
+ });
209
+ return callback(new (0, $50baca306c9e1fc2$export$e224c1080d950012)(`Stream size exceeds the maximum limit of ${MAX_SIZE} bytes`));
210
+ }
211
+ return callback(null, chunk);
212
+ },
213
+ flush (callback) {
214
+ callback();
215
+ }
216
+ });
217
+ };
218
+ const $fc26c06bc08587fb$export$e67f820dcb2fefda = (method, allowedRPCMethods)=>!allowedRPCMethods || allowedRPCMethods.includes(method);
219
+ const $fc26c06bc08587fb$var$createAllowedAddressMap = (allowedAddress)=>Object.entries(allowedAddress).reduce((acc, [chainId, addresses])=>{
220
+ acc[chainId] = new Set(addresses.map((a)=>a.toLowerCase()));
221
+ return acc;
222
+ }, {});
223
+
224
+
225
+ const $c36759493dc2a380$export$9bfcc39f106ad871 = ({ providers: providers, fetchRPC: fetchRPC, defaultChain: defaultChain, validation: validation, serverLogger: serverLogger = console, metrics: metrics })=>{
226
+ const { allowedRPCMethods: allowedRPCMethods, allowedCallAddresses: allowedCallAddresses, allowedLogsAddresses: allowedLogsAddresses, maxResponseSize: maxResponseSize = 1000000, maxBatchCount: maxBatchCount = 20, currentBlockTTLms: currentBlockTTLms = 60000, maxGetLogsRange: maxGetLogsRange = 20000, blockEmptyAddressGetLogs: blockEmptyAddressGetLogs = true } = validation;
227
+ const rpcRequestBlocked = metrics?.rpcRequestBlocked ?? {
228
+ inc: (_labels)=>{}
229
+ };
230
+ const rpcRequestMethods = metrics?.rpcRequestMethods;
231
+ const validateBaseRequest = (0, $fc26c06bc08587fb$export$564dd6c0fb12e680)(defaultChain, providers, maxBatchCount);
232
+ const validateRpcMethod = (0, $fc26c06bc08587fb$export$bd57dbd3bc9a1cc6)(allowedRPCMethods);
233
+ const validateEthCall = allowedCallAddresses && (0, $fc26c06bc08587fb$export$e67f820dcb2fefda)("eth_call", allowedRPCMethods) ? (0, $fc26c06bc08587fb$export$b724143801441d66)(allowedCallAddresses) : undefined;
234
+ const validateEthGetLogs = (allowedLogsAddresses || blockEmptyAddressGetLogs) && (0, $fc26c06bc08587fb$export$e67f820dcb2fefda)("eth_getLogs", allowedRPCMethods) ? (0, $fc26c06bc08587fb$export$5d8ee2232a9cb21a)(allowedLogsAddresses, blockEmptyAddressGetLogs, maxGetLogsRange, currentBlockTTLms) : undefined;
235
+ const validateMaxSteamSize = (0, $fc26c06bc08587fb$export$7c5a2292697deb4b)(maxResponseSize);
236
+ const requestRPC = (chainId, body)=>(0, $jf5wi$lidofinancerpc.iterateUrls)(providers[chainId], (url)=>fetchRPC(url, {
237
+ body: body
238
+ }, {
239
+ chainId: chainId
240
+ }), (error)=>{
241
+ const message = error instanceof Error ? error.message : String(error);
242
+ serverLogger.warn(`[rpcFactory] provider failed for chain ${chainId}: ${message}`);
243
+ });
244
+ return async (request, reply)=>{
245
+ const abortController = new AbortController();
246
+ try {
247
+ const { chainId: chainId, requests: requests } = validateBaseRequest(request);
248
+ const validationContext = {
249
+ chainId: chainId,
250
+ rpcRequestBlocked: rpcRequestBlocked,
251
+ requestRPC: requestRPC
252
+ };
253
+ for (const req of requests){
254
+ validateRpcMethod(req, validationContext);
255
+ rpcRequestMethods?.inc({
256
+ method: req.method
257
+ });
258
+ if (req.method === "eth_call" && validateEthCall) validateEthCall(req, validationContext);
259
+ if (req.method === "eth_getLogs" && validateEthGetLogs) await validateEthGetLogs(req, validationContext);
260
+ }
261
+ const proxiedRPC = await requestRPC(chainId, request.body);
262
+ reply.header("content-type", proxiedRPC.headers.get("content-type") ?? "application/json");
263
+ if (!proxiedRPC.body) throw new Error("There are problems with RPC provider");
264
+ await (0, $jf5wi$nodestreampromises.pipeline)((0, $jf5wi$nodestream.Readable).fromWeb(proxiedRPC.body), validateMaxSteamSize(validationContext), reply.raw, {
265
+ signal: abortController.signal
266
+ });
267
+ } catch (error) {
268
+ if (error instanceof (0, $50baca306c9e1fc2$export$bb8c263ad32caa8)) reply.status(400).send(error.message ?? (0, $50baca306c9e1fc2$export$c982278a0ddc4dbe));
269
+ else if (error instanceof Error) {
270
+ serverLogger.error("[rpcFactory] " + (error.message ?? (0, $50baca306c9e1fc2$export$c982278a0ddc4dbe)));
271
+ if (!reply.sent) reply.status(500).send((0, $50baca306c9e1fc2$export$c982278a0ddc4dbe));
272
+ } else reply.status(500).send((0, $50baca306c9e1fc2$export$56a189db5508cdcb));
273
+ } finally{
274
+ abortController.abort();
275
+ }
276
+ };
277
+ };
278
+
279
+
280
+ var $83621533ef5f6afb$exports = {};
281
+
282
+
283
+
284
+
285
+ const $d664e7ff5c5c06af$export$a063967512de3ebf = {
286
+ limit: "X-RateLimit-Limit",
287
+ remaining: "X-RateLimit-Remaining",
288
+ reset: "X-RateLimit-Reset"
289
+ };
290
+ const $d664e7ff5c5c06af$export$cc8ff9baf1a1960 = "Rate limit exceeded";
291
+
292
+
293
+ class $1837de1d3fa59747$export$50407732e532e273 {
294
+ set(key, value, durationSec) {
295
+ clearTimeout(this.store.get(key)?.timeoutId);
296
+ const timeoutId = setTimeout(()=>this.store.delete(key), durationSec * 1000);
297
+ // This is a cache-eviction timer, not pending work — it must not keep the
298
+ // process alive on its own (matters for a long-running server, unlike the
299
+ // serverless functions the ported design originally ran in).
300
+ timeoutId.unref();
301
+ this.store.set(key, {
302
+ value: value,
303
+ timeoutId: timeoutId
304
+ });
305
+ }
306
+ get(key) {
307
+ return this.store.get(key)?.value;
308
+ }
309
+ increment(key, durationSec) {
310
+ const next = (this.get(key) ?? 0) + 1;
311
+ this.set(key, next, durationSec);
312
+ return next;
313
+ }
314
+ constructor(){
315
+ this.store = new Map();
316
+ }
317
+ }
318
+
319
+
320
+
321
+ const $b79779073d6c1ff6$export$d72b6c2c9b6e498 = (ip)=>ip.trim().replace(/^::ffff:/i, "");
322
+ const $b79779073d6c1ff6$var$firstValidIp = (value)=>{
323
+ const raw = Array.isArray(value) ? value[0] : value;
324
+ if (!raw) return undefined;
325
+ const candidate = $b79779073d6c1ff6$export$d72b6c2c9b6e498(raw.split(",")[0] ?? "");
326
+ return candidate && (0, $jf5wi$nodenet.isIP)(candidate) ? candidate : undefined;
327
+ };
328
+ const $b79779073d6c1ff6$export$a136460b3a4d9dd1 = (req, customIpHeader)=>{
329
+ const customIp = customIpHeader ? $b79779073d6c1ff6$var$firstValidIp(req.headers[customIpHeader.toLowerCase()]) : undefined;
330
+ return customIp ?? $b79779073d6c1ff6$export$d72b6c2c9b6e498(req.ip || "0.0.0.0");
331
+ };
332
+
333
+
334
+ const $ed77a7c0d430b773$export$d4d313c44e137fbd = ({ max: max, windowSec: windowSec, customIpHeader: customIpHeader, onBlocked: onBlocked })=>{
335
+ const store = new (0, $1837de1d3fa59747$export$50407732e532e273)();
336
+ return async (req, reply)=>{
337
+ const ip = (0, $b79779073d6c1ff6$export$a136460b3a4d9dd1)(req, customIpHeader);
338
+ const now = Date.now() / 1000;
339
+ const window = Math.floor(now / windowSec);
340
+ const key = `${ip}:${window}`;
341
+ const count = store.increment(key, windowSec);
342
+ const remaining = max - count;
343
+ const reset = (window + 1) * windowSec;
344
+ reply.header((0, $d664e7ff5c5c06af$export$a063967512de3ebf).limit, String(max));
345
+ reply.header((0, $d664e7ff5c5c06af$export$a063967512de3ebf).remaining, String(Math.max(remaining, 0)));
346
+ reply.header((0, $d664e7ff5c5c06af$export$a063967512de3ebf).reset, String(reset));
347
+ if (remaining < 0) {
348
+ const retryAfter = Math.max(Math.ceil(reset - now), 0);
349
+ reply.header("Retry-After", String(retryAfter));
350
+ onBlocked?.(ip);
351
+ reply.status(429).send(`${(0, $d664e7ff5c5c06af$export$cc8ff9baf1a1960)} for ip:${ip}`);
352
+ }
353
+ };
354
+ };
355
+
356
+
357
+
358
+
359
+
360
+ const $197799e10b2d45f5$var$DEFAULT_HEALTH_TIMEOUT_MS = 5000;
361
+ const $197799e10b2d45f5$export$b1f76e97540655f3 = async (providers, { fetchRPC: fetchRPC, timeoutMs: timeoutMs = $197799e10b2d45f5$var$DEFAULT_HEALTH_TIMEOUT_MS, onResult: onResult, logger: logger = console })=>{
362
+ const results = await Promise.all(Object.entries(providers).map(async ([chainId, urls])=>{
363
+ const urlResults = await Promise.all(urls.map(async (url)=>{
364
+ try {
365
+ const response = await fetchRPC(url, {
366
+ body: {
367
+ id: 1,
368
+ jsonrpc: "2.0",
369
+ method: "eth_blockNumber",
370
+ params: []
371
+ },
372
+ signal: AbortSignal.timeout(timeoutMs)
373
+ }, {
374
+ chainId: chainId
375
+ });
376
+ const { result: result } = await response.json();
377
+ return response.ok && result != null;
378
+ } catch (error) {
379
+ const reason = error instanceof Error ? error.message : String(error);
380
+ logger.warn(`[health] probe failed for chain ${chainId} url ${url}: ${reason}`);
381
+ return false;
382
+ }
383
+ }));
384
+ const ok = urlResults.some(Boolean);
385
+ return {
386
+ chainId: chainId,
387
+ ok: ok
388
+ };
389
+ }));
390
+ for (const result of results)onResult?.(result);
391
+ return results;
392
+ };
393
+
394
+
395
+
396
+
397
+ const $325c7c1d154acf14$export$b3e9bcd4083b83c6 = ({ prefix: prefix, registry: registry = new (0, $jf5wi$promclient.Registry)(), collectDefault: collectDefault = true })=>{
398
+ const rpcRequestBlocked = new (0, $jf5wi$promclient.Counter)({
399
+ name: `${prefix}rpc_request_blocked_total`,
400
+ help: "Number of blocked RPC requests by reason",
401
+ labelNames: [
402
+ "reason"
403
+ ],
404
+ registers: [
405
+ registry
406
+ ]
407
+ });
408
+ // Client-requested RPC methods, counted at validation time — before a request is
409
+ // blocked or forwarded. Distinct from fetchRPC's own request-methods counter (from
410
+ // @lidofinance/api-rpc), which only counts methods that actually reached a provider.
411
+ const rpcRequestMethods = new (0, $jf5wi$promclient.Counter)({
412
+ name: `${prefix}rpc_request_methods`,
413
+ help: "RPC methods requested by clients, by method",
414
+ labelNames: [
415
+ "method"
416
+ ],
417
+ registers: [
418
+ registry
419
+ ]
420
+ });
421
+ const rateLimitBlockedCount = new (0, $jf5wi$promclient.Counter)({
422
+ name: `${prefix}rate_limit_blocked_total`,
423
+ help: "Number of requests rejected by the in-process per-IP rate limiter, by route",
424
+ labelNames: [
425
+ "route"
426
+ ],
427
+ registers: [
428
+ registry
429
+ ]
430
+ });
431
+ const apiResponse = new (0, $jf5wi$promclient.Histogram)({
432
+ name: `${prefix}api_response_seconds`,
433
+ help: "API response time",
434
+ buckets: [
435
+ 0.1,
436
+ 0.2,
437
+ 0.3,
438
+ 0.6,
439
+ 1,
440
+ 1.5,
441
+ 2,
442
+ 5
443
+ ],
444
+ labelNames: [
445
+ "method",
446
+ "route",
447
+ "status"
448
+ ],
449
+ registers: [
450
+ registry
451
+ ]
452
+ });
453
+ const rpcChainReachable = new (0, $jf5wi$promclient.Gauge)({
454
+ name: `${prefix}rpc_chain_reachable`,
455
+ help: "1 if the RPC endpoint for the chain is reachable, 0 otherwise",
456
+ labelNames: [
457
+ "chainId"
458
+ ],
459
+ registers: [
460
+ registry
461
+ ]
462
+ });
463
+ // Registers its own request/response/methods/result counters into `registry`.
464
+ const fetchRPC = (0, $jf5wi$lidofinanceapirpc.trackedFetchRpcFactory)({
465
+ prefix: prefix,
466
+ registry: registry
467
+ });
468
+ if (collectDefault) (0, $jf5wi$promclient.collectDefaultMetrics)({
469
+ register: registry,
470
+ prefix: prefix
471
+ });
472
+ return {
473
+ registry: registry,
474
+ fetchRPC: fetchRPC,
475
+ rpcRequestBlocked: rpcRequestBlocked,
476
+ rpcRequestMethods: rpcRequestMethods,
477
+ rateLimitBlockedCount: rateLimitBlockedCount,
478
+ apiResponse: apiResponse,
479
+ rpcChainReachable: rpcChainReachable
480
+ };
481
+ };
482
+
483
+
484
+
485
+
486
+
487
+
488
+ const $91c84f984aa4e6af$export$be56850439a72159 = (app, options)=>{
489
+ const { providers: providers, defaultChain: defaultChain, fetchRPC: fetchRPC, metrics: metrics, validation: validation, rateLimit: rateLimit, healthTimeoutMs: healthTimeoutMs, serverLogger: serverLogger } = options;
490
+ // Route label uses the matched route template (e.g. "/rpc"), not request.url —
491
+ // avoid request.url here because unmatched URLs (404s) can blow up label
492
+ // cardinality, hence the 'unknown' fallback instead. status is the aggregated
493
+ // 2xx/4xx/… class, not the exact code.
494
+ app.addHook("onResponse", (request, reply, done)=>{
495
+ metrics.apiResponse.observe({
496
+ method: request.method,
497
+ route: request.routeOptions.url ?? "unknown",
498
+ status: (0, $jf5wi$lidofinanceapimetrics.getStatusLabel)(reply.statusCode)
499
+ }, reply.elapsedTime / 1000);
500
+ done();
501
+ });
502
+ app.get("/health", async (_req, reply)=>{
503
+ const checks = await (0, $197799e10b2d45f5$export$b1f76e97540655f3)(providers, {
504
+ fetchRPC: fetchRPC,
505
+ timeoutMs: healthTimeoutMs,
506
+ onResult: ({ chainId: chainId, ok: ok })=>metrics.rpcChainReachable.set({
507
+ chainId: chainId
508
+ }, ok ? 1 : 0),
509
+ logger: serverLogger
510
+ });
511
+ const healthy = checks.every((c)=>c.ok);
512
+ // Structured JSON (status code still carries the pass/fail signal for simple
513
+ // probes like a Dockerfile's `wget --spider`) so infra/dashboards hitting this
514
+ // directly can see which chain is unreachable, not just an aggregate.
515
+ return reply.status(healthy ? 200 : 503).send({
516
+ status: healthy ? "ok" : "degraded",
517
+ chains: Object.fromEntries(checks.map((c)=>[
518
+ c.chainId,
519
+ c.ok ? "ok" : "unreachable"
520
+ ]))
521
+ });
522
+ });
523
+ app.get("/metrics", async (_req, reply)=>{
524
+ const content = await metrics.registry.metrics();
525
+ reply.status(200).header("Content-Type", metrics.registry.contentType).send(content);
526
+ });
527
+ const handleRpc = (0, $c36759493dc2a380$export$9bfcc39f106ad871)({
528
+ providers: providers,
529
+ defaultChain: defaultChain,
530
+ fetchRPC: fetchRPC,
531
+ metrics: {
532
+ rpcRequestBlocked: metrics.rpcRequestBlocked,
533
+ rpcRequestMethods: metrics.rpcRequestMethods
534
+ },
535
+ validation: validation,
536
+ serverLogger: serverLogger
537
+ });
538
+ const rpcRateLimit = (0, $ed77a7c0d430b773$export$d4d313c44e137fbd)({
539
+ max: rateLimit.max,
540
+ windowSec: rateLimit.windowSec,
541
+ customIpHeader: rateLimit.customIpHeader,
542
+ onBlocked: ()=>metrics.rateLimitBlockedCount.inc({
543
+ route: "/rpc"
544
+ })
545
+ });
546
+ app.register((scope)=>{
547
+ scope.addHook("preHandler", rpcRateLimit);
548
+ scope.post("/rpc", handleRpc);
549
+ return Promise.resolve();
550
+ });
551
+ };
552
+
553
+
554
+ $parcel$exportWildcard(module.exports, $83621533ef5f6afb$exports);
555
+ $parcel$exportWildcard(module.exports, $50baca306c9e1fc2$exports);
556
+
557
+
558
+ //# sourceMappingURL=index.cjs.map