| 183 | const MAX_BODY_BYTES = 256 * 1024; |
| 184 | |
| 185 | function readBody(req, max = MAX_BODY_BYTES) { |
| 186 | return new Promise((resolve) => { |
| 187 | let data = ""; |
| 188 | let size = 0; |
| 189 | let done = false; |
| 190 | req.on("data", (c) => { |
| 191 | if (done) return; |
| 192 | size += c.length; |
| 193 | if (size > max) { |
| 194 | done = true; |
| 195 | resolve({ body: "", tooLarge: true }); |
| 196 | if (typeof req.destroy === "function") req.destroy(); |
| 197 | return; |
| 198 | } |
| 199 | data += c; |
| 200 | }); |
| 201 | req.on("end", () => { |
| 202 | if (!done) { |
| 203 | done = true; |
| 204 | resolve({ body: data, tooLarge: false }); |
| 205 | } |
| 206 | }); |
| 207 | req.on("error", () => { |
| 208 | if (!done) { |
| 209 | done = true; |
| 210 | resolve({ body: "", tooLarge: false }); |
| 211 | } |
| 212 | }); |
| 213 | }); |
| 214 | } |
| 215 | |
| 216 | /** |
| 217 | * Build the request handler for an instance. Exposed for tests so routes can be |