Skip to content

Commit 872ca1a

Browse files
Copilothotlong
andcommitted
Improve JSON-RPC server error handling and security
Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
1 parent c6eeec8 commit 872ca1a

1 file changed

Lines changed: 24 additions & 7 deletions

File tree

packages/protocols/json-rpc/src/index.ts

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -195,15 +195,15 @@ export class JSONRPCPlugin implements RuntimePlugin {
195195
console.log(`[${this.name}] Starting JSON-RPC server (standalone)...`);
196196

197197
// Create HTTP server
198-
this.server = createServer((req, res) => this.handleRequest(req, res));
198+
this.server = createServer(this.handleRequest.bind(this));
199199

200200
// Start listening
201201
await new Promise<void>((resolve, reject) => {
202+
this.server!.on('error', reject);
202203
this.server!.listen(this.config.port, () => {
203204
console.log(`[${this.name}] 🚀 JSON-RPC server listening on http://localhost:${this.config.port}${this.config.basePath}`);
204205
resolve();
205206
});
206-
this.server!.on('error', reject);
207207
});
208208

209209
console.log(`[${this.name}] JSON-RPC protocol ready`);
@@ -226,7 +226,10 @@ export class JSONRPCPlugin implements RuntimePlugin {
226226
if (this.server) {
227227
console.log(`[${this.name}] Stopping JSON-RPC server...`);
228228
await new Promise<void>((resolve) => {
229-
this.server!.close(() => {
229+
this.server!.close((err) => {
230+
if (err) {
231+
console.error(`[${this.name}] Error closing server:`, err);
232+
}
230233
resolve();
231234
});
232235
});
@@ -275,12 +278,26 @@ export class JSONRPCPlugin implements RuntimePlugin {
275278
}
276279

277280
try {
278-
// Read request body
279-
let body = '';
281+
// Read request body with size limit (10MB)
282+
const maxBodySize = 10 * 1024 * 1024; // 10MB
283+
const chunks: Buffer[] = [];
284+
let totalSize = 0;
285+
280286
for await (const chunk of req) {
281-
body += chunk;
287+
totalSize += chunk.length;
288+
if (totalSize > maxBodySize) {
289+
res.writeHead(413, { 'Content-Type': 'application/json' });
290+
res.end(JSON.stringify(createErrorResponse(
291+
null,
292+
JSONRPCErrorCode.INVALID_REQUEST,
293+
'Request body too large'
294+
)));
295+
return;
296+
}
297+
chunks.push(chunk);
282298
}
283-
299+
300+
const body = Buffer.concat(chunks).toString();
284301
const jsonBody = JSON.parse(body);
285302

286303
// Handle batch or single request

0 commit comments

Comments
 (0)