Skip to content

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

Merged
merged 10 commits into from
Jul 23, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion packages/nextjs/src/app-router/server/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,11 @@ export const auth: AuthFn = (async (options?: AuthOptions) => {
});
};

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

return authObject;
Comment on lines +182 to +186
Copy link
Contributor

@coderabbitai coderabbitai bot Jul 22, 2025

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:

  1. Session tokens return authObject with redirect methods
  2. Non-session tokens return authObject without redirect methods
  3. The redirect methods work correctly when present

🏁 Script executed:

#!/bin/bash
# Description: Check for test coverage of conditional redirect method behavior

# Search for tests related to auth function with different token types
rg -A 10 -B 5 "auth.*tokenType|tokenType.*auth" --type ts --type js

# Search for tests of redirect methods on auth objects
rg -A 10 -B 5 "redirectToSignIn|redirectToSignUp" --type ts --type js packages/nextjs/src/app-router/server/__tests__/ || echo "No tests directory found"

# Search for machine token or API key auth tests
rg -A 10 -B 5 "machine_token|api_key|MachineAuthObject" --type ts --type js packages/nextjs/src/app-router/server/__tests__/ || echo "No tests directory found"

Length of output: 76688


Conditional redirect methods for session tokens – approve with security review and add missing tests

The change correctly restricts redirectToSignIn/redirectToSignUp to SessionToken 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:

  • When authObject.tokenType === TokenType.SessionToken, the returned object includes working redirectToSignIn and redirectToSignUp methods.
  • When authObject.tokenType !== TokenType.SessionToken, the returned object does not expose redirect methods (calls should error or be undefined).
🤖 Prompt for AI Agents
In packages/nextjs/src/app-router/server/auth.ts lines 182-186, the code
conditionally adds redirectToSignIn and redirectToSignUp methods only for
SessionToken token types. To fix, request a security review from the
clerk/security team for this authentication logic update. Then, add a new test
suite in packages/nextjs/src/app-router/server/__tests__/auth.test.ts that
verifies when tokenType is SessionToken, the returned object includes
functioning redirect methods, and when tokenType is not SessionToken, these
redirect methods are absent or cause errors.

Copy link
Member

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 ?

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Member Author

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

}) as AuthFn;

auth.protect = async (...args: any[]) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ describe('getAuthDataFromRequestAsync', () => {
vi.clearAllMocks();
});

it('returns invalid token auth object when token type does not match any in acceptsToken array', async () => {
it.only('returns invalid token auth object when token type does not match any in acceptsToken array', async () => {
const req = mockRequest({
url: '/api/protected',
headers: new Headers({
Expand Down
10 changes: 9 additions & 1 deletion packages/nextjs/src/server/clerkMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
getAuthObjectForAcceptedToken,
isMachineTokenByPrefix,
isTokenTypeAccepted,
makeAuthObjectSerializable,
TokenType,
} from '@clerk/backend/internal';
import { parsePublishableKey } from '@clerk/shared/keys';
Expand Down Expand Up @@ -265,7 +266,14 @@ export const clerkMiddleware = ((...args: unknown[]): NextMiddleware | NextMiddl
}
: {};

decorateRequest(clerkRequest, handlerResult, requestState, resolvedParams, keylessKeysForRequestData);
decorateRequest(
clerkRequest,
handlerResult,
requestState,
resolvedParams,
keylessKeysForRequestData,
authObject.tokenType === 'session_token' ? null : makeAuthObjectSerializable(authObject),
);

return handlerResult;
});
Expand Down
63 changes: 31 additions & 32 deletions packages/nextjs/src/server/data/getAuthDataFromRequest.ts
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';

Copy link
Contributor

Choose a reason for hiding this comment

The 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

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import type { AuthenticateContext } from 'node_modules/@clerk/backend/dist/tokens/authenticateContext';
// packages/nextjs/src/server/data/getAuthDataFromRequest.ts
-import type { AuthenticateContext } from 'node_modules/@clerk/backend/dist/tokens/authenticateContext';
+import type { AuthenticateContext } from '@clerk/backend/internal';
🤖 Prompt for AI Agents
In packages/nextjs/src/server/data/getAuthDataFromRequest.ts at line 21, the
import statement uses a direct node_modules path which is non-standard and
brittle. Change the import to use a relative or package-based path by removing
'node_modules/' and importing directly from
'@clerk/backend/dist/tokens/authenticateContext' to follow standard module
resolution practices.

import type { LoggerNoCommit } from '../../utils/debugLogger';
import { API_URL, API_VERSION, PUBLISHABLE_KEY, SECRET_KEY } from '../constants';
Expand Down Expand Up @@ -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;
Expand All @@ -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,
Copy link
Member

Choose a reason for hiding this comment

The 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 ?

treatPendingAsSignedOut seems to be missing from the async variant, is that on purpose ?

Actually are authStatus, authMessage, authReason ever used when passed as options ?

Copy link
Member Author

Choose a reason for hiding this comment

The 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;
}
Expand Down
14 changes: 10 additions & 4 deletions packages/nextjs/src/server/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { AuthObject } from '@clerk/backend';
import type { AuthenticateRequestOptions, ClerkRequest, RequestState } from '@clerk/backend/internal';
import { constants } from '@clerk/backend/internal';
import { isDevelopmentFromSecretKey } from '@clerk/shared/keys';
Expand Down Expand Up @@ -53,6 +54,7 @@ export function decorateRequest(
requestState: RequestState,
requestData: AuthenticateRequestOptions,
keylessMode: Pick<AuthenticateRequestOptions, 'publishableKey' | 'secretKey'>,
authObject: AuthObject | null,
): Response {
const { reason, message, status, token } = requestState;
// pass-through case, convert to next()
Expand Down Expand Up @@ -87,7 +89,7 @@ export function decorateRequest(
}

if (rewriteURL) {
const clerkRequestData = encryptClerkRequestData(requestData, keylessMode);
const clerkRequestData = encryptClerkRequestData(requestData, keylessMode, authObject);

setRequestHeadersOnNextResponse(res, req, {
[constants.Headers.AuthStatus]: status,
Expand Down Expand Up @@ -184,6 +186,7 @@ const KEYLESS_ENCRYPTION_KEY = 'clerk_keyless_dummy_key';
export function encryptClerkRequestData(
requestData: Partial<AuthenticateRequestOptions>,
keylessModeKeys: Pick<AuthenticateRequestOptions, 'publishableKey' | 'secretKey'>,
authObject: AuthObject | null,
) {
const isEmpty = (obj: Record<string, any> | undefined) => {
if (!obj) {
Expand All @@ -192,7 +195,7 @@ export function encryptClerkRequestData(
return !Object.values(obj).some(v => v !== undefined);
};

if (isEmpty(requestData) && isEmpty(keylessModeKeys)) {
if (isEmpty(requestData) && isEmpty(keylessModeKeys) && !authObject) {
return;
}

Expand All @@ -209,7 +212,10 @@ export function encryptClerkRequestData(
? ENCRYPTION_KEY || assertKey(SECRET_KEY, () => errorThrower.throwMissingSecretKeyError())
: ENCRYPTION_KEY || SECRET_KEY || KEYLESS_ENCRYPTION_KEY;

return AES.encrypt(JSON.stringify({ ...keylessModeKeys, ...requestData }), maybeKeylessEncryptionKey).toString();
return AES.encrypt(
JSON.stringify({ ...keylessModeKeys, ...requestData, authObject: authObject ?? undefined }),
maybeKeylessEncryptionKey,
).toString();
}

/**
Expand All @@ -218,7 +224,7 @@ export function encryptClerkRequestData(
*/
export function decryptClerkRequestData(
encryptedRequestData?: string | undefined | null,
): Partial<AuthenticateRequestOptions> {
): Partial<AuthenticateRequestOptions> & { authObject?: AuthObject } {
if (!encryptedRequestData) {
return {};
}
Expand Down
Loading