Skip to content

feat(core): add expirationStrategy support for stateful sessions - #248

Open
halvaradop wants to merge 2 commits into
masterfrom
feat/support-expiration-strategy
Open

feat(core): add expirationStrategy support for stateful sessions#248
halvaradop wants to merge 2 commits into
masterfrom
feat/support-expiration-strategy

Conversation

@halvaradop

@halvaradop halvaradop commented Aug 3, 2026

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Added session-level controls for maximum age, maximum duration, and expiration strategy.
    • Improved rolling and sliding session behavior, including activity-based updates and duration limits.
    • Added clearer handling for stateful session storage configuration.
  • Deprecations

    • JWT-level session lifetime options are deprecated in favor of session-level settings.
  • Documentation

    • Updated session configuration guidance and examples.
    • /docs now permanently redirects to /docs/introduction.
    • Updated “Get Started” links and authentication setup examples.

@vercel

vercel Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
auth Ready Ready Preview Aug 4, 2026 2:32am

@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Session expiration settings move from nested JWT configuration to session-level configuration. Core types, expiration calculations, renewal flows, tests, and documentation are updated. Documentation navigation redirects /docs to the introduction page. A generated route tree is reformatted without behavior changes.

Changes

Session expiration configuration

Layer / File(s) Summary
Session configuration and adapter contracts
packages/core/src/@types/session.ts, packages/core/src/@types/adapter.ts, packages/core/src/@types/index.ts
Adds session-level expiration fields, deprecates nested JWT expiration fields, updates stateful configuration, and permits partial session updates.
Expiration calculation utilities
packages/core/src/shared/utils/session-strategy.ts, packages/core/src/shared/assert.ts
Adds typed expiration calculations for fixed, rolling, absolute, and sliding strategies, maximum-duration ceilings, and activity debounce handling.
JWT and session renewal flows
packages/core/src/jose.ts, packages/core/src/session/..., packages/core/src/shared/logger.ts
Prioritizes session-level settings and applies calculated expiration and activity updates to stateless and stateful sessions.
Expiration configuration tests
packages/core/test/api/stateless/getSession.test.ts, packages/core/test/config/session.test.ts
Updates rolling, sliding, maximum-duration, and stateless session tests to use session-level configuration.
Configuration guidance and migration examples
packages/core/CHANGELOG.md, docs/src/content/docs/..., skills/...
Documents maxAge, maxDuration, and expirationStrategy, with updated examples and deprecation notes.

Documentation navigation

Layer / File(s) Summary
Documentation entry points
docs/next.config.ts, docs/src/components/home/call-to-action.tsx
Redirects /docs permanently to /docs/introduction and updates the “Get Started” link.

Generated route tree formatting

Layer / File(s) Summary
Generated route tree formatting
apps/tanstack-start/src/routeTree.gen.ts
Reformats generated route imports, declarations, route construction, and registration without behavior changes.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant getSession
  participant calcExpiration
  participant SessionsAdapter
  getSession->>calcExpiration: calculate expiration outcome
  calcExpiration-->>getSession: return expiration result
  getSession->>SessionsAdapter: persist expiration and lastActivityAt
Loading

Possibly related PRs

Suggested labels: feature, documentation

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the primary change: adding expiration strategy support for stateful sessions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/support-expiration-strategy

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai 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.

Actionable comments posted: 7

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/src/content/docs/`(core)/configuration/session-strategies.mdx:
- Around line 34-36: The session strategy table’s expirationStrategy entry omits
supported values. Update the type and description in the expirationStrategy row
to include fixed, rolling, absolute, and sliding, matching SessionConfigBase and
the documented section below while preserving the existing default.

In `@packages/core/src/`@types/session.ts:
- Around line 168-190: Align SessionConfigBase.expirationStrategy with the
runtime default by documenting and declaring the unset value as "absolute"
rather than "fixed". Update the stateless and stateful session configuration
resolvers to use the same "absolute" fallback whenever expirationStrategy is
omitted.
- Around line 220-223: Update StatefulStrategyConfig and its runtime consumers
to preserve the old session configuration alias, marking it deprecated and
defining explicit precedence over database when both are provided; ensure
deleteStrategy and maxSessions are read from the selected configuration.
Alternatively, document this as a breaking change and update all runtime config
consumption accordingly.

In `@packages/core/src/session/stateful/getSession.ts`:
- Around line 134-144: Update the renewal logic around updateExpires in the
stateful session flow to enforce sessionConfig.maxDuration from
session.createdAt: cap expiresAt at the createdAt-based maximum, and skip the
adapter.updateSession renewal once that cap has been reached. Preserve the
existing expiry calculation and lastActivityAt update for sessions still within
the allowed duration.
- Around line 139-144: Update the renewal logic in getSession around
adapter.updateSession so persistence failures are handled separately from
session validation failures: preserve the already-valid session and existing
expiry when the renewal write fails, and only expose the renewed expiresAt after
updateSession succeeds. Prevent renewal errors from reaching the outer catch
that returns session: null and clears the cookie.

In `@packages/core/test/config/session.test.ts`:
- Line 51: Update the migration test fixtures at the referenced session
configurations to set expirationStrategy directly on session instead of
session.jwt.expirationStrategy. Ensure these tests exercise the current
session-level configuration path, while retaining a separate fixture only if
needed to cover deprecated fallback compatibility.

In `@skills/security-practices/SKILL.md`:
- Around line 200-202: Replace the session-level maxExpiration option with
maxDuration in the hardened configuration, preserving the existing 30-day value
and surrounding session settings.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: c2c173e1-68ad-4b60-ba82-5371cd1b66fc

📥 Commits

Reviewing files that changed from the base of the PR and between fda9604 and da48a74.

📒 Files selected for processing (16)
  • apps/tanstack-start/src/routeTree.gen.ts
  • docs/next.config.ts
  • docs/proxy.ts
  • docs/src/components/home/call-to-action.tsx
  • docs/src/content/docs/(core)/api-reference/server/createAuth.mdx
  • docs/src/content/docs/(core)/configuration/session-strategies.mdx
  • packages/core/CHANGELOG.md
  • packages/core/src/@types/adapter.ts
  • packages/core/src/@types/session.ts
  • packages/core/src/jose.ts
  • packages/core/src/session/stateful/getSession.ts
  • packages/core/src/session/stateless/getSession.ts
  • packages/core/src/session/stateless/refreshSession.ts
  • packages/core/test/config/session.test.ts
  • skills/create-auth/reference/create-auth.md
  • skills/security-practices/SKILL.md
💤 Files with no reviewable changes (1)
  • docs/proxy.ts

Comment thread docs/src/content/docs/(core)/configuration/session-strategies.mdx Outdated
Comment thread packages/core/src/@types/session.ts
Comment thread packages/core/src/@types/session.ts
Comment thread packages/core/src/session/stateful/getSession.ts Outdated
Comment thread packages/core/src/session/stateful/getSession.ts Outdated
Comment thread packages/core/test/config/session.test.ts Outdated
Comment thread skills/security-practices/SKILL.md

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/session/stateless/getSession.ts`:
- Around line 29-35: Update the expiration handling in getSession around
calcStatelessExpiration so action === "invalid" returns { session: null, headers
} instead of the authenticated session; preserve the existing session return for
only "no_change" and "touch". Add a regression test covering a signed token
without an exp claim.

In `@skills/security-practices/SKILL.md`:
- Around line 230-240: Update the expiration design guidance around
`maxDuration` and `expirationStrategy` to state that `SessionConfigBase`
requires `maxDuration` for `absolute` and `sliding` strategies, and that it
bounds sliding-session renewal to prevent indefinite extension. Also recommend
setting `maxDuration` for `rolling` sessions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 255dfca7-a196-4cf0-8e44-a59209ad27c9

📥 Commits

Reviewing files that changed from the base of the PR and between da48a74 and ce1ad31.

📒 Files selected for processing (11)
  • docs/src/content/docs/(core)/configuration/session-strategies.mdx
  • packages/core/src/@types/index.ts
  • packages/core/src/@types/session.ts
  • packages/core/src/session/stateful/getSession.ts
  • packages/core/src/session/stateless/getSession.ts
  • packages/core/src/shared/assert.ts
  • packages/core/src/shared/logger.ts
  • packages/core/src/shared/utils/session-strategy.ts
  • packages/core/test/api/stateless/getSession.test.ts
  • packages/core/test/config/session.test.ts
  • skills/security-practices/SKILL.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/core/test/config/session.test.ts
  • packages/core/src/session/stateful/getSession.ts
  • docs/src/content/docs/(core)/configuration/session-strategies.mdx

Comment on lines +29 to +35
const calc = calcStatelessExpiration({
exp,
maxAge,
strategy,
})
if (calc.action === "no_change" || calc.action === "invalid" || calc.action === "touch") {
return { session, headers }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Reject sessions when expiration processing returns invalid.

calcStatelessExpiration returns invalid when exp is missing or expired. Lines 34-35 return the authenticated session for that result. An exp-less signed token can remain valid without an expiration.

Return session: null for invalid. Keep the existing session only for no_change and touch. Add a regression test for a token with no exp claim.

Proposed fix
-            if (calc.action === "no_change" || calc.action === "invalid" || calc.action === "touch") {
+            if (calc.action === "invalid") {
+                return { session: null, headers: newHeaders }
+            }
+            if (calc.action === "no_change" || calc.action === "touch") {
                 return { session, headers }
             }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/session/stateless/getSession.ts` around lines 29 - 35,
Update the expiration handling in getSession around calcStatelessExpiration so
action === "invalid" returns { session: null, headers } instead of the
authenticated session; preserve the existing session return for only "no_change"
and "touch". Add a regression test covering a signed token without an exp claim.

Comment on lines +230 to +240
## issuer, audience, maxDuration, and expiration design

- `issuer`: set canonical auth issuer URL.
- `audience`: set explicit service audience(s); avoid overly broad audiences.
- `maxAge`: session lifetime per token.
- `maxExpiration`: absolute cap to prevent indefinite extension.
- `maxDuration`: absolute cap to prevent indefinite extension.
- `expirationStrategy`:
- `absolute`: hard stop after max window (security-first default).
- `rolling`: extends active sessions; use with strict caps and monitoring.
- `fixed`: fixed TTL from issuance; no rolling extension.
- `sliding`: refreshes validity window with activity, bounded by `maxExpiration`.
- `sliding`: refreshes validity window with activity, bounded by `maxDuration`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

State when maxDuration is required.

SessionConfigBase requires maxDuration for absolute and sliding strategies. The guidance currently describes it only as a cap. Without it, the expiration utility has no duration ceiling, so a sliding session can renew indefinitely. Document this requirement and recommend maxDuration for rolling sessions.

🧰 Tools
🪛 SkillSpector (2.4.4)

[error] 3: [PE3] Credential Access: Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Remediation: Remove references to credential paths. Use environment variables or secrets managers. For docs, use placeholder paths (e.g., /path/to/config). Never load .env or token files in production code paths.

(Privilege Escalation (PE3))


[error] 28: [PE3] Credential Access: Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Remediation: Remove references to credential paths. Use environment variables or secrets managers. For docs, use placeholder paths (e.g., /path/to/config). Never load .env or token files in production code paths.

(Privilege Escalation (PE3))


[error] 65: [PE3] Credential Access: Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Remediation: Remove references to credential paths. Use environment variables or secrets managers. For docs, use placeholder paths (e.g., /path/to/config). Never load .env or token files in production code paths.

(Privilege Escalation (PE3))


[error] 268: [PE3] Credential Access: Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Remediation: Remove references to credential paths. Use environment variables or secrets managers. For docs, use placeholder paths (e.g., /path/to/config). Never load .env or token files in production code paths.

(Privilege Escalation (PE3))

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@skills/security-practices/SKILL.md` around lines 230 - 240, Update the
expiration design guidance around `maxDuration` and `expirationStrategy` to
state that `SessionConfigBase` requires `maxDuration` for `absolute` and
`sliding` strategies, and that it bounds sliding-session renewal to prevent
indefinite extension. Also recommend setting `maxDuration` for `rolling`
sessions.

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