Skip to content

chore(backend,nextjs): Improve token handling and optimize verification #6123

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: main
Choose a base branch
from

Conversation

wobsoriano
Copy link
Member

@wobsoriano wobsoriano commented Jun 14, 2025

Description

This pull request builds upon the previous PR #6112 , where we introduced the new null token type in an auth object for tokens not included in the acceptsToken array. In that PR, the changes were limited to returning a new invalid token type in auth(), getAuth() function calls.

In this follow-up PR, we:

  • Add the new null token type handling to the authenticateRequest() call. We have a tokenType property in the authenticateRequest() call state as well, so it just makes sense to include null result in here as well.
  • Optimize the auth process by reducing unnecessary parsing and verification calls early. We are short-circuiting and avoid extra verification steps when token type is not in the acceptsToken array.
  • Maintain and extend test coverage to ensure all edge cases for token type acceptance and invalid token handling are covered.
  • Still backwards compat!

Example:

const requestState = await authenticateRequest(request, { acceptsToken: ['session_token', 'oauth_token'] });
const authObject = requestState.toAuth();

// Someone sent an api key...

// requestState.tokenType === null if the token is not in the accepted array
// authObject.tokenType === null in this case as well

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • New Features
    • Improved handling of invalid or unsupported token types, providing more explicit unauthenticated states when an unaccepted token is detected.
  • Refactor
    • Streamlined authentication logic for handling multiple token types, simplifying code and consolidating token acceptance checks.
    • Converted key authentication functions to arrow functions for clearer control flow.
    • Removed intermediate helpers in async auth data retrieval, inlining logic for better clarity.
  • Bug Fixes
    • Enhanced authentication validation by relying on the authentication state rather than token presence, ensuring more accurate access control.
  • Tests
    • Expanded and standardized test coverage for multiple token types, including parameterized tests and consistent token ID usage.
    • Introduced reusable error mocks and refined test assertions to improve clarity and completeness.
  • Style
    • Standardized token strings in test cases for clarity and consistency.

Copy link

changeset-bot bot commented Jun 14, 2025

🦋 Changeset detected

Latest commit: e601c28

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 11 packages
Name Type
@clerk/backend Minor
@clerk/nextjs Minor
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link

vercel bot commented Jun 14, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
clerk-js-sandbox ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 16, 2025 2:02pm

Copy link
Contributor

coderabbitai bot commented Jun 14, 2025

📝 Walkthrough
## Walkthrough

This change refines token type handling across authentication logic and tests. It introduces explicit handling for invalid or unaccepted token types, updates type signatures to allow `null` token types, and standardizes unauthenticated state representation. Related tests and helper functions are updated for consistent behavior and to improve test coverage for multiple token scenarios.

## Changes

| Files / Areas                                                                                      | Change Summary                                                                                                                                                                                                                                                             |
|--------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `packages/backend/src/tokens/authObjects.ts`, `authStatus.ts`, `request.ts`                      | Refactored token acceptance logic, updated types to allow `null` token type, added explicit handling for invalid tokens, and updated exported/public entity signatures. Introduced early return for invalid tokens in array-acceptance cases.                              |
| `packages/backend/src/tokens/__tests__/request.test-d.ts`, `request.test.ts`                     | Updated test assertions and expectations to reflect new type signatures and unauthenticated state handling, including the addition of `null` as a possible token type.                                                                                                    |
| `packages/nextjs/src/server/data/getAuthDataFromRequest.ts`                                      | Refactored async authentication logic to streamline token type checks, removed helpers, and unified handling of accepted token types and invalid tokens. Used new utility for consistent auth object wrapping.                                                            |
| `packages/nextjs/src/server/protect.ts`                                                          | Simplified unauthorized access checks by relying on `isAuthenticated` instead of token ID or null token type.                                                                                                                                                             |
| `packages/nextjs/src/server/__tests__/clerkMiddleware.test.ts`, `getAuthDataFromRequest.test.ts` | Standardized token strings, expanded test coverage for multiple token types, and added explicit assertions for authentication state and error handling.                                                                                                                  |

## Possibly related PRs

- clerk/javascript#6112: Refactors `getAuthObjectForAcceptedToken`, introduces `InvalidTokenAuthObject`, and updates related types and tests for invalid token and unauthenticated state handling.
- clerk/javascript#6099: Enhances machine authentication object properties and token type handling, related by focus on machine auth structure and token type management.

## Suggested reviewers

- aeliox
- tmilewski

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between efcaa3b and e601c28.

📒 Files selected for processing (1)
  • packages/backend/src/tokens/request.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/backend/src/tokens/request.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@wobsoriano wobsoriano marked this pull request as ready for review June 16, 2025 00:38
@wobsoriano wobsoriano requested review from aeliox and a team as code owners June 16, 2025 00:38
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (7)
packages/backend/src/tokens/__tests__/request.test.ts (1)

1240-1245: Redundant isAuthenticated in expectations

toBeMachineUnauthenticatedToAuth ignores all properties except tokenType.
Adding isAuthenticated: false is harmless but misleading. Consider removing it to keep the test intent clear.

Also applies to: 1290-1295, 1320-1325

packages/backend/src/tokens/authStatus.ts (1)

32-41: Conditional type is clever but hard to scan

ToAuth<T, Authenticated> now handles four cases in one expression.
For maintainability, consider splitting into smaller helper types (e.g. ToAuthNull, ToAuthSession, ToAuthMachine) or at least adding an inline comment that explains each branch.

packages/nextjs/src/server/__tests__/clerkMiddleware.test.ts (1)

480-489: Nit: test token IDs are now tiny – consider clarifying comments

Switching to the shorter IDs (ak_123, oat_123, …) is fine, but it’s easy to lose track of which string represents which token type. A short inline comment next to each header would improve readability.

Example:

[constants.Headers.Authorization]: 'Bearer ak_123', // API key

Also applies to: 528-537, 556-566, 662-670, 685-694, 708-717

packages/backend/src/tokens/request.ts (1)

91-106: Duplicate logic & unnecessary fallback

isTokenTypeInAcceptedArray re-implements isTokenTypeAccepted with extra fallback to session_token.
You can:

  1. Drop the helper altogether and call isTokenTypeAccepted(parsedTokenType ?? TokenType.SessionToken, acceptsToken) directly.
  2. Or keep the helper but at least rename it to indicate the fallback behaviour to avoid surprises for future maintainers.

This will reduce duplication and potential drift.

packages/nextjs/src/server/__tests__/getAuthDataFromRequest.test.ts (2)

42-49: Redundant beforeEach

There’s a top-level beforeEach at lines 42-45 and another one right below at 47-49 doing the exact same vi.clearAllMocks() call.
Remove one of them to avoid confusion.


67-67: Typo in test description

auth obkectauth object.

packages/nextjs/src/server/data/getAuthDataFromRequest.ts (1)

123-129: Potential double work for non-session bearer tokens

If a random bearer token is present and acceptsToken excludes session_token, you correctly return invalidTokenAuthObject.
However, isMachineTokenByPrefix already filtered machine tokens above.
For other random tokens this branch still executes after the verification attempt.
Re-order the checks so that this inexpensive validation happens before any verification calls.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6e9bde8 and a7c8b83.

📒 Files selected for processing (9)
  • packages/backend/src/tokens/__tests__/request.test-d.ts (1 hunks)
  • packages/backend/src/tokens/__tests__/request.test.ts (8 hunks)
  • packages/backend/src/tokens/authObjects.ts (1 hunks)
  • packages/backend/src/tokens/authStatus.ts (5 hunks)
  • packages/backend/src/tokens/request.ts (5 hunks)
  • packages/nextjs/src/server/__tests__/clerkMiddleware.test.ts (6 hunks)
  • packages/nextjs/src/server/__tests__/getAuthDataFromRequest.test.ts (7 hunks)
  • packages/nextjs/src/server/data/getAuthDataFromRequest.ts (3 hunks)
  • packages/nextjs/src/server/protect.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (6)
packages/nextjs/src/server/__tests__/clerkMiddleware.test.ts (3)
packages/backend/src/internal.ts (3)
  • constants (1-1)
  • AuthStatus (39-39)
  • TokenType (18-18)
packages/backend/src/tokens/authStatus.ts (2)
  • AuthStatus (24-28)
  • AuthStatus (30-30)
packages/backend/src/tokens/tokenTypes.ts (2)
  • TokenType (1-6)
  • TokenType (11-11)
packages/backend/src/tokens/__tests__/request.test-d.ts (1)
packages/backend/src/tokens/authStatus.ts (1)
  • RequestState (127-130)
packages/backend/src/tokens/__tests__/request.test.ts (2)
packages/backend/src/tokens/tokenTypes.ts (2)
  • TokenType (1-6)
  • TokenType (11-11)
packages/backend/src/tokens/authStatus.ts (2)
  • AuthErrorReason (105-121)
  • AuthErrorReason (123-123)
packages/nextjs/src/server/__tests__/getAuthDataFromRequest.test.ts (4)
packages/backend/src/internal.ts (3)
  • verifyMachineAuthToken (55-55)
  • AuthenticatedMachineObject (25-25)
  • constants (1-1)
packages/backend/src/tokens/verify.ts (1)
  • verifyMachineAuthToken (248-260)
packages/nextjs/src/server/data/getAuthDataFromRequest.ts (1)
  • getAuthDataFromRequestAsync (87-130)
packages/backend/src/tokens/authObjects.ts (1)
  • AuthenticatedMachineObject (117-128)
packages/backend/src/tokens/authObjects.ts (3)
packages/backend/src/tokens/tokenTypes.ts (2)
  • TokenType (1-6)
  • TokenType (11-11)
packages/backend/src/tokens/types.ts (1)
  • AuthenticateRequestOptions (19-70)
packages/backend/src/tokens/machine.ts (2)
  • isTokenTypeAccepted (59-73)
  • isMachineTokenType (81-83)
packages/nextjs/src/server/data/getAuthDataFromRequest.ts (2)
packages/backend/src/internal.ts (8)
  • isMachineTokenByPrefix (57-57)
  • getMachineTokenType (57-57)
  • invalidTokenAuthObject (34-34)
  • verifyMachineAuthToken (55-55)
  • unauthenticatedMachineObject (33-33)
  • authenticatedMachineObject (32-32)
  • getAuthObjectForAcceptedToken (36-36)
  • TokenType (18-18)
packages/backend/src/tokens/tokenTypes.ts (2)
  • TokenType (1-6)
  • TokenType (11-11)
🔇 Additional comments (2)
packages/backend/src/tokens/__tests__/request.test-d.ts (1)

27-30: Type assertion update is correct

Including null in the expected union keeps the declaration test in sync with the new RequestState definition. Looks good.

packages/nextjs/src/server/protect.ts (1)

148-153: Double-check that isAuthenticated is always present on machine-token auth objects

The old guard relied on id; the new one relies on isAuthenticated.
If any code path creates an AuthenticatedMachineObject that omits isAuthenticated, users will now be rejected. Please verify that:

  1. authenticatedMachineObject in @clerk/backend always sets isAuthenticated: true.
  2. All mocks in unit tests include that flag (most already updated).
  3. Third-party integrators that may construct custom AuthObjects won’t break.

If any of these aren’t guaranteed, add a fallback (authObject.id ?? authObject.isAuthenticated) or ensure the object factory always populates the field.

Copy link

pkg-pr-new bot commented Jun 16, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6123

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6123

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6123

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6123

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6123

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6123

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6123

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6123

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6123

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6123

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6123

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6123

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6123

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6123

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6123

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6123

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6123

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6123

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6123

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6123

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6123

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6123

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6123

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6123

commit: e601c28

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
.changeset/twenty-beds-serve.md (1)

6-7: Fix typo and improve description clarity
Please correct authenticateRequyest() to authenticateRequest(). For readers’ context, you may also mention that this logic is implemented via the signedOutInvalidToken() helper and getAuthObjectForAcceptedToken function.

- Add handling for invalid token types when `acceptsToken` is an array in `authenticateRequyest()`: now returns a clear unauthenticated state (`tokenType: null`) if the token is not in the accepted list.
+ Add handling for invalid token types when `acceptsToken` is an array in `authenticateRequest()`: now returns a clear unauthenticated state (`tokenType: null`) if the token is not in the accepted list (via `signedOutInvalidToken()` / `getAuthObjectForAcceptedToken`).
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a7c8b83 and 96ec7b6.

📒 Files selected for processing (2)
  • .changeset/twenty-beds-serve.md (1 hunks)
  • packages/nextjs/src/server/__tests__/getAuthDataFromRequest.test.ts (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/nextjs/src/server/tests/getAuthDataFromRequest.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (24)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 13)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Static analysis
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
.changeset/twenty-beds-serve.md (1)

1-4: Validate changeset header formatting
The YAML frontmatter correctly lists both packages with a minor version bump, following the Changeset specification.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
packages/nextjs/src/server/__tests__/getAuthDataFromRequest.test.ts (4)

23-30: Prefer HeadersInit over any and simplify URL handling

headers?: any on MockRequestParams weakens type-safety. Use HeadersInit so callers can pass either Headers or a plain record.
Also, new URL(url, 'https://www.clerk.com').toString() can be shortened: NextRequest accepts a URL, so the extra .toString() isn’t needed.

-type MockRequestParams = {
+type MockRequestParams = {
   url: string;
   appendDevBrowserCookie?: boolean;
   method?: string;
-  headers?: any;
+  headers?: HeadersInit;
 };
…
-return new NextRequest(new URL(url, 'https://www.clerk.com').toString(), { method, headers: headersWithCookie });
+return new NextRequest(new URL(url, 'https://www.clerk.com'), { method, headers: headersWithCookie });

32-40: Tighten the mock error’s typing

machineTokenErrorMock is currently any[]. Add as const (or an explicit type) so accidental mutation is prevented and IntelliSense retains literal values.

-const machineTokenErrorMock = [
+const machineTokenErrorMock = [
   {
     message: 'Token type mismatch',
     code: 'token-invalid',
     status: 401,
     name: 'MachineTokenVerificationError',
     getFullMessage: () => 'Token type mismatch',
-  },
-];
+  },
+] as const;

94-96: Avoid hard-coding the generic in the cast

If the implementation ever changes to return another machine-compatible token type, the cast will silently lie.
Use typeof auth.tokenType (or keep the cast but reference the variable) to stay future-proof.

-expect((auth as AuthenticatedMachineObject<'api_key'>).id).toBe('ak_id123');
+expect(
+  (auth as AuthenticatedMachineObject<typeof auth.tokenType>).id,
+).toBe('ak_id123');

196-208: Assert that machine-token verification is skipped for session tokens

This test exercises the session-token path. Verifying that the machine-token verifier is not called clarifies intent and protects against accidental routing changes.

 expect((auth as SignedOutAuthObject).userId).toBeNull();
 expect(auth.isAuthenticated).toBe(false);
+expect(verifyMachineAuthToken).not.toHaveBeenCalled();
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 96ec7b6 and 570c6c7.

📒 Files selected for processing (3)
  • packages/backend/src/tokens/request.ts (5 hunks)
  • packages/nextjs/src/server/__tests__/getAuthDataFromRequest.test.ts (7 hunks)
  • packages/nextjs/src/server/data/getAuthDataFromRequest.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/backend/src/tokens/request.ts
  • packages/nextjs/src/server/data/getAuthDataFromRequest.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
packages/nextjs/src/server/__tests__/getAuthDataFromRequest.test.ts (1)

47-61: Validate the short-circuit by asserting verifyMachineAuthToken is untouched

The essence of this test is the early exit when the incoming token type is not accepted.
Assert that no verification occurred; it both documents intent and guards against regressions.

 expect(auth.tokenType).toBeNull();
 expect(auth.isAuthenticated).toBe(false);
+expect(verifyMachineAuthToken).not.toHaveBeenCalled();

@wobsoriano wobsoriano changed the title chore(backend,nextjs): Clean up request state and auth objects chore(backend,nextjs): Improve token handling and optimize verification Jun 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants