// @oagen-ignore-start import { FetchHttpClient } from '../common/net/fetch-client'; import { HttpClient, HttpClientError } from '../common/net/http-client'; import { OauthException } from '../common/exceptions/oauth.exception'; // @oagen-ignore-end // This file is auto-generated by oagen. Do not edit. import type { WorkOS } from '../workos'; import type { PaginationOptions } from '../common/interfaces/pagination-options.interface'; import { AutoPaginatable } from '../common/utils/pagination'; import { fetchAndDeserialize } from '../common/utils/fetch-and-deserialize'; import type { CompleteOAuth2Options } from './interfaces/complete-oauth-2-options.interface'; import type { ListApplicationsOptions } from './interfaces/list-applications-options.interface'; import type { CreateApplicationOptions } from './interfaces/create-application-options.interface'; import type { GetApplicationOptions } from './interfaces/get-application-options.interface'; import type { UpdateApplicationOptions } from './interfaces/update-application-options.interface'; import type { DeleteApplicationOptions } from './interfaces/delete-application-options.interface'; import type { ListApplicationClientSecretsOptions } from './interfaces/list-application-client-secrets-options.interface'; import type { CreateApplicationClientSecretOptions } from './interfaces/create-application-client-secret-options.interface'; import type { DeleteClientSecretOptions } from './interfaces/delete-client-secret-options.interface'; import type { ExternalAuthCompleteResponse, ExternalAuthCompleteResponseWire, } from './interfaces/external-auth-complete-response.interface'; import type { ConnectApplication, ConnectApplicationResponse, } from './interfaces/connect-application.interface'; import type { ApplicationCredentialsListItem, ApplicationCredentialsListItemResponse, } from './interfaces/application-credentials-list-item.interface'; import type { NewConnectApplicationSecret, NewConnectApplicationSecretResponse, } from './interfaces/new-connect-application-secret.interface'; import type { RedirectUriInput } from './interfaces/redirect-uri-input.interface'; import type { UserManagementLoginRequestResponse } from './interfaces/user-management-login-request.interface'; import type { CreateOAuthApplicationResponse } from './interfaces/create-oauth-application.interface'; import type { CreateM2MApplicationResponse } from './interfaces/create-m2m-application.interface'; import type { UpdateOAuthApplicationResponse } from './interfaces/update-oauth-application.interface'; import type { CreateApplicationSecretResponse } from './interfaces/create-application-secret.interface'; import { deserializeExternalAuthCompleteResponse } from './serializers/external-auth-complete-response.serializer'; // @oagen-ignore-start import type { ExchangeTokenOptions, TokenExchangeResponse, TokenExchangeResponseResponse, } from './interfaces/token-exchange.interface'; import { deserializeTokenExchangeResponse } from './serializers/token-exchange-response.serializer'; // @oagen-ignore-end import { deserializeConnectApplication } from './serializers/connect-application.serializer'; import { deserializeApplicationCredentialsListItem } from './serializers/application-credentials-list-item.serializer'; import { deserializeNewConnectApplicationSecret } from './serializers/new-connect-application-secret.serializer'; import { serializeUserManagementLoginRequest } from './serializers/user-management-login-request.serializer'; import { serializeCreateOAuthApplication } from './serializers/create-oauth-application.serializer'; import { serializeCreateM2MApplication } from './serializers/create-m2m-application.serializer'; import { serializeUpdateOAuthApplication } from './serializers/update-oauth-application.serializer'; import { serializeCreateApplicationSecret } from './serializers/create-application-secret.serializer'; const serializeListApplicationsOptions = ( options: ListApplicationsOptions, ): PaginationOptions => { const wire: Record = { limit: options.limit, before: options.before, after: options.after, order: options.order, }; if (options.organizationId !== undefined) wire.organization_id = options.organizationId; return wire as PaginationOptions; }; export class Connect { constructor(private readonly workos: WorkOS) {} /** * Complete external authentication * * Completes an external authentication flow and returns control to AuthKit. This endpoint is used with [Standalone Connect](https://workos.com/docs/authkit/connect/standalone) to bridge your existing authentication system with the Connect OAuth API infrastructure. * * After successfully authenticating a user in your application, calling this endpoint will: * * - Create or update the user in AuthKit, using the given `id` as its `external_id`. * - Return a `redirect_uri` your application should redirect to in order for AuthKit to complete the flow * * Users are automatically created or updated based on the `id` and `email` provided. If a user with the same `id` exists, their information is updated. Otherwise, a new user is created. * * If you provide a new `id` with an `email` that already belongs to an existing user, the request will fail with an error as email addresses are unique to a user. * @param options - Object containing externalAuthId, user. * @param options.externalAuthId - Identifier provided when AuthKit redirected to your login page. * @example "ext_auth_01HXYZ123456789ABCDEFGHIJ" * @param options.user - The user to create or update in AuthKit. * @param options.userConsentOptions - Array of [User Consent Options](https://workos.com/docs/reference/workos-connect/standalone/user-consent-options) to store with the session. * @returns {Promise} * @throws {BadRequestException} 400 * @throws {NotFoundException} 404 * @throws {UnprocessableEntityException} 422 */ async completeOAuth2( options: CompleteOAuth2Options, ): Promise { const payload = options; const { data } = await this.workos.post< ExternalAuthCompleteResponseWire, UserManagementLoginRequestResponse >('/authkit/oauth2/complete', serializeUserManagementLoginRequest(payload)); return deserializeExternalAuthCompleteResponse(data); } // @oagen-ignore-start /** * Exchange an access token for one issued to another Resource Indicator * * Performs an [RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693) token exchange against the environment's * `/oauth2/token` endpoint, authenticating as a first-party Connect Application with its client ID and client * secret. The issued access token keeps the subject token's user and consent and is audienced to `resource`. * * Unlike other SDK methods this does not call the WorkOS API with your API key: the request goes to the * environment's issuer (AuthKit domain) using the Connect Application's credentials. The client's `fetchFn`, * `timeout`, `maxRetries` and `config` options still apply. * @param options - Object containing issuer, clientId, clientSecret, subjectToken, resource, scope. * @returns {Promise} * @throws {OauthException} `invalid_client`, `unauthorized_client`, `invalid_grant`, `invalid_target`, * `invalid_scope`, `unsupported_grant_type` */ async exchangeToken( options: ExchangeTokenOptions, ): Promise { const { issuer, clientId, clientSecret, subjectToken, resource, scope } = options; const path = '/oauth2/token'; const client = this.createIssuerHttpClient(issuer); const body = new URLSearchParams({ client_id: clientId, client_secret: clientSecret, grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange', subject_token: subjectToken, subject_token_type: 'urn:ietf:params:oauth:token-type:access_token', requested_token_type: 'urn:ietf:params:oauth:token-type:access_token', resource, ...(scope !== undefined && { scope }), }); let res; try { res = await client.post(path, body, {}); } catch (error) { this.throwOauthErrorFromTokenEndpoint(error); this.workos.handleHttpError({ path, error }); throw error; } const data: TokenExchangeResponseResponse = await this.workos.readResponseJSON(path, res); return deserializeTokenExchangeResponse(data); } /** * Builds an HTTP client for the environment's issuer that carries the SDK's * transport settings (`fetchFn`, `timeout`, `maxRetries`, `config`) but not * the WorkOS API key. */ private createIssuerHttpClient(issuer: string): HttpClient { const { config, timeout, maxRetries, fetchFn } = this.workos.options; return new FetchHttpClient( issuer, { ...config, timeout, maxRetries, headers: { 'User-Agent': `workos-node/${this.workos.version}` }, }, fetchFn, ) as HttpClient; } /** * The token endpoint reports client authentication failures as a 401 with * an RFC 6749 error body; surface that as an `OauthException` instead of the * generic `UnauthorizedException` used for API-key failures. */ private throwOauthErrorFromTokenEndpoint(error: unknown): void { if (!(error instanceof HttpClientError) || !error.response) { return; } const { status, data, headers } = error.response as { status: number; data: { error?: string; error_description?: string }; headers: Headers; }; if (status === 401 && (data.error || data.error_description)) { throw new OauthException( status, headers.get('X-Request-ID') ?? '', data.error, data.error_description, data, ); } } // @oagen-ignore-end /** * List Connect Applications * * List all Connect Applications in the current environment with optional filtering. * @param options - Pagination and filter options. * @returns {Promise>} * @throws {UnprocessableEntityException} 422 */ async listApplications( options?: ListApplicationsOptions, ): Promise> { return new AutoPaginatable( await fetchAndDeserialize( this.workos, '/connect/applications', deserializeConnectApplication, options ? serializeListApplicationsOptions(options) : undefined, ), (params) => fetchAndDeserialize( this.workos, '/connect/applications', deserializeConnectApplication, params, ), options ? serializeListApplicationsOptions(options) : undefined, ); } /** * Create a Connect Application * * Create a new Connect Application. Supports both OAuth and Machine-to-Machine (M2M) application types. * @param options - The request body. * @returns {Promise} * @throws {NotFoundException} 404 * @throws {UnprocessableEntityException} 422 */ async createApplication( options: CreateApplicationOptions, ): Promise { const payload = options; const { data } = await this.workos.post< ConnectApplicationResponse, CreateOAuthApplicationResponse | CreateM2MApplicationResponse >( '/connect/applications', (() => { switch (payload.applicationType) { case 'oauth': return serializeCreateOAuthApplication(payload); case 'm2m': return serializeCreateM2MApplication(payload); default: { const _unknown: never = payload; throw new Error( `Unknown applicationType: ${(_unknown as { applicationType?: unknown }).applicationType}`, ); } } })(), ); return deserializeConnectApplication(data); } /** * Create oauth application. * @param name - The name of the application. * @param isFirstParty - Whether this is a first-party application. Third-party applications require an organization_id. * @param description - A description for the application. * @param scopes - The OAuth scopes granted to the application. * @param redirectUris - Redirect URIs for the application. * @param usesPkce - Whether the application uses PKCE (Proof Key for Code Exchange). * @param organizationId - The organization ID this application belongs to. Required when is_first_party is false. * @returns {Promise} */ async createOAuthApplication( name: string, isFirstParty: boolean, description?: string | null, scopes?: string[] | null, redirectUris?: RedirectUriInput[] | null, usesPkce?: boolean | null, organizationId?: string | null, ): Promise { const body: Record = { application_type: 'oauth', name: name, is_first_party: isFirstParty, }; if (description !== undefined) body.description = description; if (scopes !== undefined) body.scopes = scopes; if (redirectUris !== undefined) body.redirect_uris = redirectUris; if (usesPkce !== undefined) body.uses_pkce = usesPkce; if (organizationId !== undefined) body.organization_id = organizationId; const { data } = await this.workos.post( '/connect/applications', body, ); return deserializeConnectApplication(data); } /** * Create m2m application. * @param name - The name of the application. * @param organizationId - The organization ID this application belongs to. * @param description - A description for the application. * @param scopes - The OAuth scopes granted to the application. * @returns {Promise} */ async createM2MApplication( name: string, organizationId: string, description?: string | null, scopes?: string[] | null, ): Promise { const body: Record = { application_type: 'm2m', name: name, organization_id: organizationId, }; if (description !== undefined) body.description = description; if (scopes !== undefined) body.scopes = scopes; const { data } = await this.workos.post( '/connect/applications', body, ); return deserializeConnectApplication(data); } /** * Get a Connect Application * * Retrieve details for a specific Connect Application by ID or client ID. * @param options - The request options. * @param options.id - The application ID or client ID of the Connect Application. * @example "conn_app_01HXYZ123456789ABCDEFGHIJ" * @returns {Promise} * @throws {NotFoundException} 404 */ async getApplication( options: GetApplicationOptions, ): Promise { const { id } = options; const { data } = await this.workos.get( `/connect/applications/${encodeURIComponent(id)}`, ); return deserializeConnectApplication(data); } /** * Update a Connect Application * * Update an existing Connect Application. For OAuth applications, you can update redirect URIs. For all applications, you can update the name, description, and scopes. * @param options - The request body. * @param options.id - The application ID or client ID of the Connect Application. * @example "conn_app_01HXYZ123456789ABCDEFGHIJ" * @param options.name - The name of the application. * @example "My Application" * @param options.description - A description for the application. * @example "An application for managing user access" * @param options.scopes - The OAuth scopes granted to the application. * @example ["openid","profile","email"] * @param options.redirectUris - Updated redirect URIs for the application. OAuth applications only. * @example [{"uri":"https://example.com/callback","default":true}] * @returns {Promise} * @throws {NotFoundException} 404 * @throws {UnprocessableEntityException} 422 */ async updateApplication( options: UpdateApplicationOptions, ): Promise { const { id, ...payload } = options; const { data } = await this.workos.put< ConnectApplicationResponse, UpdateOAuthApplicationResponse >( `/connect/applications/${encodeURIComponent(id)}`, serializeUpdateOAuthApplication(payload), ); return deserializeConnectApplication(data); } /** * Delete a Connect Application * * Delete an existing Connect Application. * @param options - The request options. * @param options.id - The application ID or client ID of the Connect Application. * @example "conn_app_01HXYZ123456789ABCDEFGHIJ" * @returns {Promise} * @throws {NotFoundException} 404 */ async deleteApplication(options: DeleteApplicationOptions): Promise { const { id } = options; await this.workos.delete(`/connect/applications/${encodeURIComponent(id)}`); } /** * List Client Secrets for a Connect Application * * List all client secrets associated with a Connect Application. * @param options - The request options. * @param options.id - The application ID or client ID of the Connect Application. * @example "conn_app_01HXYZ123456789ABCDEFGHIJ" * @returns {Promise} * @throws {NotFoundException} 404 */ async listApplicationClientSecrets( options: ListApplicationClientSecretsOptions, ): Promise { const { id } = options; const { data } = await this.workos.get< ApplicationCredentialsListItemResponse[] >(`/connect/applications/${encodeURIComponent(id)}/client_secrets`); return data.map(deserializeApplicationCredentialsListItem); } /** * Create a new client secret for a Connect Application * * Create new secrets for a Connect Application. * @param options - The request body. * @param options.id - The application ID or client ID of the Connect Application. * @example "conn_app_01HXYZ123456789ABCDEFGHIJ" * @returns {Promise} * @throws {NotFoundException} 404 * @throws {UnprocessableEntityException} 422 */ async createApplicationClientSecret( options: CreateApplicationClientSecretOptions, ): Promise { const { id, ...payload } = options; const { data } = await this.workos.post< NewConnectApplicationSecretResponse, CreateApplicationSecretResponse >( `/connect/applications/${encodeURIComponent(id)}/client_secrets`, serializeCreateApplicationSecret(payload), ); return deserializeNewConnectApplicationSecret(data); } /** * Delete a Client Secret * * Delete (revoke) an existing client secret. * @param options - The request options. * @param options.id - The unique ID of the client secret. * @example "secret_01J9Q2Z3X4Y5W6V7U8T9S0R1Q" * @returns {Promise} * @throws {NotFoundException} 404 */ async deleteClientSecret(options: DeleteClientSecretOptions): Promise { const { id } = options; await this.workos.delete( `/connect/client_secrets/${encodeURIComponent(id)}`, ); } }