Skip to content

Commit 2706a23

Browse files
committed
avoid write-after-end by checking res.writableEnded
new in 12.9, but falsy undefined should be harmless for old nodes, they just won't get the improved behavior
1 parent 1117500 commit 2706a23

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

lib/configproxy.js

+7-2
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,15 @@ function argumentsArray(args) {
3636
function fail(req, res, code, msg) {
3737
// log a failure, and finish the HTTP request with an error code
3838
msg = msg || "";
39+
res._logMsg = msg;
40+
41+
if (res.writableEnded) return; // response already done
3942
if (res.writeHead) res.writeHead(code);
4043
if (res.write) {
4144
if (!msg) {
4245
msg = http.STATUS_CODES[code];
4346
}
4447
res.write(msg);
45-
res._logMsg = msg;
4648
}
4749
if (res.end) res.end();
4850
}
@@ -410,6 +412,7 @@ class ConfigurableProxy extends EventEmitter {
410412
_handleProxyErrorDefault(code, kind, req, res) {
411413
// called when no custom error handler is registered,
412414
// or is registered and doesn't work
415+
if (res.writableEnded) return; // response already done
413416
if (!res.headersSent && res.writeHead) res.writeHead(code);
414417
if (res.write) res.write(http.STATUS_CODES[code]);
415418
if (res.end) res.end();
@@ -468,13 +471,14 @@ class ConfigurableProxy extends EventEmitter {
468471
}
469472

470473
var errorRequest = (secure ? https : http).request(target, function (upstream) {
474+
if (res.writableEnded) return; // response already done
471475
["content-type", "content-encoding"].map(function (key) {
472476
if (!upstream.headers[key]) return;
473477
if (res.setHeader) res.setHeader(key, upstream.headers[key]);
474478
});
475479
if (res.writeHead) res.writeHead(code);
476480
upstream.on("data", (data) => {
477-
if (res.write) res.write(data);
481+
if (res.write && !res.writableEnded) res.write(data);
478482
});
479483
upstream.on("end", () => {
480484
if (res.end) res.end();
@@ -503,6 +507,7 @@ class ConfigurableProxy extends EventEmitter {
503507
this._handleProxyErrorDefault(code, kind, req, res);
504508
return;
505509
}
510+
if (res.writableEnded) return; // response already done
506511
if (res.writeHead) res.writeHead(code, { "Content-Type": "text/html" });
507512
if (res.write) res.write(data);
508513
if (res.end) res.end();

0 commit comments

Comments
 (0)