Skip to content

feat: signal handshake nonce support for oauth flow #5908

New issue

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

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

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions packages/backend/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export const API_VERSION = 'v1';
export const USER_AGENT = `${PACKAGE_NAME}@${PACKAGE_VERSION}`;
export const MAX_CACHE_LAST_UPDATED_AT_SECONDS = 5 * 60;
export const SUPPORTED_BAPI_VERSION = '2025-04-10';
export const SUPPORTED_HANDSHAKE_FORMAT = 'nonce';

const Attributes = {
AuthToken: '__clerkAuthToken',
Expand All @@ -21,6 +22,7 @@ const Cookies = {
Handshake: '__clerk_handshake',
DevBrowser: '__clerk_db_jwt',
RedirectCount: '__clerk_redirect_count',
HandshakeFormat: '__clerk_handshake_format',
HandshakeNonce: '__clerk_handshake_nonce',
} as const;

Expand All @@ -34,6 +36,7 @@ const QueryParameters = {
HandshakeHelp: '__clerk_help',
LegacyDevBrowser: '__dev_session',
HandshakeReason: '__clerk_hs_reason',
HandshakeFormat: Cookies.HandshakeFormat,
HandshakeNonce: Cookies.HandshakeNonce,
} as const;

Expand Down
1 change: 1 addition & 0 deletions packages/backend/src/tokens/authenticateContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ interface AuthenticateContext extends AuthenticateRequestOptions {
clientUat: number;
// handshake-related values
devBrowserToken: string | undefined;
handshakeFormat: 'nonce' | 'token' | undefined;
handshakeNonce: string | undefined;
handshakeToken: string | undefined;
handshakeRedirectLoopCounter: number;
Expand Down
7 changes: 6 additions & 1 deletion packages/backend/src/tokens/handshake.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { constants, SUPPORTED_BAPI_VERSION } from '../constants';
import { constants, SUPPORTED_BAPI_VERSION, SUPPORTED_HANDSHAKE_FORMAT } from '../constants';
import { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';
import type { VerifyJwtOptions } from '../jwt';
import { assertHeaderAlgorithm, assertHeaderType } from '../jwt/assertions';
Expand Down Expand Up @@ -145,6 +145,11 @@ export class HandshakeService {
this.authenticateContext.usesSuffixedCookies().toString(),
);
url.searchParams.append(constants.QueryParameters.HandshakeReason, reason);
/**
* Appends the supported handshake format parameter to the URL
* This parameter indicates the format of the handshake response that the client expects
*/
url.searchParams.append(constants.QueryParameters.HandshakeFormat, SUPPORTED_HANDSHAKE_FORMAT);

if (this.authenticateContext.instanceType === 'development' && this.authenticateContext.devBrowserToken) {
url.searchParams.append(constants.QueryParameters.DevBrowser, this.authenticateContext.devBrowserToken);
Expand Down
24 changes: 22 additions & 2 deletions packages/backend/src/tokens/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,26 @@ export async function authenticateRequest(
const authenticateContext = await createAuthenticateContext(createClerkRequest(request), options);
assertValidSecretKey(authenticateContext.secretKey);

/**
* Merges headers from the RequestState with a default handshake cookie.
* Creates a new Headers object with a nonce cookie and adds all headers from the result.
*
* @param result - The RequestState containing headers to merge
* @returns The RequestState with merged headers
*/
function mergeHeaders(result: RequestState): RequestState {
const headers = new Headers();
headers.append(
'Set-Cookie',
`${constants.Cookies.HandshakeFormat}=nonce; Path=/; SameSite=None; Secure; Domain=${authenticateContext.frontendApi.replace(/^clerk\./, '') || ''};`,
);
for (const [key, value] of result.headers.entries()) {
headers.append(key, value);
}
result.headers = headers;
return result;
}

if (authenticateContext.isSatellite) {
assertSignInUrlExists(authenticateContext.signInUrl, authenticateContext.secretKey);
if (authenticateContext.signInUrl && authenticateContext.origin) {
Expand Down Expand Up @@ -533,10 +553,10 @@ export async function authenticateRequest(
}

if (authenticateContext.sessionTokenInHeader) {
return authenticateRequestWithTokenInHeader();
return mergeHeaders(await authenticateRequestWithTokenInHeader());
}

return authenticateRequestWithTokenInCookie();
return mergeHeaders(await authenticateRequestWithTokenInCookie());
}

/**
Expand Down
8 changes: 8 additions & 0 deletions packages/backend/src/tokens/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ export type AuthenticateRequestOptions = {
* If the activation can't be performed, either because an organization doesn't exist or the user lacks access, the active organization in the session won't be changed. Ultimately, it's the responsibility of the page to verify that the resources are appropriate to render given the URL and handle mismatches appropriately (e.g., by returning a 404).
*/
organizationSyncOptions?: OrganizationSyncOptions;
/**
* Specifies the handshake format to be used during OAuth authentication flows.
* When set to 'nonce', the backend signals to the frontend that it can handle nonce-based handshakes
* during OAuth flow resolution.
*
* @default 'token'
*/
handshakeFormat?: 'nonce' | 'token';
/**
* @internal
*/
Expand Down
3 changes: 3 additions & 0 deletions packages/types/src/factors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,16 +106,19 @@ export type OAuthConfig = OauthFactor & {
actionCompleteRedirectUrl: string;
oidcPrompt?: string;
oidcLoginHint?: string;
handshakeFormat?: 'nonce' | 'token';
};

export type SamlConfig = SamlFactor & {
redirectUrl: string;
actionCompleteRedirectUrl: string;
handshakeFormat?: 'nonce' | 'token';
};

export type EnterpriseSSOConfig = EnterpriseSSOFactor & {
redirectUrl: string;
actionCompleteRedirectUrl: string;
handshakeFormat?: 'nonce' | 'token';
oidcPrompt?: string;
};

Expand Down
5 changes: 5 additions & 0 deletions packages/types/src/redirects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,11 @@ export type AuthenticateWithRedirectParams = {
*/
legalAccepted?: boolean;

/**
* Whether to use handshake nonce or handshake token
*/
handshakeFormat?: 'nonce' | 'token';

/**
* Optional for `oauth_<provider>` or `enterprise_sso` strategies. The value to pass to the [OIDC prompt parameter](https://openid.net/specs/openid-connect-core-1_0.html#:~:text=prompt,reauthentication%20and%20consent.) in the generated OAuth redirect URL.
*/
Expand Down
1 change: 1 addition & 0 deletions packages/types/src/signIn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ export type SignInCreateParams = (
identifier?: string;
oidcPrompt?: string;
oidcLoginHint?: string;
handshakeFormat?: 'nonce' | 'token';
}
| {
strategy: TicketStrategy;
Expand Down
Loading