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
13 changes: 13 additions & 0 deletions .changeset/quiet-devices-verify.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
---
'@clerk/astro': minor
'@clerk/clerk-js': minor
'@clerk/localizations': minor
'@clerk/nextjs': minor
'@clerk/nuxt': minor
'@clerk/react': minor
'@clerk/shared': minor
'@clerk/ui': minor
'@clerk/vue': minor
---

Add an authenticated OAuth device verification component and workflow hook for approving or denying OAuth Device Authorization Grant requests.
1 change: 1 addition & 0 deletions packages/astro/src/astro-components/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,5 +29,6 @@ export { default as CreateOrganization } from './interactive/CreateOrganization.
export { default as GoogleOneTap } from './interactive/GoogleOneTap.astro';
export { default as Waitlist } from './interactive/Waitlist.astro';
export { default as OAuthConsent } from './interactive/OAuthConsent.astro';
export { default as OAuthDeviceVerification } from './interactive/OAuthDeviceVerification.astro';
export { default as PricingTable } from './interactive/PricingTable.astro';
export { default as APIKeys } from './interactive/APIKeys.astro';
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
---
import type { OAuthDeviceVerificationProps } from '@clerk/shared/types';
type Props = OAuthDeviceVerificationProps;

import InternalUIComponentRenderer from './InternalUIComponentRenderer.astro';
---

<InternalUIComponentRenderer
{...Astro.props}
component='oauth-device-verification'
/>
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,7 @@ const mountAllClerkAstroJSComponents = () => {
waitlist: 'mountWaitlist',
'pricing-table': 'mountPricingTable',
'api-keys': 'mountAPIKeys',
'oauth-device-verification': '__internal_mountOAuthDeviceVerification',

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.

Adding this mapping exposes a mixed-version failure in the shared dynamic mount call: its optional chain guards the Clerk object, but it still calls an undefined method when @clerk/astro runs with a pinned or preloaded ClerkJS version from before this API. That throws inside mountAllClerkAstroJSComponents(), and because mounting runs before function replay and listener registration, one unsupported component aborts the rest of Astro initialization. React already feature-detects this exact case. Could we guard the selected method and add a loaded-old-ClerkJS test so this component no-ops or warns without breaking the remaining Clerk state setup?

~ 🤖

} as const satisfies Record<InternalUIComponentId, keyof Clerk>;

Object.entries(mountFns).forEach(([category, mountFn]) => {
Expand Down
48 changes: 48 additions & 0 deletions packages/astro/src/react/__tests__/uiComponents.test.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
import { render } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { $clerk, $csrState } from '../../stores/internal';
import { OAuthDeviceVerification } from '../uiComponents';

describe('<OAuthDeviceVerification />', () => {
afterEach(() => {
$clerk.set(null);
$csrState.set({
isLoaded: false,
client: undefined,
user: undefined,
session: undefined,
organization: undefined,
});
});

it('updates the mounted component when its appearance changes', () => {
const mount = vi.fn();
const unmount = vi.fn();
const updateProps = vi.fn();
$clerk.set({
__internal_mountOAuthDeviceVerification: mount,
__internal_unmountOAuthDeviceVerification: unmount,
__internal_updateProps: updateProps,
} as any);
$csrState.set({
isLoaded: true,
client: undefined,
user: undefined,
session: undefined,
organization: undefined,
});
const firstAppearance = {};
const secondAppearance = {};
const { rerender } = render(<OAuthDeviceVerification appearance={firstAppearance} />);

rerender(<OAuthDeviceVerification appearance={secondAppearance} />);

expect(mount).toHaveBeenCalledOnce();
expect(updateProps).toHaveBeenCalledOnce();
expect(updateProps).toHaveBeenCalledWith({
node: expect.any(HTMLDivElement),
props: { appearance: secondAppearance },
});
});
});
12 changes: 12 additions & 0 deletions packages/astro/src/react/uiComponents.tsx
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type {
GoogleOneTapProps,
OAuthConsentProps,
OAuthDeviceVerificationProps,
OrganizationListProps,
OrganizationProfileProps,
OrganizationSwitcherProps,
Expand DownExpand Up@@ -207,3 +208,14 @@ export const OAuthConsent = withClerk(({ clerk, ...props }: WithClerkProp<OAuthC
/>
);
}, 'OAuthConsent');

export const OAuthDeviceVerification = withClerk(({ clerk, ...props }: WithClerkProp<OAuthDeviceVerificationProps>) => {
return (
<Portal
mount={clerk?.__internal_mountOAuthDeviceVerification}
unmount={clerk?.__internal_unmountOAuthDeviceVerification}
updateProps={(clerk as any)?.__internal_updateProps}
props={props}
/>
);
}, 'OAuthDeviceVerification');
Comment thread
coderabbitai[bot] marked this conversation as resolved.
3 changes: 2 additions & 1 deletion packages/astro/src/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,4 +119,5 @@ export type InternalUIComponentId =
| 'google-one-tap'
| 'waitlist'
| 'pricing-table'
| 'api-keys';
| 'api-keys'
| 'oauth-device-verification';
31 changes: 31 additions & 0 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,6 +99,7 @@ import type {
LoadedClerk,
NavigateOptions,
OAuthApplicationNamespace,
OAuthDeviceVerificationProps,
OAuthTransport,
OrganizationListProps,
OrganizationProfileProps,
Expand DownExpand Up@@ -1545,6 +1546,36 @@ export class Clerk implements ClerkInterface {
return this.unmountOAuthConsent(node);
};

public __internal_mountOAuthDeviceVerification = (node: HTMLDivElement, props?: OAuthDeviceVerificationProps) => {
if (noUserExists(this)) {
if (this.#instanceType === 'development') {
throw new ClerkRuntimeError(warnings.cannotRenderOAuthDeviceVerificationComponentWhenUserDoesNotExist, {
code: CANNOT_RENDER_USER_MISSING_ERROR_CODE,
});
}
return;
}

this.assertComponentsReady(this.#clerkUI);
const component = 'OAuthDeviceVerification';
void this.#clerkUI
.then(ui => ui.ensureMounted({ preloadHint: component }))
.then(controls =>
controls.mountComponent({
name: component,
appearanceKey: 'oauthDeviceVerification',
node,
props,
}),
);

this.telemetry?.record(eventPrebuiltComponentMounted(component, props));
};

public __internal_unmountOAuthDeviceVerification = (node: HTMLDivElement) => {
void this.#clerkUI?.then(ui => ui.ensureMounted()).then(controls => controls.unmountComponent({ node }));
};

/**
* Mount an API keys component at the target element.
* @param targetNode Target to mount the APIKeys component.
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import type { InstanceType, OAuthConsentInfoJSON } from '@clerk/shared/types';
import type {
InstanceType,
OAuthConsentInfoJSON,
OAuthDeviceVerificationInfoJSON,
OAuthDeviceVerificationResultJSON,
} from '@clerk/shared/types';
import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from 'vitest';

import { mockFetch } from '@/test/core-fixtures';
Expand All@@ -20,6 +25,34 @@ const consentPayload: OAuthConsentInfoJSON = {
scopes: [{ scope: 'openid', description: 'OpenID', requires_consent: true }],
};

const deviceVerificationPayload: OAuthDeviceVerificationInfoJSON = {
oauth_application_name: 'TV App',
oauth_application_logo_url: null,
client_id: 'client_device',
scopes: [{ scope: 'profile', description: 'Your profile', requires_consent: true }],
status: 'pending',
expires_at: 1_800_000_000_000,
};

const deviceVerificationResultPayload: OAuthDeviceVerificationResultJSON = {
object: 'oauth_device_verification',
status: 'approved',
};

function setFapiClerk() {
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;
}

describe('OAuthApplication', () => {
let oauthApp: OAuthApplication;

Expand DownExpand Up@@ -222,4 +255,150 @@ describe('OAuthApplication', () => {
expect(result).toContain('__clerk_db_jwt=devjwt');
});
});

describe('lookupDeviceVerification', () => {
it.each([
['direct', deviceVerificationPayload],
['enveloped', { response: deviceVerificationPayload }],
])('maps a %s FAPI response', async (_shape, response) => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue(response as any);
BaseResource.clerk = {} as any;

await expect(oauthApp.lookupDeviceVerification({ userCode: 'bcdf ghjk' })).resolves.toEqual({
oauthApplicationName: 'TV App',
oauthApplicationLogoUrl: null,
clientId: 'client_device',
scopes: [{ scope: 'profile', description: 'Your profile', requiresConsent: true }],
status: 'pending',
expiresAt: 1_800_000_000_000,
});
expect(fetchSpy).toHaveBeenCalledWith(
{
method: 'POST',
path: '/me/oauth/device/lookup',
body: { userCode: 'bcdf ghjk' },
},
{ skipUpdateClient: true },
);
});

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

await expect(oauthApp.lookupDeviceVerification({ userCode: 'BCDF-GHJK' })).resolves.toMatchObject({ scopes: [] });
});

it.each(['pending', 'approved', 'denied', 'consumed'] as const)('preserves the %s lookup status', async status => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue({
response: { ...deviceVerificationPayload, status },
} as any);
BaseResource.clerk = {} as any;

await expect(oauthApp.lookupDeviceVerification({ userCode: 'BCDF-GHJK' })).resolves.toMatchObject({ status });
});

it('sends one credentialed form request with a snake-case user code field', async () => {
mockFetch(true, 200, deviceVerificationPayload);
setFapiClerk();

await oauthApp.lookupDeviceVerification({ userCode: 'BCDF-GHJK' });

expect(global.fetch).toHaveBeenCalledOnce();
const [url, init] = (global.fetch as Mock).mock.calls[0];
expect(url.toString()).toContain('/v1/me/oauth/device/lookup');
expect(init).toMatchObject({ credentials: 'include', method: 'POST', body: 'user_code=BCDF-GHJK' });
});

it('throws a network error when _fetch returns null', async () => {
vi.spyOn(BaseResource, '_fetch').mockResolvedValue(null);
BaseResource.clerk = {} as any;

await expect(oauthApp.lookupDeviceVerification({ userCode: 'BCDF-GHJK' })).rejects.toMatchObject({
code: 'network_error',
});
});

it('propagates FAPI errors without retrying', async () => {
const error = new ClerkAPIResponseError('Unknown device code', {
data: [{ code: 'resource_not_found', message: 'Unknown device code' }],
status: 404,
});
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockRejectedValue(error);
BaseResource.clerk = {} as any;

await expect(oauthApp.lookupDeviceVerification({ userCode: 'BCDF-GHJK' })).rejects.toBe(error);
expect(fetchSpy).toHaveBeenCalledOnce();
});
});

describe('submitDeviceVerification', () => {
it.each([
['direct', deviceVerificationResultPayload],
['enveloped', { response: deviceVerificationResultPayload }],
])('posts a decision and maps a %s FAPI response', async (_shape, response) => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue(response as any);
BaseResource.clerk = {} as any;

await expect(
oauthApp.submitDeviceVerification({
userCode: 'BCDF-GHJK',
approved: true,
organizationId: 'org_123',
}),
).resolves.toEqual(deviceVerificationResultPayload);
expect(fetchSpy).toHaveBeenCalledWith(
{
method: 'POST',
path: '/me/oauth/device',
body: { userCode: 'BCDF-GHJK', approved: true, organizationId: 'org_123' },
},
{ skipUpdateClient: true },
);
});

it('omits organizationId through the FAPI form encoder when undefined', async () => {
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockResolvedValue(deviceVerificationResultPayload as any);
BaseResource.clerk = {} as any;

await oauthApp.submitDeviceVerification({ userCode: 'BCDF-GHJK', approved: false });

expect(fetchSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { userCode: 'BCDF-GHJK', approved: false, organizationId: undefined },
}),
{ skipUpdateClient: true },
);
});

it('sends a snake-case decision form and omits an undefined organization', async () => {
mockFetch(true, 200, deviceVerificationResultPayload);
setFapiClerk();

await oauthApp.submitDeviceVerification({ userCode: 'BCDF-GHJK', approved: false });

expect(global.fetch).toHaveBeenCalledOnce();
const [url, init] = (global.fetch as Mock).mock.calls[0];
expect(url.toString()).toContain('/v1/me/oauth/device');
expect(init).toMatchObject({
credentials: 'include',
method: 'POST',
body: 'user_code=BCDF-GHJK&approved=false',
});
});

it('propagates decision errors without retrying', async () => {
const error = new ClerkAPIResponseError('No longer pending', {
data: [{ code: 'bad_request', message: 'No longer pending' }],
status: 400,
});
const fetchSpy = vi.spyOn(BaseResource, '_fetch').mockRejectedValue(error);
BaseResource.clerk = {} as any;

await expect(oauthApp.submitDeviceVerification({ userCode: 'BCDF-GHJK', approved: true })).rejects.toBe(error);
expect(fetchSpy).toHaveBeenCalledOnce();
});
});
});
Loading
Loading