From ddcaafd00315c327ef1c521066a1c07ee84ef130 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 28 Nov 2026 17:09:47 -0500 Subject: [PATCH 1/7] fix(notifications): cap the response a notification delivery will read A delivery is a POST whose only interesting part is the status code, but axios advertised every encoding it can decode, decompressed whatever a receiver sent back and buffered the whole result while nothing read it, so a small gzip body that decodes to hundreds of megabytes spent the delivery worker's heap. Deliveries now send accept-encoding: identity, disable decompression, never parse the body and abort past a 64 KiB maxContentLength; a 64 KiB maxBodyLength guards the request side. The empty transform list also stops an unsolicited compressed answer from failing a delivery that already returned 2xx. --- .changeset/notification-response-size-cap.md | 11 +++ src/services/notification-channels.ts | 50 ++++++---- .../services/notification-channels.spec.ts | 97 ++++++++++++++++++- 3 files changed, 140 insertions(+), 18 deletions(-) create mode 100644 .changeset/notification-response-size-cap.md diff --git a/.changeset/notification-response-size-cap.md b/.changeset/notification-response-size-cap.md new file mode 100644 index 000000000..0c53ffd84 --- /dev/null +++ b/.changeset/notification-response-size-cap.md @@ -0,0 +1,11 @@ +--- +'nostream': patch +--- + +fix(notifications): cap the response a notification delivery will read + +A delivery is a POST whose only interesting part is the status code, but axios advertised every encoding it can decode, decompressed whatever a receiver sent back, and buffered the whole result while nothing read it. A receiver answering with a small gzip body that decodes to hundreds of megabytes therefore spent the delivery worker's heap for a value nobody consumed (security issue #1257). + +Delivery requests now carry `accept-encoding: identity`, `decompress: false`, an empty transform list so the body is never parsed, and a 64 KiB `maxContentLength` that aborts a response as soon as it runs past it. The request-body cap is set to the same figure as a guard; today's payloads are a few kilobytes. + +The empty transform list also closes a second bug: a receiver that compressed unsolicited used to fail the delivery at `JSON.parse` even though it had answered 2xx. diff --git a/src/services/notification-channels.ts b/src/services/notification-channels.ts index 7f49ec8f5..19f9a1cf0 100644 --- a/src/services/notification-channels.ts +++ b/src/services/notification-channels.ts @@ -9,6 +9,35 @@ import { const REQUEST_TIMEOUT_MS = 15_000 +// A delivery is a POST whose only interesting part is the status code: nothing +// reads the response body. Axios would otherwise advertise every encoding it can +// decode, gunzip whatever a receiver sends back, and buffer the result, so a small +// compressed body that decodes to hundreds of megabytes would be charged to this +// worker's heap for a value nobody consumes. Three settings close that: the adapter +// aborts once the bytes received reach `maxContentLength`, `decompress: false` +// stops a receiver's `content-encoding` from being acted on, and an explicit +// `accept-encoding: identity` stops axios from inviting one in the first place. +export const MAX_RESPONSE_BYTES = 64 * 1024 + +// Request bodies are built here and bounded at a few kilobytes; this is a guard +// against a future caller passing something larger, not a limit today's payloads +// approach. +export const MAX_REQUEST_BYTES = 64 * 1024 + +const deliveryRequestOptions = (headers: Record = {}) => ({ + timeout: REQUEST_TIMEOUT_MS, + headers: { ...headers, 'accept-encoding': 'identity' }, + maxContentLength: MAX_RESPONSE_BYTES, + maxBodyLength: MAX_REQUEST_BYTES, + decompress: false, + // `responseType` defaults to json, and axios would parse the body before + // returning. An explicit empty transform list keeps the bytes raw, so a + // receiver that answers with HTML or gzip cannot fail a delivery that already + // succeeded by status. + transformResponse: [], + validateStatus: (status: number) => status >= 200 && status < 300, +}) + export const deliverToTarget = async ( target: OperatorNotificationTarget, envelope: OperatorNotificationEnvelope, @@ -39,11 +68,7 @@ const deliverHttp = async (target: OperatorNotificationTarget, envelope: Operato headers['x-nostream-signature'] = `sha256=${digest}` } - await axios.post(target.url, body, { - timeout: REQUEST_TIMEOUT_MS, - headers, - validateStatus: (status) => status >= 200 && status < 300, - }) + await axios.post(target.url, body, deliveryRequestOptions(headers)) } const deliverDiscord = async ( @@ -59,10 +84,7 @@ const deliverDiscord = async ( await axios.post( target.url, { content }, - { - timeout: REQUEST_TIMEOUT_MS, - validateStatus: (status) => status >= 200 && status < 300, - }, + deliveryRequestOptions(), ) } @@ -85,10 +107,7 @@ const deliverSlack = async (target: OperatorNotificationTarget, envelope: Operat }, ], }, - { - timeout: REQUEST_TIMEOUT_MS, - validateStatus: (status) => status >= 200 && status < 300, - }, + deliveryRequestOptions(), ) } @@ -110,10 +129,7 @@ const deliverTelegram = async ( text, disable_web_page_preview: true, }, - { - timeout: REQUEST_TIMEOUT_MS, - validateStatus: (status) => status >= 200 && status < 300, - }, + deliveryRequestOptions(), ) } diff --git a/test/unit/services/notification-channels.spec.ts b/test/unit/services/notification-channels.spec.ts index de25af2e0..14e1583f7 100644 --- a/test/unit/services/notification-channels.spec.ts +++ b/test/unit/services/notification-channels.spec.ts @@ -1,13 +1,16 @@ import chai from 'chai' +import http from 'http' +import { AddressInfo } from 'net' import Sinon from 'sinon' import sinonChai from 'sinon-chai' +import zlib from 'zlib' // eslint-disable-next-line @typescript-eslint/no-var-requires const axios = require('axios') // eslint-disable-next-line @typescript-eslint/no-var-requires const { OperatorNotificationEventType } = require('../../../src/@types/operator-notifications') // eslint-disable-next-line @typescript-eslint/no-var-requires -const { deliverToTarget, validateTargetConfig } = require('../../../src/services/notification-channels') +const { MAX_RESPONSE_BYTES, deliverToTarget, validateTargetConfig } = require('../../../src/services/notification-channels') chai.use(sinonChai) @@ -99,3 +102,95 @@ describe('notification-channels', () => { expect(validateTargetConfig({ id: 'x', type: 'telegram', enabled: true, botToken: 't' })).to.match(/chatId/) }) }) + +describe('notification-channels response handling', () => { + let server: http.Server + let url: string + let requests: http.IncomingMessage[] + let respond: (request: http.IncomingMessage, response: http.ServerResponse) => void + + const target = () => ({ id: 'http-1', type: 'http', enabled: true, url }) + + beforeEach(async () => { + requests = [] + respond = (_request, response) => { + response.writeHead(200, { 'content-type': 'application/json' }) + response.end('{"ok":true}') + } + + server = http.createServer((request, response) => { + requests.push(request) + response.on('error', () => { + // the delivery aborts the request when a body runs past the cap + }) + respond(request, response) + }) + server.on('clientError', () => { + // a destroyed socket is the expected ending for the oversized cases + }) + + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/hook` + }) + + afterEach(async () => { + server.closeAllConnections() + await new Promise((resolve) => server.close(() => resolve())) + }) + + it('reports a normal 2xx response as sent and asks the receiver for no compressed response', async () => { + await deliverToTarget(target() as any, envelope) + + expect(requests).to.have.lengthOf(1) + expect(requests[0].headers['accept-encoding']).to.equal('identity') + }) + + it('aborts a response that runs past the cap instead of buffering it', async () => { + respond = (_request, response) => { + response.writeHead(200, { 'content-type': 'application/json' }) + const chunk = Buffer.alloc(8 * 1024, 0x61) + let written = 0 + const write = () => { + while (written < 4 * MAX_RESPONSE_BYTES) { + if (!response.write(chunk)) { + response.once('drain', write) + return + } + written += chunk.length + } + response.end() + } + write() + } + + let error: Error | undefined + try { + await deliverToTarget(target() as any, envelope) + } catch (caught) { + error = caught as Error + } + + expect(error?.message).to.match(new RegExp(`maxContentLength size of ${MAX_RESPONSE_BYTES} exceeded`)) + }) + + it('does not decompress a response, so a small compressed body cannot inflate into the cap', async () => { + const decoded = Buffer.alloc(4 * MAX_RESPONSE_BYTES, 0x62) + const encoded = zlib.gzipSync(decoded) + expect(encoded.length).to.be.below(MAX_RESPONSE_BYTES) + + respond = (_request, response) => { + response.writeHead(200, { 'content-encoding': 'gzip', 'content-type': 'application/json' }) + response.end(encoded) + } + + const unzip = Sinon.spy(zlib, 'createUnzip') + try { + await deliverToTarget(target() as any, envelope) + } finally { + unzip.restore() + } + + expect(requests).to.have.lengthOf(1) + expect(unzip).to.not.have.been.called + }) +}) From 49169cb68a747c410039680e898d1b1448fed7d4 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 28 Nov 2026 17:13:30 -0500 Subject: [PATCH 2/7] fix(notifications): leave the request body unbounded A settings.changed envelope carries the changed values, so editing a blacklist alone produces a body past 64 KiB, and the maxBodyLength guard added in the previous commit would have failed those deliveries with nothing sent. Only the response side is capped; a loopback test now sends a 130 KiB envelope and asserts the receiver gets every byte. --- .changeset/notification-response-size-cap.md | 2 +- src/services/notification-channels.ts | 8 +++---- .../services/notification-channels.spec.ts | 22 +++++++++++++++++++ 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/.changeset/notification-response-size-cap.md b/.changeset/notification-response-size-cap.md index 0c53ffd84..af9abc8ad 100644 --- a/.changeset/notification-response-size-cap.md +++ b/.changeset/notification-response-size-cap.md @@ -6,6 +6,6 @@ fix(notifications): cap the response a notification delivery will read A delivery is a POST whose only interesting part is the status code, but axios advertised every encoding it can decode, decompressed whatever a receiver sent back, and buffered the whole result while nothing read it. A receiver answering with a small gzip body that decodes to hundreds of megabytes therefore spent the delivery worker's heap for a value nobody consumed (security issue #1257). -Delivery requests now carry `accept-encoding: identity`, `decompress: false`, an empty transform list so the body is never parsed, and a 64 KiB `maxContentLength` that aborts a response as soon as it runs past it. The request-body cap is set to the same figure as a guard; today's payloads are a few kilobytes. +Delivery requests now carry `accept-encoding: identity`, `decompress: false`, an empty transform list so the body is never parsed, and a 64 KiB `maxContentLength` that aborts a response as soon as it runs past it. The request side stays unbounded on purpose: a `settings.changed` envelope carries the changed values, so a blacklist edit alone can produce a body past any small cap, and capping it would drop deliveries that work today. The empty transform list also closes a second bug: a receiver that compressed unsolicited used to fail the delivery at `JSON.parse` even though it had answered 2xx. diff --git a/src/services/notification-channels.ts b/src/services/notification-channels.ts index 19f9a1cf0..cac43aa63 100644 --- a/src/services/notification-channels.ts +++ b/src/services/notification-channels.ts @@ -19,16 +19,14 @@ const REQUEST_TIMEOUT_MS = 15_000 // `accept-encoding: identity` stops axios from inviting one in the first place. export const MAX_RESPONSE_BYTES = 64 * 1024 -// Request bodies are built here and bounded at a few kilobytes; this is a guard -// against a future caller passing something larger, not a limit today's payloads -// approach. -export const MAX_REQUEST_BYTES = 64 * 1024 +// The request side is deliberately left unbounded: a `settings.changed` envelope +// carries the changed values, so editing a blacklist alone can produce a body far +// past any small cap, and capping it would drop deliveries that work today. const deliveryRequestOptions = (headers: Record = {}) => ({ timeout: REQUEST_TIMEOUT_MS, headers: { ...headers, 'accept-encoding': 'identity' }, maxContentLength: MAX_RESPONSE_BYTES, - maxBodyLength: MAX_REQUEST_BYTES, decompress: false, // `responseType` defaults to json, and axios would parse the body before // returning. An explicit empty transform list keeps the bytes raw, so a diff --git a/test/unit/services/notification-channels.spec.ts b/test/unit/services/notification-channels.spec.ts index 14e1583f7..b55aac74c 100644 --- a/test/unit/services/notification-channels.spec.ts +++ b/test/unit/services/notification-channels.spec.ts @@ -145,6 +145,28 @@ describe('notification-channels response handling', () => { expect(requests[0].headers['accept-encoding']).to.equal('identity') }) + it('sends a request body larger than the response cap in full', async () => { + // A settings change carries the changed values, so a blacklist edit alone can + // produce a body well past 64 KiB. Capping the request would drop those + // deliveries silently, which is why only the response side is bounded. + const body = { ...envelope, data: { blacklist: Array.from({ length: 2_000 }, () => 'a'.repeat(64)) } } + let received = 0 + respond = (request, response) => { + request.on('data', (chunk: Buffer) => { + received += chunk.length + }) + request.on('end', () => { + response.writeHead(200, { 'content-type': 'application/json' }) + response.end('{"ok":true}') + }) + } + + await deliverToTarget(target() as any, body) + + expect(JSON.stringify(body).length).to.be.above(MAX_RESPONSE_BYTES) + expect(received).to.equal(JSON.stringify(body).length) + }) + it('aborts a response that runs past the cap instead of buffering it', async () => { respond = (_request, response) => { response.writeHead(200, { 'content-type': 'application/json' }) From dd4fc4933371026151fcc3693fce5f3770e2c84b Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 28 Nov 2026 17:19:15 -0500 Subject: [PATCH 3/7] fix(notifications): drain the response instead of capping it A 2xx with a body past the cap rejected the delivery promise, so the dispatcher recorded a notification the receiver had accepted as FAILED and the outbox retried it. The response is now taken as a stream and drained for at most 8 KiB before the socket is dropped, which keeps the heap flat without ever letting a response decide whether a delivery succeeded. --- .changeset/notification-response-size-cap.md | 8 +- src/services/notification-channels.ts | 115 +++++++++++------- .../services/notification-channels.spec.ts | 55 ++++++--- 3 files changed, 110 insertions(+), 68 deletions(-) diff --git a/.changeset/notification-response-size-cap.md b/.changeset/notification-response-size-cap.md index af9abc8ad..f67d26fab 100644 --- a/.changeset/notification-response-size-cap.md +++ b/.changeset/notification-response-size-cap.md @@ -2,10 +2,8 @@ 'nostream': patch --- -fix(notifications): cap the response a notification delivery will read +fix(notifications): never buffer the response a notification delivery gets back -A delivery is a POST whose only interesting part is the status code, but axios advertised every encoding it can decode, decompressed whatever a receiver sent back, and buffered the whole result while nothing read it. A receiver answering with a small gzip body that decodes to hundreds of megabytes therefore spent the delivery worker's heap for a value nobody consumed (security issue #1257). +A delivery is a POST whose only interesting part is the status code, but axios advertised every encoding it can decode, decompressed whatever a receiver sent back and buffered the whole result while nothing read it. A receiver answering with a small gzip body that decodes to hundreds of megabytes therefore spent the delivery worker's heap for a value nobody consumed (security issue #1257). -Delivery requests now carry `accept-encoding: identity`, `decompress: false`, an empty transform list so the body is never parsed, and a 64 KiB `maxContentLength` that aborts a response as soon as it runs past it. The request side stays unbounded on purpose: a `settings.changed` envelope carries the changed values, so a blacklist edit alone can produce a body past any small cap, and capping it would drop deliveries that work today. - -The empty transform list also closes a second bug: a receiver that compressed unsolicited used to fail the delivery at `JSON.parse` even though it had answered 2xx. +Deliveries now ask for `accept-encoding: identity`, take the response as a stream so no body is buffered or parsed at all, and drain at most 8 KiB of it before dropping the socket. Success is the status and only the status: no response size can turn a notification the receiver accepted into a `FAILED` row the outbox then retries. The request side stays unbounded on purpose, because a `settings.changed` envelope carries the changed values and a blacklist edit alone can produce a body past any small cap. diff --git a/src/services/notification-channels.ts b/src/services/notification-channels.ts index cac43aa63..7c42a4423 100644 --- a/src/services/notification-channels.ts +++ b/src/services/notification-channels.ts @@ -9,15 +9,17 @@ import { const REQUEST_TIMEOUT_MS = 15_000 -// A delivery is a POST whose only interesting part is the status code: nothing -// reads the response body. Axios would otherwise advertise every encoding it can -// decode, gunzip whatever a receiver sends back, and buffer the result, so a small -// compressed body that decodes to hundreds of megabytes would be charged to this -// worker's heap for a value nobody consumes. Three settings close that: the adapter -// aborts once the bytes received reach `maxContentLength`, `decompress: false` -// stops a receiver's `content-encoding` from being acted on, and an explicit -// `accept-encoding: identity` stops axios from inviting one in the first place. -export const MAX_RESPONSE_BYTES = 64 * 1024 +// A delivery is a POST whose only interesting part is the status code. Axios would +// otherwise advertise every encoding it can decode, gunzip whatever a receiver sends +// back and buffer the whole result, so a small compressed body that decodes to +// hundreds of megabytes would be charged to this worker's heap for a value nobody +// consumes. The response is therefore taken as a stream and discarded here, and +// `accept-encoding: identity` stops a receiver from compressing it in the first place. +// +// Discarding is bounded rather than deferred: a receiver only owes us a status, and +// making the delivery fail because its body is large would record a notification it +// accepted as failed, which the outbox then retries — a duplicate. +const RESPONSE_DRAIN_LIMIT_BYTES = 8 * 1024 // The request side is deliberately left unbounded: a `settings.changed` envelope // carries the changed values, so editing a blacklist alone can produce a body far @@ -26,16 +28,51 @@ export const MAX_RESPONSE_BYTES = 64 * 1024 const deliveryRequestOptions = (headers: Record = {}) => ({ timeout: REQUEST_TIMEOUT_MS, headers: { ...headers, 'accept-encoding': 'identity' }, - maxContentLength: MAX_RESPONSE_BYTES, + // Success is the status and only the status. `stream` settles as soon as the + // headers arrive, so no body is ever buffered or parsed — which also means a + // receiver answering with HTML, gzip or a large echo cannot fail a delivery it + // already accepted. + responseType: 'stream' as const, decompress: false, - // `responseType` defaults to json, and axios would parse the body before - // returning. An explicit empty transform list keeps the bytes raw, so a - // receiver that answers with HTML or gzip cannot fail a delivery that already - // succeeded by status. - transformResponse: [], validateStatus: (status: number) => status >= 200 && status < 300, }) +const discardResponseBody = async (data: unknown): Promise => { + const body = data as + | (NodeJS.ReadableStream & { destroy?: () => void; removeAllListeners?: () => void }) + | undefined + + if (!body || typeof body.on !== 'function') { + return + } + + await new Promise((resolve) => { + let drained = 0 + const finish = () => { + body.removeAllListeners?.() + body.on?.('error', () => { + // the socket is being dropped on purpose + }) + body.destroy?.() + resolve() + } + + body.on('data', (chunk: { length: number }) => { + drained += chunk.length + if (drained >= RESPONSE_DRAIN_LIMIT_BYTES) { + finish() + } + }) + body.on('end', finish) + body.on('error', finish) + }) +} + +const postDelivery = async (url: string, body: unknown, headers?: Record): Promise => { + const response = await axios.post(url, body, deliveryRequestOptions(headers)) + await discardResponseBody(response?.data) +} + export const deliverToTarget = async ( target: OperatorNotificationTarget, envelope: OperatorNotificationEnvelope, @@ -66,7 +103,7 @@ const deliverHttp = async (target: OperatorNotificationTarget, envelope: Operato headers['x-nostream-signature'] = `sha256=${digest}` } - await axios.post(target.url, body, deliveryRequestOptions(headers)) + await postDelivery(target.url, body, headers) } const deliverDiscord = async ( @@ -79,11 +116,7 @@ const deliverDiscord = async ( const content = `[${envelope.event}] ${envelope.relay}\n\`\`\`json\n${JSON.stringify(envelope.data, null, 2).slice(0, 1800)}\n\`\`\`` - await axios.post( - target.url, - { content }, - deliveryRequestOptions(), - ) + await postDelivery(target.url, { content }) } const deliverSlack = async (target: OperatorNotificationTarget, envelope: OperatorNotificationEnvelope): Promise => { @@ -91,22 +124,18 @@ const deliverSlack = async (target: OperatorNotificationTarget, envelope: Operat throw new Error('Slack notification target requires webhook url') } - await axios.post( - target.url, - { - text: `[${envelope.event}] ${envelope.relay}`, - blocks: [ - { - type: 'section', - text: { - type: 'mrkdwn', - text: `*${envelope.event}* on \`${envelope.relay}\`\n\`\`\`${JSON.stringify(envelope.data).slice(0, 2800)}\`\`\``, - }, + await postDelivery(target.url, { + text: `[${envelope.event}] ${envelope.relay}`, + blocks: [ + { + type: 'section', + text: { + type: 'mrkdwn', + text: `*${envelope.event}* on \`${envelope.relay}\`\n\`\`\`${JSON.stringify(envelope.data).slice(0, 2800)}\`\`\``, }, - ], - }, - deliveryRequestOptions(), - ) + }, + ], + }) } const deliverTelegram = async ( @@ -120,15 +149,11 @@ const deliverTelegram = async ( const text = `[${envelope.event}] ${envelope.relay}\n${JSON.stringify(envelope.data).slice(0, 3500)}` const url = `https://api.telegram.org/bot${target.botToken}/sendMessage` - await axios.post( - url, - { - chat_id: target.chatId, - text, - disable_web_page_preview: true, - }, - deliveryRequestOptions(), - ) + await postDelivery(url, { + chat_id: target.chatId, + text, + disable_web_page_preview: true, + }) } export const validateTargetConfig = (target: OperatorNotificationTarget): string | undefined => { diff --git a/test/unit/services/notification-channels.spec.ts b/test/unit/services/notification-channels.spec.ts index b55aac74c..316692bef 100644 --- a/test/unit/services/notification-channels.spec.ts +++ b/test/unit/services/notification-channels.spec.ts @@ -10,7 +10,7 @@ const axios = require('axios') // eslint-disable-next-line @typescript-eslint/no-var-requires const { OperatorNotificationEventType } = require('../../../src/@types/operator-notifications') // eslint-disable-next-line @typescript-eslint/no-var-requires -const { MAX_RESPONSE_BYTES, deliverToTarget, validateTargetConfig } = require('../../../src/services/notification-channels') +const { deliverToTarget, validateTargetConfig } = require('../../../src/services/notification-channels') chai.use(sinonChai) @@ -104,6 +104,11 @@ describe('notification-channels', () => { }) describe('notification-channels response handling', () => { + // What a receiver answers is kept well away from what a delivery means: the body + // is never buffered, so these bodies are sized against what an early copy of this + // change would have capped rather than against anything the code now reads. + const LARGE_BODY_BYTES = 256 * 1024 + let server: http.Server let url: string let requests: http.IncomingMessage[] @@ -121,12 +126,12 @@ describe('notification-channels response handling', () => { server = http.createServer((request, response) => { requests.push(request) response.on('error', () => { - // the delivery aborts the request when a body runs past the cap + // an oversized response is dropped from this side once it has been drained }) respond(request, response) }) server.on('clientError', () => { - // a destroyed socket is the expected ending for the oversized cases + // dropping the socket is how a drained response ends }) await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) @@ -145,10 +150,10 @@ describe('notification-channels response handling', () => { expect(requests[0].headers['accept-encoding']).to.equal('identity') }) - it('sends a request body larger than the response cap in full', async () => { + it('sends a request body larger than any response it would read in full', async () => { // A settings change carries the changed values, so a blacklist edit alone can - // produce a body well past 64 KiB. Capping the request would drop those - // deliveries silently, which is why only the response side is bounded. + // produce a body well past this size. Capping the request would drop those + // deliveries, which is why the request side stays unbounded. const body = { ...envelope, data: { blacklist: Array.from({ length: 2_000 }, () => 'a'.repeat(64)) } } let received = 0 respond = (request, response) => { @@ -163,17 +168,17 @@ describe('notification-channels response handling', () => { await deliverToTarget(target() as any, body) - expect(JSON.stringify(body).length).to.be.above(MAX_RESPONSE_BYTES) + expect(JSON.stringify(body).length).to.be.above(64 * 1024) expect(received).to.equal(JSON.stringify(body).length) }) - it('aborts a response that runs past the cap instead of buffering it', async () => { + it('reports a 2xx as sent when the response body is larger than it will read', async () => { respond = (_request, response) => { response.writeHead(200, { 'content-type': 'application/json' }) const chunk = Buffer.alloc(8 * 1024, 0x61) let written = 0 const write = () => { - while (written < 4 * MAX_RESPONSE_BYTES) { + while (written < LARGE_BODY_BYTES) { if (!response.write(chunk)) { response.once('drain', write) return @@ -185,20 +190,34 @@ describe('notification-channels response handling', () => { write() } - let error: Error | undefined - try { - await deliverToTarget(target() as any, envelope) - } catch (caught) { - error = caught as Error + await deliverToTarget(target() as any, envelope) + + expect(requests).to.have.lengthOf(1) + }) + + it('stops reading the body once it has drained enough, rather than waiting for the end', async () => { + let serverFinished = false + respond = (_request, response) => { + response.writeHead(200, { 'content-type': 'application/json' }) + response.write(Buffer.alloc(8 * 1024, 0x61)) + setTimeout(() => { + serverFinished = true + try { + response.end('tail') + } catch { + // the client has already dropped this socket + } + }, 200) } - expect(error?.message).to.match(new RegExp(`maxContentLength size of ${MAX_RESPONSE_BYTES} exceeded`)) + await deliverToTarget(target() as any, envelope) + + expect(serverFinished).to.equal(false) }) - it('does not decompress a response, so a small compressed body cannot inflate into the cap', async () => { - const decoded = Buffer.alloc(4 * MAX_RESPONSE_BYTES, 0x62) + it('does not decompress a compressed response', async () => { + const decoded = Buffer.alloc(4 * 64 * 1024, 0x62) const encoded = zlib.gzipSync(decoded) - expect(encoded.length).to.be.below(MAX_RESPONSE_BYTES) respond = (_request, response) => { response.writeHead(200, { 'content-encoding': 'gzip', 'content-type': 'application/json' }) From b5ab90800f597080b68816c4fbd3dd05a05d8563 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 28 Nov 2026 17:22:30 -0500 Subject: [PATCH 4/7] fix(notifications): close the response of a failed delivery A rejected status settles with its body still attached and unread, so the stream stayed open for every failed attempt and every retry of it. postDelivery now discards that body before rethrowing, and a loopback test answers 500 with a body that is still being written: it fails without this because the socket outlives the rejection. --- src/services/notification-channels.ts | 12 +++++-- .../services/notification-channels.spec.ts | 33 +++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/services/notification-channels.ts b/src/services/notification-channels.ts index 7c42a4423..12e60565e 100644 --- a/src/services/notification-channels.ts +++ b/src/services/notification-channels.ts @@ -69,8 +69,16 @@ const discardResponseBody = async (data: unknown): Promise => { } const postDelivery = async (url: string, body: unknown, headers?: Record): Promise => { - const response = await axios.post(url, body, deliveryRequestOptions(headers)) - await discardResponseBody(response?.data) + try { + const response = await axios.post(url, body, deliveryRequestOptions(headers)) + await discardResponseBody(response?.data) + } catch (error) { + // A rejected status settles with its body still attached and unread, so without + // this the socket stays open for every failed attempt — and every retry of it. + const rejected = (error as { response?: { data?: unknown } } | undefined)?.response + await discardResponseBody(rejected?.data) + throw error + } } export const deliverToTarget = async ( diff --git a/test/unit/services/notification-channels.spec.ts b/test/unit/services/notification-channels.spec.ts index 316692bef..4c386970b 100644 --- a/test/unit/services/notification-channels.spec.ts +++ b/test/unit/services/notification-channels.spec.ts @@ -215,6 +215,39 @@ describe('notification-channels response handling', () => { expect(serverFinished).to.equal(false) }) + it('closes the response stream of a failed delivery instead of leaving its socket open', async () => { + let bodyFinished = false + let closedBeforeTheBodyEnded = false + respond = (_request, response) => { + response.writeHead(500, { 'content-type': 'text/plain' }) + response.on('close', () => { + if (!bodyFinished) { + closedBeforeTheBodyEnded = true + } + }) + response.write(Buffer.alloc(8 * 1024, 0x61)) + setTimeout(() => { + bodyFinished = true + try { + response.end('tail') + } catch { + // the client has already dropped this socket + } + }, 400) + } + + let error: Error | undefined + try { + await deliverToTarget(target() as any, envelope) + } catch (caught) { + error = caught as Error + } + + expect(error).to.be.instanceOf(Error) + await new Promise((resolve) => setTimeout(resolve, 150)) + expect(closedBeforeTheBodyEnded).to.equal(true) + }) + it('does not decompress a compressed response', async () => { const decoded = Buffer.alloc(4 * 64 * 1024, 0x62) const encoded = zlib.gzipSync(decoded) From 59a15bdcdbe7e0d17973cec203849d4d4c24a38c Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 28 Nov 2026 17:23:24 -0500 Subject: [PATCH 5/7] refactor(notifications): remove only the drain's own stream listeners removeAllListeners would have taken Node's and axios's bookkeeping with it when a response is dropped; the drain now detaches exactly the three listeners it added and is idempotent on the paths that can race. --- src/services/notification-channels.ts | 31 ++++++++++++++++++++------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/src/services/notification-channels.ts b/src/services/notification-channels.ts index 12e60565e..e22690504 100644 --- a/src/services/notification-channels.ts +++ b/src/services/notification-channels.ts @@ -39,7 +39,10 @@ const deliveryRequestOptions = (headers: Record = {}) => ({ const discardResponseBody = async (data: unknown): Promise => { const body = data as - | (NodeJS.ReadableStream & { destroy?: () => void; removeAllListeners?: () => void }) + | (NodeJS.ReadableStream & { + destroy?: () => void + off?: (event: string, listener: (...args: never[]) => void) => void + }) | undefined if (!body || typeof body.on !== 'function') { @@ -48,8 +51,25 @@ const discardResponseBody = async (data: unknown): Promise => { await new Promise((resolve) => { let drained = 0 + let finished = false + + const onData = (chunk: { length: number }) => { + drained += chunk.length + if (drained >= RESPONSE_DRAIN_LIMIT_BYTES) { + finish() + } + } + + // Only this function's listeners are removed: the rest of the stream's + // bookkeeping belongs to Node and axios. const finish = () => { - body.removeAllListeners?.() + if (finished) { + return + } + finished = true + body.off?.('data', onData as (...args: never[]) => void) + body.off?.('end', finish) + body.off?.('error', finish) body.on?.('error', () => { // the socket is being dropped on purpose }) @@ -57,12 +77,7 @@ const discardResponseBody = async (data: unknown): Promise => { resolve() } - body.on('data', (chunk: { length: number }) => { - drained += chunk.length - if (drained >= RESPONSE_DRAIN_LIMIT_BYTES) { - finish() - } - }) + body.on('data', onData) body.on('end', finish) body.on('error', finish) }) From 65856179b47c2057e615ab96cbb7aae559645a03 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 28 Nov 2026 17:26:45 -0500 Subject: [PATCH 6/7] fix(notifications): bound the drain so a stalled receiver cannot hang it A streamed response settles at its headers, which spends axios's request timeout before the drain begins, so a receiver that answers and then stalls would hold the delivery promise open for good. The drain now carries its own two-second deadline; the test answers 200 with a partial body and fails against the previous commit. --- src/services/notification-channels.ts | 8 ++++++++ test/unit/services/notification-channels.spec.ts | 16 ++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/services/notification-channels.ts b/src/services/notification-channels.ts index e22690504..2201c613e 100644 --- a/src/services/notification-channels.ts +++ b/src/services/notification-channels.ts @@ -21,6 +21,11 @@ const REQUEST_TIMEOUT_MS = 15_000 // accepted as failed, which the outbox then retries — a duplicate. const RESPONSE_DRAIN_LIMIT_BYTES = 8 * 1024 +// A streamed response settles at its headers, so axios's own timeout is spent by the +// time the drain starts: a receiver that answers and then stalls would hold this +// promise open forever. The drain gets a deadline of its own. +const RESPONSE_DRAIN_TIMEOUT_MS = 2_000 + // The request side is deliberately left unbounded: a `settings.changed` envelope // carries the changed values, so editing a blacklist alone can produce a body far // past any small cap, and capping it would drop deliveries that work today. @@ -52,6 +57,7 @@ const discardResponseBody = async (data: unknown): Promise => { await new Promise((resolve) => { let drained = 0 let finished = false + let deadline: NodeJS.Timeout | undefined const onData = (chunk: { length: number }) => { drained += chunk.length @@ -67,6 +73,7 @@ const discardResponseBody = async (data: unknown): Promise => { return } finished = true + clearTimeout(deadline) body.off?.('data', onData as (...args: never[]) => void) body.off?.('end', finish) body.off?.('error', finish) @@ -77,6 +84,7 @@ const discardResponseBody = async (data: unknown): Promise => { resolve() } + deadline = setTimeout(finish, RESPONSE_DRAIN_TIMEOUT_MS) body.on('data', onData) body.on('end', finish) body.on('error', finish) diff --git a/test/unit/services/notification-channels.spec.ts b/test/unit/services/notification-channels.spec.ts index 4c386970b..11644fb81 100644 --- a/test/unit/services/notification-channels.spec.ts +++ b/test/unit/services/notification-channels.spec.ts @@ -215,6 +215,22 @@ describe('notification-channels response handling', () => { expect(serverFinished).to.equal(false) }) + it('does not wait forever on a receiver that answers and then stalls', async () => { + // A streamed response settles at its headers, so the request timeout is already + // spent when the drain starts: the drain carries its own deadline. + respond = (_request, response) => { + response.writeHead(200, { 'content-type': 'application/json' }) + response.write('{"ok"') + } + + const startedAt = Date.now() + await deliverToTarget(target() as any, envelope) + const elapsed = Date.now() - startedAt + + expect(elapsed).to.be.below(5_000) + expect(requests).to.have.lengthOf(1) + }) + it('closes the response stream of a failed delivery instead of leaving its socket open', async () => { let bodyFinished = false let closedBeforeTheBodyEnded = false From 7ba2435a251724e145d96d86cfc7f0ecabe6458c Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 28 Nov 2026 17:29:30 -0500 Subject: [PATCH 7/7] test(notifications): give the stalled-response case room in mocha It waits out the drain's two-second deadline, which is mocha's default, so the unit job would have timed out before the assertion ran. --- test/unit/services/notification-channels.spec.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/test/unit/services/notification-channels.spec.ts b/test/unit/services/notification-channels.spec.ts index 11644fb81..a81315627 100644 --- a/test/unit/services/notification-channels.spec.ts +++ b/test/unit/services/notification-channels.spec.ts @@ -215,7 +215,10 @@ describe('notification-channels response handling', () => { expect(serverFinished).to.equal(false) }) - it('does not wait forever on a receiver that answers and then stalls', async () => { + // The drain deadline is two seconds, so this test is slower than mocha's default. + it('does not wait forever on a receiver that answers and then stalls', async function () { + this.timeout(6_000) + // A streamed response settles at its headers, so the request timeout is already // spent when the drain starts: the drain carries its own deadline. respond = (_request, response) => { @@ -227,7 +230,7 @@ describe('notification-channels response handling', () => { await deliverToTarget(target() as any, envelope) const elapsed = Date.now() - startedAt - expect(elapsed).to.be.below(5_000) + expect(elapsed).to.be.below(4_000) expect(requests).to.have.lengthOf(1) })