Skip to content
27 changes: 27 additions & 0 deletions .changeset/cookie-and-response-fixes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
"@tinyhttp/cookie": patch
"@tinyhttp/res": patch
"@tinyhttp/send": patch
---

fix: validate cookie grammar and stop emitting `undefined` content types

`cookie.serialize` validated names and values with the RFC 7230 field-content
grammar, which accepts almost any printable character. A name containing
whitespace or one of `"(),/:;<=>?@[\]{}` was serialized as-is, and a value that
a custom `encode` left raw could carry `;`, adding an attribute to `Set-Cookie`
that the caller did not ask for. Names are now checked against the RFC 6265
`cookie-name` grammar and values against `cookie-value`, so such input throws
`argument name is invalid` / `argument val is invalid` instead of producing a
malformed header. Values encoded by the default `encodeURIComponent` are
unaffected, because its output is always a valid `cookie-value`.

`res.type()`, `res.attachment()` and `res.sendFile()` passed the result of the
mime lookup straight to the header. When the extension is unknown or absent
(`.ico` is not in the mime table, and neither is an extensionless file) the
header became `Content-Type: undefined; charset=utf-8`. The lookup now falls
back to `application/octet-stream`.

`res.send()` with no body called `toString()` on `undefined` and threw a
`TypeError`, which surfaced as a 500 response. It now ends the response with an
empty body and no `Content-Type`, the same response as `res.send(null)`.
17 changes: 15 additions & 2 deletions packages/cookie/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,19 @@ const pairSplitRegExp = /; */
// biome-ignore lint/suspicious/noControlCharactersInRegex: RFC 7230 field-content includes HTAB
const fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/

/**
* RegExp to match cookie-name in RFC 6265 sec 4.1.1, which refers to the
* `token` definition in RFC 2616 sec 2.2.
*/
const cookieNameRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/

/**
* RegExp to match cookie-value in RFC 6265 sec 4.1.1:
*
* cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
*/
const cookieValueRegExp = /^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/

function tryDecode(str: string, decode: (str: string) => string) {
try {
return decode(str)
Expand Down Expand Up @@ -70,11 +83,11 @@ export type SerializeOptions = Partial<{
export function serialize(name: string, val: string, opt: SerializeOptions = {}): string {
if (!opt.encode) opt.encode = encodeURIComponent

if (!fieldContentRegExp.test(name)) throw new TypeError('argument name is invalid')
if (!cookieNameRegExp.test(name)) throw new TypeError('argument name is invalid')

const value = opt.encode(val)

if (value && !fieldContentRegExp.test(value)) throw new TypeError('argument val is invalid')
if (!cookieValueRegExp.test(value)) throw new TypeError('argument val is invalid')

let str = `${name}=${value}`

Expand Down
4 changes: 2 additions & 2 deletions packages/res/src/headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export const setVaryHeader =
export const setContentType =
<Response extends Res = Res>(res: Response) =>
(type: string): Response => {
const ct = type.indexOf('/') === -1 ? lookup(type) : type
setHeader(res)('Content-Type', ct as string)
const ct = type.indexOf('/') === -1 ? (lookup(type) ?? 'application/octet-stream') : type
setHeader(res)('Content-Type', ct)
return res
}
5 changes: 5 additions & 0 deletions packages/send/src/send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ export const send =
res.end(bodyToSend)
} else json(res)(bodyToSend, encoding)
} else {
if (bodyToSend === undefined) {
res.end('')
return res
}

if (typeof bodyToSend !== 'string') bodyToSend = bodyToSend.toString()

res.end(bodyToSend, encoding)
Expand Down
3 changes: 2 additions & 1 deletion packages/send/src/sendFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ export const sendFile =

headers.ETag = createETag(stats, encoding)

if (!res.getHeader('Content-Type')) headers['Content-Type'] = `${lookup(extname(path))}; charset=utf-8`
if (!res.getHeader('Content-Type'))
headers['Content-Type'] = `${lookup(extname(path)) ?? 'application/octet-stream'}; charset=utf-8`

let status = res.statusCode || 200

Expand Down
12 changes: 12 additions & 0 deletions tests/modules/cookie.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,18 @@ describe('Cookie serializing', () => {
}
throw new Error('Did not throw an error')
})
it('should throw an error if argument name is not a valid cookie name', () => {
expect(() => cookie.serialize('a b', 'bar')).toThrow('argument name is invalid')
})
it('should throw an error if argument val contains characters outside the cookie value grammar', () => {
expect(() => cookie.serialize('foo', 'bar;baz', { encode: (val) => val })).toThrow('argument val is invalid')
})
it('should throw an error if argument name contains a separator', () => {
expect(() => cookie.serialize('a:b', 'bar')).toThrow('argument name is invalid')
})
it('should accept a value that the default encoder percent-encodes', () => {
expect(cookie.serialize('foo', 'a=b')).toBe('foo=a%3Db')
})
it('should throw an error if opt.domain is invalid', () => {
try {
const customOpt = { domain: '➡️' }
Expand Down
7 changes: 7 additions & 0 deletions tests/modules/res.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,13 @@ describe('Response extensions', () => {

await makeFetch(app)('/').expect('Content-Type', 'application/json; charset=utf-8')
})
it('should fall back to application/octet-stream for an unknown extension', async () => {
const app = runServer((_, res) => {
setContentType(res)('.qqq').end()
})

await makeFetch(app)('/').expect('Content-Type', 'application/octet-stream; charset=utf-8')
})
})
describe('res.attachment(filename)', () => {
it('should set Content-Disposition without a filename specified', async () => {
Expand Down
18 changes: 18 additions & 0 deletions tests/modules/send.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@ describe('send(body)', () => {

await makeFetch(app)('/').expectBody('')
})
it('should send an empty body when the body is undefined', async () => {
const app = runServer((req, res) => send(req, res)(undefined))

await makeFetch(app)('/').expectStatus(200).expectBody('').expectHeader('Content-Type', null)
})
it('should remove some headers for 204 status', async () => {
const app = runServer((req, res) => {
res.statusCode = 204
Expand Down Expand Up @@ -235,6 +240,19 @@ describe('sendFile(path)', () => {

await makeFetch(app)('/').expectHeader('Content-Type', 'text/plain; charset=utf-8')
})
it('should fall back to application/octet-stream for an unknown extension', async () => {
const unknownFilePath = path.resolve(__dirname, 'test.qqq')

fs.writeFileSync(unknownFilePath, 'Hello World')

try {
const app = runServer((req, res) => sendFile(req, res)(unknownFilePath, {}))

await makeFetch(app)('/').expectHeader('Content-Type', 'application/octet-stream; charset=utf-8')
} finally {
fs.unlinkSync(unknownFilePath)
}
})
it('should send a relative path inside root', async () => {
const app = runServer((req, res) => sendFile(req, res)('test.txt', { root: __dirname }))

Expand Down
Loading