镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

fix: save session when replaced with empty object - #226

Open
RaphaelFakhri wants to merge 1 commit into
expressjs:masterfrom
RaphaelFakhri:fix-replace-empty-session
Open

RaphaelFakhri wants to merge 1 commit into
expressjs:masterfrom
RaphaelFakhri:fix-replace-empty-session

Conversation

@RaphaelFakhri

Copy link
Copy Markdown

Assigning req.session = {} on a request that carries a valid session cookie sends no Set-Cookie header, so the old session data stays in the browser and comes back on the next request.

req.session = {} creates a new session, and a new session is saved only when it is populated. This change records, at assignment time, whether the request carried a valid session. If it did, the replacement session is saved even when empty, which matches the behavior of deleting every key from an existing session.

Behavior without a request session is unchanged: req.session = {} on a request with no session cookie still sends no Set-Cookie header (covered by the existing when session = {} test).

Tests

  • Adds saved session when replaced with {} should Set-Cookie with empty session.
  • Fails on master (no Set-Cookie header), passes with this change.
  • npm test and npm run lint pass.

Fixes #225

@yxshee yxshee left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ran this locally: 43 passing, and the new "when replaced with {}" test fails on master (42 passing, 1 failing). The repo's pinned mocha doesn't start on Node 26 (its yargs is ESM-only), so I used npx mocha@11 with the same flags.

I also checked the end-to-end flow from #225 against an Express app:

  • /login → /reset (req.session = {}) now sends session=e30= plus a fresh .sig, and the next request sees {}, where master still returned {"user":"alice"}.
  • req.session = {} with no incoming cookie still sends no Set-Cookie, so empty new sessions aren't written. 👍
  • With a tampered/unsigned incoming cookie, tryGetSession returns nothing, so no replacement cookie is written. That seems right: there was no valid session to replace.

One small thing: tryGetSession decodes and verifies the request cookie again on every assignment, even when req.session was already read earlier in the request. It's cheap enough that it probably doesn't matter, but the parsed session from the getter could be reused if you want to avoid the second signature check. LGTM either way.

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.

Assigning an empty object to req.session does not clear an existing session

2 participants