Skip to content

fix: stop saving anonymous sessions the client never receives - #456

Merged
omegascorp merged 6 commits into
mainfrom
fix/no-orphan-anonymous-sessions
Nov 12, 2026
Merged

omegascorp merged 6 commits into
mainfrom
fix/no-orphan-anonymous-sessions

Conversation

@omegascorp

@omegascorp omegascorp commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

obtainSession inserts 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:

  • method calls with a missing or expired token
  • custom routes that receive an unknown token
  • Socket.IO handshakes
  • live-query subscriptions

Repeating any of these requests grows _modelenceSessions without 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

  • obtainSession and authenticate take a persistNewSession option. When it is false and the token is missing or unknown, they return an anonymous session without writing it. Unsaved sessions are tracked in a WeakSet, so the public Session type does not change.
  • getCallContext, custom routes, the Socket.IO handshake and live-query subscriptions pass persistNewSession: false.
  • _system.session.init saves an unsaved session before returning it. SSR calls init in-process, so it is covered too.
  • _system.session.heartbeat skips the database update for an unsaved session.

Compatibility

  • authenticate and obtainSession are exported from modelence/server and still save new sessions by default.
  • No server code relies on an anonymous session being saved: login, magic link and OAuth sign-in create a fresh session and delete the previous one (a no-op for an unsaved session). Logout and the OAuth link cookie require a logged-in session.
  • The OAuth callback hooks receive an unsaved anonymous session for signed-out users. They previously received a brand-new saved session unrelated to the browser, because anonymous users have no cookie, so nothing could have relied on it.

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

  • New tests in session.test.ts: unsaved sessions for missing and unknown tokens, existing sessions still returned, default still saves, init saves an unsaved session and leaves a saved one alone, heartbeat skips unsaved sessions
  • authenticate passes the option through and defaults to saving
  • New live-query/handlers.test.ts, plus updated assertions for getCallContext, custom routes and the Socket.IO handshake
  • Full suite: 1556 tests pass; tsc, eslint, prettier and build pass
  • Manual check on a dev app: first visit and SSR first visit get a working session; calling a method with a bogus token inserts no session record

Refs #312, #437

🤖 Generated with Claude Code


Note

Medium Risk
Touches core session creation and authentication paths, but behavior for clients that receive tokens via init is preserved and defaults still persist for direct authenticate/obtainSession callers.

Overview
Stops orphan session records from piling up in _modelenceSessions when 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 / authenticate now accept persistNewSession (defaults to true for backward compatibility). With false, they mint an in-memory anonymous session tracked via a WeakSet and the new isSessionSaved() helper—no DB insert. getCallContext, route handlers, websocket handshake, and live-query auth pass persistNewSession: false.

_system.session.init is the single place that persists an unsaved session (same token for SSR and client hydration). heartbeat skips DB updates for unsaved sessions. API docs list isSessionSaved; 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.

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]>

@cursor cursor Bot 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.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ 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.

Comment thread packages/modelence/src/auth/session.ts Resolved
@artahian

artahian commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

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]>
@omegascorp

Copy link
Copy Markdown
Collaborator Author

@eduard-piliposyan please check

@eduard-piliposyan eduard-piliposyan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:

  1. Behavior change for app code: anonymous callers with a missing/unknown token now get an unsaved context.session in user methods, routes and live queries. Worth a changelog line.
  2. The unsaved flag depends on object identity, so a future copy of the session before init would 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 });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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>();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

omegascorp and others added 4 commits November 12, 2026 19:08
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]>
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.

3 participants