Sample audits · Open-source projects, first eight

expressjs/session

Session middleware for Express.

Summary card for this audit: 11 findings after review, 0 High, 1 Medium, 7 Low, 3 Info
Auditedexpressjs/session at commit 8947e169ae838b22cc1af198e50e370e6fc09f96
Date11 October 2026 (audited again; first audit 11 October 2026)
How it ranlocal run on our workstation, full audit, Standard review
Verdict after reviewPass with notes (Fail if a High finding remains after review, otherwise Pass with notes)
0
High after review
1
Medium after review
7
Low after review
3
Info after review
0
excluded on review

Compared with the first audit

Same commit as the first audit: the project's default branch has no later commits (checked 11 October 2026), so nothing could have been fixed upstream in between. Each finding of the first audit (11 October 2026) was checked again against the code audited now. 10 findings in the first audit; 10 still open (7 found again, 3 not reported again but still present). This audit has 11 findings after review, 5 of them new.

First auditFindingReviewed rating thenNowIn this audit
#1rolling + resave:false + store without touch(): store expiry not extendedLowStill open#2
#2After reload(), unchanged session written backLowStill opennot reported again
#3regenerate() sessions skip save trackingLowStill opennot reported again
#4Cookie-only changes invisible to change checkLowStill open#2
#5Store event listeners accumulateLowStill open#3
#6defer shim copied into 3 filesInfoStill open#7
#7unset default 'keep' postponed to next majorInfoStill opennot reported again
#8Headers sent before store write finishesMediumStill open#4
#9Middleware overwrites generate on shared storeLowStill open#1
#10Default MemoryStore grows without limitLowStill open#10
How to read this page

Each finding keeps the number it has in the audit report. The rating shown first is the one after review; the first automated rating is listed with it. 4 findings were first rated Medium or High; 1 of them are Medium or High after review. Text marked "From the report" is quoted from the audit report; fixes are suggestions and were not tested. Code locations link to the file and line at the audited commit.

Medium after review (1)

4. Medium The response completes as a success when the session save or destroy fails
First rating: Medium · Reviewed rating: Medium · Review: confirmed · also in the first audit (#8)
Location: index.js:354
From the report
Evidence
req.session.save(function onsave(err) {
  if (err) {
    defer(next, err);
Why it matters

before the store answers, the body has already been written except for its last byte, and the status line and Set-Cookie header are already committed. When the save fails, writeend() still finishes the response, and the error goes to next() only after the client has the response. The client sees a successful response and keeps a cookie for a session that was never stored. For example, a login or cart change that looked successful is lost on the next request. The destroy path at lines 329-336 behaves the same way.

Suggested fix, not tested

do not commit the response as a success before the store confirms the write. Hold back the status and body until the save callback runs. On failure, answer with an error status and send no Set-Cookie for a session that was not stored.

Review: On error the callbacks do defer(next, err) and then writeend() anyway (354-360, 329-336, and the touch path 366-373). Headers are committed by _implicitHeader at 294-296. One nuance: the "all but the last byte" split happens only when Content-Length is set (303-317). Otherwise the whole chunk is written at 320.

Low after review (7)

1. Low Session generation settings are stored on the shared store object
First rating: Medium · Reviewed rating: Low · Review: rated too high · also in the first audit (#9)
Location: index.js:158
From the report
Evidence
store.generate = function(req){
  req.sessionID = generateId(req);
  req.session = new Session(req);
Why it matters

each call to session() replaces generate on the store it was given. This function captures the middleware's own ID generator, cookie options and proxy-trust setting. An application can mount two session middlewares on one store, for example with different cookie paths or options. In that case every new session and every regenerate() uses the settings of whichever middleware was created last. Sessions from the first middleware then get the wrong cookie flags, the wrong secure or SameSite resolution, or the wrong ID format. Nothing reports an error.

Suggested fix, not tested

keep the generator in the middleware's closure and do not attach it to the store. Pass it to regenerate through the request, for example as a request-scoped function set by the owning middleware. Give the base Store an explicit generate contract instead of relying on the middleware to inject one (session/store.js:53).

Review: store.generate is overwritten on each session() call, and Store.regenerate calls it at store.js:53. It matters only when two middlewares share one explicit store, since the default MemoryStore is created per call.

2. Low Cookie-only changes are skipped by the unchanged-session check
First rating: Low · Reviewed rating: Low · Review: confirmed · also in the first audit (#4)
Location: index.js:655
From the report
Evidence
// ignore sess.cookie property
if (this === sess && key === 'cookie') {
  return
Why it matters

the check that decides whether to save the session leaves out the cookie. Suppose resave is false and the store has no touch() method. Then a change that touches only the cookie, such as a per-user maxAge or a new expiry, is never written to the store. The browser and the stored record end up with different expiry times.

Suggested fix, not tested

include the persistent cookie fields (expires, originalMaxAge) in the comparison when the store does not implement touch(). Alternatively, require touch() from stores and document it.

Review: hash() drops cookie at 655. With resave:false and no touch(), a cookie-only change is never saved. With the default resave:true it is saved anyway.

3. Low Store event listeners accumulate on every middleware creation
First rating: Low · Reviewed rating: Low · Review: confirmed · also in the first audit (#5)
Location: index.js:179
From the report
Evidence
store.on('disconnect', function ondisconnect() {
  storeReady = false
})
Why it matters

every session() call adds a connect listener and a disconnect listener to the store, and nothing ever removes them. If the middleware is created repeatedly on a shared store, as happens in tests, hot reload or per-route setups, the listeners pile up. Node then prints MaxListeners warnings, and the closures stay in memory.

Suggested fix, not tested

register the listeners once per store, or provide a teardown that removes them.

Review: Each session() adds a disconnect and a connect listener (179-184) and nothing removes them. The MaxListeners warning appears after 10 on one store.

5. Low A stored session record without a cookie object throws inside a store callback
First rating: Low · Reviewed rating: Low · Review: confirmed · new in this audit
From the report
Evidence
var expires = sess.cookie.expires
var originalMaxAge = sess.cookie.originalMaxAge
Why it matters

createSession assumes every stored record has a cookie object. The middleware guards its own call (index.js:512-523), but Session.reload (session/session.js:95) and Store.load (session/store.js:73) call it unguarded inside the store's asynchronous callback. A malformed record or one in an older format then throws an uncaught exception instead of returning an error.

Suggested fix, not tested

treat a missing or non-object cookie as empty options, or return an error to the callback. Wrap these two calls in try/catch and pass the error on.

Review: sess.cookie.expires at store.js:87 throws on a missing cookie. Session.reload (session.js:95) and Store.load (store.js:73) call it unguarded in an async callback. The middleware path is guarded at index.js:512-523. This needs a malformed or foreign record, since save() always writes cookie.

8. Low The test run silences every deprecation warning of the package
First rating: Low · Reviewed rating: Low · Review: confirmed · new in this audit
From the report
Evidence
process.env.NO_DEPRECATION = 'express-session';
Why it matters

the whole test suite turns off every deprecation message from the package. If a code change starts triggering a deprecation on a normal path, or makes one fire on every request, the test logs will never show it.

Suggested fix, not tested

silence only the deprecations that tests trigger on purpose. Add tests that check which deprecation messages each configuration emits and how often.

Review: as a pattern. env.js:2 sets NO_DEPRECATION, and it is loaded through --require in package.json:45. No test mentions "deprecat" (0 hits in test/), so no defect is shown.

10. Low The default in-memory store grows without bound
First rating: Medium · Reviewed rating: Low · Review: rated too high · also in the first audit (#10)
Location: session/memory.js:120 (defaults at index.js:100 and index.js:128)
From the report
Evidence
MemoryStore.prototype.set = function set(sessionId, session, callback) {
  this.sessions[sessionId] = JSON.stringify(session)
Why it matters

when no store is configured, the middleware uses the in-memory store. When saveUninitialized is not set, it defaults to true, so every request without a cookie creates and stores a new session. The store has no size limit and no periodic cleanup. An expired entry is removed only if the same session ID is read again, and with the default cookie settings entries never expire at all. Any anonymous client can therefore make the process use more and more memory until it fails. The README warns about this and the code prints a warning in production, but the default setup still runs this way.

Suggested fix, not tested

make saveUninitialized default to false. Give the in-memory store a periodic sweep of expired entries (on a timer that does not keep the process alive) and an optional maximum size with eviction. Refuse to start with the in-memory store in production instead of only logging a warning.

Review: The mechanism is real: saveUninitialized defaults to true (126-129), there is no limit or sweep, and maxAge is null by default. It is documented, a production warning is printed (153-155), and the README describes the default as deprecated.

11. Low Concurrent requests overwrite each other's session changes, and the default rewrites unchanged sessions
First rating: Medium · Reviewed rating: Low · Review: rated too high · new in this audit
Location: index.js:123 (write at session/session.js:72)
From the report
Evidence
deprecate('undefined resave option; provide resave option');
resaveSession = true;
Why it matters

each request loads the whole session, and at the end writes the whole object back with no version check. When two requests for the same user overlap, the one that finishes last silently discards the other's changes. When resave is not set, it defaults to true, so even a request that changed nothing writes its old copy back. For example, a slow page load can undo a login, a cart update or a flash message set by a parallel request.

Suggested fix, not tested

make resave default to false. For stores that support it, add a version counter or compare-and-set to set() that rejects or merges stale writes. Otherwise, document last-writer-wins clearly and offer an update hook that writes only changed fields.

Review: The mechanism is real (resave defaults to true at 121-124, and session.js:72 writes the whole object). But README.md:277-293 documents exactly this race, and the default is deprecated with the advice to use false.

Info after review (3)

6. Info The main module mixes several responsibilities in one closure
First rating: Low · Reviewed rating: Info · Review: rated too high · new in this audit
Location: index.js:87
From the report
Evidence
function session(options) {
Why it matters

this one 740-line file holds option parsing, cookie transport (read, sign, unsign, secure detection, path matching), interception of the response end with commit logic, and change tracking (hashes, saved and touched flags). These parts share variables inside a single closure of about 340 lines. Finding 4 comes from this coupling, and it makes each part harder to test and change on its own.

Suggested fix, not tested

move cookie transport (getcookie, setcookie, unsigncookie, issecure, rfcPathMatch) and change tracking (hash, isModified, isSaved) into their own modules, so the middleware closure only connects them.

Review: getcookie, setcookie, unsigncookie, issecure and rfcPathMatch are already module-level functions (540-741), not part of the closure. Only change tracking and the end interception share closure variables. The claim that finding 4 "comes from this coupling" is unsupported.

7. Info The deferral helper is copied into three modules
First rating: Low · Reviewed rating: Info · Review: rated too high · also in the first audit (#6)
From the report
Evidence
var defer = typeof setImmediate === 'function'
  ? setImmediate
  : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) }
Why it matters

the same compatibility shim is kept in three places, two of them in shipped code. A fix to one copy can easily miss the others.

Suggested fix, not tested

keep one shared helper module and require it everywhere. If the copies are deliberate, say so in a comment.

Review: All three copies are real (index.js:65, memory.js:25, smart-store.js:7). The copies are deliberate: package.json has engines node >= 0.8.0, and the memory.js comment says "Shim setImmediate for node.js < 0.10".

9. Info The test script overwrites its certificate fixtures on every run
First rating: Low · Reviewed rating: Info · Review: rated too high · new in this audit
From the report
Evidence
openssl req -x509 -nodes -newkey rsa:2048 -keyout ./test/fixtures/server.key -out ./test/fixtures/server.crt -days 3650 \
Why it matters

npm test runs this script every time. It creates a new key and certificate each run and overwrites any existing files without checking. This slows each run, makes the runs differ from one another, and silently replaces fixtures a developer may have put there.

Suggested fix, not tested

generate the pair only when it is missing, or write it to a temporary directory that the tests point to.

Review: The overwrite on every run is true (gencert.sh:4, run by npm test). But server.key and server.crt are gitignored and generated (.gitignore:6-7), so "silently replaces fixtures a developer may have put there" is wrong.

Want this for your code?

Upload a ZIP or link a public GitHub repo, pick the areas and the depth, and get findings by severity with fixes.