-
Notifications
You must be signed in to change notification settings - Fork 382
feat(astro): Introduce machine authentication #6671
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
🦋 Changeset detectedLatest commit: bd9642b The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
WalkthroughAdds machine-token support to Astro auth: Changes
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)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Assessment against linked issues
✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
The latest updates on your projects. Learn more about Vercel for GitHub. 1 Skipped Deployment
|
There was a problem hiding this 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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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.
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this 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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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 inclerk-middleware.ts
(line 262) viacontext.locals.__internal_authObject = JSON.parse(JSON.stringify(rawAuthObject));
, matching theenv.d.ts
declaration.
There was a problem hiding this 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 isPromise<User | null>
, consider mapping 404 tonull
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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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-checkingauthObject.tokenType
ensures machine tokens never reach user resolution. LGTM.
There was a problem hiding this 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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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' });
There was a problem hiding this 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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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.
There was a problem hiding this 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 doubletoAuth()
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
: CarrytreatPendingAsSignedOut
through tosessionStatus
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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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 newlocals.auth
surface.
There was a problem hiding this 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
ImportingTokenType
from@clerk/backend/internal
is brittle; tests should assert the stable string returned by the API. Verified that everyacceptsToken
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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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
There was a problem hiding this 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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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.
const asyncStorageAuthObject = | ||
authObjectFn().tokenType === TokenType.SessionToken ? authObjectFn() : signedOutAuthObject({}); |
There was a problem hiding this comment.
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
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; | ||
}; |
There was a problem hiding this comment.
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)
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(), | ||
}); | ||
}; |
There was a problem hiding this comment.
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.
There was a problem hiding this 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 explicitoptions.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 sessionStatusGating redirect methods to session tokens solves the earlier type mismatch. Reuse the already computed
authObject.sessionStatus
instead of an extratoAuth()
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 fallbackCompute once and reuse. Also no need to pass
{}
tosignedOutAuthObject()
.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
theAuthFn
type to avoidas
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 betweenauthHandler
andlocals.auth
.Also applies to: 138-138
180-195
: Add brief JSDoc for createAuthenticateRequestOptionsIt’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 fromunknown
toAuthObject
Inpackages/astro/src/global.d.ts
changeexport 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 moreas any
casts).
119-131
: AddredirectToSignUp
to Astro’sauthHandler
SessionAuthObjectWithRedirect only definesredirectToSignIn
; includeredirectToSignUp
alongside it for parity with Next.js.
File: packages/astro/src/server/clerk-middleware.ts, within theObject.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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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 — LGTMThis unlocks machine tokens in user code via
auth(options)
. No concerns here.
106-111
: Passing authObjectFn into decorateAstroLocal — LGTMThis keeps locals wired to the same source of truth and avoids early materialization.
Description
Adds machine authentication support to the Astro SDK
Example usage accepting any token type:
Example accepting api keys:
Resolves USER-2457
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
New Features
Refactor
Removed
Tests