Repository navigation
Fix res.send binary bodies, res.redirect, res.set, res.cookie and res.jsonp - #64
Merged
Merged
Conversation
….jsonp src/response.ts, five fixes from the "Bug fixes on the compatible line" roadmap rows: - res.send sends the bytes of an ArrayBuffer, SharedArrayBuffer, DataView or any typed array (expressjs#7362, expressjs#7510, expressjs#7538). A view that isn't a Buffer is wrapped in a Buffer over its own byteOffset/byteLength window before the length, ETag and write, so the body, Content-Length and ETag agree with or without ETags. Ported from PR expressjs#7574 by Jasper (jipeng6036-del), based on PR expressjs#7542 by Prince Jain. ArrayBuffer and SharedArrayBuffer support from PR expressjs#7363 by Siddharth Mehta, detected with util.types.isAnyArrayBuffer instead of Symbol.toStringTag (which any object can fake). Not in upstream: a detached buffer sends an empty body, as 5.3.0 did for views, where Buffer.from would throw. - res.redirect leaves out Content-Length when Transfer-Encoding is set, as res.send does (expressjs#7506). Ported from PR expressjs#7508 by 0d00ciallo0721. - res.set('Content-Type', unknown) keeps the value as given instead of writing "false" (expressjs#7034). Ported from PR expressjs#7035 by Varun Chawla. Not in upstream: res.send with a string body keeps a Content-Type with no "/" as it is, since it has no charset to add. With the upstream change alone, res.set('Content-Type', 'custom').send('x') (and .json()) would throw "Invalid type" and answer 500, where 5.3.0 answered 200. - res.cookie with expires: 0 and a maxAge sends Max-Age without Expires (expressjs#5150). Ported from PR expressjs#5151 by Mart (nbkhope). - res.jsonp sanitises the callback before deciding on JSONP, so a callback with no allowed characters gets plain JSON instead of broken JavaScript. Ported from PR expressjs#7161 by Andrew Stellman. Tests: - The 7 matching bug() tests in test/regressions/response.js are normal tests now. - test/fork-response-bodies.js: every typed-array kind, whole and as a window, with ETags on and off; DataView windows; ArrayBuffer, SharedArrayBuffer and a cross-realm ArrayBuffer; cross-realm views; detached buffers; empty views; HEAD; 304; the 1,000-element path; a preset Content-Type; res.set's unknown type through end, the object form, an empty value, send and json, plus a known shorthand and an invalid type with "/" (still a 500); res.cookie with maxAge 0, the options object, and expires undefined, null or a Date; res.redirect on GET and HEAD; res.jsonp with several callbacks. - Differential: 6 new scenarios, and 12 hand-written ones in `allowed`. The generated scenarios get an `allowed` list too, by call (res.send Float64Array, ArrayBuffer and DataView), where at least one scenario of each call must differ. Planted reverts: the view fix fails 59 tests, the ArrayBuffer branch 14, the detached guard 2, redirect 7, res.set 10 (its res.send part 2), res.cookie 5, res.jsonp 7. REGRESSIONS_ALL=1: 22 failing bug tests before, 15 after (exactly these 7 fixed, none new).
Coverage Report for CI Build 44981645728Coverage remained the same at 100.0%Details
Uncovered ChangesNo uncovered changes found. Coverage RegressionsNo coverage regressions found. Coverage Stats
💛 - Coveralls |
This was referenced Nov 22, 2026
# Conflicts: # ROADMAP.md # test/differential/scenarios.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Five
res.*bug fixes from the "Bug fixes on the compatible line" roadmap rows:res.sendcorrupts ArrayBuffer, DataView and typed-array bodies (res.send(ArrayBuffer) silently sends {} as JSON expressjs/express#7362, res.send(DataView) silently drops the view’s bytes expressjs/express#7510, res.send() with a non-Uint8Array typed array loses data, or returns 500 without ETag expressjs/express#7538).res.redirectsends Content-Length with Transfer-Encoding (res.redirect() sets Content-Length when Transfer-Encoding is already set expressjs/express#7506).res.setsendsContent-Type: falsefor unknown types (res.set('Content-Type') silently sets header to literal string 'false' for unknown types expressjs/express#7034).res.cookieadds Expires despiteexpires: 0(res.cookie does not allow setting Max-Age only, without Expires (One should be able to set maxAge alone, with expires: 0) expressjs/express#5150).Upstream fixes are ported with credit; two places go further than upstream (detached buffers, and
res.sendafter an unknownres.settype), explained below.Changes
src/response.tsres.send: a view that isn't aBufferbecomesBuffer.from(view.buffer, view.byteOffset, view.byteLength)before the length, ETag and write. An ArrayBuffer or SharedArrayBuffer (util.types.isAnyArrayBuffer, which also works across realms and can't be faked bySymbol.toStringTag) becomesBuffer.from(ab)and getsapplication/octet-streamunless a type is set. A zero-length view or buffer becomesBuffer.alloc(0), becauseBuffer.fromthrows on a detached buffer. Ported from upstream PR fix(res.send): preserve raw bytes of ArrayBuffer views expressjs/express#7574 by Jasper (based on PR fix(response): send raw bytes of non-Uint8Array typed arrays in res.send() expressjs/express#7542 by Prince Jain) and PR fix(res.send): handle raw ArrayBuffer as binary data expressjs/express#7363 by Siddharth Mehta.res.sendwith a string body: a Content-Type with no/is kept as it is (it isn't a media type, so there's no charset to add). Not in upstream; see Behaviour.res.set:mimeContentType(value) || value. Ported from upstream PR fix: prevent Content-Type header from being set to 'false' expressjs/express#7035 by Varun Chawla.res.cookie: anexpiresof exactly0is kept whenmaxAgeis set. Ported from upstream PR Don't automatically add Expires in res.cookie if expires option is explicitly set to 0 expressjs/express#5151 by Mart (nbkhope).res.redirect: sets Content-Length only without Transfer-Encoding. Ported from upstream PR fix(res.redirect): avoid Content-Length with Transfer-Encoding expressjs/express#7508 by 0d00ciallo0721.res.jsonp: the callback is sanitised before the JSONP check. Ported from upstream PR fix: fall back to JSON when JSONP callback sanitizes to empty expressjs/express#7161 by Andrew Stellman.test/regressions/response.js: the 7 matchingbug()tests are normalit()tests.test/fork-response-bodies.js(new):Int8toBigUint64, andFloat16Arraywhere Node has it), whole and as abyteOffset/byteLengthwindow, with ETags on and off;byteLength(still JSON);res.setwith an unknown type throughend, the object form, an empty value,sendandjson, a known shorthand, and an invalid type with/(still a 500);res.cookiewithmaxAge0, the options object unchanged, andexpiresundefined, null or a Date (unchanged);res.redirecton GET and HEAD, and without Transfer-Encoding;res.jsonpwith several callbacks and a partly kept callback.test/differential/:scenarios.js: 6 new scenarios, and 12 hand-written scenarios inallowed, each with its reason.generated.jsandgenerated.spec.js: the generated scenarios get anallowedlist too, keyed by call (res.send Float64Array,res.send ArrayBuffer,res.send DataView). Some of their scenarios give both sides the same 304 or 412, so each allowed call must differ in at least one scenario rather than in all of them; a test after the scenarios checks that.[x], History.md "Bug fixes" bullets with credit,docs/fork/differences.mdruntime entries.Behaviour
res.send(new Uint8Array([1,2,3]).buffer){}asapplication/json01 02 03,application/octet-streamres.send(new SharedArrayBuffer(n)){}as JSONres.send(new DataView(buf, 1, 3))res.send(new Uint16Array([0x0102]))with ETag0202 01on little-endianetagoff, under 1,000 elementsres.endrejects it)res.send(new BigInt64Array(...))res.send(Buffer),res.send(Uint8Array), a detached viewres.redirect(...)afterTransfer-Encoding: chunkedres.set('Content-Type', 'custom').end()Content-Type: falseContent-Type: customres.set('Content-Type', 'custom').send('x')text/html; charset=utf-8customres.set('Content-Type', 'custom').json(...),.send(Buffer),.sendFile(...)customres.cookie('a', 'b', { maxAge: 60000, expires: 0 })Max-Age=60; Path=/; Expires=...Max-Age=60; Path=/res.jsonp(...)with?callback=!!!text/javascript:/**/ typeof === 'function' && ({...});application/json:{...}Not changed:
res.set('Content-Type', 'foo/bar baz').send('x')still answers 500 ("Invalid type"), as in 5.3.0.expiresvalues other than0(undefined, null, a Date) still get themaxAgedate.Proof
REGRESSIONS_ALL=1) and pass here.REGRESSIONS_ALL=1 npm testfails 5 bug tests, down from 12 on master (50ff1567, after Fix req.host userinfo, X-Forwarded-Proto case and IPv6 subdomains #63, Fix // mounts (security), router cycles and # fragments in routing #65 and Fix app.listen's leftover error listener and empty /proc files #67). Compared by name, exactly these 7 are fixed and nothing new fails:test/res.*.js):res.redirect: 7;res.set: 10, and itsres.sendpart alone: 2;res.cookie: 5;res.jsonp: 7.npx vitest run test/differentialpasses 3,927 tests; every allowed scenario differs from 5.3.0.npm run test-cigives 8,503 passed and 9 skipped (139 files), after merging master, at 100% statements, branches, functions and lines, with all 23 source files in the coverage report.npm run lint,npm run typecheckandnpm run test:typesare clean.Benchmark
n/a: bug fix; benchmark and instruction-count workflows are paused.
Risks / follow-ups
res.set('Content-Type', 'custom'),res.send,res.json,res.jsonpandres.sendFilekeepcustomwhere 5.3.0 silently used their default type (it had storedfalse). That is what "keep the value as given" means, and nothing throws, but an app that relied on the default type would see a different header. The upstream PR alone would have made those calls answer 500./set by hand (res.setHeader('Content-Type', 'html')) followed byres.send('x')used to answer 500 and now sends it as given. An invalid type with a/still answers 500; I left that alone because no roadmap row covers it.Bufferbodies always were. Changing the array right afterres.send, before the socket writes it, can change what goes out; 5.3.0 already did this for smallUint8Arraybodies without ETags.typings/still typesCookieOptions.expiresas aDate, as@types/expressdoes, so TypeScript users need a cast to pass0. Left unchanged because no signature changed.Stack
masterThey share lines in ROADMAP.md, History.md,
docs/fork/differences.mdand the differentialallowedlists, so they are stacked. Merge in that order.