Commit 08eff138e3f for nodejs

commit 08eff138e3f3a138a963a2998b68f832474cc8d0
Author: Matteo Collina <hello@matteocollina.com>
Date:   Sat Nov 21 17:33:22 2026 +0100

    stream: stop reusing a detached onread buffer

    CustomBufferJSListener keeps only the raw address (uv_buf_t) of the
    user-supplied onread buffer, without retaining the backing store. If
    application code transfers (and thereby detaches) that buffer during the
    onread callback, for example by enqueuing a view into a byte
    ReadableStream, the backing store is moved away from under the listener
    and the raw address is left dangling. Reading subsequent peer data into
    that address then corrupts memory the application owns, and if the
    backing store is later released, it becomes a use-after-free.

    Retain the backing store in CustomBufferJSListener so the raw address
    never dangles, and stop reading when the onread callback detaches the
    buffer so the stale address is not handed back to libuv.

    Signed-off-by: Matteo Collina <hello@matteocollina.com>
    PR-URL: https://github.com/nodejs/node/pull/67542
    Reviewed-By: James M Snell <jasnell@gmail.com>
    Reviewed-By: Paolo Insogna <paolo@cowtech.it>

diff --git a/lib/internal/stream_base_commons.js b/lib/internal/stream_base_commons.js
index 7bf3a2bab63..1c5d935ff6a 100644
--- a/lib/internal/stream_base_commons.js
+++ b/lib/internal/stream_base_commons.js
@@ -2,6 +2,7 @@

 const {
   Array,
+  ArrayBufferPrototypeGetDetached,
   Symbol,
 } = primordials;

@@ -188,6 +189,15 @@ function onStreamRead(arrayBuffer) {
         if (isUint8Array(nextBuf))
           stream[kBuffer] = ret = nextBuf;
       }
+      // If the buffer that will be reused for the next read was detached during
+      // the callback (e.g. by transferring a view into a byte `ReadableStream`),
+      // it can no longer be safely written to. Stop reading instead of handing
+      // the stale address back to the native read path.
+      const reusableBuf = stream[kBuffer];
+      if (isUint8Array(reusableBuf) &&
+          ArrayBufferPrototypeGetDetached(reusableBuf.buffer)) {
+        result = false;
+      }
     } else {
       const offset = streamBaseState[kArrayBufferOffset];
       const buf = new FastBuffer(arrayBuffer, offset, nread);
diff --git a/src/stream_base.cc b/src/stream_base.cc
index 8592ca269a0..629d4613bf0 100644
--- a/src/stream_base.cc
+++ b/src/stream_base.cc
@@ -164,7 +164,9 @@ int StreamBase::UseUserBuffer(const FunctionCallbackInfo<Value>& args) {
   CHECK(Buffer::HasInstance(args[0]));

   uv_buf_t buf = uv_buf_init(Buffer::Data(args[0]), Buffer::Length(args[0]));
-  PushStreamListener(new CustomBufferJSListener(buf));
+  Local<ArrayBuffer> array_buffer = args[0].As<v8::ArrayBufferView>()->Buffer();
+  PushStreamListener(
+      new CustomBufferJSListener(array_buffer->GetBackingStore(), buf));
   return 0;
 }

@@ -825,8 +827,11 @@ void CustomBufferJSListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
                              StreamBase::SKIP_NREAD_CHECKS);
   Local<Value> next_buf_v;
   if (ret.ToLocal(&next_buf_v) && !next_buf_v->IsUndefined()) {
+    Local<ArrayBuffer> array_buffer =
+        next_buf_v.As<v8::ArrayBufferView>()->Buffer();
     buffer_.base = Buffer::Data(next_buf_v);
     buffer_.len = Buffer::Length(next_buf_v);
+    backing_store_ = array_buffer->GetBackingStore();
   }
 }

diff --git a/src/stream_base.h b/src/stream_base.h
index 450205a1b86..146047439b5 100644
--- a/src/stream_base.h
+++ b/src/stream_base.h
@@ -211,9 +211,17 @@ class CustomBufferJSListener : public ReportWritesToJSStreamListener {
   void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override;
   void OnStreamDestroy() override { delete this; }

-  explicit CustomBufferJSListener(uv_buf_t buffer) : buffer_(buffer) {}
+  explicit CustomBufferJSListener(
+      std::shared_ptr<v8::BackingStore> backing_store, uv_buf_t buffer)
+      : backing_store_(std::move(backing_store)), buffer_(buffer) {}

  private:
+  // Retain the backing store for the lifetime of the listener. The raw address
+  // in `buffer_` is derived from it, so retaining the backing store guarantees
+  // the address does not dangle even if application code later transfers (and
+  // thereby detaches) the buffer, e.g. by enqueuing a view into a byte
+  // `ReadableStream`.
+  std::shared_ptr<v8::BackingStore> backing_store_;
   uv_buf_t buffer_;
 };

diff --git a/test/parallel/test-net-onread-buffer-detached.js b/test/parallel/test-net-onread-buffer-detached.js
new file mode 100644
index 00000000000..41bebe5e1f9
--- /dev/null
+++ b/test/parallel/test-net-onread-buffer-detached.js
@@ -0,0 +1,77 @@
+'use strict';
+
+const common = require('../common');
+const net = require('net');
+const assert = require('assert');
+
+// Regression test.
+//
+// When an `onread` callback transfers a view of the reusable buffer into a byte
+// `ReadableStream`, the transfer detaches the buffer's backing store. The socket
+// must not keep writing subsequent peer data into the detached backing store,
+// otherwise it corrupts the chunk the application has retained.
+
+let controller;
+const stream = new ReadableStream({
+  type: 'bytes',
+  start(c) {
+    controller = c;
+  },
+});
+const reader = stream.getReader();
+
+const server = net.createServer(common.mustCall((socket) => {
+  socket.setNoDelay(true);
+  socket.write('first');
+  // Send more data shortly after the client transfers the first chunk.
+  const timer = setTimeout(() => {
+    socket.write('Z'.repeat(1024));
+  }, 50);
+  socket.on('close', () => clearTimeout(timer));
+  socket.on('error', common.mustNotCall());
+}));
+
+server.listen(0, common.mustCall(() => {
+  const port = server.address().port;
+
+  let transferred = false;
+
+  const client = net.createConnection({
+    host: '127.0.0.1',
+    port,
+    onread: {
+      buffer: Buffer.alloc(4096),
+      callback(nread, buf) {
+        // Enqueueing a view transfers (and thereby detaches) the underlying
+        // ArrayBuffer. An affected binary then keeps writing later peer data
+        // over this chunk's memory.
+        if (transferred) return;
+        transferred = true;
+        const view = new Uint8Array(buf.buffer, buf.byteOffset, nread);
+        controller.enqueue(view);
+      },
+    },
+  });
+
+  client.on('error', common.mustNotCall());
+
+  (async () => {
+    const { value: chunk, done } = await reader.read();
+    assert.strictEqual(done, false);
+
+    // The first peer write ("first", 5 bytes) is delivered intact.
+    assert.strictEqual(chunk[0], 0x66); // 'f'
+    assert.strictEqual(Buffer.from(chunk).toString(), 'first');
+
+    // Give the second peer write time to reach the client. Reading has stopped,
+    // so the retained chunk must not be overwritten.
+    await new Promise((resolve) => setTimeout(resolve, 200));
+
+    assert.strictEqual(chunk[0], 0x66,
+                       `retained chunk was corrupted: 0x${chunk[0].toString(16)}`);
+    assert.strictEqual(Buffer.from(chunk).toString(), 'first');
+
+    client.end();
+    server.close();
+  })().then(common.mustCall());
+}));