Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
5 changes: 5 additions & 0 deletions .changeset/few-stamps-retire.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/clerk-js': patch
---

Add OAuthApplication resource and fetchConsentInfo method
13 changes: 12 additions & 1 deletion packages/clerk-js/src/core/clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ import type {
ListenerOptions,
LoadedClerk,
NavigateOptions,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand Down Expand 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 Down Expand 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 Down Expand Up @@ -403,6 +405,15 @@ export class Clerk implements ClerkInterface {
return Clerk._apiKeys;
}

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

__experimental_checkout(options: __experimental_CheckoutOptions): CheckoutSignalValue {
if (!this._checkout) {
this._checkout = (params: any) => createCheckoutInstance(this, params);
Expand Down
44 changes: 44 additions & 0 deletions packages/clerk-js/src/core/resources/OAuthApplication.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { ClerkRuntimeError } from '@clerk/shared/error';
import type {
ClerkResourceJSON,
FetchOAuthConsentInfoParams,
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 fetchConsentInfo(params: FetchOAuthConsentInfoParams): Promise<OAuthConsentInfo> {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Small nit: we don't use a fetch* prefix elsewhere in resources (closest precedents for non-standard verbs are Waitlist.join and Passkey.registerPasskey).

Not blocking, just wondering if getConsentInfo / retrieveConsentInfo or similar would sit better with the rest of the codebase. Happy to keep as-is if you prefer.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Oh cool, good catch. Looks like get is more common e.g. getSessions, getToken, getDomains, etc. I'll update it!

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' });
}

const envelope = json;
const data = envelope.response ?? json;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why do we coalesce here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Seems to be the common pattern that callers to _fetch use .response. I assume that is for client piggybacking. We don't do that for this endpoint (it just uses json directly). But I guess it's good to make sure it will work either way. I added a unit test so we cover both cases.

return {
oauth_application_name: data.oauth_application_name,
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think this is deviating from the standard convention of having camelCase property being returned for SDK consumers

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ah yes, thanks @jacekradko

oauth_application_logo_url: data.oauth_application_logo_url,
oauth_application_url: data.oauth_application_url,
client_id: data.client_id,
state: data.state,
scopes: data.scopes ?? [],
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
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.fetchConsentInfo', () => {
afterEach(() => {
(global.fetch as Mock)?.mockClear?.();
BaseResource.clerk = null as any;
vi.restoreAllMocks();
});

it('throws ClerkRuntimeError when there is no active session', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch');

BaseResource.clerk = {
session: undefined,
} as any;

await expect(OAuthApplication.fetchConsentInfo({ oauthClientId: 'cid' })).rejects.toMatchObject({
code: 'cannot_fetch_oauth_consent_no_session',
});
expect(fetchSpy).not.toHaveBeenCalled();
});

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

BaseResource.clerk = {
session: { id: 'sess_test' },
} as any;

await OAuthApplication.fetchConsentInfo({ oauthClientId: 'my/client id', scope: 'openid email' });
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I thought this was an odd client id but I think it's actually good to verify that we url escape this to avoid path traversal issues.


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

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

BaseResource.clerk = {
session: { id: 'sess_test' },
} as any;

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

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

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

BaseResource.clerk = {
session: { id: 'sess_test' },
} as any;

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

expect(info).toEqual({
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 }],
});
});

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

BaseResource.clerk = {
session: { id: 'sess_test' },
} as any;

const info = await OAuthApplication.fetchConsentInfo({ 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 = {
session: { id: 'sess_1' },
getFapiClient: () =>
createFapiClient({
frontendApi: 'clerk.example.com',
getSessionId: () => 'sess_1',
instanceType: 'development' as InstanceType,
}),
__internal_setCountry: vi.fn(),
handleUnauthenticated: vi.fn(),
__internal_handleUnauthenticatedDevBrowser: vi.fn(),
} as any;

await expect(OAuthApplication.fetchConsentInfo({ 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 = {
session: { id: 'sess_test' },
} as any;

await expect(OAuthApplication.fetchConsentInfo({ oauthClientId: 'cid' })).rejects.toMatchObject({
code: 'network_error',
});
});
});
1 change: 1 addition & 0 deletions packages/clerk-js/src/core/resources/internal.ts
Original file line number Diff line number Diff 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 number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import type {
ListenerCallback,
ListenerOptions,
LoadedClerk,
OAuthApplicationNamespace,
OrganizationListProps,
OrganizationProfileProps,
OrganizationResource,
Expand Down Expand 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 Down Expand 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
6 changes: 6 additions & 0 deletions packages/shared/src/types/clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { ClerkGlobalHookError } from '@/errors/globalHookError';

import type { ClerkUIConstructor } from '../ui/types';
import type { APIKeysNamespace } from './apiKeys';
import type { OAuthApplicationNamespace } from './oauthApplication';
import type {
BillingCheckoutResource,
BillingNamespace,
Expand Down Expand Up @@ -1027,6 +1028,11 @@ export interface Clerk {
*/
apiKeys: APIKeysNamespace;

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

/**
* Checkout API
*
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/types/index.ts
Original file line number Diff line number Diff 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
54 changes: 54 additions & 0 deletions packages/shared/src/types/oauthApplication.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import type { ClerkResourceJSON } from './json';

/**
* A single OAuth scope row returned by the Frontend API consent metadata endpoint.
*/
export type OAuthConsentScopeJSON = {
scope: string;
description: string | null;
requires_consent: boolean;
};

/**
* OAuth consent screen metadata from `GET /v1/me/oauth/consent/{oauthClientId}`.
* Field names match the Frontend API JSON (snake_case).
*/
export type OAuthConsentInfo = {
oauth_application_name: string;
oauth_application_logo_url: string;
oauth_application_url: string;
client_id: string;
state: string;
scopes: OAuthConsentScopeJSON[];
};

/**
* @internal
*/
export interface OAuthConsentInfoJSON extends ClerkResourceJSON {
object: 'oauth_consent_info';
oauth_application_name: string;
oauth_application_logo_url: string;
oauth_application_url: string;
client_id: string;
state: string;
scopes: OAuthConsentScopeJSON[];
}

export type FetchOAuthConsentInfoParams = {
/** OAuth `client_id` from the authorize request. */
oauthClientId: string;
/** Optional normalized scope string (e.g. space-delimited). */
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

"e.g." means "for example". Is space-delimited just an example of a scope string or is this something we should enforce?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

😆 good catch

scope?: string;
};

/**
* Namespace exposed on `Clerk` for OAuth application / consent helpers.
*/
export interface OAuthApplicationNamespace {
/**
* Loads consent metadata for the given OAuth client for the signed-in user.
* Uses the Frontend API session (cookies, `_clerk_session_id`, dev browser, etc.) like other `/me` requests.
*/
fetchConsentInfo: (params: FetchOAuthConsentInfoParams) => Promise<OAuthConsentInfo>;
}
Loading