Skip to content

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

Merged
halvaradop merged 4 commits into
masterfrom
feat/support-expiration-strategy
Aug 4, 2026
Merged

feat(core): add expirationStrategy support for stateful sessions#248
halvaradop merged 4 commits into
masterfrom
feat/support-expiration-strategy

Conversation

@halvaradop

@halvaradop halvaradop commented Aug 3, 2026

Copy link
Copy Markdown
Member

Description

This pull request adds support for configurable session expiration strategies in the Stateful session strategy and unifies session lifetime configuration across both Stateless (JWT) and Stateful (Database) strategies.

Previously, options such as maxAge, maxExpiration, and expirationStrategy were only available under the jwt configuration, making them specific to the Stateless strategy. With this change, session lifetime is now configured at the session level, allowing both session strategies to share the same configuration model while retaining strategy-specific options.

In addition, this PR introduces database-specific options for managing activity updates and session renewal, giving Stateful sessions more control over expiration and last-activity tracking.

Key Changes

  • Added expirationStrategy support for the Stateful session strategy.
  • Moved maxAge, maxDuration (formerly maxExpiration), and expirationStrategy to the top-level session configuration.
  • Added touchInterval for controlling how frequently Stateful sessions update their last activity timestamp.
  • Unified session lifetime configuration across Stateless and Stateful strategies.
  • Improved rolling and sliding expiration behavior, including activity-based renewal and maximum session duration limits.
  • Deprecated jwt.maxAge, jwt.maxExpiration, and jwt.expirationStrategy.

Usage

import { createAuth } from "@aura-stack/auth"
import { PrismaPg } from "@prisma/adapter-pg"
import { prismaAdapter } from "@aura-stack/prisma"
import { PrismaClient } from "@/generated/prisma/client"

const adapterPg = new PrismaPg({
  connectionString: process.env.DATABASE_URL,
})

export const prismaClient = new PrismaClient({
  adapter: adapterPg,
})

export const adapter = prismaAdapter({
  client: prismaClient,
  deleteStrategy: "soft",
})

export const stateless = createAuth({
  oauth: [],
  session: {
    strategy: "jwt",
    maxAge: 60 * 60 * 24 * 25,
    maxDuration: 60 * 60 * 24 * 30,
    expirationStrategy: "sliding",
    slidingThreshold: 0.25,
  },
})

export const stateful = createAuth({
  oauth: [],
  session: {
    strategy: "database",
    adapter,
    maxAge: 60 * 60 * 24 * 25,
    maxDuration: 60 * 60 * 24 * 30,
    expirationStrategy: "sliding",
    database: {
      touchInterval: 5 * 60 * 1000,
    },
  },
})

Warning

The following options have been deprecated under the jwt configuration and will be removed in a future major release:

  • jwt.maxAge
  • jwt.maxExpiration
  • jwt.expirationStrategy

Use the equivalent options under the top-level session configuration instead.

Related PRs

@coderabbitai ignore

@vercel

vercel Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

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

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
auth Skipped Skipped Aug 4, 2026 5:39pm

@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, validation, 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 validation
packages/core/src/shared/errors.ts, packages/core/test/...
Adds invalid sliding-threshold errors and updates tests for session-level expiration settings.
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 accurately identifies the main feature area, although the changes also include stateless expiration and related session options.
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 Outdated
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 thread packages/core/src/session/stateless/getSession.ts
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/CHANGELOG.md`:
- Around line 13-14: Update the stateful session flow in getSession and its
verifyDebounceLastActivity call to pass sessionConfig.touchInterval converted to
milliseconds, so touchSession uses the configured debounce interval instead of
DEFAULT_TOUCH_THRESHOLD_MS. Add a test using a non-default touchInterval that
verifies both the default debounce behavior and the configured interval
behavior.

In `@packages/core/src/shared/assert.ts`:
- Around line 273-275: Update isInvalidSlidingThreshold to reject NaN and other
non-finite numeric values while preserving the existing 0–1 range validation for
finite numbers. Add a regression test alongside the session configuration tests
covering slidingThreshold: NaN through the relevant validation path.
🪄 Autofix

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: eee89bb0-1e39-4895-a7fb-0a911036a5f8

📥 Commits

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

📒 Files selected for processing (8)
  • packages/core/CHANGELOG.md
  • 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/errors.ts
  • packages/core/src/shared/utils/session-strategy.ts
  • packages/core/test/config/session.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/core/src/shared/utils/session-strategy.ts
  • packages/core/src/session/stateful/getSession.ts
  • packages/core/src/@types/session.ts

Comment thread packages/core/CHANGELOG.md
Comment thread packages/core/src/shared/assert.ts
@halvaradop
halvaradop merged commit c9954c8 into master Aug 4, 2026
7 checks passed
@halvaradop
halvaradop deleted the feat/support-expiration-strategy branch August 4, 2026 17:42
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