Repository navigation
fix: stop saving anonymous sessions the client never receives - #456
Conversation
A request with a missing or unknown token used to insert a new session, but only _system.session.init returns that token to the client. Method calls, custom routes, Socket.IO handshakes and live-query subscriptions all wrote records nobody could use, so repeated requests could grow the sessions collection without bound. Those paths now get an unsaved anonymous session. _system.session.init saves it before returning the token, which also covers SSR. The public authenticate and obtainSession keep saving by default; internal callers opt out with persistNewSession: false. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit b7bd467. Configure here.
|
I'm ok with these changes as long as @eduard-piliposyan approves. |
`_system.session.init` minted a new session for an unsaved one, so during SSR the in-process call context kept the original unsaved token while the client hydrated with a different saved token. Save the existing session under its own token instead, so both refer to the same record. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@eduard-piliposyan please check |
eduard-piliposyan
left a comment
There was a problem hiding this comment.
Looks good. I traced SSR (getCallContext → in-process init keeps the same session object, so the WeakSet check holds), sign-in via startUserSession (deleting an unsaved previous token is a no-op), and the link-cookie/nonce/linking routes (all require userId, so the session is always saved). No blockers.
Two non-blocking notes, left inline:
- Behavior change for app code: anonymous callers with a missing/unknown token now get an unsaved
context.sessionin user methods, routes and live queries. Worth a changelog line. - The unsaved flag depends on object identity, so a future copy of the session before
initwould break it silently.
| const { session, user, roles } = await authenticate(authToken); | ||
| // Only _system.session.init returns a new token to the client, and it saves | ||
| // the session itself. Other requests must not leave unusable records. | ||
| const { session, user, roles } = await authenticate(authToken, { persistNewSession: false }); |
There was a problem hiding this comment.
Non-blocking: this also changes what app code sees. User methods/routes/live queries called with a missing or unknown token now get a session with no DB record. If app code returns context.session.authToken to the client itself, or calls the exported setSessionUser(session.authToken, …) for an anonymous caller, it now hands out a dead token / updates 0 rows. Before this PR that code would have worked. isSessionSaved isn't exported from modelence/server, so apps can't check for it. Probably fine, but worth a changelog note (and maybe exporting isSessionSaved).
|
|
||
| // Anonymous sessions that were handed out without being written to the | ||
| // database. Tracked by object identity so the public Session type stays as is. | ||
| const unsavedSessions = new WeakSet<Session>(); |
There was a problem hiding this comment.
Non-blocking: since this is tracked by identity, anything that copies the session between getCallContext and init (e.g. { ...session } or structuredClone) would make init treat the copy as saved, skip the insert, and return a token with no record behind it. Nothing does that today. A short note at the getCallContext/runMethod boundary, or one end-to-end test from getCallContext through init, would guard against a future refactor.
App code that runs for an anonymous caller with a missing or unknown token now gets a session with no database record until _system.session.init saves it. Export isSessionSaved from modelence/server so apps can check for that. The unsaved flag is tracked by object identity, so add a test that runs getCallContext through the in-process init call. It fails if anything on that path copies the session. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The live-query client IP test from #437 asserted authenticate calls without options. This branch passes persistNewSession: false on the Socket.IO handshake and live-query subscriptions, so assert that. Co-Authored-By: Claude Opus 5.5 <[email protected]>

Problem
obtainSessioninserts a new session whenever a request's token is missing or unknown. Only_system.session.init(over HTTP, or in-process during SSR) ever returns that new token to the client. Every other path wrote a record nobody could use:Repeating any of these requests grows
_modelenceSessionswithout bound; the 7-day TTL caps how long records live, not how many get written. This was reported in #312 and #437 tried to rate-limit it per IP. This PR removes the writes instead, so nothing needs limiting.Fix
obtainSessionandauthenticatetake apersistNewSessionoption. When it isfalseand the token is missing or unknown, they return an anonymous session without writing it. Unsaved sessions are tracked in aWeakSet, so the publicSessiontype does not change.getCallContext, custom routes, the Socket.IO handshake and live-query subscriptions passpersistNewSession: false._system.session.initsaves an unsaved session before returning it. SSR callsinitin-process, so it is covered too._system.session.heartbeatskips the database update for an unsaved session.Compatibility
authenticateandobtainSessionare exported frommodelence/serverand still save new sessions by default.Not covered
An anonymous visitor who has a token in localStorage but no cookie still gets a saved session during SSR, which the client then discards when it reconciles with its own token. Fixing that means changing how SSR hydrates the session, so it is left for a follow-up.
Test plan
session.test.ts: unsaved sessions for missing and unknown tokens, existing sessions still returned, default still saves,initsaves an unsaved session and leaves a saved one alone, heartbeat skips unsaved sessionsauthenticatepasses the option through and defaults to savinglive-query/handlers.test.ts, plus updated assertions forgetCallContext, custom routes and the Socket.IO handshaketsc, eslint, prettier and build passRefs #312, #437
🤖 Generated with Claude Code
Note
Medium Risk
Touches core session creation and authentication paths, but behavior for clients that receive tokens via
initis preserved and defaults still persist for directauthenticate/obtainSessioncallers.Overview
Stops orphan session records from piling up in
_modelenceSessionswhen requests authenticate with a missing or unknown token but never hand a new token back to the client (method calls, custom routes, Socket.IO, live-query subscriptions).obtainSession/authenticatenow acceptpersistNewSession(defaults to true for backward compatibility). Withfalse, they mint an in-memory anonymous session tracked via aWeakSetand the newisSessionSaved()helper—no DB insert.getCallContext, route handlers, websocket handshake, and live-query auth passpersistNewSession: false._system.session.initis the single place that persists an unsaved session (same token for SSR and client hydration).heartbeatskips DB updates for unsaved sessions. API docs listisSessionSaved; tests cover SSR init, init/heartbeat behavior, and the updated call sites.Reviewed by Cursor Bugbot for commit 4d86357. Bugbot is set up for automated code reviews on this repo. Configure here.