Skip to content

refactor(core): add dedicated signInCredentials strategy function - #245

Merged
halvaradop merged 1 commit into
masterfrom
refactor/add-sign-in-credentials-fn
Aug 1, 2026
Merged

refactor(core): add dedicated signInCredentials strategy function#245
halvaradop merged 1 commit into
masterfrom
refactor/add-sign-in-credentials-fn

Conversation

@halvaradop

@halvaradop halvaradop commented Aug 1, 2026

Copy link
Copy Markdown
Member

Description

This pull request refactors the credentials sign-in flow by introducing a dedicated signInCredentials strategy for both the Stateless (JWT) and Stateful (Database) session strategies.

Previously, the credentials sign-in flow relied on the shared createSession implementation. While this approach was sufficient for creating authenticated sessions, it coupled credentials authentication with generic session creation logic, making it difficult to introduce validations and behaviors specific to credentials-based authentication.

By separating the credentials flow into its own strategy, the authentication process now has full control over the sign-in lifecycle, enabling cleaner implementations and making it easier to introduce additional features and validations in the future.

Key Changes

  • Introduced a dedicated signInCredentials strategy for the Stateless (JWT) session strategy.
  • Introduced a dedicated signInCredentials strategy for the Stateful (Database) session strategy.
  • Decoupled credentials authentication from the shared createSession implementation.
  • Improved separation of concerns between session creation and credentials authentication.
  • Established a foundation for future credentials-specific features and validations.

Warning

In the Stateful session strategy, the authenticated user is identified by the sub value returned from the credentials.authorize() callback. Within this callback, sub is treated as the unique identifier of the user and is used to retrieve the corresponding database record.

The remaining fields returned by authorize() (such as name, email, image, or custom identity fields) are not persisted or synchronized with the database. They are only used during the authentication process.

This behavior differs from the Stateless strategy, where the returned identity is stored directly in the session token.

Usage

import { createAuth } from "@aura-stack/auth"
import { prismaClient } from "@/lib/prisma"

export const auth = createAuth({
  oauth: [],
  credentials: {
    authorize: async ({ credentials }) => {
      const { username, password } = credentials

      if (!username || !password) {
        return null
      }

      const user = await prismaClient.user.findUnique({
        where: {
          email: username,
        },
      })

      if (!user) {
        return null
      }

      return {
        sub: user.id,
        // ...
      }
    },
  },
})

@coderabbitai ignore

@vercel

vercel Bot commented Aug 1, 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 1, 2026 9:29pm

@coderabbitai

coderabbitai Bot commented Aug 1, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Credential sign-in now uses dedicated stateful and stateless session strategy handlers. Stateful sign-in validates users, creates sessions, and logs progress. The API records structured error metadata. Tests now use existing users and verify session resolution.

Changes

Credential Sign-In

Layer / File(s) Summary
Strategy contract and wiring
packages/core/src/@types/session.ts, packages/core/src/session/stateful/index.ts, packages/core/src/session/stateless/index.ts
SessionStrategy and both strategy factories now expose signInCredentials.
Stateful credential session creation
packages/core/src/session/stateful/signInCredentials.ts, packages/core/src/shared/logger.ts
The stateful handler validates the payload, finds the user, creates device and token data, creates a 15-day active credentials session, and logs start and success events.
Stateless handler and API integration
packages/core/src/session/stateless/signInCredentials.ts, packages/core/src/api/signInCredentials.ts
The stateless handler creates a session from the credential payload. The API delegates token creation to sessionStrategy.signInCredentials and adds normalized error metadata to structured logs.
Credential sign-in validation
packages/core/test/actions/signIn/signInCredentials/stateful.test.ts, packages/core/test/api/stateful/signInCredentials.test.ts, packages/elysia/test/stateful/index.test.ts
Tests use existing users for successful flows, retain redirect and session checks, verify resolved session data, and expect status 400 for missing provider tokens.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SignInAPI
  participant SessionStrategy
  participant StatefulSignInCredentials
  participant UserLookup
  participant SessionStore
  SignInAPI->>SessionStrategy: signInCredentials(payload, request)
  SessionStrategy->>StatefulSignInCredentials: validate credentials
  StatefulSignInCredentials->>UserLookup: find user by sub
  UserLookup-->>StatefulSignInCredentials: return user entity
  StatefulSignInCredentials->>SessionStore: create device and credentials session
  SessionStore-->>SignInAPI: return hashed session token
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
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.
Title check ✅ Passed The title clearly and concisely describes the addition of a dedicated signInCredentials strategy function in core.
✨ 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 refactor/add-sign-in-credentials-fn

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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/core/src/api/signInCredentials.ts (1)

74-107: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Do not log arbitrary credential authorization error messages.

credentials.authorize can throw an error that includes submitted credentials or provider response data. Lines 95 and 106 persist error_message to the configured logger. Keep error_type and the stable error code, but remove the raw exception message from authentication logs.

Proposed fix
-        const error_message = error instanceof Error ? error.message : String(error)
         const headers = new Headers(secureApiHeaders)
...
-                    error_message,
                 },
...
-                error_message,
             },
🤖 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/api/signInCredentials.ts` around lines 74 - 107, Remove the
raw error_message field from both authentication logger structuredData payloads
in the invalid-credentials and failed sign-in branches. Preserve logging of
error_type and the stable error_code, and leave the response behavior unchanged.
🧹 Nitpick comments (1)
packages/core/test/actions/signIn/signInCredentials/stateful.test.ts (1)

23-28: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Use identifier-sensitive user lookup mocks.

Both core suites return the same user for every lookup key. This can allow an incorrect sub or an unverified existing-user path to pass.

  • packages/core/test/actions/signIn/signInCredentials/stateful.test.ts#L23-L28: Make getUserByIdMock return userEntity only for "user-123" and assert that argument.
  • packages/core/test/actions/signIn/signInCredentials/stateful.test.ts#L186-L191: Apply the same conditional lookup and argument assertion.
  • packages/core/test/actions/signIn/signInCredentials/stateful.test.ts#L245-L250: Apply the same conditional lookup and argument assertion.
  • packages/core/test/actions/signIn/signInCredentials/stateful.test.ts#L304-L309: Apply the same conditional lookup and argument assertion.
  • packages/core/test/actions/signIn/signInCredentials/stateful.test.ts#L363-L368: Apply the same conditional lookup and argument assertion.
  • packages/core/test/api/stateful/signInCredentials.test.ts#L23-L28: Make getUserByIdMock return userEntity only for "user-123" and assert that argument.
  • packages/core/test/api/stateful/signInCredentials.test.ts#L232-L237: Apply the same conditional lookup and argument assertion.
  • packages/core/test/api/stateful/signInCredentials.test.ts#L293-L298: Apply the same conditional lookup and argument assertion.
  • packages/core/test/api/stateful/signInCredentials.test.ts#L354-L359: Apply the same conditional lookup and argument assertion.
  • packages/core/test/api/stateful/signInCredentials.test.ts#L415-L420: Apply the same conditional lookup and argument assertion.
🤖 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/test/actions/signIn/signInCredentials/stateful.test.ts` around
lines 23 - 28, Update each getUserByIdMock setup in
packages/core/test/actions/signIn/signInCredentials/stateful.test.ts at lines
23-28, 186-191, 245-250, 304-309, and 363-368, and
packages/core/test/api/stateful/signInCredentials.test.ts at lines 23-28,
232-237, 293-298, 354-359, and 415-420, so the mock returns userEntity only when
called with "user-123" and otherwise does not match; add assertions verifying
getUserByIdMock received the expected "user-123" identifier in every affected
test.
🤖 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/stateful/signInCredentials.ts`:
- Around line 43-94: Update the return value at the end of the sign-in flow to
return the raw secret token generated as secretValue, while continuing to
persist tokenHash in createSession. Keep the existing hashing, logging, and
session creation behavior unchanged so cookie-based lookup can resolve the
stored hash.

---

Outside diff comments:
In `@packages/core/src/api/signInCredentials.ts`:
- Around line 74-107: Remove the raw error_message field from both
authentication logger structuredData payloads in the invalid-credentials and
failed sign-in branches. Preserve logging of error_type and the stable
error_code, and leave the response behavior unchanged.

---

Nitpick comments:
In `@packages/core/test/actions/signIn/signInCredentials/stateful.test.ts`:
- Around line 23-28: Update each getUserByIdMock setup in
packages/core/test/actions/signIn/signInCredentials/stateful.test.ts at lines
23-28, 186-191, 245-250, 304-309, and 363-368, and
packages/core/test/api/stateful/signInCredentials.test.ts at lines 23-28,
232-237, 293-298, 354-359, and 415-420, so the mock returns userEntity only when
called with "user-123" and otherwise does not match; add assertions verifying
getUserByIdMock received the expected "user-123" identifier in every affected
test.
🪄 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: 881da655-38f9-4471-a0ef-79cddf4b7a78

📥 Commits

Reviewing files that changed from the base of the PR and between aab2898 and 9a8d11b.

📒 Files selected for processing (10)
  • packages/core/src/@types/session.ts
  • packages/core/src/api/signInCredentials.ts
  • packages/core/src/session/stateful/index.ts
  • packages/core/src/session/stateful/signInCredentials.ts
  • packages/core/src/session/stateless/index.ts
  • packages/core/src/session/stateless/signInCredentials.ts
  • packages/core/src/shared/logger.ts
  • packages/core/test/actions/signIn/signInCredentials/stateful.test.ts
  • packages/core/test/api/stateful/signInCredentials.test.ts
  • packages/elysia/test/stateful/index.test.ts

Comment thread packages/core/src/session/stateful/signInCredentials.ts
@halvaradop
halvaradop merged commit be5e025 into master Aug 1, 2026
7 checks passed
@halvaradop
halvaradop deleted the refactor/add-sign-in-credentials-fn branch August 1, 2026 21:41
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