-
Notifications
You must be signed in to change notification settings - Fork 376
chore(nextjs): Improve machine auth verification calls #6367
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
Changes from 3 commits
73bf0e4
321711b
57a6875
ee53247
176182b
56a7c86
bbdc5ca
83e00ed
0c7e51f
cc4358b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
@@ -1,24 +1,24 @@ | ||||||||||||
import type { AuthObject } from '@clerk/backend'; | ||||||||||||
import type { AuthObject, MachineAuthObject } from '@clerk/backend'; | ||||||||||||
import type { | ||||||||||||
AuthenticateRequestOptions, | ||||||||||||
MachineTokenType, | ||||||||||||
SignedInAuthObject, | ||||||||||||
SignedOutAuthObject, | ||||||||||||
} from '@clerk/backend/internal'; | ||||||||||||
import { | ||||||||||||
authenticatedMachineObject, | ||||||||||||
type AuthenticateRequestOptions, | ||||||||||||
AuthStatus, | ||||||||||||
constants, | ||||||||||||
getAuthObjectForAcceptedToken, | ||||||||||||
getAuthObjectFromJwt, | ||||||||||||
getMachineTokenType, | ||||||||||||
invalidTokenAuthObject, | ||||||||||||
isMachineTokenByPrefix, | ||||||||||||
isTokenTypeAccepted, | ||||||||||||
type SignedInAuthObject, | ||||||||||||
type SignedOutAuthObject, | ||||||||||||
signedOutAuthObject, | ||||||||||||
TokenType, | ||||||||||||
unauthenticatedMachineObject, | ||||||||||||
verifyMachineAuthToken, | ||||||||||||
} from '@clerk/backend/internal'; | ||||||||||||
import { decodeJwt } from '@clerk/backend/jwt'; | ||||||||||||
import type { PendingSessionOptions } from '@clerk/types'; | ||||||||||||
import type { AuthenticateContext } from 'node_modules/@clerk/backend/dist/tokens/authenticateContext'; | ||||||||||||
|
||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion Use relative import path instead of node_modules reference. The import is referencing the node_modules directory directly, which is brittle and non-standard. -import type { AuthenticateContext } from 'node_modules/@clerk/backend/dist/tokens/authenticateContext';
+import type { AuthenticateContext } from '@clerk/backend/internal'; 📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents
|
||||||||||||
import type { LoggerNoCommit } from '../../utils/debugLogger'; | ||||||||||||
import { API_URL, API_VERSION, PUBLISHABLE_KEY, SECRET_KEY } from '../constants'; | ||||||||||||
|
@@ -80,35 +80,31 @@ export const getAuthDataFromRequestSync = ( | |||||||||||
return authObject; | ||||||||||||
}; | ||||||||||||
|
||||||||||||
const handleMachineToken = async ( | ||||||||||||
const handleMachineToken = ( | ||||||||||||
bearerToken: string | undefined, | ||||||||||||
rawAuthObject: AuthObject | undefined, | ||||||||||||
acceptsToken: NonNullable<AuthenticateRequestOptions['acceptsToken']>, | ||||||||||||
options: GetAuthDataFromRequestOptions, | ||||||||||||
): Promise<AuthObject | null> => { | ||||||||||||
options: Partial<AuthenticateContext>, | ||||||||||||
): MachineAuthObject<MachineTokenType> | null => { | ||||||||||||
const hasMachineToken = bearerToken && isMachineTokenByPrefix(bearerToken); | ||||||||||||
|
||||||||||||
const acceptsOnlySessionToken = | ||||||||||||
acceptsToken === TokenType.SessionToken || | ||||||||||||
(Array.isArray(acceptsToken) && acceptsToken.length === 1 && acceptsToken[0] === TokenType.SessionToken); | ||||||||||||
|
||||||||||||
if (hasMachineToken && !acceptsOnlySessionToken) { | ||||||||||||
const machineTokenType = getMachineTokenType(bearerToken); | ||||||||||||
|
||||||||||||
// Early return if the token type is not accepted to save on the verify call | ||||||||||||
if (Array.isArray(acceptsToken) && !acceptsToken.includes(machineTokenType)) { | ||||||||||||
return invalidTokenAuthObject(); | ||||||||||||
} | ||||||||||||
// Early return for scalar acceptsToken if it does not match the machine token type | ||||||||||||
if (!Array.isArray(acceptsToken) && acceptsToken !== 'any' && machineTokenType !== acceptsToken) { | ||||||||||||
const authObject = unauthenticatedMachineObject(acceptsToken, options); | ||||||||||||
return getAuthObjectForAcceptedToken({ authObject, acceptsToken }); | ||||||||||||
} | ||||||||||||
|
||||||||||||
const { data, errors } = await verifyMachineAuthToken(bearerToken, options); | ||||||||||||
const authObject = errors | ||||||||||||
? unauthenticatedMachineObject(machineTokenType, options) | ||||||||||||
: authenticatedMachineObject(machineTokenType, bearerToken, data); | ||||||||||||
return getAuthObjectForAcceptedToken({ authObject, acceptsToken }); | ||||||||||||
if (hasMachineToken && rawAuthObject && !acceptsOnlySessionToken) { | ||||||||||||
const authObject = getAuthObjectForAcceptedToken({ | ||||||||||||
authObject: { | ||||||||||||
...rawAuthObject, | ||||||||||||
debug: () => options, | ||||||||||||
}, | ||||||||||||
acceptsToken, | ||||||||||||
}); | ||||||||||||
return { | ||||||||||||
...authObject, | ||||||||||||
getToken: () => (authObject.isAuthenticated ? Promise.resolve(bearerToken) : Promise.resolve(null)), | ||||||||||||
has: () => false, | ||||||||||||
} as MachineAuthObject<MachineTokenType>; | ||||||||||||
} | ||||||||||||
|
||||||||||||
return null; | ||||||||||||
|
@@ -125,19 +121,22 @@ export const getAuthDataFromRequestAsync = async ( | |||||||||||
const { authStatus, authMessage, authReason } = getAuthHeaders(req); | ||||||||||||
opts.logger?.debug('headers', { authStatus, authMessage, authReason }); | ||||||||||||
|
||||||||||||
const encryptedRequestData = getHeader(req, constants.Headers.ClerkRequestData); | ||||||||||||
const decryptedRequestData = decryptClerkRequestData(encryptedRequestData); | ||||||||||||
|
||||||||||||
const bearerToken = getHeader(req, constants.Headers.Authorization)?.replace('Bearer ', ''); | ||||||||||||
const acceptsToken = opts.acceptsToken || TokenType.SessionToken; | ||||||||||||
const options = { | ||||||||||||
secretKey: opts?.secretKey || SECRET_KEY, | ||||||||||||
publishableKey: PUBLISHABLE_KEY, | ||||||||||||
secretKey: opts?.secretKey || decryptedRequestData.secretKey || SECRET_KEY, | ||||||||||||
publishableKey: decryptedRequestData.publishableKey || PUBLISHABLE_KEY, | ||||||||||||
apiUrl: API_URL, | ||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Parts of the sync versus the async variant seem to be getting out of sync. Can we remove duplication ?
Actually are There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Updated and removed redundant logic |
||||||||||||
authStatus, | ||||||||||||
authMessage, | ||||||||||||
authReason, | ||||||||||||
}; | ||||||||||||
|
||||||||||||
// If the request has a machine token in header, handle it first. | ||||||||||||
const machineAuthObject = await handleMachineToken(bearerToken, acceptsToken, options); | ||||||||||||
const machineAuthObject = handleMachineToken(bearerToken, decryptedRequestData.authObject, acceptsToken, options); | ||||||||||||
if (machineAuthObject) { | ||||||||||||
return machineAuthObject; | ||||||||||||
} | ||||||||||||
|
Uh oh!
There was an error while loading. Please reload this page.
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.
💡 Verification agent
🧩 Analysis chain
Conditional redirect methods based on token type - approve with security review needed.
This change correctly restricts redirect methods to session tokens only, which makes semantic sense since machine tokens, API keys, and OAuth tokens are for programmatic access and don't need user redirect capabilities.
However, this modifies core authentication logic and should be reviewed by the security team.
Please tag
clerk/security
for review of this authentication logic change.Also, ensure test coverage exists for both branches of this conditional logic:
If test coverage is missing, please add tests to verify:
🏁 Script executed:
Length of output: 76688
Conditional redirect methods for session tokens – approve with security review and add missing tests
The change correctly restricts
redirectToSignIn
/redirectToSignUp
toSessionToken
cases, aligning behavior with token semantics.However, no unit tests currently cover this branch in
packages/nextjs/src/app-router/server/auth.ts
.• Tag
clerk/security
for review of the updated authentication logic.• Add a new test suite under
packages/nextjs/src/app-router/server/__tests__/auth.test.ts
covering:authObject.tokenType === TokenType.SessionToken
, the returned object includes workingredirectToSignIn
andredirectToSignUp
methods.authObject.tokenType !== TokenType.SessionToken
, the returned object does not expose redirect methods (calls should error or be undefined).🤖 Prompt for AI Agents
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.
@wobsoriano Do types already cover this case ?
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.
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.
@panteliselef yes, but want to make sure machine auth objects dont include redirect functions at runtime as well