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/few-stamps-retire.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/clerk-js': minor
'@clerk/react': minor
'@clerk/shared': minor
---

Add `OAuthApplication` resource and `getConsentInfo()` method for retrieving OAuth consent information, enabling custom OAuth consent flows.
13 changes: 12 additions & 1 deletion packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,6 +88,7 @@ import type {
ListenerOptions,
LoadedClerk,
NavigateOptions,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand DownExpand Up@@ -178,7 +179,7 @@ import { APIKeys } from './modules/apiKeys';
import { Billing } from './modules/billing';
import { createCheckoutInstance } from './modules/checkout/instance';
import { Protect } from './protect';
import { BaseResource, Client, Environment, Organization, Waitlist } from './resources/internal';
import { BaseResource, Client, Environment, OAuthApplication, Organization, Waitlist } from './resources/internal';
import { State } from './state';

type SetActiveHook = (intent?: 'sign-out') => void | Promise<void>;
Expand DownExpand Up@@ -224,6 +225,7 @@ export class Clerk implements ClerkInterface {

private static _billing: BillingNamespace;
private static _apiKeys: APIKeysNamespace;
private static _oauthApplication: OAuthApplicationNamespace;
private _checkout: ClerkInterface['__experimental_checkout'] | undefined;

public client: ClientResource | undefined;
Expand DownExpand Up@@ -403,6 +405,15 @@ export class Clerk implements ClerkInterface {
return Clerk._apiKeys;
}

get oauthApplication(): OAuthApplicationNamespace {
if (!Clerk._oauthApplication) {
Clerk._oauthApplication = {
getConsentInfo: params => OAuthApplication.getConsentInfo(params),
};
}
return Clerk._oauthApplication;
}

__experimental_checkout(options: __experimental_CheckoutOptions): CheckoutSignalValue {
if (!this._checkout) {
this._checkout = (params: any) => createCheckoutInstance(this, params);
Expand Down
49 changes: 49 additions & 0 deletions packages/clerk-js/src/core/resources/OAuthApplication.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
import { ClerkRuntimeError } from '@clerk/shared/error';
import type {
ClerkResourceJSON,
GetOAuthConsentInfoParams,
OAuthConsentInfo,
OAuthConsentInfoJSON,
} from '@clerk/shared/types';

import { BaseResource } from './internal';

export class OAuthApplication extends BaseResource {
pathRoot = '';

protected fromJSON(_data: ClerkResourceJSON | null): this {
return this;
}

static async getConsentInfo(params: GetOAuthConsentInfoParams): Promise<OAuthConsentInfo> {
const { oauthClientId, scope } = params;
const json = await BaseResource._fetch<OAuthConsentInfoJSON>(
{
method: 'GET',
path: `/me/oauth/consent/${encodeURIComponent(oauthClientId)}`,
search: scope !== undefined ? { scope } : undefined,
},
{ skipUpdateClient: true },
);

if (!json) {
throw new ClerkRuntimeError('Network request failed while offline', { code: 'network_error' });
}

// Handle in case we start wrapping the response in the future
const data = json.response ?? json;
return {
oauthApplicationName: data.oauth_application_name,
oauthApplicationLogoUrl: data.oauth_application_logo_url,
oauthApplicationUrl: data.oauth_application_url,
clientId: data.client_id,
state: data.state,
scopes:
data.scopes?.map(scope => ({
scope: scope.scope,
description: scope.description,
requiresConsent: scope.requires_consent,
})) ?? [],
};
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import type { InstanceType, OAuthConsentInfoJSON } from '@clerk/shared/types';
import { afterEach, describe, expect, it, type Mock, vi } from 'vitest';

import { mockFetch } from '@/test/core-fixtures';

import { SUPPORTED_FAPI_VERSION } from '../../constants';
import { createFapiClient } from '../../fapiClient';
import { BaseResource } from '../internal';
import { OAuthApplication } from '../OAuthApplication';

const consentPayload: OAuthConsentInfoJSON = {
object: 'oauth_consent_info',
id: 'client_abc',
oauth_application_name: 'My App',
oauth_application_logo_url: 'https://img.example/logo.png',
oauth_application_url: 'https://app.example',
client_id: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requires_consent: true }],
};

describe('OAuthApplication.getConsentInfo', () => {
afterEach(() => {
(global.fetch as Mock)?.mockClear?.();
BaseResource.clerk = null as any;
vi.restoreAllMocks();
});

it('calls BaseResource._fetch with GET, encoded path, optional scope, and skipUpdateClient', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

await OAuthApplication.getConsentInfo({ oauthClientId: 'my/client id', scope: 'openid email' });

expect(fetchSpy).toHaveBeenCalledWith(
{
method: 'GET',
path: '/me/oauth/consent/my%2Fclient%20id',
search: { scope: 'openid email' },
},
{ skipUpdateClient: true },
);
});

it('omits search when scope is undefined', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

await OAuthApplication.getConsentInfo({ oauthClientId: 'cid' });

expect(fetchSpy).toHaveBeenCalledWith(
expect.objectContaining({
search: undefined,
}),
{ skipUpdateClient: true },
);
});

it('returns OAuthConsentInfo from the FAPI response', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue(consentPayload as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });

expect(info).toEqual({
oauthApplicationName: 'My App',
oauthApplicationLogoUrl: 'https://img.example/logo.png',
oauthApplicationUrl: 'https://app.example',
clientId: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requiresConsent: true }],
});
});

it('returns OAuthConsentInfo from the FAPI response (enveloped)', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });

expect(info).toEqual({
oauthApplicationName: 'My App',
oauthApplicationLogoUrl: 'https://img.example/logo.png',
oauthApplicationUrl: 'https://app.example',
clientId: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requiresConsent: true }],
});
});

it('defaults scopes to an empty array when absent', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: { ...consentPayload, scopes: undefined },
} as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });
expect(info.scopes).toEqual([]);
});

it('maps ClerkAPIResponseError from FAPI on non-2xx', async () => {
mockFetch(false, 422, {
errors: [{ code: 'oauth_consent_error', long_message: 'Consent metadata unavailable' }],
});

BaseResource.clerk = {
getFapiClient: () =>
createFapiClient({
frontendApi: 'clerk.example.com',
getSessionId: () => undefined,
instanceType: 'development' as InstanceType,
}),
__internal_setCountry: vi.fn(),
handleUnauthenticated: vi.fn(),
__internal_handleUnauthenticatedDevBrowser: vi.fn(),
} as any;

await expect(OAuthApplication.getConsentInfo({ oauthClientId: 'cid' })).rejects.toSatisfy(
(err: unknown) => err instanceof ClerkAPIResponseError && err.message === 'Consent metadata unavailable',
);

expect(global.fetch).toHaveBeenCalledTimes(1);
const [url] = (global.fetch as Mock).mock.calls[0];
expect(url.toString()).toContain(`/v1/me/oauth/consent/cid`);
expect(url.toString()).toContain(`__clerk_api_version=${SUPPORTED_FAPI_VERSION}`);
});

it('throws ClerkRuntimeError when _fetch returns null (offline)', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue(null);

BaseResource.clerk = {} as any;

await expect(OAuthApplication.getConsentInfo({ oauthClientId: 'cid' })).rejects.toMatchObject({
code: 'network_error',
});
});
});
1 change: 1 addition & 0 deletions packages/clerk-js/src/core/resources/internal.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,6 +22,7 @@ export * from './ExternalAccount';
export * from './Feature';
export * from './IdentificationLink';
export * from './Image';
export * from './OAuthApplication';
export * from './Organization';
export * from './OrganizationDomain';
export * from './OrganizationInvitation';
Expand Down
7 changes: 7 additions & 0 deletions packages/react/src/isomorphicClerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,7 @@ import type {
ListenerCallback,
ListenerOptions,
LoadedClerk,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand DownExpand Up@@ -118,11 +119,13 @@ type IsomorphicLoadedClerk = Without<
| '__internal_reloadInitialResources'
| 'billing'
| 'apiKeys'
| 'oauthApplication'
| '__internal_setActiveInProgress'
> & {
client: ClientResource | undefined;
billing: BillingNamespace | undefined;
apiKeys: APIKeysNamespace | undefined;
oauthApplication: OAuthApplicationNamespace | undefined;
};

export class IsomorphicClerk implements IsomorphicLoadedClerk {
Expand DownExpand Up@@ -844,6 +847,10 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.clerkjs?.apiKeys;
}

get oauthApplication(): OAuthApplicationNamespace | undefined {
return this.clerkjs?.oauthApplication;
}

__experimental_checkout = (...args: Parameters<Clerk['__experimental_checkout']>) => {
return this.loaded && this.clerkjs
? this.clerkjs.__experimental_checkout(...args)
Expand Down
11 changes: 11 additions & 0 deletions packages/shared/src/types/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@ import type { DisplayThemeJSON } from './json';
import type { LocalizationResource } from './localization';
import type { DomainOrProxyUrl, MultiDomainAndOrProxy } from './multiDomain';
import type { OAuthProvider, OAuthScope } from './oauth';
import type { OAuthApplicationNamespace } from './oauthApplication';
import type { OrganizationResource } from './organization';
import type { OrganizationCustomRoleKey } from './organizationMembership';
import type { ClerkPaginationParams } from './pagination';
Expand DownExpand Up@@ -168,6 +169,7 @@ export type SetActiveNavigate = (params: {
session: SessionResource;
/**
* Decorate the destination URL to enable Safari ITP cookie refresh when needed.
*
* @see {@link DecorateUrl}
*/
decorateUrl: DecorateUrl;
Expand DownExpand Up@@ -1027,6 +1029,11 @@ export interface Clerk {
*/
apiKeys: APIKeysNamespace;

/**
* OAuth application helpers (e.g. consent metadata for custom consent UIs).
*/
oauthApplication: OAuthApplicationNamespace;

/**
* Checkout API
*
Expand DownExpand Up@@ -2496,21 +2503,25 @@ export type IsomorphicClerkOptions = Without<ClerkOptions, 'isSatellite'> & {
Clerk?: ClerkProp;
/**
* The URL that `@clerk/clerk-js` should be hot-loaded from.
*
* @internal
*/
__internal_clerkJSUrl?: string;
/**
* The npm version for `@clerk/clerk-js`.
*
* @internal
*/
__internal_clerkJSVersion?: string;
/**
* The URL that `@clerk/ui` should be hot-loaded from.
*
* @internal
*/
__internal_clerkUIUrl?: string;
/**
* The npm version for `@clerk/ui`.
*
* @internal
*/
__internal_clerkUIVersion?: string;
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/types/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,6 +33,7 @@ export type * from './key';
export type * from './localization';
export type * from './multiDomain';
export type * from './oauth';
export type * from './oauthApplication';
export type * from './organization';
export type * from './organizationCreationDefaults';
export type * from './organizationDomain';
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
feat(js): add clerk.oauthApplication.getConsentInfo by jfoshee · Pull Request #8275 · clerk/javascript · GitHub
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/few-stamps-retire.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/clerk-js': minor
'@clerk/react': minor
'@clerk/shared': minor
---

Add `OAuthApplication` resource and `getConsentInfo()` method for retrieving OAuth consent information, enabling custom OAuth consent flows.
13 changes: 12 additions & 1 deletion packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,6 +88,7 @@ import type {
ListenerOptions,
LoadedClerk,
NavigateOptions,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand DownExpand Up@@ -178,7 +179,7 @@ import { APIKeys } from './modules/apiKeys';
import { Billing } from './modules/billing';
import { createCheckoutInstance } from './modules/checkout/instance';
import { Protect } from './protect';
import { BaseResource, Client, Environment, Organization, Waitlist } from './resources/internal';
import { BaseResource, Client, Environment, OAuthApplication, Organization, Waitlist } from './resources/internal';
import { State } from './state';

type SetActiveHook = (intent?: 'sign-out') => void | Promise<void>;
Expand DownExpand Up@@ -224,6 +225,7 @@ export class Clerk implements ClerkInterface {

private static _billing: BillingNamespace;
private static _apiKeys: APIKeysNamespace;
private static _oauthApplication: OAuthApplicationNamespace;
private _checkout: ClerkInterface['__experimental_checkout'] | undefined;

public client: ClientResource | undefined;
Expand DownExpand Up@@ -403,6 +405,15 @@ export class Clerk implements ClerkInterface {
return Clerk._apiKeys;
}

get oauthApplication(): OAuthApplicationNamespace {
if (!Clerk._oauthApplication) {
Clerk._oauthApplication = {
getConsentInfo: params => OAuthApplication.getConsentInfo(params),
};
}
return Clerk._oauthApplication;
}

__experimental_checkout(options: __experimental_CheckoutOptions): CheckoutSignalValue {
if (!this._checkout) {
this._checkout = (params: any) => createCheckoutInstance(this, params);
Expand Down
49 changes: 49 additions & 0 deletions packages/clerk-js/src/core/resources/OAuthApplication.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
import { ClerkRuntimeError } from '@clerk/shared/error';
import type {
ClerkResourceJSON,
GetOAuthConsentInfoParams,
OAuthConsentInfo,
OAuthConsentInfoJSON,
} from '@clerk/shared/types';

import { BaseResource } from './internal';

export class OAuthApplication extends BaseResource {
pathRoot = '';

protected fromJSON(_data: ClerkResourceJSON | null): this {
return this;
}

static async getConsentInfo(params: GetOAuthConsentInfoParams): Promise<OAuthConsentInfo> {
const { oauthClientId, scope } = params;
const json = await BaseResource._fetch<OAuthConsentInfoJSON>(
{
method: 'GET',
path: `/me/oauth/consent/${encodeURIComponent(oauthClientId)}`,
search: scope !== undefined ? { scope } : undefined,
},
{ skipUpdateClient: true },
);

if (!json) {
throw new ClerkRuntimeError('Network request failed while offline', { code: 'network_error' });
}

// Handle in case we start wrapping the response in the future
const data = json.response ?? json;
return {
oauthApplicationName: data.oauth_application_name,
oauthApplicationLogoUrl: data.oauth_application_logo_url,
oauthApplicationUrl: data.oauth_application_url,
clientId: data.client_id,
state: data.state,
scopes:
data.scopes?.map(scope => ({
scope: scope.scope,
description: scope.description,
requiresConsent: scope.requires_consent,
})) ?? [],
};
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import type { InstanceType, OAuthConsentInfoJSON } from '@clerk/shared/types';
import { afterEach, describe, expect, it, type Mock, vi } from 'vitest';

import { mockFetch } from '@/test/core-fixtures';

import { SUPPORTED_FAPI_VERSION } from '../../constants';
import { createFapiClient } from '../../fapiClient';
import { BaseResource } from '../internal';
import { OAuthApplication } from '../OAuthApplication';

const consentPayload: OAuthConsentInfoJSON = {
object: 'oauth_consent_info',
id: 'client_abc',
oauth_application_name: 'My App',
oauth_application_logo_url: 'https://img.example/logo.png',
oauth_application_url: 'https://app.example',
client_id: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requires_consent: true }],
};

describe('OAuthApplication.getConsentInfo', () => {
afterEach(() => {
(global.fetch as Mock)?.mockClear?.();
BaseResource.clerk = null as any;
vi.restoreAllMocks();
});

it('calls BaseResource._fetch with GET, encoded path, optional scope, and skipUpdateClient', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

await OAuthApplication.getConsentInfo({ oauthClientId: 'my/client id', scope: 'openid email' });

expect(fetchSpy).toHaveBeenCalledWith(
{
method: 'GET',
path: '/me/oauth/consent/my%2Fclient%20id',
search: { scope: 'openid email' },
},
{ skipUpdateClient: true },
);
});

it('omits search when scope is undefined', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

await OAuthApplication.getConsentInfo({ oauthClientId: 'cid' });

expect(fetchSpy).toHaveBeenCalledWith(
expect.objectContaining({
search: undefined,
}),
{ skipUpdateClient: true },
);
});

it('returns OAuthConsentInfo from the FAPI response', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue(consentPayload as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });

expect(info).toEqual({
oauthApplicationName: 'My App',
oauthApplicationLogoUrl: 'https://img.example/logo.png',
oauthApplicationUrl: 'https://app.example',
clientId: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requiresConsent: true }],
});
});

it('returns OAuthConsentInfo from the FAPI response (enveloped)', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });

expect(info).toEqual({
oauthApplicationName: 'My App',
oauthApplicationLogoUrl: 'https://img.example/logo.png',
oauthApplicationUrl: 'https://app.example',
clientId: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requiresConsent: true }],
});
});

it('defaults scopes to an empty array when absent', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: { ...consentPayload, scopes: undefined },
} as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });
expect(info.scopes).toEqual([]);
});

it('maps ClerkAPIResponseError from FAPI on non-2xx', async () => {
mockFetch(false, 422, {
errors: [{ code: 'oauth_consent_error', long_message: 'Consent metadata unavailable' }],
});

BaseResource.clerk = {
getFapiClient: () =>
createFapiClient({
frontendApi: 'clerk.example.com',
getSessionId: () => undefined,
instanceType: 'development' as InstanceType,
}),
__internal_setCountry: vi.fn(),
handleUnauthenticated: vi.fn(),
__internal_handleUnauthenticatedDevBrowser: vi.fn(),
} as any;

await expect(OAuthApplication.getConsentInfo({ oauthClientId: 'cid' })).rejects.toSatisfy(
(err: unknown) => err instanceof ClerkAPIResponseError && err.message === 'Consent metadata unavailable',
);

expect(global.fetch).toHaveBeenCalledTimes(1);
const [url] = (global.fetch as Mock).mock.calls[0];
expect(url.toString()).toContain(`/v1/me/oauth/consent/cid`);
expect(url.toString()).toContain(`__clerk_api_version=${SUPPORTED_FAPI_VERSION}`);
});

it('throws ClerkRuntimeError when _fetch returns null (offline)', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue(null);

BaseResource.clerk = {} as any;

await expect(OAuthApplication.getConsentInfo({ oauthClientId: 'cid' })).rejects.toMatchObject({
code: 'network_error',
});
});
});
1 change: 1 addition & 0 deletions packages/clerk-js/src/core/resources/internal.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,6 +22,7 @@ export * from './ExternalAccount';
export * from './Feature';
export * from './IdentificationLink';
export * from './Image';
export * from './OAuthApplication';
export * from './Organization';
export * from './OrganizationDomain';
export * from './OrganizationInvitation';
Expand Down
7 changes: 7 additions & 0 deletions packages/react/src/isomorphicClerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,7 @@ import type {
ListenerCallback,
ListenerOptions,
LoadedClerk,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand DownExpand Up@@ -118,11 +119,13 @@ type IsomorphicLoadedClerk = Without<
| '__internal_reloadInitialResources'
| 'billing'
| 'apiKeys'
| 'oauthApplication'
| '__internal_setActiveInProgress'
> & {
client: ClientResource | undefined;
billing: BillingNamespace | undefined;
apiKeys: APIKeysNamespace | undefined;
oauthApplication: OAuthApplicationNamespace | undefined;
};

export class IsomorphicClerk implements IsomorphicLoadedClerk {
Expand DownExpand Up@@ -844,6 +847,10 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.clerkjs?.apiKeys;
}

get oauthApplication(): OAuthApplicationNamespace | undefined {
return this.clerkjs?.oauthApplication;
}

__experimental_checkout = (...args: Parameters<Clerk['__experimental_checkout']>) => {
return this.loaded && this.clerkjs
? this.clerkjs.__experimental_checkout(...args)
Expand Down
11 changes: 11 additions & 0 deletions packages/shared/src/types/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@ import type { DisplayThemeJSON } from './json';
import type { LocalizationResource } from './localization';
import type { DomainOrProxyUrl, MultiDomainAndOrProxy } from './multiDomain';
import type { OAuthProvider, OAuthScope } from './oauth';
import type { OAuthApplicationNamespace } from './oauthApplication';
import type { OrganizationResource } from './organization';
import type { OrganizationCustomRoleKey } from './organizationMembership';
import type { ClerkPaginationParams } from './pagination';
Expand DownExpand Up@@ -168,6 +169,7 @@ export type SetActiveNavigate = (params: {
session: SessionResource;
/**
* Decorate the destination URL to enable Safari ITP cookie refresh when needed.
*
* @see {@link DecorateUrl}
*/
decorateUrl: DecorateUrl;
Expand DownExpand Up@@ -1027,6 +1029,11 @@ export interface Clerk {
*/
apiKeys: APIKeysNamespace;

/**
* OAuth application helpers (e.g. consent metadata for custom consent UIs).
*/
oauthApplication: OAuthApplicationNamespace;

/**
* Checkout API
*
Expand DownExpand Up@@ -2496,21 +2503,25 @@ export type IsomorphicClerkOptions = Without<ClerkOptions, 'isSatellite'> & {
Clerk?: ClerkProp;
/**
* The URL that `@clerk/clerk-js` should be hot-loaded from.
*
* @internal
*/
__internal_clerkJSUrl?: string;
/**
* The npm version for `@clerk/clerk-js`.
*
* @internal
*/
__internal_clerkJSVersion?: string;
/**
* The URL that `@clerk/ui` should be hot-loaded from.
*
* @internal
*/
__internal_clerkUIUrl?: string;
/**
* The npm version for `@clerk/ui`.
*
* @internal
*/
__internal_clerkUIVersion?: string;
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/types/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,6 +33,7 @@ export type * from './key';
export type * from './localization';
export type * from './multiDomain';
export type * from './oauth';
export type * from './oauthApplication';
export type * from './organization';
export type * from './organizationCreationDefaults';
export type * from './organizationDomain';
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(js): add clerk.oauthApplication.getConsentInfo by jfoshee · Pull Request #8275 · clerk/javascript · GitHub
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/few-stamps-retire.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/clerk-js': minor
'@clerk/react': minor
'@clerk/shared': minor
---

Add `OAuthApplication` resource and `getConsentInfo()` method for retrieving OAuth consent information, enabling custom OAuth consent flows.
13 changes: 12 additions & 1 deletion packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,6 +88,7 @@ import type {
ListenerOptions,
LoadedClerk,
NavigateOptions,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand DownExpand Up@@ -178,7 +179,7 @@ import { APIKeys } from './modules/apiKeys';
import { Billing } from './modules/billing';
import { createCheckoutInstance } from './modules/checkout/instance';
import { Protect } from './protect';
import { BaseResource, Client, Environment, Organization, Waitlist } from './resources/internal';
import { BaseResource, Client, Environment, OAuthApplication, Organization, Waitlist } from './resources/internal';
import { State } from './state';

type SetActiveHook = (intent?: 'sign-out') => void | Promise<void>;
Expand DownExpand Up@@ -224,6 +225,7 @@ export class Clerk implements ClerkInterface {

private static _billing: BillingNamespace;
private static _apiKeys: APIKeysNamespace;
private static _oauthApplication: OAuthApplicationNamespace;
private _checkout: ClerkInterface['__experimental_checkout'] | undefined;

public client: ClientResource | undefined;
Expand DownExpand Up@@ -403,6 +405,15 @@ export class Clerk implements ClerkInterface {
return Clerk._apiKeys;
}

get oauthApplication(): OAuthApplicationNamespace {
if (!Clerk._oauthApplication) {
Clerk._oauthApplication = {
getConsentInfo: params => OAuthApplication.getConsentInfo(params),
};
}
return Clerk._oauthApplication;
}

__experimental_checkout(options: __experimental_CheckoutOptions): CheckoutSignalValue {
if (!this._checkout) {
this._checkout = (params: any) => createCheckoutInstance(this, params);
Expand Down
49 changes: 49 additions & 0 deletions packages/clerk-js/src/core/resources/OAuthApplication.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
import { ClerkRuntimeError } from '@clerk/shared/error';
import type {
ClerkResourceJSON,
GetOAuthConsentInfoParams,
OAuthConsentInfo,
OAuthConsentInfoJSON,
} from '@clerk/shared/types';

import { BaseResource } from './internal';

export class OAuthApplication extends BaseResource {
pathRoot = '';

protected fromJSON(_data: ClerkResourceJSON | null): this {
return this;
}

static async getConsentInfo(params: GetOAuthConsentInfoParams): Promise<OAuthConsentInfo> {
const { oauthClientId, scope } = params;
const json = await BaseResource._fetch<OAuthConsentInfoJSON>(
{
method: 'GET',
path: `/me/oauth/consent/${encodeURIComponent(oauthClientId)}`,
search: scope !== undefined ? { scope } : undefined,
},
{ skipUpdateClient: true },
);

if (!json) {
throw new ClerkRuntimeError('Network request failed while offline', { code: 'network_error' });
}

// Handle in case we start wrapping the response in the future
const data = json.response ?? json;
return {
oauthApplicationName: data.oauth_application_name,
oauthApplicationLogoUrl: data.oauth_application_logo_url,
oauthApplicationUrl: data.oauth_application_url,
clientId: data.client_id,
state: data.state,
scopes:
data.scopes?.map(scope => ({
scope: scope.scope,
description: scope.description,
requiresConsent: scope.requires_consent,
})) ?? [],
};
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import type { InstanceType, OAuthConsentInfoJSON } from '@clerk/shared/types';
import { afterEach, describe, expect, it, type Mock, vi } from 'vitest';

import { mockFetch } from '@/test/core-fixtures';

import { SUPPORTED_FAPI_VERSION } from '../../constants';
import { createFapiClient } from '../../fapiClient';
import { BaseResource } from '../internal';
import { OAuthApplication } from '../OAuthApplication';

const consentPayload: OAuthConsentInfoJSON = {
object: 'oauth_consent_info',
id: 'client_abc',
oauth_application_name: 'My App',
oauth_application_logo_url: 'https://img.example/logo.png',
oauth_application_url: 'https://app.example',
client_id: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requires_consent: true }],
};

describe('OAuthApplication.getConsentInfo', () => {
afterEach(() => {
(global.fetch as Mock)?.mockClear?.();
BaseResource.clerk = null as any;
vi.restoreAllMocks();
});

it('calls BaseResource._fetch with GET, encoded path, optional scope, and skipUpdateClient', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

await OAuthApplication.getConsentInfo({ oauthClientId: 'my/client id', scope: 'openid email' });

expect(fetchSpy).toHaveBeenCalledWith(
{
method: 'GET',
path: '/me/oauth/consent/my%2Fclient%20id',
search: { scope: 'openid email' },
},
{ skipUpdateClient: true },
);
});

it('omits search when scope is undefined', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

await OAuthApplication.getConsentInfo({ oauthClientId: 'cid' });

expect(fetchSpy).toHaveBeenCalledWith(
expect.objectContaining({
search: undefined,
}),
{ skipUpdateClient: true },
);
});

it('returns OAuthConsentInfo from the FAPI response', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue(consentPayload as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });

expect(info).toEqual({
oauthApplicationName: 'My App',
oauthApplicationLogoUrl: 'https://img.example/logo.png',
oauthApplicationUrl: 'https://app.example',
clientId: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requiresConsent: true }],
});
});

it('returns OAuthConsentInfo from the FAPI response (enveloped)', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });

expect(info).toEqual({
oauthApplicationName: 'My App',
oauthApplicationLogoUrl: 'https://img.example/logo.png',
oauthApplicationUrl: 'https://app.example',
clientId: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requiresConsent: true }],
});
});

it('defaults scopes to an empty array when absent', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: { ...consentPayload, scopes: undefined },
} as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });
expect(info.scopes).toEqual([]);
});

it('maps ClerkAPIResponseError from FAPI on non-2xx', async () => {
mockFetch(false, 422, {
errors: [{ code: 'oauth_consent_error', long_message: 'Consent metadata unavailable' }],
});

BaseResource.clerk = {
getFapiClient: () =>
createFapiClient({
frontendApi: 'clerk.example.com',
getSessionId: () => undefined,
instanceType: 'development' as InstanceType,
}),
__internal_setCountry: vi.fn(),
handleUnauthenticated: vi.fn(),
__internal_handleUnauthenticatedDevBrowser: vi.fn(),
} as any;

await expect(OAuthApplication.getConsentInfo({ oauthClientId: 'cid' })).rejects.toSatisfy(
(err: unknown) => err instanceof ClerkAPIResponseError && err.message === 'Consent metadata unavailable',
);

expect(global.fetch).toHaveBeenCalledTimes(1);
const [url] = (global.fetch as Mock).mock.calls[0];
expect(url.toString()).toContain(`/v1/me/oauth/consent/cid`);
expect(url.toString()).toContain(`__clerk_api_version=${SUPPORTED_FAPI_VERSION}`);
});

it('throws ClerkRuntimeError when _fetch returns null (offline)', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue(null);

BaseResource.clerk = {} as any;

await expect(OAuthApplication.getConsentInfo({ oauthClientId: 'cid' })).rejects.toMatchObject({
code: 'network_error',
});
});
});
1 change: 1 addition & 0 deletions packages/clerk-js/src/core/resources/internal.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,6 +22,7 @@ export * from './ExternalAccount';
export * from './Feature';
export * from './IdentificationLink';
export * from './Image';
export * from './OAuthApplication';
export * from './Organization';
export * from './OrganizationDomain';
export * from './OrganizationInvitation';
Expand Down
7 changes: 7 additions & 0 deletions packages/react/src/isomorphicClerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,7 @@ import type {
ListenerCallback,
ListenerOptions,
LoadedClerk,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand DownExpand Up@@ -118,11 +119,13 @@ type IsomorphicLoadedClerk = Without<
| '__internal_reloadInitialResources'
| 'billing'
| 'apiKeys'
| 'oauthApplication'
| '__internal_setActiveInProgress'
> & {
client: ClientResource | undefined;
billing: BillingNamespace | undefined;
apiKeys: APIKeysNamespace | undefined;
oauthApplication: OAuthApplicationNamespace | undefined;
};

export class IsomorphicClerk implements IsomorphicLoadedClerk {
Expand DownExpand Up@@ -844,6 +847,10 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.clerkjs?.apiKeys;
}

get oauthApplication(): OAuthApplicationNamespace | undefined {
return this.clerkjs?.oauthApplication;
}

__experimental_checkout = (...args: Parameters<Clerk['__experimental_checkout']>) => {
return this.loaded && this.clerkjs
? this.clerkjs.__experimental_checkout(...args)
Expand Down
11 changes: 11 additions & 0 deletions packages/shared/src/types/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@ import type { DisplayThemeJSON } from './json';
import type { LocalizationResource } from './localization';
import type { DomainOrProxyUrl, MultiDomainAndOrProxy } from './multiDomain';
import type { OAuthProvider, OAuthScope } from './oauth';
import type { OAuthApplicationNamespace } from './oauthApplication';
import type { OrganizationResource } from './organization';
import type { OrganizationCustomRoleKey } from './organizationMembership';
import type { ClerkPaginationParams } from './pagination';
Expand DownExpand Up@@ -168,6 +169,7 @@ export type SetActiveNavigate = (params: {
session: SessionResource;
/**
* Decorate the destination URL to enable Safari ITP cookie refresh when needed.
*
* @see {@link DecorateUrl}
*/
decorateUrl: DecorateUrl;
Expand DownExpand Up@@ -1027,6 +1029,11 @@ export interface Clerk {
*/
apiKeys: APIKeysNamespace;

/**
* OAuth application helpers (e.g. consent metadata for custom consent UIs).
*/
oauthApplication: OAuthApplicationNamespace;

/**
* Checkout API
*
Expand DownExpand Up@@ -2496,21 +2503,25 @@ export type IsomorphicClerkOptions = Without<ClerkOptions, 'isSatellite'> & {
Clerk?: ClerkProp;
/**
* The URL that `@clerk/clerk-js` should be hot-loaded from.
*
* @internal
*/
__internal_clerkJSUrl?: string;
/**
* The npm version for `@clerk/clerk-js`.
*
* @internal
*/
__internal_clerkJSVersion?: string;
/**
* The URL that `@clerk/ui` should be hot-loaded from.
*
* @internal
*/
__internal_clerkUIUrl?: string;
/**
* The npm version for `@clerk/ui`.
*
* @internal
*/
__internal_clerkUIVersion?: string;
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/types/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,6 +33,7 @@ export type * from './key';
export type * from './localization';
export type * from './multiDomain';
export type * from './oauth';
export type * from './oauthApplication';
export type * from './organization';
export type * from './organizationCreationDefaults';
export type * from './organizationDomain';
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(js): add clerk.oauthApplication.getConsentInfo by jfoshee · Pull Request #8275 · clerk/javascript · GitHub
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/few-stamps-retire.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/clerk-js': minor
'@clerk/react': minor
'@clerk/shared': minor
---

Add `OAuthApplication` resource and `getConsentInfo()` method for retrieving OAuth consent information, enabling custom OAuth consent flows.
13 changes: 12 additions & 1 deletion packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,6 +88,7 @@ import type {
ListenerOptions,
LoadedClerk,
NavigateOptions,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand DownExpand Up@@ -178,7 +179,7 @@ import { APIKeys } from './modules/apiKeys';
import { Billing } from './modules/billing';
import { createCheckoutInstance } from './modules/checkout/instance';
import { Protect } from './protect';
import { BaseResource, Client, Environment, Organization, Waitlist } from './resources/internal';
import { BaseResource, Client, Environment, OAuthApplication, Organization, Waitlist } from './resources/internal';
import { State } from './state';

type SetActiveHook = (intent?: 'sign-out') => void | Promise<void>;
Expand DownExpand Up@@ -224,6 +225,7 @@ export class Clerk implements ClerkInterface {

private static _billing: BillingNamespace;
private static _apiKeys: APIKeysNamespace;
private static _oauthApplication: OAuthApplicationNamespace;
private _checkout: ClerkInterface['__experimental_checkout'] | undefined;

public client: ClientResource | undefined;
Expand DownExpand Up@@ -403,6 +405,15 @@ export class Clerk implements ClerkInterface {
return Clerk._apiKeys;
}

get oauthApplication(): OAuthApplicationNamespace {
if (!Clerk._oauthApplication) {
Clerk._oauthApplication = {
getConsentInfo: params => OAuthApplication.getConsentInfo(params),
};
}
return Clerk._oauthApplication;
}

__experimental_checkout(options: __experimental_CheckoutOptions): CheckoutSignalValue {
if (!this._checkout) {
this._checkout = (params: any) => createCheckoutInstance(this, params);
Expand Down
49 changes: 49 additions & 0 deletions packages/clerk-js/src/core/resources/OAuthApplication.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
import { ClerkRuntimeError } from '@clerk/shared/error';
import type {
ClerkResourceJSON,
GetOAuthConsentInfoParams,
OAuthConsentInfo,
OAuthConsentInfoJSON,
} from '@clerk/shared/types';

import { BaseResource } from './internal';

export class OAuthApplication extends BaseResource {
pathRoot = '';

protected fromJSON(_data: ClerkResourceJSON | null): this {
return this;
}

static async getConsentInfo(params: GetOAuthConsentInfoParams): Promise<OAuthConsentInfo> {
const { oauthClientId, scope } = params;
const json = await BaseResource._fetch<OAuthConsentInfoJSON>(
{
method: 'GET',
path: `/me/oauth/consent/${encodeURIComponent(oauthClientId)}`,
search: scope !== undefined ? { scope } : undefined,
},
{ skipUpdateClient: true },
);

if (!json) {
throw new ClerkRuntimeError('Network request failed while offline', { code: 'network_error' });
}

// Handle in case we start wrapping the response in the future
const data = json.response ?? json;
return {
oauthApplicationName: data.oauth_application_name,
oauthApplicationLogoUrl: data.oauth_application_logo_url,
oauthApplicationUrl: data.oauth_application_url,
clientId: data.client_id,
state: data.state,
scopes:
data.scopes?.map(scope => ({
scope: scope.scope,
description: scope.description,
requiresConsent: scope.requires_consent,
})) ?? [],
};
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import type { InstanceType, OAuthConsentInfoJSON } from '@clerk/shared/types';
import { afterEach, describe, expect, it, type Mock, vi } from 'vitest';

import { mockFetch } from '@/test/core-fixtures';

import { SUPPORTED_FAPI_VERSION } from '../../constants';
import { createFapiClient } from '../../fapiClient';
import { BaseResource } from '../internal';
import { OAuthApplication } from '../OAuthApplication';

const consentPayload: OAuthConsentInfoJSON = {
object: 'oauth_consent_info',
id: 'client_abc',
oauth_application_name: 'My App',
oauth_application_logo_url: 'https://img.example/logo.png',
oauth_application_url: 'https://app.example',
client_id: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requires_consent: true }],
};

describe('OAuthApplication.getConsentInfo', () => {
afterEach(() => {
(global.fetch as Mock)?.mockClear?.();
BaseResource.clerk = null as any;
vi.restoreAllMocks();
});

it('calls BaseResource._fetch with GET, encoded path, optional scope, and skipUpdateClient', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

await OAuthApplication.getConsentInfo({ oauthClientId: 'my/client id', scope: 'openid email' });

expect(fetchSpy).toHaveBeenCalledWith(
{
method: 'GET',
path: '/me/oauth/consent/my%2Fclient%20id',
search: { scope: 'openid email' },
},
{ skipUpdateClient: true },
);
});

it('omits search when scope is undefined', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

await OAuthApplication.getConsentInfo({ oauthClientId: 'cid' });

expect(fetchSpy).toHaveBeenCalledWith(
expect.objectContaining({
search: undefined,
}),
{ skipUpdateClient: true },
);
});

it('returns OAuthConsentInfo from the FAPI response', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue(consentPayload as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });

expect(info).toEqual({
oauthApplicationName: 'My App',
oauthApplicationLogoUrl: 'https://img.example/logo.png',
oauthApplicationUrl: 'https://app.example',
clientId: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requiresConsent: true }],
});
});

it('returns OAuthConsentInfo from the FAPI response (enveloped)', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });

expect(info).toEqual({
oauthApplicationName: 'My App',
oauthApplicationLogoUrl: 'https://img.example/logo.png',
oauthApplicationUrl: 'https://app.example',
clientId: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requiresConsent: true }],
});
});

it('defaults scopes to an empty array when absent', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: { ...consentPayload, scopes: undefined },
} as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });
expect(info.scopes).toEqual([]);
});

it('maps ClerkAPIResponseError from FAPI on non-2xx', async () => {
mockFetch(false, 422, {
errors: [{ code: 'oauth_consent_error', long_message: 'Consent metadata unavailable' }],
});

BaseResource.clerk = {
getFapiClient: () =>
createFapiClient({
frontendApi: 'clerk.example.com',
getSessionId: () => undefined,
instanceType: 'development' as InstanceType,
}),
__internal_setCountry: vi.fn(),
handleUnauthenticated: vi.fn(),
__internal_handleUnauthenticatedDevBrowser: vi.fn(),
} as any;

await expect(OAuthApplication.getConsentInfo({ oauthClientId: 'cid' })).rejects.toSatisfy(
(err: unknown) => err instanceof ClerkAPIResponseError && err.message === 'Consent metadata unavailable',
);

expect(global.fetch).toHaveBeenCalledTimes(1);
const [url] = (global.fetch as Mock).mock.calls[0];
expect(url.toString()).toContain(`/v1/me/oauth/consent/cid`);
expect(url.toString()).toContain(`__clerk_api_version=${SUPPORTED_FAPI_VERSION}`);
});

it('throws ClerkRuntimeError when _fetch returns null (offline)', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue(null);

BaseResource.clerk = {} as any;

await expect(OAuthApplication.getConsentInfo({ oauthClientId: 'cid' })).rejects.toMatchObject({
code: 'network_error',
});
});
});
1 change: 1 addition & 0 deletions packages/clerk-js/src/core/resources/internal.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,6 +22,7 @@ export * from './ExternalAccount';
export * from './Feature';
export * from './IdentificationLink';
export * from './Image';
export * from './OAuthApplication';
export * from './Organization';
export * from './OrganizationDomain';
export * from './OrganizationInvitation';
Expand Down
7 changes: 7 additions & 0 deletions packages/react/src/isomorphicClerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,7 @@ import type {
ListenerCallback,
ListenerOptions,
LoadedClerk,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand DownExpand Up@@ -118,11 +119,13 @@ type IsomorphicLoadedClerk = Without<
| '__internal_reloadInitialResources'
| 'billing'
| 'apiKeys'
| 'oauthApplication'
| '__internal_setActiveInProgress'
> & {
client: ClientResource | undefined;
billing: BillingNamespace | undefined;
apiKeys: APIKeysNamespace | undefined;
oauthApplication: OAuthApplicationNamespace | undefined;
};

export class IsomorphicClerk implements IsomorphicLoadedClerk {
Expand DownExpand Up@@ -844,6 +847,10 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.clerkjs?.apiKeys;
}

get oauthApplication(): OAuthApplicationNamespace | undefined {
return this.clerkjs?.oauthApplication;
}

__experimental_checkout = (...args: Parameters<Clerk['__experimental_checkout']>) => {
return this.loaded && this.clerkjs
? this.clerkjs.__experimental_checkout(...args)
Expand Down
11 changes: 11 additions & 0 deletions packages/shared/src/types/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@ import type { DisplayThemeJSON } from './json';
import type { LocalizationResource } from './localization';
import type { DomainOrProxyUrl, MultiDomainAndOrProxy } from './multiDomain';
import type { OAuthProvider, OAuthScope } from './oauth';
import type { OAuthApplicationNamespace } from './oauthApplication';
import type { OrganizationResource } from './organization';
import type { OrganizationCustomRoleKey } from './organizationMembership';
import type { ClerkPaginationParams } from './pagination';
Expand DownExpand Up@@ -168,6 +169,7 @@ export type SetActiveNavigate = (params: {
session: SessionResource;
/**
* Decorate the destination URL to enable Safari ITP cookie refresh when needed.
*
* @see {@link DecorateUrl}
*/
decorateUrl: DecorateUrl;
Expand DownExpand Up@@ -1027,6 +1029,11 @@ export interface Clerk {
*/
apiKeys: APIKeysNamespace;

/**
* OAuth application helpers (e.g. consent metadata for custom consent UIs).
*/
oauthApplication: OAuthApplicationNamespace;

/**
* Checkout API
*
Expand DownExpand Up@@ -2496,21 +2503,25 @@ export type IsomorphicClerkOptions = Without<ClerkOptions, 'isSatellite'> & {
Clerk?: ClerkProp;
/**
* The URL that `@clerk/clerk-js` should be hot-loaded from.
*
* @internal
*/
__internal_clerkJSUrl?: string;
/**
* The npm version for `@clerk/clerk-js`.
*
* @internal
*/
__internal_clerkJSVersion?: string;
/**
* The URL that `@clerk/ui` should be hot-loaded from.
*
* @internal
*/
__internal_clerkUIUrl?: string;
/**
* The npm version for `@clerk/ui`.
*
* @internal
*/
__internal_clerkUIVersion?: string;
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/types/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,6 +33,7 @@ export type * from './key';
export type * from './localization';
export type * from './multiDomain';
export type * from './oauth';
export type * from './oauthApplication';
export type * from './organization';
export type * from './organizationCreationDefaults';
export type * from './organizationDomain';
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' feat(js): add clerk.oauthApplication.getConsentInfo by jfoshee · Pull Request #8275 · clerk/javascript · GitHub
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/few-stamps-retire.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/clerk-js': minor
'@clerk/react': minor
'@clerk/shared': minor
---

Add `OAuthApplication` resource and `getConsentInfo()` method for retrieving OAuth consent information, enabling custom OAuth consent flows.
13 changes: 12 additions & 1 deletion packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,6 +88,7 @@ import type {
ListenerOptions,
LoadedClerk,
NavigateOptions,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand DownExpand Up@@ -178,7 +179,7 @@ import { APIKeys } from './modules/apiKeys';
import { Billing } from './modules/billing';
import { createCheckoutInstance } from './modules/checkout/instance';
import { Protect } from './protect';
import { BaseResource, Client, Environment, Organization, Waitlist } from './resources/internal';
import { BaseResource, Client, Environment, OAuthApplication, Organization, Waitlist } from './resources/internal';
import { State } from './state';

type SetActiveHook = (intent?: 'sign-out') => void | Promise<void>;
Expand DownExpand Up@@ -224,6 +225,7 @@ export class Clerk implements ClerkInterface {

private static _billing: BillingNamespace;
private static _apiKeys: APIKeysNamespace;
private static _oauthApplication: OAuthApplicationNamespace;
private _checkout: ClerkInterface['__experimental_checkout'] | undefined;

public client: ClientResource | undefined;
Expand DownExpand Up@@ -403,6 +405,15 @@ export class Clerk implements ClerkInterface {
return Clerk._apiKeys;
}

get oauthApplication(): OAuthApplicationNamespace {
if (!Clerk._oauthApplication) {
Clerk._oauthApplication = {
getConsentInfo: params => OAuthApplication.getConsentInfo(params),
};
}
return Clerk._oauthApplication;
}

__experimental_checkout(options: __experimental_CheckoutOptions): CheckoutSignalValue {
if (!this._checkout) {
this._checkout = (params: any) => createCheckoutInstance(this, params);
Expand Down
49 changes: 49 additions & 0 deletions packages/clerk-js/src/core/resources/OAuthApplication.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
import { ClerkRuntimeError } from '@clerk/shared/error';
import type {
ClerkResourceJSON,
GetOAuthConsentInfoParams,
OAuthConsentInfo,
OAuthConsentInfoJSON,
} from '@clerk/shared/types';

import { BaseResource } from './internal';

export class OAuthApplication extends BaseResource {
pathRoot = '';

protected fromJSON(_data: ClerkResourceJSON | null): this {
return this;
}

static async getConsentInfo(params: GetOAuthConsentInfoParams): Promise<OAuthConsentInfo> {
const { oauthClientId, scope } = params;
const json = await BaseResource._fetch<OAuthConsentInfoJSON>(
{
method: 'GET',
path: `/me/oauth/consent/${encodeURIComponent(oauthClientId)}`,
search: scope !== undefined ? { scope } : undefined,
},
{ skipUpdateClient: true },
);

if (!json) {
throw new ClerkRuntimeError('Network request failed while offline', { code: 'network_error' });
}

// Handle in case we start wrapping the response in the future
const data = json.response ?? json;
return {
oauthApplicationName: data.oauth_application_name,
oauthApplicationLogoUrl: data.oauth_application_logo_url,
oauthApplicationUrl: data.oauth_application_url,
clientId: data.client_id,
state: data.state,
scopes:
data.scopes?.map(scope => ({
scope: scope.scope,
description: scope.description,
requiresConsent: scope.requires_consent,
})) ?? [],
};
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import type { InstanceType, OAuthConsentInfoJSON } from '@clerk/shared/types';
import { afterEach, describe, expect, it, type Mock, vi } from 'vitest';

import { mockFetch } from '@/test/core-fixtures';

import { SUPPORTED_FAPI_VERSION } from '../../constants';
import { createFapiClient } from '../../fapiClient';
import { BaseResource } from '../internal';
import { OAuthApplication } from '../OAuthApplication';

const consentPayload: OAuthConsentInfoJSON = {
object: 'oauth_consent_info',
id: 'client_abc',
oauth_application_name: 'My App',
oauth_application_logo_url: 'https://img.example/logo.png',
oauth_application_url: 'https://app.example',
client_id: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requires_consent: true }],
};

describe('OAuthApplication.getConsentInfo', () => {
afterEach(() => {
(global.fetch as Mock)?.mockClear?.();
BaseResource.clerk = null as any;
vi.restoreAllMocks();
});

it('calls BaseResource._fetch with GET, encoded path, optional scope, and skipUpdateClient', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

await OAuthApplication.getConsentInfo({ oauthClientId: 'my/client id', scope: 'openid email' });

expect(fetchSpy).toHaveBeenCalledWith(
{
method: 'GET',
path: '/me/oauth/consent/my%2Fclient%20id',
search: { scope: 'openid email' },
},
{ skipUpdateClient: true },
);
});

it('omits search when scope is undefined', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

await OAuthApplication.getConsentInfo({ oauthClientId: 'cid' });

expect(fetchSpy).toHaveBeenCalledWith(
expect.objectContaining({
search: undefined,
}),
{ skipUpdateClient: true },
);
});

it('returns OAuthConsentInfo from the FAPI response', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue(consentPayload as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });

expect(info).toEqual({
oauthApplicationName: 'My App',
oauthApplicationLogoUrl: 'https://img.example/logo.png',
oauthApplicationUrl: 'https://app.example',
clientId: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requiresConsent: true }],
});
});

it('returns OAuthConsentInfo from the FAPI response (enveloped)', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });

expect(info).toEqual({
oauthApplicationName: 'My App',
oauthApplicationLogoUrl: 'https://img.example/logo.png',
oauthApplicationUrl: 'https://app.example',
clientId: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requiresConsent: true }],
});
});

it('defaults scopes to an empty array when absent', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: { ...consentPayload, scopes: undefined },
} as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });
expect(info.scopes).toEqual([]);
});

it('maps ClerkAPIResponseError from FAPI on non-2xx', async () => {
mockFetch(false, 422, {
errors: [{ code: 'oauth_consent_error', long_message: 'Consent metadata unavailable' }],
});

BaseResource.clerk = {
getFapiClient: () =>
createFapiClient({
frontendApi: 'clerk.example.com',
getSessionId: () => undefined,
instanceType: 'development' as InstanceType,
}),
__internal_setCountry: vi.fn(),
handleUnauthenticated: vi.fn(),
__internal_handleUnauthenticatedDevBrowser: vi.fn(),
} as any;

await expect(OAuthApplication.getConsentInfo({ oauthClientId: 'cid' })).rejects.toSatisfy(
(err: unknown) => err instanceof ClerkAPIResponseError && err.message === 'Consent metadata unavailable',
);

expect(global.fetch).toHaveBeenCalledTimes(1);
const [url] = (global.fetch as Mock).mock.calls[0];
expect(url.toString()).toContain(`/v1/me/oauth/consent/cid`);
expect(url.toString()).toContain(`__clerk_api_version=${SUPPORTED_FAPI_VERSION}`);
});

it('throws ClerkRuntimeError when _fetch returns null (offline)', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue(null);

BaseResource.clerk = {} as any;

await expect(OAuthApplication.getConsentInfo({ oauthClientId: 'cid' })).rejects.toMatchObject({
code: 'network_error',
});
});
});
1 change: 1 addition & 0 deletions packages/clerk-js/src/core/resources/internal.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,6 +22,7 @@ export * from './ExternalAccount';
export * from './Feature';
export * from './IdentificationLink';
export * from './Image';
export * from './OAuthApplication';
export * from './Organization';
export * from './OrganizationDomain';
export * from './OrganizationInvitation';
Expand Down
7 changes: 7 additions & 0 deletions packages/react/src/isomorphicClerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,7 @@ import type {
ListenerCallback,
ListenerOptions,
LoadedClerk,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand DownExpand Up@@ -118,11 +119,13 @@ type IsomorphicLoadedClerk = Without<
| '__internal_reloadInitialResources'
| 'billing'
| 'apiKeys'
| 'oauthApplication'
| '__internal_setActiveInProgress'
> & {
client: ClientResource | undefined;
billing: BillingNamespace | undefined;
apiKeys: APIKeysNamespace | undefined;
oauthApplication: OAuthApplicationNamespace | undefined;
};

export class IsomorphicClerk implements IsomorphicLoadedClerk {
Expand DownExpand Up@@ -844,6 +847,10 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.clerkjs?.apiKeys;
}

get oauthApplication(): OAuthApplicationNamespace | undefined {
return this.clerkjs?.oauthApplication;
}

__experimental_checkout = (...args: Parameters<Clerk['__experimental_checkout']>) => {
return this.loaded && this.clerkjs
? this.clerkjs.__experimental_checkout(...args)
Expand Down
11 changes: 11 additions & 0 deletions packages/shared/src/types/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@ import type { DisplayThemeJSON } from './json';
import type { LocalizationResource } from './localization';
import type { DomainOrProxyUrl, MultiDomainAndOrProxy } from './multiDomain';
import type { OAuthProvider, OAuthScope } from './oauth';
import type { OAuthApplicationNamespace } from './oauthApplication';
import type { OrganizationResource } from './organization';
import type { OrganizationCustomRoleKey } from './organizationMembership';
import type { ClerkPaginationParams } from './pagination';
Expand DownExpand Up@@ -168,6 +169,7 @@ export type SetActiveNavigate = (params: {
session: SessionResource;
/**
* Decorate the destination URL to enable Safari ITP cookie refresh when needed.
*
* @see {@link DecorateUrl}
*/
decorateUrl: DecorateUrl;
Expand DownExpand Up@@ -1027,6 +1029,11 @@ export interface Clerk {
*/
apiKeys: APIKeysNamespace;

/**
* OAuth application helpers (e.g. consent metadata for custom consent UIs).
*/
oauthApplication: OAuthApplicationNamespace;

/**
* Checkout API
*
Expand DownExpand Up@@ -2496,21 +2503,25 @@ export type IsomorphicClerkOptions = Without<ClerkOptions, 'isSatellite'> & {
Clerk?: ClerkProp;
/**
* The URL that `@clerk/clerk-js` should be hot-loaded from.
*
* @internal
*/
__internal_clerkJSUrl?: string;
/**
* The npm version for `@clerk/clerk-js`.
*
* @internal
*/
__internal_clerkJSVersion?: string;
/**
* The URL that `@clerk/ui` should be hot-loaded from.
*
* @internal
*/
__internal_clerkUIUrl?: string;
/**
* The npm version for `@clerk/ui`.
*
* @internal
*/
__internal_clerkUIVersion?: string;
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/types/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,6 +33,7 @@ export type * from './key';
export type * from './localization';
export type * from './multiDomain';
export type * from './oauth';
export type * from './oauthApplication';
export type * from './organization';
export type * from './organizationCreationDefaults';
export type * from './organizationDomain';
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(js): add clerk.oauthApplication.getConsentInfo by jfoshee · Pull Request #8275 · clerk/javascript · GitHub
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/few-stamps-retire.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/clerk-js': minor
'@clerk/react': minor
'@clerk/shared': minor
---

Add `OAuthApplication` resource and `getConsentInfo()` method for retrieving OAuth consent information, enabling custom OAuth consent flows.
13 changes: 12 additions & 1 deletion packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,6 +88,7 @@ import type {
ListenerOptions,
LoadedClerk,
NavigateOptions,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand DownExpand Up@@ -178,7 +179,7 @@ import { APIKeys } from './modules/apiKeys';
import { Billing } from './modules/billing';
import { createCheckoutInstance } from './modules/checkout/instance';
import { Protect } from './protect';
import { BaseResource, Client, Environment, Organization, Waitlist } from './resources/internal';
import { BaseResource, Client, Environment, OAuthApplication, Organization, Waitlist } from './resources/internal';
import { State } from './state';

type SetActiveHook = (intent?: 'sign-out') => void | Promise<void>;
Expand DownExpand Up@@ -224,6 +225,7 @@ export class Clerk implements ClerkInterface {

private static _billing: BillingNamespace;
private static _apiKeys: APIKeysNamespace;
private static _oauthApplication: OAuthApplicationNamespace;
private _checkout: ClerkInterface['__experimental_checkout'] | undefined;

public client: ClientResource | undefined;
Expand DownExpand Up@@ -403,6 +405,15 @@ export class Clerk implements ClerkInterface {
return Clerk._apiKeys;
}

get oauthApplication(): OAuthApplicationNamespace {
if (!Clerk._oauthApplication) {
Clerk._oauthApplication = {
getConsentInfo: params => OAuthApplication.getConsentInfo(params),
};
}
return Clerk._oauthApplication;
}

__experimental_checkout(options: __experimental_CheckoutOptions): CheckoutSignalValue {
if (!this._checkout) {
this._checkout = (params: any) => createCheckoutInstance(this, params);
Expand Down
49 changes: 49 additions & 0 deletions packages/clerk-js/src/core/resources/OAuthApplication.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
import { ClerkRuntimeError } from '@clerk/shared/error';
import type {
ClerkResourceJSON,
GetOAuthConsentInfoParams,
OAuthConsentInfo,
OAuthConsentInfoJSON,
} from '@clerk/shared/types';

import { BaseResource } from './internal';

export class OAuthApplication extends BaseResource {
pathRoot = '';

protected fromJSON(_data: ClerkResourceJSON | null): this {
return this;
}

static async getConsentInfo(params: GetOAuthConsentInfoParams): Promise<OAuthConsentInfo> {
const { oauthClientId, scope } = params;
const json = await BaseResource._fetch<OAuthConsentInfoJSON>(
{
method: 'GET',
path: `/me/oauth/consent/${encodeURIComponent(oauthClientId)}`,
search: scope !== undefined ? { scope } : undefined,
},
{ skipUpdateClient: true },
);

if (!json) {
throw new ClerkRuntimeError('Network request failed while offline', { code: 'network_error' });
}

// Handle in case we start wrapping the response in the future
const data = json.response ?? json;
return {
oauthApplicationName: data.oauth_application_name,
oauthApplicationLogoUrl: data.oauth_application_logo_url,
oauthApplicationUrl: data.oauth_application_url,
clientId: data.client_id,
state: data.state,
scopes:
data.scopes?.map(scope => ({
scope: scope.scope,
description: scope.description,
requiresConsent: scope.requires_consent,
})) ?? [],
};
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import type { InstanceType, OAuthConsentInfoJSON } from '@clerk/shared/types';
import { afterEach, describe, expect, it, type Mock, vi } from 'vitest';

import { mockFetch } from '@/test/core-fixtures';

import { SUPPORTED_FAPI_VERSION } from '../../constants';
import { createFapiClient } from '../../fapiClient';
import { BaseResource } from '../internal';
import { OAuthApplication } from '../OAuthApplication';

const consentPayload: OAuthConsentInfoJSON = {
object: 'oauth_consent_info',
id: 'client_abc',
oauth_application_name: 'My App',
oauth_application_logo_url: 'https://img.example/logo.png',
oauth_application_url: 'https://app.example',
client_id: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requires_consent: true }],
};

describe('OAuthApplication.getConsentInfo', () => {
afterEach(() => {
(global.fetch as Mock)?.mockClear?.();
BaseResource.clerk = null as any;
vi.restoreAllMocks();
});

it('calls BaseResource._fetch with GET, encoded path, optional scope, and skipUpdateClient', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

await OAuthApplication.getConsentInfo({ oauthClientId: 'my/client id', scope: 'openid email' });

expect(fetchSpy).toHaveBeenCalledWith(
{
method: 'GET',
path: '/me/oauth/consent/my%2Fclient%20id',
search: { scope: 'openid email' },
},
{ skipUpdateClient: true },
);
});

it('omits search when scope is undefined', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

await OAuthApplication.getConsentInfo({ oauthClientId: 'cid' });

expect(fetchSpy).toHaveBeenCalledWith(
expect.objectContaining({
search: undefined,
}),
{ skipUpdateClient: true },
);
});

it('returns OAuthConsentInfo from the FAPI response', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue(consentPayload as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });

expect(info).toEqual({
oauthApplicationName: 'My App',
oauthApplicationLogoUrl: 'https://img.example/logo.png',
oauthApplicationUrl: 'https://app.example',
clientId: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requiresConsent: true }],
});
});

it('returns OAuthConsentInfo from the FAPI response (enveloped)', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });

expect(info).toEqual({
oauthApplicationName: 'My App',
oauthApplicationLogoUrl: 'https://img.example/logo.png',
oauthApplicationUrl: 'https://app.example',
clientId: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requiresConsent: true }],
});
});

it('defaults scopes to an empty array when absent', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: { ...consentPayload, scopes: undefined },
} as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });
expect(info.scopes).toEqual([]);
});

it('maps ClerkAPIResponseError from FAPI on non-2xx', async () => {
mockFetch(false, 422, {
errors: [{ code: 'oauth_consent_error', long_message: 'Consent metadata unavailable' }],
});

BaseResource.clerk = {
getFapiClient: () =>
createFapiClient({
frontendApi: 'clerk.example.com',
getSessionId: () => undefined,
instanceType: 'development' as InstanceType,
}),
__internal_setCountry: vi.fn(),
handleUnauthenticated: vi.fn(),
__internal_handleUnauthenticatedDevBrowser: vi.fn(),
} as any;

await expect(OAuthApplication.getConsentInfo({ oauthClientId: 'cid' })).rejects.toSatisfy(
(err: unknown) => err instanceof ClerkAPIResponseError && err.message === 'Consent metadata unavailable',
);

expect(global.fetch).toHaveBeenCalledTimes(1);
const [url] = (global.fetch as Mock).mock.calls[0];
expect(url.toString()).toContain(`/v1/me/oauth/consent/cid`);
expect(url.toString()).toContain(`__clerk_api_version=${SUPPORTED_FAPI_VERSION}`);
});

it('throws ClerkRuntimeError when _fetch returns null (offline)', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue(null);

BaseResource.clerk = {} as any;

await expect(OAuthApplication.getConsentInfo({ oauthClientId: 'cid' })).rejects.toMatchObject({
code: 'network_error',
});
});
});
1 change: 1 addition & 0 deletions packages/clerk-js/src/core/resources/internal.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,6 +22,7 @@ export * from './ExternalAccount';
export * from './Feature';
export * from './IdentificationLink';
export * from './Image';
export * from './OAuthApplication';
export * from './Organization';
export * from './OrganizationDomain';
export * from './OrganizationInvitation';
Expand Down
7 changes: 7 additions & 0 deletions packages/react/src/isomorphicClerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,7 @@ import type {
ListenerCallback,
ListenerOptions,
LoadedClerk,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand DownExpand Up@@ -118,11 +119,13 @@ type IsomorphicLoadedClerk = Without<
| '__internal_reloadInitialResources'
| 'billing'
| 'apiKeys'
| 'oauthApplication'
| '__internal_setActiveInProgress'
> & {
client: ClientResource | undefined;
billing: BillingNamespace | undefined;
apiKeys: APIKeysNamespace | undefined;
oauthApplication: OAuthApplicationNamespace | undefined;
};

export class IsomorphicClerk implements IsomorphicLoadedClerk {
Expand DownExpand Up@@ -844,6 +847,10 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.clerkjs?.apiKeys;
}

get oauthApplication(): OAuthApplicationNamespace | undefined {
return this.clerkjs?.oauthApplication;
}

__experimental_checkout = (...args: Parameters<Clerk['__experimental_checkout']>) => {
return this.loaded && this.clerkjs
? this.clerkjs.__experimental_checkout(...args)
Expand Down
11 changes: 11 additions & 0 deletions packages/shared/src/types/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@ import type { DisplayThemeJSON } from './json';
import type { LocalizationResource } from './localization';
import type { DomainOrProxyUrl, MultiDomainAndOrProxy } from './multiDomain';
import type { OAuthProvider, OAuthScope } from './oauth';
import type { OAuthApplicationNamespace } from './oauthApplication';
import type { OrganizationResource } from './organization';
import type { OrganizationCustomRoleKey } from './organizationMembership';
import type { ClerkPaginationParams } from './pagination';
Expand DownExpand Up@@ -168,6 +169,7 @@ export type SetActiveNavigate = (params: {
session: SessionResource;
/**
* Decorate the destination URL to enable Safari ITP cookie refresh when needed.
*
* @see {@link DecorateUrl}
*/
decorateUrl: DecorateUrl;
Expand DownExpand Up@@ -1027,6 +1029,11 @@ export interface Clerk {
*/
apiKeys: APIKeysNamespace;

/**
* OAuth application helpers (e.g. consent metadata for custom consent UIs).
*/
oauthApplication: OAuthApplicationNamespace;

/**
* Checkout API
*
Expand DownExpand Up@@ -2496,21 +2503,25 @@ export type IsomorphicClerkOptions = Without<ClerkOptions, 'isSatellite'> & {
Clerk?: ClerkProp;
/**
* The URL that `@clerk/clerk-js` should be hot-loaded from.
*
* @internal
*/
__internal_clerkJSUrl?: string;
/**
* The npm version for `@clerk/clerk-js`.
*
* @internal
*/
__internal_clerkJSVersion?: string;
/**
* The URL that `@clerk/ui` should be hot-loaded from.
*
* @internal
*/
__internal_clerkUIUrl?: string;
/**
* The npm version for `@clerk/ui`.
*
* @internal
*/
__internal_clerkUIVersion?: string;
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/types/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,6 +33,7 @@ export type * from './key';
export type * from './localization';
export type * from './multiDomain';
export type * from './oauth';
export type * from './oauthApplication';
export type * from './organization';
export type * from './organizationCreationDefaults';
export type * from './organizationDomain';
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); feat(js): add clerk.oauthApplication.getConsentInfo by jfoshee · Pull Request #8275 · clerk/javascript · GitHub
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/few-stamps-retire.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/clerk-js': minor
'@clerk/react': minor
'@clerk/shared': minor
---

Add `OAuthApplication` resource and `getConsentInfo()` method for retrieving OAuth consent information, enabling custom OAuth consent flows.
13 changes: 12 additions & 1 deletion packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,6 +88,7 @@ import type {
ListenerOptions,
LoadedClerk,
NavigateOptions,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand DownExpand Up@@ -178,7 +179,7 @@ import { APIKeys } from './modules/apiKeys';
import { Billing } from './modules/billing';
import { createCheckoutInstance } from './modules/checkout/instance';
import { Protect } from './protect';
import { BaseResource, Client, Environment, Organization, Waitlist } from './resources/internal';
import { BaseResource, Client, Environment, OAuthApplication, Organization, Waitlist } from './resources/internal';
import { State } from './state';

type SetActiveHook = (intent?: 'sign-out') => void | Promise<void>;
Expand DownExpand Up@@ -224,6 +225,7 @@ export class Clerk implements ClerkInterface {

private static _billing: BillingNamespace;
private static _apiKeys: APIKeysNamespace;
private static _oauthApplication: OAuthApplicationNamespace;
private _checkout: ClerkInterface['__experimental_checkout'] | undefined;

public client: ClientResource | undefined;
Expand DownExpand Up@@ -403,6 +405,15 @@ export class Clerk implements ClerkInterface {
return Clerk._apiKeys;
}

get oauthApplication(): OAuthApplicationNamespace {
if (!Clerk._oauthApplication) {
Clerk._oauthApplication = {
getConsentInfo: params => OAuthApplication.getConsentInfo(params),
};
}
return Clerk._oauthApplication;
}

__experimental_checkout(options: __experimental_CheckoutOptions): CheckoutSignalValue {
if (!this._checkout) {
this._checkout = (params: any) => createCheckoutInstance(this, params);
Expand Down
49 changes: 49 additions & 0 deletions packages/clerk-js/src/core/resources/OAuthApplication.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
import { ClerkRuntimeError } from '@clerk/shared/error';
import type {
ClerkResourceJSON,
GetOAuthConsentInfoParams,
OAuthConsentInfo,
OAuthConsentInfoJSON,
} from '@clerk/shared/types';

import { BaseResource } from './internal';

export class OAuthApplication extends BaseResource {
pathRoot = '';

protected fromJSON(_data: ClerkResourceJSON | null): this {
return this;
}

static async getConsentInfo(params: GetOAuthConsentInfoParams): Promise<OAuthConsentInfo> {
const { oauthClientId, scope } = params;
const json = await BaseResource._fetch<OAuthConsentInfoJSON>(
{
method: 'GET',
path: `/me/oauth/consent/${encodeURIComponent(oauthClientId)}`,
search: scope !== undefined ? { scope } : undefined,
},
{ skipUpdateClient: true },
);

if (!json) {
throw new ClerkRuntimeError('Network request failed while offline', { code: 'network_error' });
}

// Handle in case we start wrapping the response in the future
const data = json.response ?? json;
return {
oauthApplicationName: data.oauth_application_name,
oauthApplicationLogoUrl: data.oauth_application_logo_url,
oauthApplicationUrl: data.oauth_application_url,
clientId: data.client_id,
state: data.state,
scopes:
data.scopes?.map(scope => ({
scope: scope.scope,
description: scope.description,
requiresConsent: scope.requires_consent,
})) ?? [],
};
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import type { InstanceType, OAuthConsentInfoJSON } from '@clerk/shared/types';
import { afterEach, describe, expect, it, type Mock, vi } from 'vitest';

import { mockFetch } from '@/test/core-fixtures';

import { SUPPORTED_FAPI_VERSION } from '../../constants';
import { createFapiClient } from '../../fapiClient';
import { BaseResource } from '../internal';
import { OAuthApplication } from '../OAuthApplication';

const consentPayload: OAuthConsentInfoJSON = {
object: 'oauth_consent_info',
id: 'client_abc',
oauth_application_name: 'My App',
oauth_application_logo_url: 'https://img.example/logo.png',
oauth_application_url: 'https://app.example',
client_id: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requires_consent: true }],
};

describe('OAuthApplication.getConsentInfo', () => {
afterEach(() => {
(global.fetch as Mock)?.mockClear?.();
BaseResource.clerk = null as any;
vi.restoreAllMocks();
});

it('calls BaseResource._fetch with GET, encoded path, optional scope, and skipUpdateClient', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

await OAuthApplication.getConsentInfo({ oauthClientId: 'my/client id', scope: 'openid email' });

expect(fetchSpy).toHaveBeenCalledWith(
{
method: 'GET',
path: '/me/oauth/consent/my%2Fclient%20id',
search: { scope: 'openid email' },
},
{ skipUpdateClient: true },
);
});

it('omits search when scope is undefined', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

await OAuthApplication.getConsentInfo({ oauthClientId: 'cid' });

expect(fetchSpy).toHaveBeenCalledWith(
expect.objectContaining({
search: undefined,
}),
{ skipUpdateClient: true },
);
});

it('returns OAuthConsentInfo from the FAPI response', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue(consentPayload as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });

expect(info).toEqual({
oauthApplicationName: 'My App',
oauthApplicationLogoUrl: 'https://img.example/logo.png',
oauthApplicationUrl: 'https://app.example',
clientId: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requiresConsent: true }],
});
});

it('returns OAuthConsentInfo from the FAPI response (enveloped)', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: consentPayload,
} as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });

expect(info).toEqual({
oauthApplicationName: 'My App',
oauthApplicationLogoUrl: 'https://img.example/logo.png',
oauthApplicationUrl: 'https://app.example',
clientId: 'client_abc',
state: 'st',
scopes: [{ scope: 'openid', description: 'OpenID', requiresConsent: true }],
});
});

it('defaults scopes to an empty array when absent', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: { ...consentPayload, scopes: undefined },
} as any);

BaseResource.clerk = {} as any;

const info = await OAuthApplication.getConsentInfo({ oauthClientId: 'client_abc' });
expect(info.scopes).toEqual([]);
});

it('maps ClerkAPIResponseError from FAPI on non-2xx', async () => {
mockFetch(false, 422, {
errors: [{ code: 'oauth_consent_error', long_message: 'Consent metadata unavailable' }],
});

BaseResource.clerk = {
getFapiClient: () =>
createFapiClient({
frontendApi: 'clerk.example.com',
getSessionId: () => undefined,
instanceType: 'development' as InstanceType,
}),
__internal_setCountry: vi.fn(),
handleUnauthenticated: vi.fn(),
__internal_handleUnauthenticatedDevBrowser: vi.fn(),
} as any;

await expect(OAuthApplication.getConsentInfo({ oauthClientId: 'cid' })).rejects.toSatisfy(
(err: unknown) => err instanceof ClerkAPIResponseError && err.message === 'Consent metadata unavailable',
);

expect(global.fetch).toHaveBeenCalledTimes(1);
const [url] = (global.fetch as Mock).mock.calls[0];
expect(url.toString()).toContain(`/v1/me/oauth/consent/cid`);
expect(url.toString()).toContain(`__clerk_api_version=${SUPPORTED_FAPI_VERSION}`);
});

it('throws ClerkRuntimeError when _fetch returns null (offline)', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue(null);

BaseResource.clerk = {} as any;

await expect(OAuthApplication.getConsentInfo({ oauthClientId: 'cid' })).rejects.toMatchObject({
code: 'network_error',
});
});
});
1 change: 1 addition & 0 deletions packages/clerk-js/src/core/resources/internal.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,6 +22,7 @@ export * from './ExternalAccount';
export * from './Feature';
export * from './IdentificationLink';
export * from './Image';
export * from './OAuthApplication';
export * from './Organization';
export * from './OrganizationDomain';
export * from './OrganizationInvitation';
Expand Down
7 changes: 7 additions & 0 deletions packages/react/src/isomorphicClerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,7 @@ import type {
ListenerCallback,
ListenerOptions,
LoadedClerk,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand DownExpand Up@@ -118,11 +119,13 @@ type IsomorphicLoadedClerk = Without<
| '__internal_reloadInitialResources'
| 'billing'
| 'apiKeys'
| 'oauthApplication'
| '__internal_setActiveInProgress'
> & {
client: ClientResource | undefined;
billing: BillingNamespace | undefined;
apiKeys: APIKeysNamespace | undefined;
oauthApplication: OAuthApplicationNamespace | undefined;
};

export class IsomorphicClerk implements IsomorphicLoadedClerk {
Expand DownExpand Up@@ -844,6 +847,10 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.clerkjs?.apiKeys;
}

get oauthApplication(): OAuthApplicationNamespace | undefined {
return this.clerkjs?.oauthApplication;
}

__experimental_checkout = (...args: Parameters<Clerk['__experimental_checkout']>) => {
return this.loaded && this.clerkjs
? this.clerkjs.__experimental_checkout(...args)
Expand Down
11 changes: 11 additions & 0 deletions packages/shared/src/types/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@ import type { DisplayThemeJSON } from './json';
import type { LocalizationResource } from './localization';
import type { DomainOrProxyUrl, MultiDomainAndOrProxy } from './multiDomain';
import type { OAuthProvider, OAuthScope } from './oauth';
import type { OAuthApplicationNamespace } from './oauthApplication';
import type { OrganizationResource } from './organization';
import type { OrganizationCustomRoleKey } from './organizationMembership';
import type { ClerkPaginationParams } from './pagination';
Expand DownExpand Up@@ -168,6 +169,7 @@ export type SetActiveNavigate = (params: {
session: SessionResource;
/**
* Decorate the destination URL to enable Safari ITP cookie refresh when needed.
*
* @see {@link DecorateUrl}
*/
decorateUrl: DecorateUrl;
Expand DownExpand Up@@ -1027,6 +1029,11 @@ export interface Clerk {
*/
apiKeys: APIKeysNamespace;

/**
* OAuth application helpers (e.g. consent metadata for custom consent UIs).
*/
oauthApplication: OAuthApplicationNamespace;

/**
* Checkout API
*
Expand DownExpand Up@@ -2496,21 +2503,25 @@ export type IsomorphicClerkOptions = Without<ClerkOptions, 'isSatellite'> & {
Clerk?: ClerkProp;
/**
* The URL that `@clerk/clerk-js` should be hot-loaded from.
*
* @internal
*/
__internal_clerkJSUrl?: string;
/**
* The npm version for `@clerk/clerk-js`.
*
* @internal
*/
__internal_clerkJSVersion?: string;
/**
* The URL that `@clerk/ui` should be hot-loaded from.
*
* @internal
*/
__internal_clerkUIUrl?: string;
/**
* The npm version for `@clerk/ui`.
*
* @internal
*/
__internal_clerkUIVersion?: string;
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/types/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,6 +33,7 @@ export type * from './key';
export type * from './localization';
export type * from './multiDomain';
export type * from './oauth';
export type * from './oauthApplication';
export type * from './organization';
export type * from './organizationCreationDefaults';
export type * from './organizationDomain';
Expand Down
Loading
Loading