Skip to content

Conversation

wobsoriano
Copy link
Member

@wobsoriano wobsoriano commented Aug 29, 2025

Description

Adds machine authentication support to the Astro SDK

Example usage accepting any token type:

export const GET: APIRoute = ({ locals }) => {
  const authObject = locals.auth({ acceptsToken: 'any' })

  if (authObject.tokenType === 'session_token') {
    console.log('this is session token from a user')
  } else {
    console.log('this is some other type of machine token')
    console.log('more specifically, a ' + authObject.tokenType)
  }

  return new Response(JSON.stringify({}))
}

Example accepting api keys:

export const GET: APIRoute = ({ locals }) => {
  const { userId } = locals.auth({ acceptsToken: 'api_keys' })

  return new Response(JSON.stringify({ userId }))
}

Resolves USER-2457

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

    • Machine authentication added (api_key, oauth_token, m2m_token, session_token); session_token remains default.
    • locals.auth() gains acceptsToken (single, array, or 'any') and exposes tokenType for branching.
  • Refactor

    • Unified auth flow so session vs. machine tokens are handled appropriately; sign-in redirect applies only to session tokens.
    • currentUser now resolves via locals.auth().
  • Removed

    • Legacy get-auth helper removed.
  • Tests

    • Integration tests added for machine auth; package minor version bumped.

Copy link

changeset-bot bot commented Aug 29, 2025

🦋 Changeset detected

Latest commit: bd9642b

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

This PR includes changesets to release 1 package
Name Type
@clerk/astro Minor

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
Contributor

coderabbitai bot commented Aug 29, 2025

Walkthrough

Adds machine-token support to Astro auth: locals.auth() accepts an acceptsToken option and returns an AuthObject with tokenType; middleware, typings, current-user logic, integration tests, and a changeset were updated; legacy get-auth module was removed and AuthFn / AuthOptions types added. (≤50 words)

Changes

Cohort / File(s) Summary
Astro locals & typings
packages/astro/env.d.ts, packages/astro/src/server/types.ts, packages/astro/src/server/index.ts
Replace App.Locals.auth signature with exported AuthFn; add AuthOptions and AuthFn overloads supporting acceptsToken; add deprecated GetAuthReturn alias and re-export AuthFn.
Middleware wiring
packages/astro/src/server/clerk-middleware.ts
decorateAstroLocal now accepts an authObjectFn, wires locals.auth as AuthFn, uses getAuthObjectForAcceptedToken to resolve token types, stores auth object via async storage, and defaults authenticate options to acceptsToken: 'any'.
Removed public surface
packages/astro/src/server/get-auth.ts
Remove legacy get-auth module and its createGetAuth/getAuth exports and related JWT/session decoding logic.
Current user resolution
packages/astro/src/server/current-user.ts
createCurrentUser signature changed to take context only and now calls context.locals.auth() to obtain userId before fetching the user.
Integration tests & example route
integration/tests/astro/machine.test.ts, test app src/pages/api/auth/me.ts, src/middleware.ts (test app)
Add tests and example API route using locals.auth({ acceptsToken: 'api_key' }); cover missing/invalid/valid API-key flows asserting { userId, tokenType }; add middleware example protecting API routes.
Meta / changeset
.changeset/floppy-tigers-push.md
Document new token types (api_key, oauth_token, m2m_token, session_token), the acceptsToken option, default behavior, example usage, and a minor version bump for @clerk/astro.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant Middleware as ClerkMiddleware
  participant LocalsAuth as locals.auth(options)
  participant AuthSvc as getAuthObjectForAcceptedToken

  Client->>Middleware: HTTP request
  Note right of Middleware #EFEFEF: middleware builds authObjectFn and decorates locals
  Client->>LocalsAuth: call auth({ acceptsToken })
  LocalsAuth->>AuthSvc: resolve auth object from headers/cookies with acceptsToken
  Note right of AuthSvc #DDFFDD: determine TokenType (session_token | api_key | oauth_token | m2m_token)
  alt TokenType == session_token
    AuthSvc-->>LocalsAuth: SessionAuthObject (tokenType=session_token)
    Note right of LocalsAuth #FFF4D6: attach redirectToSignIn
  else TokenType in (api_key, oauth_token, m2m_token)
    AuthSvc-->>LocalsAuth: MachineAuthObject (tokenType != session_token)
  else no acceptable token
    AuthSvc-->>LocalsAuth: InvalidTokenAuthObject
  end
  LocalsAuth-->>Client: return AuthObject (includes tokenType)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Assessment against linked issues

Objective (issue) Addressed Explanation
Add support for machine auth in Astro: Astro.locals.auth() with acceptsToken option (USER-2457)

"I thump my paws at tokens four,
Keys, OAuth, machine—sessions and more.
I sniff the header, pick the right track,
Sessions may redirect, machines come back.
A carrot blink — auth hops on guard. 🥕🐇"

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch rob/user-2457-astro-machine-auth

🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

Copy link

vercel bot commented Aug 29, 2025

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

1 Skipped Deployment
Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Skipped Skipped Sep 2, 2025 7:54pm

@wobsoriano wobsoriano marked this pull request as ready for review August 29, 2025 23:46
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: 7

Caution

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

⚠️ Outside diff range comments (1)
packages/astro/src/server/clerk-middleware.ts (1)

163-172: Do not override user-provided acceptsToken; default only when undefined.
Current code forces 'any' and can unintentionally broaden acceptance, weakening auth constraints.

Apply:

   return {
     ...options,
     secretKey: options.secretKey || getSafeEnv(context).sk,
     publishableKey: options.publishableKey || getSafeEnv(context).pk,
     signInUrl: options.signInUrl || getSafeEnv(context).signInUrl,
     signUpUrl: options.signUpUrl || getSafeEnv(context).signUpUrl,
     ...handleMultiDomainAndProxy(clerkRequest, options, context),
-    acceptsToken: 'any',
+    acceptsToken: options.acceptsToken ?? 'any',
   };
🧹 Nitpick comments (7)
packages/astro/env.d.ts (1)

9-11: Add JSDoc to clarify overloads and redirectToSignIn availability.
Helps consumers understand that redirectToSignIn is only present for session_token when no acceptsToken is provided or when it includes session_token.

Apply:

   interface Locals {
     authToken: string | null;
     authStatus: string;
     authMessage: string | null;
     authReason: string | null;
-    auth: import('@clerk/astro/server').AuthFn;
+    /**
+     * Authenticate the request.
+     * - Without options: returns a session auth object including `redirectToSignIn`.
+     * - With `acceptsToken`: narrows to the allowed token types; `redirectToSignIn` is only present for `session_token`.
+     */
+    auth: import('@clerk/astro/server').AuthFn;
     currentUser: () => Promise<import('@clerk/astro/server').User | null>;
   }
packages/astro/src/server/types.ts (1)

35-69: Document redirectToSignIn availability in overload docs.
Small doc improvement to prevent misuse when selecting machine tokens.

Apply:

 export interface AuthFn {
   /**
    * @example
    * const auth = await context.locals.auth({ acceptsToken: ['session_token', 'api_key'] })
+   * Note: `redirectToSignIn` is only present when the resolved token is `session_token`.
    */
   <T extends TokenType[]>(
packages/astro/src/server/clerk-middleware.ts (2)

262-292: Gate redirectToSignIn only for session_token: good—minor nit to avoid recomputing.
Reuse the existing authObject’s sessionStatus instead of calling requestState.toAuth() again.

Apply:

-          sessionStatus: requestState.toAuth()?.sessionStatus,
+          sessionStatus: authObject.sessionStatus,

262-292: Optional: avoid passing undefined acceptsToken to improve overload inference.
Skip adding the property when not provided to favor the default session overload at type level.

Apply:

-  context.locals.auth = (({ acceptsToken, treatPendingAsSignedOut }: AuthOptions = {}) => {
-    const authObject = getAuth(clerkRequest, rawAuthObject, context.locals, { treatPendingAsSignedOut, acceptsToken });
+  context.locals.auth = (({ acceptsToken, treatPendingAsSignedOut }: AuthOptions = {}) => {
+    const opts = acceptsToken === undefined ? { treatPendingAsSignedOut } : { treatPendingAsSignedOut, acceptsToken };
+    const authObject = getAuth(clerkRequest, rawAuthObject, context.locals, opts);
packages/astro/src/server/get-auth.ts (3)

52-58: Harden Authorization parsing (case-insensitive “Bearer”, trim) and compute a boolean.
Current parsing can miss “bearer” (lowercase) and may retain stray spaces. Also, hasMachineToken becomes a string|boolean. Normalize and ensure boolean.

-    const bearerToken = req.headers.get(constants.Headers.Authorization)?.replace('Bearer ', '');
-    const machineAuthObject = handleMachineToken(bearerToken, rawAuthObject, acceptsToken, options);
+    const rawAuthz = req.headers.get(constants.Headers.Authorization) ?? req.headers.get('authorization');
+    const bearerToken = rawAuthz?.replace(/^Bearer\s+/i, '').trim();
+    const machineAuthObject = handleMachineToken(bearerToken, rawAuthObject, acceptsToken, options);

And in handleMachineToken:

-  const hasMachineToken = bearerToken && isMachineTokenByPrefix(bearerToken);
+  const hasMachineToken = Boolean(bearerToken) && isMachineTokenByPrefix(bearerToken!);

75-80: Type the options param instead of Record<string, any>.
Strengthen types for better DX and maintainability.

-import type { AuthenticateRequestOptions, MachineTokenType } from '@clerk/backend/internal';
+import type { AuthenticateRequestOptions, MachineTokenType, AuthenticateContext } from '@clerk/backend/internal';
...
-  options: Record<string, any>,
+  options: Partial<AuthenticateContext> & {
+    authStatus: AuthStatus;
+    authMessage?: string;
+    authReason?: string;
+    secretKey?: string;
+  },

97-100: Preserve has() behavior from the underlying auth object.
Overriding has to always return false changes semantics and could regress permission checks for machine tokens.

-      has: () => false,
+      // Preserve original has() if present
+      has: authObject.has,
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 53dadcf and c972db6.

📒 Files selected for processing (6)
  • .changeset/floppy-tigers-push.md (1 hunks)
  • packages/astro/env.d.ts (1 hunks)
  • packages/astro/src/server/clerk-middleware.ts (6 hunks)
  • packages/astro/src/server/get-auth.ts (2 hunks)
  • packages/astro/src/server/index.ts (1 hunks)
  • packages/astro/src/server/types.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/astro/src/server/index.ts
  • packages/astro/env.d.ts
  • packages/astro/src/server/types.ts
  • packages/astro/src/server/get-auth.ts
  • packages/astro/src/server/clerk-middleware.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/astro/src/server/index.ts
  • packages/astro/env.d.ts
  • packages/astro/src/server/types.ts
  • packages/astro/src/server/get-auth.ts
  • packages/astro/src/server/clerk-middleware.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/astro/src/server/index.ts
  • packages/astro/env.d.ts
  • packages/astro/src/server/types.ts
  • packages/astro/src/server/get-auth.ts
  • packages/astro/src/server/clerk-middleware.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/astro/src/server/index.ts
  • packages/astro/env.d.ts
  • packages/astro/src/server/types.ts
  • packages/astro/src/server/get-auth.ts
  • packages/astro/src/server/clerk-middleware.ts
packages/**/index.{js,ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use tree-shaking friendly exports

Files:

  • packages/astro/src/server/index.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/astro/src/server/index.ts
  • packages/astro/env.d.ts
  • packages/astro/src/server/types.ts
  • packages/astro/src/server/get-auth.ts
  • packages/astro/src/server/clerk-middleware.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/astro/src/server/index.ts
  • packages/astro/env.d.ts
  • packages/astro/src/server/types.ts
  • packages/astro/src/server/get-auth.ts
  • packages/astro/src/server/clerk-middleware.ts
**/index.ts

📄 CodeRabbit inference engine (.cursor/rules/react.mdc)

Use index.ts files for clean imports but avoid deep barrel exports

Avoid barrel files (index.ts re-exports) as they can cause circular dependencies

Files:

  • packages/astro/src/server/index.ts
.changeset/**

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/floppy-tigers-push.md
🧬 Code graph analysis (3)
packages/astro/src/server/types.ts (2)
packages/types/src/session.ts (1)
  • PendingSessionOptions (34-40)
packages/astro/src/server/index.ts (1)
  • AuthFn (41-41)
packages/astro/src/server/get-auth.ts (7)
packages/tanstack-react-start/src/server/getAuth.ts (1)
  • getAuth (11-26)
packages/express/src/getAuth.ts (1)
  • getAuth (18-26)
packages/fastify/src/getAuth.ts (1)
  • getAuth (14-22)
packages/backend/src/tokens/authObjects.ts (5)
  • AuthObject (161-166)
  • invalidTokenAuthObject (362-370)
  • signedOutAuthObject (224-245)
  • getAuthObjectFromJwt (438-449)
  • getAuthObjectForAcceptedToken (462-492)
packages/backend/src/tokens/tokenTypes.ts (3)
  • TokenType (1-6)
  • TokenType (11-11)
  • MachineTokenType (20-20)
packages/backend/src/tokens/types.ts (2)
  • AuthenticateRequestOptions (19-75)
  • MachineAuthObject (186-188)
packages/backend/src/tokens/machine.ts (1)
  • isMachineTokenByPrefix (21-23)
packages/astro/src/server/clerk-middleware.ts (5)
packages/astro/src/server/types.ts (2)
  • AuthOptions (29-29)
  • AuthFn (35-69)
packages/astro/src/server/get-auth.ts (1)
  • getAuth (112-114)
packages/tanstack-react-start/src/server/getAuth.ts (1)
  • getAuth (11-26)
packages/backend/src/tokens/tokenTypes.ts (2)
  • TokenType (1-6)
  • TokenType (11-11)
packages/backend/src/createRedirect.ts (2)
  • RedirectFun (67-67)
  • createRedirect (85-141)
🔇 Additional comments (4)
packages/astro/src/server/types.ts (1)

29-34: Nice: unified AuthOptions and explicit SessionAuthObjectWithRedirect.
The composition with PendingSessionOptions and AuthenticateRequestOptions['acceptsToken'] makes the overloads clear.

packages/astro/src/server/clerk-middleware.ts (1)

103-104: OK to pass rawAuthObject into locals decoration.
Wiring raw auth to the locals-bound getter makes token-narrowing possible per call.

packages/astro/src/server/get-auth.ts (2)

1-12: Imports look solid (type-only where appropriate).
No issues spotted in the import set; consistent with tree-shaking and type-only import guidance.


72-73: Return value OK.
Factory pattern and export look fine after the signature change.

Copy link

pkg-pr-new bot commented Aug 30, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: bd9642b

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

♻️ Duplicate comments (1)
packages/astro/src/server/get-auth.ts (1)

74-103: Machine path: type safety, secret redaction, and guard on raw auth token type.

  • Unsafe cast to MachineAuthObject; the result might be invalid or signed-out. Return AuthObject instead.
  • debug() leaks secretKey via options; redact it.
  • Ensure rawAuthObject corresponds to a non-session token before reconstructing.
-const handleMachineToken = (
+const handleMachineToken = (
   bearerToken: string | undefined,
   rawAuthObject: AuthObject | undefined,
   acceptsToken: NonNullable<AuthenticateRequestOptions['acceptsToken']>,
-  options: Record<string, any>,
-): MachineAuthObject<MachineTokenType> | null => {
+  options: Record<string, unknown>,
+): AuthObject | null => {
   const hasMachineToken = bearerToken && isMachineTokenByPrefix(bearerToken);
 
   const acceptsOnlySessionToken =
     acceptsToken === TokenType.SessionToken ||
     (Array.isArray(acceptsToken) && acceptsToken.length === 1 && acceptsToken[0] === TokenType.SessionToken);
 
-  // Reconstruct machine auth object here since edge middleware serializes auth object
-  if (hasMachineToken && rawAuthObject && !acceptsOnlySessionToken) {
+  // Reconstruct machine auth object here since edge middleware serializes auth object
+  const isRawMachine = !!rawAuthObject?.tokenType && rawAuthObject.tokenType !== TokenType.SessionToken;
+  if (hasMachineToken && rawAuthObject && isRawMachine && !acceptsOnlySessionToken) {
     const authObject = getAuthObjectForAcceptedToken({
       authObject: {
         ...rawAuthObject,
-        debug: () => options,
+        debug: () => {
+          const { secretKey: _sk, ...safe } = (options as Record<string, unknown>) || {};
+          return safe;
+        },
       },
       acceptsToken,
     });
-    return {
-      ...authObject,
-      getToken: () => (authObject.isAuthenticated ? Promise.resolve(bearerToken) : Promise.resolve(null)),
-      has: () => false,
-    } as MachineAuthObject<MachineTokenType>;
+    return {
+      ...authObject,
+      getToken: () => (authObject.isAuthenticated ? Promise.resolve(bearerToken) : Promise.resolve(null)),
+      has: () => false,
+    } as AuthObject;
   }
 
   return null;
🧹 Nitpick comments (1)
packages/astro/src/server/current-user.ts (1)

2-2: Prefer public exports over internal paths (if available).

If TokenType is publicly exported from '@clerk/backend', use that instead of '@clerk/backend/internal' to avoid coupling to internals. If not available, keep as-is.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c972db6 and cc4ef8e.

📒 Files selected for processing (4)
  • packages/astro/env.d.ts (1 hunks)
  • packages/astro/src/server/clerk-middleware.ts (6 hunks)
  • packages/astro/src/server/current-user.ts (1 hunks)
  • packages/astro/src/server/get-auth.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/astro/env.d.ts
  • packages/astro/src/server/clerk-middleware.ts
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/astro/src/server/current-user.ts
  • packages/astro/src/server/get-auth.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/astro/src/server/current-user.ts
  • packages/astro/src/server/get-auth.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/astro/src/server/current-user.ts
  • packages/astro/src/server/get-auth.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/astro/src/server/current-user.ts
  • packages/astro/src/server/get-auth.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/astro/src/server/current-user.ts
  • packages/astro/src/server/get-auth.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/astro/src/server/current-user.ts
  • packages/astro/src/server/get-auth.ts
🧬 Code graph analysis (2)
packages/astro/src/server/current-user.ts (1)
packages/astro/src/server/get-auth.ts (1)
  • getAuth (111-113)
packages/astro/src/server/get-auth.ts (4)
packages/backend/src/tokens/tokenTypes.ts (3)
  • TokenType (1-6)
  • TokenType (11-11)
  • MachineTokenType (20-20)
packages/backend/src/tokens/types.ts (1)
  • AuthenticateRequestOptions (19-75)
packages/backend/src/tokens/authObjects.ts (5)
  • AuthObject (161-166)
  • invalidTokenAuthObject (362-370)
  • signedOutAuthObject (224-245)
  • getAuthObjectFromJwt (438-449)
  • getAuthObjectForAcceptedToken (462-492)
packages/backend/src/tokens/machine.ts (1)
  • isMachineTokenByPrefix (21-23)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/astro/src/server/get-auth.ts (1)

51-57: locals.__internal_authObject is populated by the middleware
It’s assigned in clerk-middleware.ts (line 262) via context.locals.__internal_authObject = JSON.parse(JSON.stringify(rawAuthObject));, matching the env.d.ts declaration.

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

♻️ Duplicate comments (1)
packages/astro/src/server/current-user.ts (1)

8-9: Add explicit return type and JSDoc for the exported factory.

This is a public export; per guidelines, it should declare its return type and have JSDoc.

-export const createCurrentUser = (req: Request, context: APIContext) => {
+/**
+ * Returns a getter that resolves the current user for session-token auth only.
+ * Rejects all machine tokens.
+ * @public
+ */
+export const createCurrentUser = (req: Request, context: APIContext): () => Promise<User | null> => {
🧹 Nitpick comments (2)
packages/astro/src/server/current-user.ts (2)

16-21: Optionally normalize “user not found” to null.

getUser likely throws on 404. Since this helper’s contract is Promise<User | null>, consider mapping 404 to null for consistency.

-    return clerkClient(context).users.getUser(userId);
+    try {
+      return await clerkClient(context).users.getUser(userId);
+    } catch (e) {
+      if (typeof e === 'object' && e && 'status' in e && (e as { status?: number }).status === 404) {
+        return null;
+      }
+      throw e;
+    }

2-2: Export TokenType from the public API
No public entrypoint in @clerk/backend re-exports TokenType (it’s only in @clerk/backend/internal). In packages/backend/src/index.ts add:

export type { TokenType } from './internal';

then update this import:

-import { TokenType } from '@clerk/backend/internal';
+import { TokenType } from '@clerk/backend';
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between cc4ef8e and cd41ae2.

📒 Files selected for processing (1)
  • packages/astro/src/server/current-user.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/astro/src/server/current-user.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/astro/src/server/current-user.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/astro/src/server/current-user.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/astro/src/server/current-user.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/astro/src/server/current-user.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/astro/src/server/current-user.ts
🧬 Code graph analysis (1)
packages/astro/src/server/current-user.ts (1)
packages/astro/src/server/get-auth.ts (1)
  • getAuth (111-113)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (27)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Static analysis
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/astro/src/server/current-user.ts (1)

10-14: Good: explicit gating to SessionToken at call site and at runtime.

Passing acceptsToken: TokenType.SessionToken and re-checking authObject.tokenType ensures machine tokens never reach user resolution. LGTM.

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 (5)
integration/tests/astro/machine.test.ts (5)

2-2: Avoid importing internals; assert on public surface instead.

@clerk/backend/internal is unstable. Prefer a public export or assert the literal returned by the API.

Option A (if TokenType is publicly exported):

-import { TokenType } from '@clerk/backend/internal';
+import { TokenType } from '@clerk/backend';

Option B (decouple from enums):

-import { TokenType } from '@clerk/backend/internal';
+// Avoid internal import; assert literal token type instead.

And update the assertion:

-    expect(apiKeyData.tokenType).toBe(TokenType.ApiKey);
+    expect(apiKeyData.tokenType).toBe('api_key');

27-31: Fix typo: “unauthorized”.

Minor readability nit.

-        const unautorized = () =>
+        const unauthorized = () =>
             new Response('Unauthorized', {
                 status: 401,
             });
@@
-            if (!userId) {
-                return unautorized();
+            if (!userId) {
+                return unauthorized();

Also applies to: 35-37


82-85: Assert status before parsing JSON to improve failure signals.

If the route unexpectedly returns non‑JSON on error, res.json() will throw and mask the HTTP status.

-    const apiKeyData = await res.json();
-    expect(res.status()).toBe(200);
+    expect(res.status()).toBe(200);
+    const apiKeyData = await res.json();

11-11: Parallel mode may be brittle for a shared dev app.

All tests hit the same dev server; keep this serial unless we’re confident the server is reentrant under concurrent auth failures.

-  test.describe.configure({ mode: 'parallel' });
+  test.describe.configure({ mode: 'serial' });

75-86: Optional: Add coverage for acceptsToken: 'any' path.

Validate that “any” accepts API keys and that tokenType reflects the source.

Example (append a new test):

+  test('should work with acceptsToken: "any"', async ({ request }) => {
+    const url = new URL('/api/auth/me', app.serverUrl);
+    const res = await request.get(url.toString(), {
+      headers: { Authorization: `Bearer ${fakeAPIKey.secret}` },
+    });
+    expect(res.status()).toBe(200);
+    const data = await res.json();
+    expect(data.userId).toBe(fakeBapiUser.id);
+    expect(data.tokenType).toBe('api_key');
+  });
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7605b24 and 5d4b2fa.

📒 Files selected for processing (1)
  • integration/tests/astro/machine.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • integration/tests/astro/machine.test.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • integration/tests/astro/machine.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • integration/tests/astro/machine.test.ts
integration/**

📄 CodeRabbit inference engine (.cursor/rules/global.mdc)

Framework integration templates and E2E tests should be placed under the integration/ directory

Files:

  • integration/tests/astro/machine.test.ts
integration/**/*

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

End-to-end tests and integration templates must be located in the 'integration/' directory.

Files:

  • integration/tests/astro/machine.test.ts
integration/**/*.{test,spec}.{js,ts}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Integration tests should use Playwright.

Files:

  • integration/tests/astro/machine.test.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • integration/tests/astro/machine.test.ts
🧬 Code graph analysis (1)
integration/tests/astro/machine.test.ts (3)
integration/models/application.ts (1)
  • Application (7-7)
integration/presets/index.ts (1)
  • appConfigs (14-30)
integration/testUtils/index.ts (1)
  • createTestUtils (24-86)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
integration/tests/astro/machine.test.ts (1)

33-33: Confirm acceptsToken literal (‘api_key’ vs ‘api_keys’).

PR text shows ‘api_keys’ while this route uses ‘api_key’. Align with the actual union in the Astro SDK types.

If the correct literal is plural:

-            const { userId, tokenType } = await locals.auth({ acceptsToken: 'api_key' });
+            const { userId, tokenType } = await locals.auth({ acceptsToken: 'api_keys' });

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

♻️ Duplicate comments (3)
packages/astro/src/server/get-auth.ts (3)

56-61: Early invalid return for non-machine bearer token is acceptable.

Matches the intended behavior discussed previously.


62-67: Consider enforcing acceptsToken on the final session auth object.

To make policy uniform for cookie-based sessions too, gate via getAuthObjectForAcceptedToken. If the current behavior (allowing session tokens when cookies are used even if excluded) is intentional, please document it.

-    // Handle session tokens
-    if (authStatus !== AuthStatus.SignedIn) {
-      return signedOutAuthObject(options);
-    }
-    return getAuthObjectFromJwt(decodeJwt(authToken as string), { ...options, treatPendingAsSignedOut });
+    // Handle session tokens (apply acceptsToken uniformly)
+    const sessionAuthObject =
+      authStatus !== AuthStatus.SignedIn
+        ? signedOutAuthObject(options)
+        : getAuthObjectFromJwt(decodeJwt(authToken as string), { ...options, treatPendingAsSignedOut });
+    return getAuthObjectForAcceptedToken({ authObject: sessionAuthObject, acceptsToken });

88-90: Do not expose secretKey via debug().

options includes secretKey; returning it risks leakage in logs/tooling.

-        debug: () => options,
+        debug: () => {
+          const { secretKey: _sk, ...safe } = options as Record<string, unknown>;
+          return safe;
+        },
🧹 Nitpick comments (3)
packages/astro/src/server/get-auth.ts (3)

41-47: Avoid repeated getSafeEnv(locals) calls.

Minor clarity/perf: cache once.

-    const options = {
-      authStatus,
-      apiUrl: getSafeEnv(locals).apiUrl,
-      apiVersion: getSafeEnv(locals).apiVersion,
-      authMessage,
-      secretKey: opts?.secretKey || getSafeEnv(locals).sk,
-      authReason,
-    };
+    const env = getSafeEnv(locals);
+    const options = {
+      authStatus,
+      apiUrl: env.apiUrl,
+      apiVersion: env.apiVersion,
+      authMessage,
+      secretKey: opts?.secretKey ?? env.sk,
+      authReason,
+    };

49-55: Parse Bearer token robustly (case/whitespace).

Current replace('Bearer ', '') can misparse; use a regex.

-    const bearerToken = req.headers.get(constants.Headers.Authorization)?.replace('Bearer ', '');
+    const authz = req.headers.get(constants.Headers.Authorization) || '';
+    const match = authz.match(/^\s*Bearer\s+(.+)\s*$/i);
+    const bearerToken = match?.[1];

72-77: Tighten type for options param.

Prefer unknown (or a proper internal type) over any.

-  options: Record<string, any>,
+  options: Record<string, unknown>,
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5d4b2fa and 525e28e.

📒 Files selected for processing (3)
  • integration/tests/astro/machine.test.ts (1 hunks)
  • packages/astro/src/server/get-auth.ts (2 hunks)
  • packages/astro/src/server/types.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • integration/tests/astro/machine.test.ts
  • packages/astro/src/server/types.ts
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/astro/src/server/get-auth.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/astro/src/server/get-auth.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/astro/src/server/get-auth.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/astro/src/server/get-auth.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/astro/src/server/get-auth.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/astro/src/server/get-auth.ts
🧬 Code graph analysis (1)
packages/astro/src/server/get-auth.ts (4)
packages/backend/src/tokens/types.ts (2)
  • AuthenticateRequestOptions (19-75)
  • MachineAuthObject (186-188)
packages/backend/src/tokens/authObjects.ts (5)
  • AuthObject (161-166)
  • invalidTokenAuthObject (362-370)
  • signedOutAuthObject (224-245)
  • getAuthObjectFromJwt (438-449)
  • getAuthObjectForAcceptedToken (462-492)
packages/backend/src/tokens/tokenTypes.ts (3)
  • TokenType (1-6)
  • TokenType (11-11)
  • MachineTokenType (20-20)
packages/backend/src/tokens/machine.ts (1)
  • isMachineTokenByPrefix (21-23)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/astro/src/server/get-auth.ts (2)

1-12: Imports look good.

Type-only imports are used correctly; runtime imports align with usage.


20-27: Factory + inner signature are clear.

Explicit return type on the inner getAuth is good for TS; no further action.

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

♻️ Duplicate comments (1)
packages/astro/src/server/current-user.ts (1)

7-7: Add explicit return type and brief JSDoc on the exported factory.

Keeps the API surface clear and aligns with the guidelines. This was requested previously; re-applying after the signature change.

- export const createCurrentUser = (context: APIContext) => {
+ /**
+  * Returns a getter that resolves the current user for session-token auth only.
+  * @public
+  */
+ export const createCurrentUser = (context: APIContext): (() => Promise<User | null>) => {
🧹 Nitpick comments (4)
packages/astro/src/server/index.ts (1)

40-46: Deprecation type leaks internal types in public .d.ts — consider shielding or verify acceptability.

GetAuthReturn references @clerk/backend/internal types; consumers may see internal import paths in their type hints. If feasible, re-export a stable replacement (e.g., AuthObject) here or annotate deprecation with removal timeline and keep this only temporarily. At minimum, confirm this exposure is acceptable for Astro.

packages/astro/src/server/clerk-middleware.ts (3)

117-120: Avoid double toAuth() calls and keep ALS in sync with the session-only surface.

Reuse baseAuthObj from above for ALS; prevents redundant work and keeps consistency.

-    const asyncAuthObject =
-      authObjectFn().tokenType === TokenType.SessionToken ? authObjectFn() : signedOutAuthObject({});
+    const asyncAuthObject =
+      baseAuthObj.tokenType === TokenType.SessionToken ? baseAuthObj : signedOutAuthObject({});

272-304: Carry treatPendingAsSignedOut through to sessionStatus for consistency.

Use the same pending-session treatment when building the redirect payload.

-          sessionStatus: requestState.toAuth()?.sessionStatus,
+          sessionStatus: requestState.toAuth({ treatPendingAsSignedOut })?.sessionStatus,

324-329: Content-Type check should handle charset.

Use an includes/prefix check to cover values like text/html; charset=utf-8.

-  if (res.headers.get('content-type') === 'text/html') {
+  if (res.headers.get('content-type')?.includes('text/html')) {
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 62bba3d and 103aa25.

📒 Files selected for processing (4)
  • packages/astro/src/server/clerk-middleware.ts (6 hunks)
  • packages/astro/src/server/current-user.ts (1 hunks)
  • packages/astro/src/server/get-auth.ts (0 hunks)
  • packages/astro/src/server/index.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • packages/astro/src/server/get-auth.ts
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/astro/src/server/current-user.ts
  • packages/astro/src/server/index.ts
  • packages/astro/src/server/clerk-middleware.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/astro/src/server/current-user.ts
  • packages/astro/src/server/index.ts
  • packages/astro/src/server/clerk-middleware.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/astro/src/server/current-user.ts
  • packages/astro/src/server/index.ts
  • packages/astro/src/server/clerk-middleware.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/astro/src/server/current-user.ts
  • packages/astro/src/server/index.ts
  • packages/astro/src/server/clerk-middleware.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/astro/src/server/current-user.ts
  • packages/astro/src/server/index.ts
  • packages/astro/src/server/clerk-middleware.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/astro/src/server/current-user.ts
  • packages/astro/src/server/index.ts
  • packages/astro/src/server/clerk-middleware.ts
packages/**/index.{js,ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use tree-shaking friendly exports

Files:

  • packages/astro/src/server/index.ts
**/index.ts

📄 CodeRabbit inference engine (.cursor/rules/react.mdc)

Use index.ts files for clean imports but avoid deep barrel exports

Avoid barrel files (index.ts re-exports) as they can cause circular dependencies

Files:

  • packages/astro/src/server/index.ts
🧬 Code graph analysis (1)
packages/astro/src/server/clerk-middleware.ts (6)
packages/types/src/session.ts (1)
  • PendingSessionOptions (34-40)
packages/backend/src/tokens/tokenTypes.ts (2)
  • TokenType (1-6)
  • TokenType (11-11)
packages/backend/src/internal.ts (3)
  • TokenType (18-18)
  • signedOutAuthObject (30-30)
  • getAuthObjectForAcceptedToken (36-36)
packages/backend/src/tokens/authObjects.ts (3)
  • signedOutAuthObject (224-245)
  • AuthObject (161-166)
  • getAuthObjectForAcceptedToken (462-492)
packages/astro/src/server/types.ts (2)
  • AuthOptions (29-29)
  • AuthFn (35-69)
packages/astro/src/server/current-user.ts (1)
  • createCurrentUser (7-17)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/astro/src/server/current-user.ts (1)

9-15: Session-token gating looks correct.

Using acceptsToken: TokenType.SessionToken avoids accidentally treating machine tokens as user sessions.

packages/astro/src/server/index.ts (1)

50-50: Good re-export.

Re-exporting AuthFn from ./types aligns the public API with the new locals.auth surface.

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 (5)
integration/tests/astro/machine.test.ts (5)

27-31: Typo: rename helper to “unauthorized”.

Minor readability nit in the test fixture code you write to the app.

-        const unautorized = () =>
+        const unauthorized = () =>
             new Response('Unauthorized', {
                 status: 401,
             });

-                return unautorized();
+                return unauthorized();

Also applies to: 36-36


121-123: Remove unused parameter from APIRoute signature.

request isn’t used; drop it to keep the sample terse.

-        export const GET: APIRoute = ({ locals, request }) => {
+        export const GET: APIRoute = ({ locals }) => {

10-16: Add a test for acceptsToken: 'any' and negative case for session tokens.

To fully cover the new surface:

  • When acceptsToken is 'any', ensure a session token also succeeds.
  • When acceptsToken is 'api_key', ensure a session token is rejected (401).

I can draft these tests using the existing harness if you want.

Also applies to: 89-95


61-66: Strengthen 401 assertions with body checks.

Optionally assert the response body to catch regressions in middleware/route behavior.

-    expect(res.status()).toBe(401);
+    expect(res.status()).toBe(401);
+    expect(await res.text()).toContain('Unauthorized');

Also applies to: 67-74, 145-150, 151-158


2-2: Use literal 'api_key' instead of internal TokenType
Importing TokenType from @clerk/backend/internal is brittle; tests should assert the stable string returned by the API. Verified that every acceptsToken usage is 'api_key'.

-import { TokenType } from '@clerk/backend/internal';
+// Avoid internal import; assert against literal.

-expect(apiKeyData.tokenType).toBe(TokenType.ApiKey);
+expect(apiKeyData.tokenType).toBe('api_key');
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a0ae39a and 41eca5f.

📒 Files selected for processing (1)
  • integration/tests/astro/machine.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • integration/tests/astro/machine.test.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • integration/tests/astro/machine.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • integration/tests/astro/machine.test.ts
integration/**

📄 CodeRabbit inference engine (.cursor/rules/global.mdc)

Framework integration templates and E2E tests should be placed under the integration/ directory

Files:

  • integration/tests/astro/machine.test.ts
integration/**/*

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

End-to-end tests and integration templates must be located in the 'integration/' directory.

Files:

  • integration/tests/astro/machine.test.ts
integration/**/*.{test,spec}.{js,ts}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Integration tests should use Playwright.

Files:

  • integration/tests/astro/machine.test.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • integration/tests/astro/machine.test.ts
🧬 Code graph analysis (1)
integration/tests/astro/machine.test.ts (3)
integration/models/application.ts (1)
  • Application (7-7)
integration/presets/index.ts (1)
  • appConfigs (14-30)
integration/testUtils/index.ts (1)
  • createTestUtils (24-86)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (25)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Static analysis
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan

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

Caution

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

⚠️ Outside diff range comments (2)
packages/astro/src/server/clerk-middleware.ts (2)

184-193: Don’t override user-provided acceptsToken in authenticateRequest.

Current code always forces 'any', ignoring options.acceptsToken. Respect caller intent; default to 'any' only when unset.

   return {
     ...options,
     secretKey: options.secretKey || getSafeEnv(context).sk,
     publishableKey: options.publishableKey || getSafeEnv(context).pk,
     signInUrl: options.signInUrl || getSafeEnv(context).signInUrl,
     signUpUrl: options.signUpUrl || getSafeEnv(context).signUpUrl,
     ...handleMultiDomainAndProxy(clerkRequest, options, context),
-    acceptsToken: 'any',
+    acceptsToken: options.acceptsToken ?? 'any',
   };

335-345: Content-Type check is too strict; misses common headers with charset.

Use startsWith/includes to ensure HTML injection runs for "text/html; charset=utf-8".

-  if (res.headers.get('content-type') === 'text/html') {
+  const ct = res.headers.get('content-type') || '';
+  if (ct.startsWith('text/html')) {
♻️ Duplicate comments (1)
packages/astro/src/server/clerk-middleware.ts (1)

106-120: Good fix: ALS store gated to session tokens only.

Using SessionToken-only for the ALS value and falling back to signedOut prevents machine tokens from leaking into SSR hooks. Matches the intended surface.

🧹 Nitpick comments (4)
packages/astro/src/server/clerk-middleware.ts (4)

272-318: Parity: expose redirectToSignUp alongside redirectToSignIn for session auth.

Next.js returns both; adding redirectToSignUp improves DX consistency and feature parity without impacting machine tokens.

   if (authObject.tokenType === TokenType.SessionToken) {
     const clerkUrl = clerkRequest.clerkUrl;

     const redirectToSignIn: RedirectFun<Response> = (opts = {}) => {
       const devBrowserToken =
         clerkRequest.clerkUrl.searchParams.get(constants.QueryParameters.DevBrowser) ||
         clerkRequest.cookies.get(constants.Cookies.DevBrowser);

       return createRedirect({
         redirectAdapter,
         devBrowserToken: devBrowserToken,
         baseUrl: clerkUrl.toString(),
         // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
         publishableKey: getSafeEnv(context).pk!,
         signInUrl: requestState.signInUrl,
         signUpUrl: requestState.signUpUrl,
         sessionStatus: requestState.toAuth()?.sessionStatus,
       }).redirectToSignIn({
         returnBackUrl: opts.returnBackUrl === null ? '' : opts.returnBackUrl || clerkUrl.toString(),
       });
     };
+
+    const redirectToSignUp: RedirectFun<Response> = (opts = {}) => {
+      const devBrowserToken =
+        clerkRequest.clerkUrl.searchParams.get(constants.QueryParameters.DevBrowser) ||
+        clerkRequest.cookies.get(constants.Cookies.DevBrowser);
+
+      return createRedirect({
+        redirectAdapter,
+        devBrowserToken,
+        baseUrl: clerkUrl.toString(),
+        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+        publishableKey: getSafeEnv(context).pk!,
+        signInUrl: requestState.signInUrl,
+        signUpUrl: requestState.signUpUrl,
+        sessionStatus: requestState.toAuth()?.sessionStatus,
+      }).redirectToSignUp({
+        returnBackUrl: opts.returnBackUrl === null ? '' : opts.returnBackUrl || clerkUrl.toString(),
+      });
+    };
 
-    return Object.assign(authObject, { redirectToSignIn });
+    return Object.assign(authObject, { redirectToSignIn, redirectToSignUp });
   }

If you want parity in control-flow (throwing) redirects too, I can add createMiddlewareRedirectToSignUp and handle it in handleControlFlowErrors.


137-139: Prefer unknown over any in catch; narrow safely.

Aligns with TS best practices and your guidelines.

-      } catch (e: any) {
+      } catch (e: unknown) {
         handlerResult = handleControlFlowErrors(e, clerkRequest, requestState, context);
       }

413-432: Type the control-flow error path; avoid any.

Use unknown and narrow with instanceof/Error shape checks. Minimal change shown.

-const handleControlFlowErrors = (
-  e: any,
+const handleControlFlowErrors = (
+  e: unknown,
   clerkRequest: ClerkRequest,
   requestState: RequestState,
   context: AstroMiddlewareContextParam,
 ): Response => {
-  switch (e.message) {
+  if (e instanceof Error && e.message === CONTROL_FLOW_ERROR.REDIRECT_TO_SIGN_IN) {
+    const returnBackUrl =
+      typeof (e as any).returnBackUrl === 'string'
+        ? (e as any).returnBackUrl
+        : clerkRequest.clerkUrl.toString();
+    return createRedirect({
+      redirectAdapter,
+      baseUrl: clerkRequest.clerkUrl,
+      signInUrl: requestState.signInUrl,
+      signUpUrl: requestState.signUpUrl,
+      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+      publishableKey: getSafeEnv(context).pk!,
+      sessionStatus: requestState.toAuth()?.sessionStatus,
+    }).redirectToSignIn({ returnBackUrl });
+  }
-    case CONTROL_FLOW_ERROR.REDIRECT_TO_SIGN_IN:
-      return createRedirect({
-        redirectAdapter,
-        baseUrl: clerkRequest.clerkUrl,
-        signInUrl: requestState.signInUrl,
-        signUpUrl: requestState.signUpUrl,
-        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-        publishableKey: getSafeEnv(context).pk!,
-        sessionStatus: requestState.toAuth()?.sessionStatus,
-      }).redirectToSignIn({ returnBackUrl: e.returnBackUrl });
-    default:
-      throw e;
-  }
+  throw e;
 };

395-403: Avoid casting Error to any; use a typed error helper.

Small helper yields typed returnBackUrl and keeps types clean.

-  return (opts = {}) => {
-    const err = new Error(CONTROL_FLOW_ERROR.REDIRECT_TO_SIGN_IN) as any;
-    err.returnBackUrl = opts.returnBackUrl === null ? '' : opts.returnBackUrl || clerkRequest.clerkUrl.toString();
-    throw err;
-  };
+  return (opts = {}) => {
+    class RedirectToSignInError extends Error {
+      constructor(readonly returnBackUrl: string) {
+        super(CONTROL_FLOW_ERROR.REDIRECT_TO_SIGN_IN);
+        this.name = 'RedirectToSignInError';
+      }
+    }
+    const url = opts.returnBackUrl === null ? '' : opts.returnBackUrl || clerkRequest.clerkUrl.toString();
+    throw new RedirectToSignInError(url);
+  };
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 41eca5f and 5375af0.

📒 Files selected for processing (1)
  • packages/astro/src/server/clerk-middleware.ts (7 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/astro/src/server/clerk-middleware.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/astro/src/server/clerk-middleware.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/astro/src/server/clerk-middleware.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/astro/src/server/clerk-middleware.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/astro/src/server/clerk-middleware.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/astro/src/server/clerk-middleware.ts
🧬 Code graph analysis (1)
packages/astro/src/server/clerk-middleware.ts (7)
packages/nextjs/src/app-router/server/auth.ts (3)
  • auth (117-187)
  • AuthFn (51-108)
  • AuthOptions (49-49)
packages/astro/src/server/types.ts (2)
  • AuthFn (35-69)
  • AuthOptions (29-29)
packages/backend/src/tokens/tokenTypes.ts (2)
  • TokenType (1-6)
  • TokenType (11-11)
packages/backend/src/internal.ts (4)
  • TokenType (18-18)
  • signedOutAuthObject (30-30)
  • getAuthObjectForAcceptedToken (36-36)
  • createRedirect (2-2)
packages/backend/src/tokens/authObjects.ts (3)
  • signedOutAuthObject (224-245)
  • getAuthObjectForAcceptedToken (462-492)
  • AuthObject (161-166)
packages/backend/src/createRedirect.ts (1)
  • createRedirect (85-141)
packages/astro/src/server/current-user.ts (1)
  • createCurrentUser (6-16)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/astro/src/server/clerk-middleware.ts (1)

126-136: AuthFn wrapper correctly delegates token filtering.

Leveraging getAuthObjectForAcceptedToken per call keeps middleware-wide acceptance broad while letting handlers narrow as needed.

Comment on lines +116 to +117
const asyncStorageAuthObject =
authObjectFn().tokenType === TokenType.SessionToken ? authObjectFn() : signedOutAuthObject({});
Copy link
Member Author

@wobsoriano wobsoriano Sep 2, 2025

Choose a reason for hiding this comment

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

For ALS, we dont really need the redirectToSignIn method to be passed to useAuth(). If auth object is any of the machine token types, we just pass a signed out session auth object

Comment on lines +119 to +130
const authHandler = (opts?: AuthOptions) => {
const authObject = getAuthObjectForAcceptedToken({
authObject: authObjectFn({ treatPendingAsSignedOut: opts?.treatPendingAsSignedOut }),
acceptsToken: opts?.acceptsToken,
});

if (authObject.tokenType === TokenType.SessionToken) {
return Object.assign(authObject, { redirectToSignIn });
}

return authObject;
};
Copy link
Member Author

Choose a reason for hiding this comment

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

Supports the acceptsToken and treatPendingAsSignedOut options when auth() is called within middleware. Only adds redirectToSignIn method to session tokens (similar to Nextjs implementation)

Comment on lines +285 to +311
context.locals.auth = (({ acceptsToken, treatPendingAsSignedOut }: AuthOptions = {}) => {
const authObject = getAuthObjectForAcceptedToken({
authObject: authObjectFn({ treatPendingAsSignedOut }),
acceptsToken,
});

const redirectToSignIn: RedirectFun<Response> = (opts = {}) => {
const devBrowserToken =
clerkRequest.clerkUrl.searchParams.get(constants.QueryParameters.DevBrowser) ||
clerkRequest.cookies.get(constants.Cookies.DevBrowser);
if (authObject.tokenType === TokenType.SessionToken) {
const clerkUrl = clerkRequest.clerkUrl;

const redirectToSignIn: RedirectFun<Response> = (opts = {}) => {
const devBrowserToken =
clerkRequest.clerkUrl.searchParams.get(constants.QueryParameters.DevBrowser) ||
clerkRequest.cookies.get(constants.Cookies.DevBrowser);

return createRedirect({
redirectAdapter,
devBrowserToken: devBrowserToken,
baseUrl: clerkUrl.toString(),
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
publishableKey: getSafeEnv(context).pk!,
signInUrl: requestState.signInUrl,
signUpUrl: requestState.signUpUrl,
sessionStatus: requestState.toAuth()?.sessionStatus,
}).redirectToSignIn({
returnBackUrl: opts.returnBackUrl === null ? '' : opts.returnBackUrl || clerkUrl.toString(),
});
};
Copy link
Member Author

Choose a reason for hiding this comment

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

Simplified by reusing the auth object we get from calling authenticateRequest(). We can revisit later if we plan on supporting edge middleware.

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

Caution

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

⚠️ Outside diff range comments (1)
packages/astro/src/server/clerk-middleware.ts (1)

180-195: Use options.acceptsToken ?? 'any' instead of hardcoding 'any'
Explicitly respect an explicit options.acceptsToken, defaulting to 'any' only when it’s undefined.

   return {
     ...options,
     secretKey: options.secretKey || getSafeEnv(context).sk,
     publishableKey: options.publishableKey || getSafeEnv(context).pk,
     signInUrl: options.signInUrl || getSafeEnv(context).signInUrl,
     signUpUrl: options.signUpUrl || getSafeEnv(context).signUpUrl,
     ...handleMultiDomainAndProxy(clerkRequest, options, context),
-    acceptsToken: 'any',
+    acceptsToken: options.acceptsToken ?? 'any',
   };
♻️ Duplicate comments (1)
packages/astro/src/server/clerk-middleware.ts (1)

274-320: locals.auth gating — great fix; avoid recomputing sessionStatus

Gating redirect methods to session tokens solves the earlier type mismatch. Reuse the already computed authObject.sessionStatus instead of an extra toAuth() call.

Apply:

-          sessionStatus: requestState.toAuth()?.sessionStatus,
+          sessionStatus: authObject.sessionStatus,
#!/bin/bash
# Ensure SessionAuthObject has 'sessionStatus' so the above change is type-correct
rg -nC2 "interface\\s+SessionAuthObject|type\\s+SessionAuthObject" packages | sed -n '1,120p'
🧹 Nitpick comments (5)
packages/astro/src/server/clerk-middleware.ts (5)

116-118: Avoid double toAuth() call; simplify signed-out fallback

Compute once and reuse. Also no need to pass {} to signedOutAuthObject().

Apply:

-    const asyncStorageAuthObject =
-      authObjectFn().tokenType === TokenType.SessionToken ? authObjectFn() : signedOutAuthObject({});
+    const baseAuthObject = authObjectFn();
+    const asyncStorageAuthObject =
+      baseAuthObject.tokenType === TokenType.SessionToken ? baseAuthObject : signedOutAuthObject();

119-131: Type authHandler as AuthFn (remove cast) and de-duplicate logic with locals.auth

  • Give authHandler the AuthFn type to avoid as casting at call site.
  • Optional: extract a small helper to share the accept/gate + redirect logic with locals.auth.

Apply:

-    const authHandler = (opts?: AuthOptions) => {
+    const authHandler: AuthFn = (opts?: AuthOptions) => {
       const authObject = getAuthObjectForAcceptedToken({
         authObject: authObjectFn({ treatPendingAsSignedOut: opts?.treatPendingAsSignedOut }),
         acceptsToken: opts?.acceptsToken,
       });

       if (authObject.tokenType === TokenType.SessionToken) {
         return Object.assign(authObject, { redirectToSignIn });
       }

       return authObject;
     };

And:

-        handlerResult = (await handler?.(authHandler as AuthFn, context, next)) || (await next());
+        handlerResult = (await handler?.(authHandler, context, next)) || (await next());

If you want, I can extract a shared buildAuthHandler(...) to avoid duplicating the gating logic between authHandler and locals.auth.

Also applies to: 138-138


180-195: Add brief JSDoc for createAuthenticateRequestOptions

It’s exported; a short JSDoc clarifies why 'any' is the default and how proxy/multi-domain are resolved.

Example:

/**
 * Builds options for `authenticateRequest`.
 * - Defaults `acceptsToken` to `'any'` so `locals.auth({ acceptsToken })` can narrow later.
 * - Merges env and per-request multi-domain/proxy settings.
 */

132-156: Tighten authAsyncStorage’s generic from unknown to AuthObject
In packages/astro/src/global.d.ts change

export const authAsyncStorage: AsyncLocalStorage<unknown>;

to

import type { AuthObject } from '@clerk/backend';
export const authAsyncStorage: AsyncLocalStorage<AuthObject>;

This restores full type-safety for run/getStore (no more as any casts).


119-131: Add redirectToSignUp to Astro’s authHandler
SessionAuthObjectWithRedirect only defines redirectToSignIn; include redirectToSignUp alongside it for parity with Next.js.
File: packages/astro/src/server/clerk-middleware.ts, within the Object.assign on lines 119–131.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 10c9b4a and bd9642b.

📒 Files selected for processing (1)
  • packages/astro/src/server/clerk-middleware.ts (7 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/astro/src/server/clerk-middleware.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/astro/src/server/clerk-middleware.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/astro/src/server/clerk-middleware.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/astro/src/server/clerk-middleware.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/astro/src/server/clerk-middleware.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/astro/src/server/clerk-middleware.ts
🧬 Code graph analysis (1)
packages/astro/src/server/clerk-middleware.ts (7)
packages/nextjs/src/app-router/server/auth.ts (3)
  • auth (117-187)
  • AuthFn (51-108)
  • AuthOptions (49-49)
packages/astro/src/server/types.ts (2)
  • AuthFn (35-69)
  • AuthOptions (29-29)
packages/backend/src/tokens/tokenTypes.ts (2)
  • TokenType (1-6)
  • TokenType (11-11)
packages/backend/src/tokens/authObjects.ts (3)
  • signedOutAuthObject (224-245)
  • getAuthObjectForAcceptedToken (462-492)
  • AuthObject (161-166)
packages/astro/src/global.d.ts (1)
  • authAsyncStorage (7-7)
packages/backend/src/createRedirect.ts (2)
  • RedirectFun (67-67)
  • createRedirect (85-141)
packages/astro/src/server/current-user.ts (1)
  • createCurrentUser (6-16)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/astro/src/server/clerk-middleware.ts (2)

52-55: Handler now receives AuthFn — LGTM

This unlocks machine tokens in user code via auth(options). No concerns here.


106-111: Passing authObjectFn into decorateAstroLocal — LGTM

This keeps locals wired to the same source of truth and avoids early materialization.

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.

3 participants