Skip to content

fix(cookies): keep an Expires of 0 when serializing a cookie - #5808

Open
NgoQuocViet2001 wants to merge 1 commit into
nodejs:mainfrom
NgoQuocViet2001:fix-cookie-expires-epoch
Open

fix(cookies): keep an Expires of 0 when serializing a cookie#5808
NgoQuocViet2001 wants to merge 1 commit into
nodejs:mainfrom
NgoQuocViet2001:fix-cookie-expires-epoch

Conversation

@NgoQuocViet2001

Copy link
Copy Markdown

Problem

stringify tests expires for truthiness:

if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {
  out.push(`Expires=${toIMFDate(cookie.expires)}`)
}

expires is typed Date | number, and a numeric 0 is the Unix epoch — the canonical way to say expire this cookie now. It is falsy, so the attribute is silently dropped.

The Max-Age branch a few lines above already avoids exactly this:

if (typeof cookie.maxAge === 'number') {   // 0 is a real value

Effect

expires: 0             -> "a=b"                                            <- attribute lost
expires: new Date(0)   -> "a=b; Expires=Thu, 01 Jan 1970 00:00:00 GMT"
expires: 1000          -> "a=b; Expires=Thu, 01 Jan 1970 00:00:01 GMT"
maxAge: 0              -> "a=b; Max-Age=0"

Only the numeric-zero case, and only for expires. No error is raised — a caller asking for immediate expiry gets a session cookie instead, which is the unsafe direction for the usual purpose (clearing a cookie on logout).

Fix

Treat null/undefined as absent instead of treating every falsy value that way. After the change:

expires: 0            -> "a=b; Expires=Thu, 01 Jan 1970 00:00:00 GMT"
expires: null         -> "a=b"
no expires            -> "a=b"
expires: new Date(0)  -> "a=b; Expires=Thu, 01 Jan 1970 00:00:00 GMT"
expires: invalid Date -> "a=b"

Test plan

  • Added two cases to test/cookie/cookies.js beside the existing numeric-expires test: expires: 0 serializes the epoch, and expires: null still omits the attribute.
  • Ran: node --test test/cookie/*.js93 passing.
  • Checked: reverting only util.js fails the new test with 'Space=Cat' == 'Space=Cat; Expires=Thu, 01 Jan 1970 00:00:00 GMT'.
  • Ran: npx standard on both touched files → clean.

The Expires branch tested cookie.expires for truthiness, so a numeric 0 -- the
Unix epoch, and the canonical way to say "expire this cookie now" -- dropped
the attribute entirely. expires is typed Date | number, and the Max-Age check
directly above already tests the type rather than truthiness for the same
reason.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant