Skip to content
Merged
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
7 changes: 7 additions & 0 deletions .changeset/oauth-consent-use-hook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@clerk/shared': minor
'@clerk/react': minor
'@clerk/nextjs': minor
---

Introduce internal `useOAuthConsent()` hook for fetching OAuth consent screen metadata for the signed-in user.
1 change: 1 addition & 0 deletions packages/nextjs/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
* If you do, app router will break.
*/
export { MultisessionAppSupport } from './client-boundary/controlComponents';
export { useOAuthConsent } from '@clerk/shared/react';
1 change: 1 addition & 0 deletions packages/react/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { ClerkProviderProps } from './types';

export { setErrorThrowerOptions } from './errors/errorThrower';
export { MultisessionAppSupport } from './components/controlComponents';
export { useOAuthConsent } from '@clerk/shared/react';
export { useRoutingProps } from './hooks/useRoutingProps';
export { useDerivedAuth } from './hooks/useAuth';
export { IS_REACT_SHARED_VARIANT_COMPATIBLE } from './utils/versionCheck';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { describe, expect, it } from 'vitest';

import { readOAuthConsentFromSearch } from '../useOAuthConsent.shared';

describe('readOAuthConsentFromSearch', () => {
it('parses client_id and scope from a location.search-style string', () => {
expect(readOAuthConsentFromSearch('?client_id=myapp&scope=openid%20email')).toEqual({
oauthClientId: 'myapp',
scope: 'openid email',
});
});

it('parses without a leading question mark', () => {
expect(readOAuthConsentFromSearch('client_id=x&scope=y')).toEqual({
oauthClientId: 'x',
scope: 'y',
});
});

it('returns empty client id and undefined scope when search is empty', () => {
expect(readOAuthConsentFromSearch('')).toEqual({
oauthClientId: '',
});
});

it('omits scope in the result when scope is absent', () => {
expect(readOAuthConsentFromSearch('?client_id=only')).toEqual({
oauthClientId: 'only',
});
});
});
148 changes: 148 additions & 0 deletions packages/shared/src/react/hooks/__tests__/useOAuthConsent.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import { renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { useOAuthConsent } from '../useOAuthConsent';
import { createMockClerk, createMockQueryClient, createMockUser } from './mocks/clerk';
import { wrapper } from './wrapper';

const consentInfo = {
oauthApplicationName: 'My App',
oauthApplicationLogoUrl: 'https://img.example/logo.png',
oauthApplicationUrl: 'https://app.example',
clientId: 'client_abc',
state: 's',
scopes: [] as { scope: string; description: string | null; requiresConsent: boolean }[],
};

const getConsentInfoSpy = vi.fn(() => Promise.resolve(consentInfo));

const defaultQueryClient = createMockQueryClient();

const mockClerk = createMockClerk({
oauthApplication: {
getConsentInfo: getConsentInfoSpy,
},
queryClient: defaultQueryClient,
});

const userState: { current: { id: string } | null } = {
current: createMockUser(),
};

vi.mock('../../contexts', () => {
return {
useAssertWrappedByClerkProvider: () => {},
useClerkInstanceContext: () => mockClerk,
useInitialStateContext: () => undefined,
};
});

vi.mock('../base/useUserBase', () => ({
useUserBase: () => userState.current,
}));

describe('useOAuthConsent', () => {
beforeEach(() => {
vi.clearAllMocks();
defaultQueryClient.client.clear();
mockClerk.loaded = true;
userState.current = createMockUser();
mockClerk.oauthApplication = {
getConsentInfo: getConsentInfoSpy,
};
window.history.replaceState({}, '', '/');
});

it('fetches consent metadata when signed in', async () => {
const { result } = renderHook(() => useOAuthConsent({ oauthClientId: 'my_client' }), { wrapper });

await waitFor(() => expect(result.current.isLoading).toBe(false));

expect(getConsentInfoSpy).toHaveBeenCalledTimes(1);
expect(getConsentInfoSpy).toHaveBeenCalledWith({ oauthClientId: 'my_client' });
expect(result.current.data).toEqual(consentInfo);
expect(result.current.error).toBeNull();
});

it('passes scope to getConsentInfo when provided', async () => {
const { result } = renderHook(() => useOAuthConsent({ oauthClientId: 'cid', scope: 'openid email' }), { wrapper });

await waitFor(() => expect(result.current.isLoading).toBe(false));

expect(getConsentInfoSpy).toHaveBeenCalledWith({ oauthClientId: 'cid', scope: 'openid email' });
expect(result.current.data).toEqual(consentInfo);
});

it('does not call getConsentInfo when user is null', () => {
userState.current = null;

const { result } = renderHook(() => useOAuthConsent({ oauthClientId: 'cid' }), { wrapper });

expect(getConsentInfoSpy).not.toHaveBeenCalled();
expect(result.current.isLoading).toBe(false);
});

it('does not call getConsentInfo when clerk.loaded is false', () => {
mockClerk.loaded = false;

const { result } = renderHook(() => useOAuthConsent({ oauthClientId: 'cid' }), { wrapper });

expect(getConsentInfoSpy).not.toHaveBeenCalled();
expect(result.current.isLoading).toBe(false);
});

it('does not call getConsentInfo when enabled is false', () => {
const { result } = renderHook(() => useOAuthConsent({ oauthClientId: 'cid', enabled: false }), { wrapper });

expect(getConsentInfoSpy).not.toHaveBeenCalled();
expect(result.current.isLoading).toBe(false);
});

it('does not call getConsentInfo when oauthClientId is empty', () => {
const { result } = renderHook(() => useOAuthConsent({ oauthClientId: '' }), { wrapper });

expect(getConsentInfoSpy).not.toHaveBeenCalled();
expect(result.current.isLoading).toBe(false);
});

it('uses client_id and scope from the URL when hook params omit them', async () => {
window.history.replaceState({}, '', '/?client_id=from_url&scope=openid%20email');

const { result } = renderHook(() => useOAuthConsent(), { wrapper });

await waitFor(() => expect(result.current.isLoading).toBe(false));

expect(getConsentInfoSpy).toHaveBeenCalledTimes(1);
expect(getConsentInfoSpy).toHaveBeenCalledWith({ oauthClientId: 'from_url', scope: 'openid email' });
expect(result.current.data).toEqual(consentInfo);
});

it('prefers explicit oauthClientId over URL client_id', async () => {
window.history.replaceState({}, '', '/?client_id=from_url');

const { result } = renderHook(() => useOAuthConsent({ oauthClientId: 'explicit_id' }), { wrapper });

await waitFor(() => expect(result.current.isLoading).toBe(false));

expect(getConsentInfoSpy).toHaveBeenCalledWith({ oauthClientId: 'explicit_id' });
});

it('does not fall back to URL client_id when oauthClientId is explicitly empty', () => {
window.history.replaceState({}, '', '/?client_id=from_url');

const { result } = renderHook(() => useOAuthConsent({ oauthClientId: '' }), { wrapper });

expect(getConsentInfoSpy).not.toHaveBeenCalled();
expect(result.current.isLoading).toBe(false);
});

it('prefers explicit scope over URL scope', async () => {
window.history.replaceState({}, '', '/?client_id=cid&scope=from_url');

const { result } = renderHook(() => useOAuthConsent({ scope: 'explicit_scope' }), { wrapper });

await waitFor(() => expect(result.current.isLoading).toBe(false));

expect(getConsentInfoSpy).toHaveBeenCalledWith({ oauthClientId: 'cid', scope: 'explicit_scope' });
});
});
2 changes: 2 additions & 0 deletions packages/shared/src/react/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
export { assertContextExists, createContextAndHook } from './createContextAndHook';
export { useAPIKeys } from './useAPIKeys';
export { useOAuthConsent } from './useOAuthConsent';
export type { UseOAuthConsentParams, UseOAuthConsentReturn } from './useOAuthConsent.types';
export { useOrganization } from './useOrganization';
export { useOrganizationCreationDefaults } from './useOrganizationCreationDefaults';
export type {
Expand Down
43 changes: 43 additions & 0 deletions packages/shared/src/react/hooks/useOAuthConsent.shared.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { useMemo } from 'react';

import type { GetOAuthConsentInfoParams } from '../../types';
import { STABLE_KEYS } from '../stable-keys';
import { createCacheKeys } from './createCacheKeys';

/**
* Parses OAuth authorize-style query data from a search string (typically `window.location.search`).
*
* @internal
*/
export function readOAuthConsentFromSearch(search: string): {
oauthClientId: string;
scope?: string;
} {
const sp = new URLSearchParams(search);
const oauthClientId = sp.get('client_id') ?? '';
const scopeValue = sp.get('scope');
if (scopeValue === null) {
return { oauthClientId };
}
return { oauthClientId, scope: scopeValue };
}

export function useOAuthConsentCacheKeys(params: { userId: string | null; oauthClientId: string; scope?: string }) {
const { userId, oauthClientId, scope } = params;
return useMemo(() => {
const args: Pick<GetOAuthConsentInfoParams, 'oauthClientId'> & { scope?: string } = { oauthClientId };
if (scope !== undefined) {
args.scope = scope;
}
return createCacheKeys({
stablePrefix: STABLE_KEYS.OAUTH_CONSENT_INFO_KEY,
authenticated: true,
tracked: {
userId: userId ?? null,
},
untracked: {
args,
},
});
}, [userId, oauthClientId, scope]);
}
96 changes: 96 additions & 0 deletions packages/shared/src/react/hooks/useOAuthConsent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
'use client';

import { useMemo } from 'react';

import { eventMethodCalled } from '../../telemetry/events/method-called';
import type { LoadedClerk } from '../../types/clerk';
import { defineKeepPreviousDataFn } from '../clerk-rq/keep-previous-data';
import { useClerkQuery } from '../clerk-rq/useQuery';
import { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';
import { useUserBase } from './base/useUserBase';
import { readOAuthConsentFromSearch, useOAuthConsentCacheKeys } from './useOAuthConsent.shared';
import type { UseOAuthConsentParams, UseOAuthConsentReturn } from './useOAuthConsent.types';

const HOOK_NAME = 'useOAuthConsent';

/**
* The `useOAuthConsent()` hook loads OAuth application consent metadata for the **signed-in** user
* (`GET /me/oauth/consent/{oauthClientId}`). Ensure the user is authenticated before relying on this hook
* (for example, redirect to sign-in on your custom consent route).
*
* `oauthClientId` and `scope` are optional. On the client, values default from a single snapshot of
* `window.location.search` (`client_id` and `scope`). Pass them explicitly to override.
*
* @internal
*
* @example
* ### From the URL (`?client_id=...&scope=...`)
*
* ```tsx
* import { useOAuthConsent } from '@clerk/react/internal'
*
* export default function OAuthConsentPage() {
* const { data, isLoading, error } = useOAuthConsent()
* // ...
* }
* ```
*
* @example
* ### Explicit values (override URL)
*
* ```tsx
* import { useOAuthConsent } from '@clerk/react/internal'
*
* const { data, isLoading, error } = useOAuthConsent({
* oauthClientId: clientIdFromProps,
* scope: scopeFromProps,
* })
* ```
*/
export function useOAuthConsent(params: UseOAuthConsentParams = {}): UseOAuthConsentReturn {
useAssertWrappedByClerkProvider(HOOK_NAME);

const { oauthClientId: oauthClientIdParam, scope: scopeParam, keepPreviousData = true, enabled = true } = params;
const clerk = useClerkInstanceContext();
const user = useUserBase();

const fromUrl = useMemo(() => {
if (typeof window === 'undefined' || !window.location) {
return { oauthClientId: '' };
}
return readOAuthConsentFromSearch(window.location.search);
}, []);

const oauthClientId = (oauthClientIdParam !== undefined ? oauthClientIdParam : fromUrl.oauthClientId).trim();
const scope = scopeParam !== undefined ? scopeParam : fromUrl.scope;

clerk.telemetry?.record(eventMethodCalled(HOOK_NAME));

const { queryKey } = useOAuthConsentCacheKeys({
userId: user?.id ?? null,
oauthClientId,
scope,
});

const hasClientId = oauthClientId.length > 0;
const queryEnabled = Boolean(user) && hasClientId && enabled && clerk.loaded;

const query = useClerkQuery({
queryKey,
queryFn: () => fetchConsentInfo(clerk, { oauthClientId, scope }),
enabled: queryEnabled,
placeholderData: defineKeepPreviousDataFn(keepPreviousData && queryEnabled),
});

return {
data: query.data,
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

let's change data to consentInfo

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

After doing another review, I'd say we should keep data here. Every other useClerkQuery-based hook returns data, not a named field.

The hook name already tells us what data is here, which is the consent info, and consumers can always destructure as const { data: consentInfo } = useOAuthConsent() if they want a named variable.

error: (query.error ?? null) as UseOAuthConsentReturn['error'],
isLoading: query.isLoading,
isFetching: query.isFetching,
};
}

function fetchConsentInfo(clerk: LoadedClerk, params: { oauthClientId: string; scope?: string }) {
const { oauthClientId, scope } = params;
return clerk.oauthApplication.getConsentInfo(scope !== undefined ? { oauthClientId, scope } : { oauthClientId });
}
Loading
Loading