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