]> zoso.dev Git - nano-pow.git/commitdiff
Shorten HTTP 400 response lines. Reject post requests with no data.
authorChris Duncan <chris@zoso.dev>
Tue, 22 Apr 2025 03:22:37 +0000 (20:22 -0700)
committerChris Duncan <chris@zoso.dev>
Tue, 22 Apr 2025 03:22:37 +0000 (20:22 -0700)
src/bin/server.ts

index 58b97e7f768a799935012753be8d3818dceded12..68514ac2e856f5cb2f4fc3234ebb34fc268b944b 100755 (executable)
@@ -140,8 +140,7 @@ async function respond (res: http.ServerResponse, data: Buffer[]): Promise<void>
 // Create server
 const server = http.createServer((req, res): void => {
        if (req.socket.remoteAddress == null) {
-               res.writeHead(401, { 'Content-Type': 'text/plain' })
-               res.end('Unauthorized')
+               res.writeHead(401).end('Unauthorized')
                return
        }
        const client = requests.get(req.socket.remoteAddress)
@@ -150,25 +149,23 @@ const server = http.createServer((req, res): void => {
        } else {
                if (--client.tokens <= 0) {
                        log(`${req.socket.remoteAddress} potential abuse`)
-                       res.writeHead(429, { 'Content-Type': 'text/plain' })
-                       res.end('Too Many Requests')
+                       res.writeHead(429).end('Too Many Requests')
                        return
                }
        }
        let data: Buffer[] = []
        let reqSize = 0
        if (req.method === 'POST') {
-               if (+(req.headers['content-length'] ?? 0) > MAX_BODY_SIZE) {
-                       res.writeHead(413, { 'Content-Type': 'text/plain' })
-                       res.end('Content Too Large')
+               const contentLength = +(req.headers['content-length'] ?? 0)
+               if (contentLength == 0 || contentLength > MAX_BODY_SIZE) {
+                       res.writeHead(413).end('Content Too Large')
                        req.socket.destroy()
                        return
                }
                req.on('data', (chunk: Buffer): void => {
                        reqSize += chunk.byteLength
                        if (reqSize > MAX_REQUEST_SIZE) {
-                               res.writeHead(413, { 'Content-Type': 'text/plain' })
-                               res.end('Content Too Large')
+                               res.writeHead(413).end('Content Too Large')
                                req.socket.destroy()
                                return
                        }