diff --git a/.changeset/backend-cimd-oauth-applications.md b/.changeset/backend-cimd-oauth-applications.md new file mode 100644 index 00000000000..c7cccc96c29 --- /dev/null +++ b/.changeset/backend-cimd-oauth-applications.md @@ -0,0 +1,5 @@ +--- +'@clerk/backend': minor +--- + +Add Client ID Metadata Document (CIMD) client support to `clerkClient.oauthApplications`. Pass `clientIdMetadataDocumentUrl` to `create()` to pre-register a client from its metadata document URL; `name` is optional in that case, and only `name` and `scopes` can be set. Pass `clientIdMetadataDocument: true` to `list()` to list only CIMD clients. `OAuthApplication` now exposes `clientIdMetadataDocument` and `clientIdMetadataDocumentDetails`, which holds the client's admission status and the state of its last metadata fetch. diff --git a/.typedoc/__tests__/extract-methods.test.ts b/.typedoc/__tests__/extract-methods.test.ts index 932395404b0..b04fb9313f5 100644 --- a/.typedoc/__tests__/extract-methods.test.ts +++ b/.typedoc/__tests__/extract-methods.test.ts @@ -38,6 +38,33 @@ describe('extract-methods snapshots', () => { expect(content).not.toContain('revoke-session-params.mdx'); }); + it('marks union-merged params optional unless every arm requires them', async () => { + const createOAuthApplication = await readGenerated('backend/o-auth-applications-api/methods/create.mdx'); + expect(createOAuthApplication).toContain('| `clientIdMetadataDocumentUrl?` |'); + expect(createOAuthApplication).toContain('| `name?` |'); + expect(createOAuthApplication).not.toContain('`never`'); + + const getOrganization = await readGenerated('backend/organization-api/methods/get-organization.mdx'); + expect(getOrganization).toContain('| `organizationId?` |'); + expect(getOrganization).toContain('| `slug?` |'); + + const createUser = await readGenerated('backend/user-api/methods/create-user.mdx'); + expect(createUser).toContain('| `passwordDigest?` |'); + + const updateOAuthApplication = await readGenerated('backend/o-auth-applications-api/methods/update.mdx'); + expect(updateOAuthApplication).toContain('| `name` |'); + }); + + it('marks union-merged properties optional on standalone type pages', async () => { + const createOAuthApplicationParams = await readGenerated('backend/create-o-auth-application-params.mdx'); + expect(createOAuthApplicationParams).toMatch(/\| `clientIdMetadataDocumentUrl\?` +\| `string`/); + expect(createOAuthApplicationParams).toMatch(/\| `redirectUris\?` +\| string\[\] \\\| null<\/code>/); + expect(createOAuthApplicationParams).not.toContain('`never`'); + + const getOrganizationParams = await readGenerated('backend/get-organization-params.mdx'); + expect(getOrganizationParams).toMatch(/\| `organizationId\?` +\|/); + }); + it('simple callable: clerk.signOut()', async () => { const content = await readGenerated('shared/clerk/methods/sign-out.mdx'); await expect(content).toMatchFileSnapshot('./__snapshots__/clerk-methods-sign-out.mdx'); diff --git a/.typedoc/__tests__/type-utils.test.ts b/.typedoc/__tests__/type-utils.test.ts new file mode 100644 index 00000000000..358bf5a00f8 --- /dev/null +++ b/.typedoc/__tests__/type-utils.test.ts @@ -0,0 +1,144 @@ +import { + DeclarationReflection, + FileRegistry, + ProjectReflection, + ReferenceType, + ReflectionKind, + ReflectionType, +} from 'typedoc'; +import { describe, expect, it, vi } from 'vitest'; + +import { collectUnionArms, markOptionalUnlessRequiredInEveryArm } from '../type-utils.mjs'; + +const project = new ProjectReflection('project', new FileRegistry()); +const parent = new DeclarationReflection('Params', ReflectionKind.TypeAlias, project); +const findNothing = () => undefined; +const property = (name: string) => new DeclarationReflection(name, ReflectionKind.Property, parent); + +describe('union property merging', () => { + it('ignores an arm whose properties could not be collected', () => { + const strategy = property('strategy'); + const collected = { type: 'reference', name: 'EmailCodeConfig' }; + const unresolved = { type: 'reference', name: 'Omit' }; + const union = { type: 'union', types: [collected, unresolved] } as any; + + const { arms, requirednessArms } = collectUnionArms( + union, + t => (t === collected ? [strategy] : undefined), + findNothing, + ); + + expect(arms).toHaveLength(2); + expect(markOptionalUnlessRequiredInEveryArm([strategy], requirednessArms)[0].flags.isOptional).toBe(false); + }); + + it('ignores an intersection arm with an uncollected member', () => { + const strategy = property('strategy'); + const collected = { type: 'reference', name: 'EmailCodeConfig' }; + const unresolved = { type: 'reference', name: 'Omit' }; + const partial = { type: 'intersection', types: [{ type: 'reference', name: 'Other' }, unresolved] }; + const union = { type: 'union', types: [collected, partial] } as any; + + const { requirednessArms } = collectUnionArms( + union, + t => { + if (t === collected) { + return [strategy]; + } + return t === unresolved ? undefined : [property('other')]; + }, + findNothing, + ); + + expect(markOptionalUnlessRequiredInEveryArm([strategy], requirednessArms)[0].flags.isOptional).toBe(false); + }); + + it('counts an arm that resolved to no properties', () => { + const x = property('x'); + const base = { type: 'reference', name: 'X' }; + const omitted = { type: 'reference', name: 'Omit' }; + const union = { type: 'union', types: [base, omitted] } as any; + + const { requirednessArms } = collectUnionArms(union, t => (t === base ? [x] : []), findNothing); + + expect(markOptionalUnlessRequiredInEveryArm([x], requirednessArms)[0].flags.isOptional).toBe(true); + }); + + it.each([ + ['an empty interface', ReflectionKind.Interface], + ['an alias of an empty object type', ReflectionKind.TypeAlias], + ])('counts %s that the collector reports as undefined', (_, kind) => { + const a = property('a'); + const empty = new DeclarationReflection('Empty', kind, project); + project.registerReflection(empty, undefined, undefined); + if (kind === ReflectionKind.TypeAlias) { + empty.type = new ReflectionType(new DeclarationReflection('__type', ReflectionKind.TypeLiteral, empty)); + } + const base = { type: 'reference', name: 'A' }; + const union = { + type: 'union', + types: [base, ReferenceType.createResolvedReference('Empty', empty, project)], + } as any; + + const { requirednessArms } = collectUnionArms(union, t => (t === base ? [a] : undefined), findNothing); + + expect(markOptionalUnlessRequiredInEveryArm([a], requirednessArms)[0].flags.isOptional).toBe(true); + }); + + it.each([ + ['counts an empty declaration found by name', true], + ['ignores a reference not found by name', false], + ])('%s', (_, isFound) => { + const a = property('a'); + const empty = new DeclarationReflection('EmptyByName', ReflectionKind.Interface, project); + const base = { type: 'reference', name: 'A' }; + const union = { type: 'union', types: [base, { type: 'reference', name: 'EmptyByName' }] } as any; + + const { requirednessArms } = collectUnionArms( + union, + t => (t === base ? [a] : undefined), + name => (isFound && name === 'EmptyByName' ? empty : undefined), + ); + + expect(markOptionalUnlessRequiredInEveryArm([a], requirednessArms)[0].flags.isOptional).toBe(isFound); + }); + + it('collects each arm and intersection member once', () => { + const a = { type: 'reference', name: 'A' }; + const b = { type: 'reference', name: 'B' }; + const c = { type: 'reference', name: 'C' }; + const union = { type: 'union', types: [a, { type: 'intersection', types: [b, c] }] } as any; + const collect = vi.fn(() => [property('x')]); + + collectUnionArms(union, collect, findNothing); + + expect(collect.mock.calls).toEqual([[a], [b], [c]]); + }); + + it('treats `object` as an arm that requires nothing, and ignores null', () => { + const digest = property('passwordDigest'); + const hashing = { type: 'reference', name: 'UserPasswordHashingParams' }; + const collect = (t: unknown) => (t === hashing ? [digest] : undefined); + const withObject = { type: 'union', types: [hashing, { type: 'intrinsic', name: 'object' }] } as any; + const withNull = { type: 'union', types: [hashing, { type: 'literal', value: null }] } as any; + const isOptional = (union: any) => + markOptionalUnlessRequiredInEveryArm([digest], collectUnionArms(union, collect, findNothing).requirednessArms)[0] + .flags.isOptional; + + expect(isOptional(withObject)).toBe(true); + expect(isOptional(withNull)).toBe(false); + }); + + it('changes only the optional flag on the copy and leaves the original alone', () => { + const original = property('organizationId'); + + const [copy] = markOptionalUnlessRequiredInEveryArm([original], [[original], []]); + + expect(copy).not.toBe(original); + expect(copy.flags.isOptional).toBe(true); + expect(original.flags.isOptional).toBe(false); + expect(copy.parent).toBe(parent); + expect(copy.project).toBe(project); + expect(copy.getFullName()).toBe(original.getFullName()); + }); +}); diff --git a/.typedoc/custom-theme.mjs b/.typedoc/custom-theme.mjs index 1a7244848f2..1e2635a462c 100644 --- a/.typedoc/custom-theme.mjs +++ b/.typedoc/custom-theme.mjs @@ -6,7 +6,12 @@ import { applyTodoStrippingToComment } from './comment-utils.mjs'; import { backTicks, heading, htmlTable, removeLineBreaks, table } from './markdown-helpers.mjs'; import { REFERENCE_OBJECTS_LIST } from './reference-objects.mjs'; import { isInlineModifierWithoutStandalonePage } from './standalone-page-tag.mjs'; -import { unwrapOptional } from './type-utils.mjs'; +import { + collectUnionArms, + markOptionalUnlessRequiredInEveryArm, + propertyReflectionTypeIsNever, + unwrapOptional, +} from './type-utils.mjs'; export { REFERENCE_OBJECTS_LIST }; @@ -391,14 +396,25 @@ function collectPropertyReflectionsFromUnionObjectArms(t, visitedReflectionIds, return []; } const union = /** @type {import('typedoc').UnionType} */ (unwrapped); + const { arms, requirednessArms } = collectUnionArms( + union, + arm => { + const properties = collectPropertyReflectionsFromIntersectionArm(arm, visitedReflectionIds, project); + return properties.length ? properties : undefined; + }, + name => (project ? findNamedTypeDeclaration(project, name) : undefined), + ); /** @type {Map} */ const byName = new Map(); - for (const arm of union.types) { - for (const p of collectPropertyReflectionsFromIntersectionArm(arm, visitedReflectionIds, project)) { - byName.set(p.name, p); + for (const arm of arms) { + for (const p of arm) { + if (!propertyReflectionTypeIsNever(p)) { + byName.set(p.name, p); + } } } - return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)); + const merged = [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)); + return markOptionalUnlessRequiredInEveryArm(merged, requirednessArms); } /** diff --git a/.typedoc/extract-methods.mjs b/.typedoc/extract-methods.mjs index d85f1e435ed..1062c790b31 100644 --- a/.typedoc/extract-methods.mjs +++ b/.typedoc/extract-methods.mjs @@ -51,7 +51,12 @@ function methodFormatForPageUrl(pageUrl) { } import { toFileSlug } from './slug.mjs'; import { isInlineModifierWithoutStandalonePage } from './standalone-page-tag.mjs'; -import { unwrapOptional } from './type-utils.mjs'; +import { + collectUnionArms, + markOptionalUnlessRequiredInEveryArm, + propertyReflectionTypeIsNever, + unwrapOptional, +} from './type-utils.mjs'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); @@ -769,14 +774,6 @@ function appendSignatureOnlyReturns(declComment, sigComment) { return formatReturnsLineFromTag(tag); } -/** - * @param {import('typedoc').DeclarationReflection} prop - */ -function propertyReflectionTypeIsNever(prop) { - const ty = unwrapOptional(prop.type, { deep: true }); - return ty?.type === 'intrinsic' && ty.name === 'never'; -} - /** * Union discriminators often use `otherProp?: never`. Prefer the branch with a documentable type. * @@ -955,10 +952,13 @@ function resolveDeclarationWithObjectMembers(t, project) { } if (t.type === 'union') { const u = /** @type {import('typedoc').UnionType} */ (t); - return mergePropertyArms( - u.types.map(inner => resolveDeclarationWithObjectMembers(inner, project)), - { skipNever: true, pickBetter: true }, + const { arms, requirednessArms } = collectUnionArms( + u, + inner => resolveDeclarationWithObjectMembers(inner, project), + name => (project ? lookupInterfaceOrTypeAliasByName(project, name) : undefined), ); + const merged = mergePropertyArms(arms, { skipNever: true, pickBetter: true }); + return merged && markOptionalUnlessRequiredInEveryArm(merged, requirednessArms); } return undefined; } diff --git a/.typedoc/type-utils.mjs b/.typedoc/type-utils.mjs index 38ba45c4e5f..45d4d1d1ebb 100644 --- a/.typedoc/type-utils.mjs +++ b/.typedoc/type-utils.mjs @@ -1,5 +1,7 @@ // @ts-check — JSDoc-typed plugin helpers shared between custom-theme.mjs and extract-methods.mjs. +import { ReflectionFlag, ReflectionFlags, ReflectionKind } from 'typedoc'; + /** * Strip one (or, with `{ deep: true }`, all) `OptionalType` layers and return the inner type. Returns `t` unchanged when it isn't an `OptionalType`, or when `t` is nullish. * @@ -25,3 +27,130 @@ export function unwrapOptional(t, options) { } return cur; } + +/** + * @param {import('typedoc').DeclarationReflection} prop + */ +export function propertyReflectionTypeIsNever(prop) { + const ty = unwrapOptional(prop.type, { deep: true }); + return ty?.type === 'intrinsic' && ty.name === 'never'; +} + +/** + * Whether a union arm can contribute properties. Literal and primitive arms such as `null`, `undefined` or `false` make the whole value an alternative, not its properties optional. `object` counts, because it accepts a value without any of the other arms' properties. + * + * @param {import('typedoc').Type | import('typedoc').SomeType | undefined} t + */ +function isObjectLikeUnionArm(t) { + const u = unwrapOptional(t); + if (!u) { + return false; + } + if (u.type === 'literal') { + return false; + } + if (u.type === 'intrinsic') { + return /** @type {import('typedoc').IntrinsicType} */ (u).name === 'object'; + } + return true; +} + +/** + * Whether `t` is an object type TypeDoc resolved, even if it declares no properties. Collectors report an empty interface the same way as a reference they cannot resolve, so this tells the two apart. + * + * @param {import('typedoc').Type | import('typedoc').SomeType | undefined} t + * @param {(name: string) => import('typedoc').DeclarationReflection | undefined} findDeclaration + * @param {Set} [visitedIds] + * @returns {boolean} + */ +function isResolvedObjectType(t, findDeclaration, visitedIds = new Set()) { + const u = unwrapOptional(t); + if (!u) { + return false; + } + if (u.type === 'reflection') { + return true; + } + if (u.type === 'intrinsic') { + return /** @type {import('typedoc').IntrinsicType} */ (u).name === 'object'; + } + if (u.type !== 'reference') { + return false; + } + const ref = /** @type {import('typedoc').ReferenceType} */ (u); + const decl = /** @type {import('typedoc').DeclarationReflection | undefined} */ ( + ref.reflection ?? findDeclaration(ref.name) + ); + if (!decl || visitedIds.has(decl.id)) { + return false; + } + if (decl.kind === ReflectionKind.Interface || decl.kind === ReflectionKind.Class) { + return true; + } + return isResolvedObjectType(decl.type, findDeclaration, new Set([...visitedIds, decl.id])); +} + +/** + * Collect one union arm, visiting each intersection member once. An arm is complete when every member resolved. + * + * @param {import('typedoc').Type | import('typedoc').SomeType} t + * @param {(t: any) => import('typedoc').DeclarationReflection[] | undefined} collect + * @param {(name: string) => import('typedoc').DeclarationReflection | undefined} findDeclaration + * @returns {{ properties: import('typedoc').DeclarationReflection[], isComplete: boolean }} + */ +function collectUnionArm(t, collect, findDeclaration) { + const u = unwrapOptional(t); + if (u.type === 'intersection') { + const members = /** @type {import('typedoc').IntersectionType} */ (u).types.map(inner => + collectUnionArm(inner, collect, findDeclaration), + ); + return { + properties: members.flatMap(member => member.properties), + isComplete: members.every(member => member.isComplete), + }; + } + const properties = collect(u); + return { + properties: properties ?? [], + isComplete: properties !== undefined || isResolvedObjectType(u, findDeclaration), + }; +} + +/** + * Collect the properties of each object-like union arm. `arms` is every arm, for merging. `requirednessArms` leaves out arms with a member that could not be resolved, for {@link markOptionalUnlessRequiredInEveryArm}: an `Omit` reference TypeDoc leaves unresolved says nothing about which properties are required. + * + * @param {import('typedoc').UnionType} union + * @param {(t: any) => import('typedoc').DeclarationReflection[] | undefined} collect Returns `undefined` for a type it cannot resolve, and an empty list for one it resolved to no properties. + * @param {(name: string) => import('typedoc').DeclarationReflection | undefined} findDeclaration The lookup `collect` uses when a reference has no `reflection`. + */ +export function collectUnionArms(union, collect, findDeclaration) { + const collected = union.types.filter(isObjectLikeUnionArm).map(t => collectUnionArm(t, collect, findDeclaration)); + return { + arms: collected.map(arm => [...new Map(arm.properties.map(p => [p.name, p])).values()]), + requirednessArms: collected.filter(arm => arm.isComplete).map(arm => arm.properties), + }; +} + +/** + * Mark each merged union property optional unless every object-like arm requires it. Optional rows are shallow copies, so other pages that render the same reflection keep its flag. + * + * @param {import('typedoc').DeclarationReflection[]} merged + * @param {import('typedoc').DeclarationReflection[][]} armProperties One entry per fully collected object-like union arm. + * @returns {import('typedoc').DeclarationReflection[]} + */ +export function markOptionalUnlessRequiredInEveryArm(merged, armProperties) { + return merged.map(prop => { + const requiredInEveryArm = armProperties.every(arm => + arm.some(p => p.name === prop.name && !p.flags.isOptional && !propertyReflectionTypeIsNever(p)), + ); + if (requiredInEveryArm || prop.flags.isOptional) { + return prop; + } + const flags = new ReflectionFlags(); + flags.flags = prop.flags.flags; + flags.setFlag(ReflectionFlag.Optional, true); + const copy = Object.create(Object.getPrototypeOf(prop), Object.getOwnPropertyDescriptors(prop)); + copy.flags = flags; + return copy; + }); +} diff --git a/packages/backend/src/api/__tests__/OAuthApplicationsApi.test.ts b/packages/backend/src/api/__tests__/OAuthApplicationsApi.test.ts index fea5080abad..99008ed352e 100644 --- a/packages/backend/src/api/__tests__/OAuthApplicationsApi.test.ts +++ b/packages/backend/src/api/__tests__/OAuthApplicationsApi.test.ts @@ -5,11 +5,42 @@ import { describe, expect, it } from 'vitest'; import { OAuthTokenExchangeError } from '../../errors'; import { server, validateHeaders } from '../../mock-server'; -import type { ExchangeOAuthApplicationTokenParams } from '../endpoints'; +import type { CreateOAuthApplicationParams, ExchangeOAuthApplicationTokenParams } from '../endpoints'; import { createBackendApiClient } from '../factory'; describe('OAuthApplications', () => { const oauthApplicationId = 'oauthapp_xxxxx'; + const cimdUrl = 'https://mcp-client.example.com/oauth/client-metadata.json'; + const cimdClientJSON = { + object: 'oauth_application', + id: oauthApplicationId, + instance_id: 'ins_xxxxx', + name: 'MCP Client', + client_id: cimdUrl, + client_uri: null, + client_image_url: null, + dynamically_registered: false, + client_id_metadata_document: true, + client_id_metadata_document_details: { + pre_registered: true, + status: 'explicitly_allowed', + metadata_status: 'error', + metadata_fetched_at: null, + metadata_error: 'metadata document returned HTTP 404', + }, + consent_screen_enabled: true, + pkce_required: true, + public: true, + scopes: 'profile email offline_access', + redirect_uris: [], + authorize_url: 'https://clerk.example.test/oauth/authorize', + token_fetch_url: 'https://clerk.example.test/oauth/token', + user_info_url: 'https://clerk.example.test/oauth/userinfo', + discovery_url: 'https://clerk.example.test/.well-known/openid-configuration', + token_introspection_url: 'https://clerk.example.test/oauth/token_info', + created_at: 1764600000000, + updated_at: 1764600000000, + }; describe('list', () => { it('forwards the name filter alongside pagination', async () => { @@ -36,6 +67,112 @@ describe('OAuthApplications', () => { expect(response).toEqual({ data: [], totalCount: 100 }); }); + + it('lists only CIMD clients when clientIdMetadataDocument is true', async () => { + const apiClient = createBackendApiClient({ + apiUrl: 'https://api.clerk.test', + secretKey: 'sk_xxxxx', + }); + + server.use( + http.get( + 'https://api.clerk.test/v1/oauth_applications', + validateHeaders(({ request }) => { + expect(Object.fromEntries(new URL(request.url).searchParams)).toEqual({ + client_id_metadata_document: 'true', + }); + return HttpResponse.json({ data: [cimdClientJSON], total_count: 1 }); + }), + ), + ); + + const response = await apiClient.oauthApplications.list({ clientIdMetadataDocument: true }); + + expect(response.totalCount).toBe(1); + expect(response.data[0].clientId).toBe(cimdUrl); + expect(response.data[0].clientIdMetadataDocument).toBe(true); + }); + }); + + describe('create', () => { + it('pre-registers a CIMD client from its metadata document URL', async () => { + const apiClient = createBackendApiClient({ + apiUrl: 'https://api.clerk.test', + secretKey: 'sk_xxxxx', + }); + + server.use( + http.post( + 'https://api.clerk.test/v1/oauth_applications', + validateHeaders(async ({ request }) => { + expect(await request.json()).toEqual({ + client_id_metadata_document_url: cimdUrl, + scopes: 'profile email', + }); + return HttpResponse.json(cimdClientJSON); + }), + ), + ); + + const response = await apiClient.oauthApplications.create({ + clientIdMetadataDocumentUrl: cimdUrl, + scopes: 'profile email', + }); + + expect(response.clientId).toBe(cimdUrl); + expect(response.clientSecret).toBeUndefined(); + expect(response.clientIdMetadataDocument).toBe(true); + expect(response.clientIdMetadataDocumentDetails).toEqual({ + preRegistered: true, + status: 'explicitly_allowed', + metadataStatus: 'error', + metadataFetchedAt: null, + metadataError: 'metadata document returned HTTP 404', + }); + }); + + it('deserializes a regular OAuth application with no CIMD details', async () => { + const apiClient = createBackendApiClient({ + apiUrl: 'https://api.clerk.test', + secretKey: 'sk_xxxxx', + }); + + server.use( + http.post( + 'https://api.clerk.test/v1/oauth_applications', + validateHeaders(() => + HttpResponse.json({ + ...cimdClientJSON, + client_id: 'generated_client_id', + client_secret: 'secret', + client_id_metadata_document: false, + client_id_metadata_document_details: null, + }), + ), + ), + ); + + const response = await apiClient.oauthApplications.create({ + name: 'My App', + redirectUris: ['https://example.com/callback'], + }); + + expect(response.clientIdMetadataDocument).toBe(false); + expect(response.clientIdMetadataDocumentDetails).toBeNull(); + }); + + it('requires a name unless clientIdMetadataDocumentUrl is set, and rejects redirect URIs alongside it', () => { + const cimd: CreateOAuthApplicationParams = { clientIdMetadataDocumentUrl: cimdUrl }; + // @ts-expect-error name is required without clientIdMetadataDocumentUrl + const missingName: CreateOAuthApplicationParams = { scopes: 'profile' }; + // @ts-expect-error the metadata document defines a CIMD client's redirect URIs + const withRedirectUris: CreateOAuthApplicationParams = { + clientIdMetadataDocumentUrl: cimdUrl, + redirectUris: ['https://example.com/callback'], + }; + + expect([cimd, missingName, withRedirectUris]).toHaveLength(3); + }); }); describe('revokeToken', () => { diff --git a/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts b/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts index c35e66ef390..83c26a8408a 100644 --- a/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts +++ b/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts @@ -12,22 +12,54 @@ import type { WithSign } from './util-types'; const basePath = '/oauth_applications'; -/** @generateWithEmptyComment */ -export type CreateOAuthApplicationParams = { +/** @inline */ +export type OAuthApplicationParams = { /** * A descriptive name for the OAuth application (e.g., "My Web App", "My Mobile App"). Maximum length: 256 characters. */ name: string; /** An array of redirect URIs for the OAuth application. */ redirectUris?: Array | null | undefined; - /** Scopes for the OAuth application that dictate the user payload of the OAuth user info endpoint. Available scopes are `profile`, `email`, `public_metadata`, `private_metadata`. Provide the requested scopes as a string, separated by spaces. */ + /** The scopes of the OAuth application, as a space-separated string of built-in scopes, such as `profile`, `email`, `public_metadata` and `private_metadata`, and custom scope keys from the instance's OAuth scope catalog. `offline_access` is always included. */ scopes?: string | null | undefined; /** Whether the OAuth application is public. If `true`, the Proof Key of Code Exchange (PKCE) flow can be used. */ public?: boolean | null | undefined; }; /** @generateWithEmptyComment */ -export type UpdateOAuthApplicationParams = CreateOAuthApplicationParams & { +export type CreateOAuthApplicationParams = ( + | { + /** + * A descriptive name for the OAuth application (e.g., "My Web App", "My Mobile App"). Maximum length: 256 characters. Required unless `clientIdMetadataDocumentUrl` is set, in which case it defaults to the metadata document's `client_name`, or to the URL's host. + */ + name: string; + /** An array of redirect URIs for the OAuth application. Not allowed with `clientIdMetadataDocumentUrl`, because the metadata document defines the redirect URIs. */ + redirectUris?: Array | null | undefined; + /** Whether the OAuth application is public. If `true`, the Proof Key of Code Exchange (PKCE) flow can be used. Not allowed with `clientIdMetadataDocumentUrl`, because Clerk always makes those clients public. */ + public?: boolean | null | undefined; + clientIdMetadataDocumentUrl?: never; + } + | { + /** + * The HTTPS URL of a [Client ID Metadata Document (CIMD)](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/), at most 512 bytes, with a path and without credentials or a fragment. Pre-registers the client the document describes, using the URL as its `clientId`. The metadata document defines the redirect URIs, and Clerk makes the client public with the consent screen and PKCE required. If the instance already has an implicitly provisioned client for the URL, including a blocked one, that client becomes pre-registered. Requires the new OAuth provider. + */ + clientIdMetadataDocumentUrl: string; + /** + * A descriptive name for the OAuth application (e.g., "My Web App", "My Mobile App"). Maximum length: 256 characters. Required unless `clientIdMetadataDocumentUrl` is set, in which case it defaults to the metadata document's `client_name`, or to the URL's host. + */ + name?: string; + redirectUris?: never; + public?: never; + } +) & { + /** The scopes of the OAuth application, as a space-separated string of built-in scopes, such as `profile`, `email`, `public_metadata` and `private_metadata`, and custom scope keys from the instance's OAuth scope catalog. `offline_access` is always included. When `clientIdMetadataDocumentUrl` is set and `scopes` is omitted, a new client gets the default scopes, and an implicitly provisioned client that becomes pre-registered keeps its scopes. */ + scopes?: string | null | undefined; +}; + +/** + * The parameters for updating an OAuth application. For a client identified by a Client ID Metadata Document (`clientIdMetadataDocument` is `true`), only `name` and `scopes` can be updated. + */ +export type UpdateOAuthApplicationParams = OAuthApplicationParams & { /** The ID of the OAuth application to update. */ oauthApplicationId: string; }; @@ -91,13 +123,17 @@ export type ExchangeOAuthApplicationTokenResult = { /** @generateWithEmptyComment */ export type GetOAuthApplicationListParams = ClerkPaginationRequest<{ /** - * Filters by a case-insensitive substring of the application name or an exact client ID. + * Filters by a case-insensitive substring of the application name or an exact client ID. To look up a client by its Client ID Metadata Document URL, also set `clientIdMetadataDocument` to `true`. */ nameQuery?: string; /** * Returns OAuth applications in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`. */ orderBy?: WithSign<'name' | 'created_at'>; + /** + * When `true`, returns only clients identified by a Client ID Metadata Document (CIMD), both pre-registered and implicitly provisioned, including blocked ones. When omitted or `false`, returns only regular OAuth applications. + */ + clientIdMetadataDocument?: boolean; }>; type TokenExchangeResponseJSON = { @@ -280,6 +316,17 @@ export class OAuthApplicationsApi extends AbstractAPI { /** * Creates a new OAuth application. + * + * To pre-register a client identified by a Client ID Metadata Document (CIMD), set `clientIdMetadataDocumentUrl`. Only `name` and `scopes` can be set alongside it. The response has no client secret. Requires the new OAuth provider: otherwise the request fails with `feature_requires_oidc_provider`. If the client is already pre-registered, the request fails with `cimd_client_already_exists`. + * + * @example + * ```ts + * const client = await clerkClient.oauthApplications.create({ + * clientIdMetadataDocumentUrl: 'https://mcp-client.example.com/oauth/client-metadata.json', + * scopes: 'profile email', + * }); + * ``` + * * @param params - The parameters to create the OAuth application with. * @returns The created [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object. */ @@ -292,7 +339,7 @@ export class OAuthApplicationsApi extends AbstractAPI { } /** - * Updates the given OAuth application. + * Updates the given OAuth application. For a client identified by a Client ID Metadata Document, only `name` and `scopes` can be updated. `scopes` replaces the complete scope set, and `offline_access` is always kept. For a CIMD client, an empty `scopes` resets it to the default scopes. * @returns The updated [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object. */ public async update(params: UpdateOAuthApplicationParams) { @@ -322,7 +369,7 @@ export class OAuthApplicationsApi extends AbstractAPI { } /** - * Rotates the secret of the given OAuth application. When the client secret is rotated, ensure that you update it in your authorized OAuth clients. + * Rotates the secret of the given OAuth application. When the client secret is rotated, ensure that you update it in your authorized OAuth clients. Clients identified by a Client ID Metadata Document have no secret, and the request fails with `cimd_client_operation_not_supported`. * @param oauthApplicationId - The ID of the OAuth application to rotate the secret of. * @returns The [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object. */ diff --git a/packages/backend/src/api/resources/JSON.ts b/packages/backend/src/api/resources/JSON.ts index ce2f2e00a0d..ebdcaad5388 100644 --- a/packages/backend/src/api/resources/JSON.ts +++ b/packages/backend/src/api/resources/JSON.ts @@ -359,6 +359,14 @@ export interface OauthAccessTokenJSON { id_token?: string; } +export interface OAuthApplicationClientIdMetadataDocumentDetailsJSON { + pre_registered: boolean; + status: 'explicitly_allowed' | 'implicitly_allowed' | 'blocked'; + metadata_status: 'ok' | 'error' | 'metadata_unavailable'; + metadata_fetched_at: number | null; + metadata_error: string | null; +} + export interface OAuthApplicationJSON extends ClerkResourceJSON { object: typeof ObjectType.OAuthApplication; id: string; @@ -368,6 +376,8 @@ export interface OAuthApplicationJSON extends ClerkResourceJSON { client_uri: string | null; client_image_url: string | null; dynamically_registered: boolean; + client_id_metadata_document: boolean; + client_id_metadata_document_details: OAuthApplicationClientIdMetadataDocumentDetailsJSON | null; consent_screen_enabled: boolean; pkce_required: boolean; public: boolean; diff --git a/packages/backend/src/api/resources/OAuthApplication.ts b/packages/backend/src/api/resources/OAuthApplication.ts index bb871cdf559..7f1402a2f3a 100644 --- a/packages/backend/src/api/resources/OAuthApplication.ts +++ b/packages/backend/src/api/resources/OAuthApplication.ts @@ -1,4 +1,35 @@ -import type { OAuthApplicationJSON } from './JSON'; +import type { OAuthApplicationClientIdMetadataDocumentDetailsJSON, OAuthApplicationJSON } from './JSON'; + +/** + * The admission and metadata state of a client identified by a Client ID Metadata Document (CIMD). + */ +export type OAuthApplicationClientIdMetadataDocumentDetails = { + /** Whether the client was pre-registered through the Dashboard or the Backend API. `false` when Clerk provisioned it on the client's first OAuth flow. */ + preRegistered: boolean; + /** Whether the instance currently admits the client. Pre-registered clients are `'explicitly_allowed'`. Other clients are `'blocked'` when the instance blocks implicitly allowed clients, and `'implicitly_allowed'` otherwise. */ + status: 'explicitly_allowed' | 'implicitly_allowed' | 'blocked'; + /** The outcome of the last metadata document fetch, or `'metadata_unavailable'` when no fetched document backs the client. */ + metadataStatus: 'ok' | 'error' | 'metadata_unavailable'; + /** The Unix timestamp, in milliseconds, of the last successful metadata document fetch. */ + metadataFetchedAt: number | null; + /** Why the last metadata document fetch failed, when `metadataStatus` is `'error'`. */ + metadataError: string | null; +}; + +function clientIdMetadataDocumentDetailsFromJSON( + data: OAuthApplicationClientIdMetadataDocumentDetailsJSON | null, +): OAuthApplicationClientIdMetadataDocumentDetails | null { + if (!data) { + return null; + } + return { + preRegistered: data.pre_registered, + status: data.status, + metadataStatus: data.metadata_status, + metadataFetchedAt: data.metadata_fetched_at, + metadataError: data.metadata_error, + }; +} /** * The Backend `OAuthApplication` object holds information about an OAuth application. @@ -45,6 +76,10 @@ export class OAuthApplication { readonly updatedAt: number, /** The client secret associated with the OAuth application. Empty if public client. */ readonly clientSecret?: string, + /** Whether the `clientId` is the HTTPS URL of the client's Client ID Metadata Document (CIMD) rather than an identifier Clerk generated. CIMD clients are always public, with PKCE and the consent screen required. */ + readonly clientIdMetadataDocument: boolean = false, + /** The admission and metadata state of the client. `null` unless `clientIdMetadataDocument` is `true`. */ + readonly clientIdMetadataDocumentDetails: OAuthApplicationClientIdMetadataDocumentDetails | null = null, ) {} static fromJSON(data: OAuthApplicationJSON) { @@ -69,6 +104,8 @@ export class OAuthApplication { data.created_at, data.updated_at, data.client_secret, + data.client_id_metadata_document, + clientIdMetadataDocumentDetailsFromJSON(data.client_id_metadata_document_details), ); } } diff --git a/packages/backend/src/index.ts b/packages/backend/src/index.ts index 8ba5394c209..c1430816ead 100644 --- a/packages/backend/src/index.ts +++ b/packages/backend/src/index.ts @@ -79,6 +79,7 @@ export type { InvitationJSON, JwtTemplateJSON, OauthAccessTokenJSON, + OAuthApplicationClientIdMetadataDocumentDetailsJSON, OAuthApplicationJSON, OrganizationJSON, OrganizationDomainJSON, @@ -150,6 +151,7 @@ export type { M2MToken, OauthAccessToken, OAuthApplication, + OAuthApplicationClientIdMetadataDocumentDetails, Organization, OrganizationDomain, OrganizationDomainVerification,