Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

16.1 KB
Raw Blame
import { isNil } from '@activepieces/core-utils';
import {
  OAuth2Property,
  OAuth2Props,
  PieceMetadataModel,
  PieceMetadataModelSummary,
} from '@activepieces/pieces-framework';
import {
  ApErrorParams,
  ApFlagId,
  AppConnectionType,
  ErrorCode,
  OAuth2GrantType,
  UpsertCloudOAuth2Request,
  UpsertOAuth2Request,
  UpsertPlatformOAuth2Request,
} from '@activepieces/shared';
import { t } from 'i18next';
import { ChevronDown } from 'lucide-react';
import { Dispatch, SetStateAction, useState } from 'react';
import { useFormContext, UseFormReturn } from 'react-hook-form';

import { LogoPlate } from '@/components/custom/logo-plate';
import {
  MultiSelect,
  MultiSelectContent,
  MultiSelectItem,
  MultiSelectList,
  MultiSelectSearch,
  MultiSelectTrigger,
  MultiSelectValue,
} from '@/components/custom/multi-select';
import { Button } from '@/components/ui/button';
import { CommandEmpty } from '@/components/ui/command';
import {
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { OAuth2App, oauth2Utils } from '@/features/connections';
import { appConnectionsApi } from '@/features/connections/api/app-connections';
import { flagsHooks } from '@/hooks/flags-hooks';
import { api } from '@/lib/api';
import { cn } from '@/lib/utils';

import { GenericPropertiesForm } from '../builder/piece-properties/generic-properties-form';

import { SecretInput } from './secret-input';

function OAuth2ConnectionSettings({
  authProperty,
  oauth2App,
  piece,
  grantType,
}: OAuth2ConnectionSettingsProps) {
  const form = useFormContext<{
    request:
      | UpsertCloudOAuth2Request
      | UpsertOAuth2Request
      | UpsertPlatformOAuth2Request;
  }>();

  const [discoveryFailed, setDiscoveryFailed] = useState(false);
  // Endpoints and credentials are fetched from the server's own metadata on Connect,
  // so the fields that would carry them stay hidden until that fails.
  const useDiscovery = !isNil(authProperty.discovery) && !discoveryFailed;

  const isClientIdValid = isNil(
    form.formState.errors.request?.value?.client_id,
  );
  const isClientSecretValid =
    oauth2App.oauth2Type !== AppConnectionType.OAUTH2 ||
    useDiscovery ||
    form.getValues('request.value.client_secret');
  // Discovery fills these on Connect, so their emptiness must not gate the button
  // that triggers it — but every other prop (the server URL) still gates it.
  const propErrors = form.formState.errors.request?.value?.props;
  const discoveredNames = discoveredPropNames(authProperty.discovery);
  const isPropsValid =
    isNil(propErrors) ||
    (useDiscovery &&
      Object.keys(propErrors).every((name) => discoveredNames.includes(name)));
  const selectedScopeString = form.watch('request.value.scope') ?? '';
  const showScopeSelector = authProperty.scope.length > 1;
  const hasSelectedScopes =
    !showScopeSelector || selectedScopeString.trim().length > 0;
  const isConnectButtonEnabled =
    isClientIdValid && isClientSecretValid && isPropsValid && hasSelectedScopes;
  const { data: thirdPartyUrl } = flagsHooks.useFlag<string>(
    ApFlagId.THIRD_PARTY_AUTH_PROVIDER_REDIRECT_URL,
  );
  const redirectUrl = oauth2Utils.resolveRedirectUrl({
    oauth2Type: oauth2App.oauth2Type,
    platformRedirectUrl: thirdPartyUrl ?? 'no_redirect_url_found',
  });

  const showRedirectUrlInput =
    oauth2App.oauth2Type === AppConnectionType.OAUTH2 &&
    grantType === OAuth2GrantType.AUTHORIZATION_CODE;
  const [loading, setLoading] = useState(false);
  const [scopesEditing, setScopesEditing] = useState(false);
  const [scopeSearch, setScopeSearch] = useState('');
  const filteredScopes = authProperty.scope.filter((scope) =>
    scope.toLowerCase().includes(scopeSearch.toLowerCase()),
  );

  return (
    <div className="flex flex-col gap-4">
      {showRedirectUrlInput && (
        <div className="flex flex-col gap-2">
          <FormLabel>{t('Redirect URL')}</FormLabel>
          <FormControl>
            <Input disabled type="text" value={redirectUrl} />
          </FormControl>
          <FormMessage />
        </div>
      )}

      {oauth2App.oauth2Type === AppConnectionType.OAUTH2 && !useDiscovery && (
        <>
          <FormField
            name="request.value.client_id"
            control={form.control}
            render={({ field }) => (
              <FormItem className="flex flex-col gap-2">
                <FormLabel
                  className="flex items-center gap-1"
                  showRequiredIndicator
                >
                  <span>{t('Client ID')}</span>
                </FormLabel>
                <FormControl>
                  <SecretInput {...field} type="text" />
                </FormControl>
              </FormItem>
            )}
          ></FormField>
          <FormField
            name="request.value.client_secret"
            control={form.control}
            render={({ field }) => (
              <FormItem className="flex flex-col gap-2">
                <FormLabel
                  className="flex items-center gap-1"
                  showRequiredIndicator
                >
                  <span>{t('Client Secret')}</span>
                </FormLabel>
                <FormControl>
                  <SecretInput {...field} type="password" />
                </FormControl>
              </FormItem>
            )}
          ></FormField>
        </>
      )}
      {authProperty.props && (
        <GenericPropertiesForm
          prefixValue="request.value.props"
          props={authProperty.props}
          useMentionTextInput={false}
          propertySettings={null}
          dynamicPropsInfo={null}
          hiddenPropNames={useDiscovery ? discoveredNames : []}
        />
      )}

      {showScopeSelector && (
        <FormField
          name="request.value.scope"
          control={form.control}
          render={({ field }) => {
            const selected = parseScopeString(field.value);
            return (
              <FormItem className="flex flex-col gap-2">
                <FormControl>
                  <div className="flex flex-col gap-2">
                    <div
                      role="button"
                      tabIndex={0}
                      onClick={() => setScopesEditing((v) => !v)}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter' || e.key === ' ') {
                          e.preventDefault();
                          setScopesEditing((v) => !v);
                        }
                      }}
                      className="flex w-full items-center gap-2 text-sm font-medium cursor-pointer select-none"
                    >
                      <span className="leading-none">{t('Permissions')}</span>
                      <ChevronDown
                        className={cn(
                          'h-4 w-4 shrink-0 text-gray-11 transition-transform',
                          !scopesEditing && '-rotate-90',
                        )}
                      />
                    </div>
                    {scopesEditing && (
                      <MultiSelect
                        modal={true}
                        value={selected}
                        onValueChange={(next) => field.onChange(next.join(' '))}
                        items={authProperty.scope.map((scope) => ({
                          value: scope,
                          label: scope,
                        }))}
                        onSearch={(keyword) => setScopeSearch(keyword ?? '')}
                        onOpenChange={(open) => {
                          if (!open) {
                            setScopeSearch('');
                          }
                        }}
                      >
                        <MultiSelectTrigger>
                          {selected.length < 10 ? (
                            <MultiSelectValue
                              placeholder={t('Select permissions')}
                            />
                          ) : (
                            t('{number} items selected', {
                              number: selected.length,
                            })
                          )}
                        </MultiSelectTrigger>
                        <MultiSelectContent>
                          <MultiSelectSearch
                            placeholder={t('Search permissions')}
                          />
                          <MultiSelectList>
                            {scopeSearch === '' && (
                              <div
                                onClick={(e) => {
                                  e.stopPropagation();
                                  e.preventDefault();
                                  field.onChange(authProperty.scope.join(' '));
                                }}
                              >
                                <MultiSelectItem>
                                  {t('Select All')}
                                </MultiSelectItem>
                              </div>
                            )}
                            {filteredScopes.map((scope) => (
                              <MultiSelectItem key={scope} value={scope}>
                                <span className="truncate min-w-0">
                                  {scope}
                                </span>
                              </MultiSelectItem>
                            ))}
                            {filteredScopes.length === 0 && (
                              <CommandEmpty>
                                {t('No results found.')}
                              </CommandEmpty>
                            )}
                          </MultiSelectList>
                        </MultiSelectContent>
                      </MultiSelect>
                    )}
                  </div>
                </FormControl>
                <FormMessage />
              </FormItem>
            );
          }}
        />
      )}

      {grantType !== OAuth2GrantType.CLIENT_CREDENTIALS && (
        <FormField
          name="request.value.code"
          control={form.control}
          render={({ field }) => {
            const hasCode = !isNil(field.value) && field.value !== '';
            return (
              <FormItem className="flex flex-col gap-2">
                <FormControl>
                  <input type="hidden" {...field} />
                </FormControl>
                <div className="border border-solid p-2 rounded-xl gap-2 flex text-center items-center justify-center h-full">
                  <LogoPlate
                    src={piece.logoUrl}
                    alt=""
                    border
                    className="size-7.5 rounded-full"
                    innerClassName="p-1"
                  />
                  <div className="text-sm">{piece.displayName}</div>
                  <div className="grow"></div>
                  <Button
                    size={'sm'}
                    variant={'basic'}
                    className={cn(hasCode && 'text-danger-11')}
                    disabled={!isConnectButtonEnabled}
                    loading={loading}
                    type="button"
                    onClick={async () => {
                      if (!hasCode) {
                        const scopesList = parseScopeString(
                          form.getValues().request.value.scope,
                        );
                        openPopup({
                          redirectUrl,
                          oauth2Type: oauth2App.oauth2Type,
                          clientId: form.getValues().request.value.client_id,
                          props: form.getValues().request.value.props,
                          pieceName: piece.name,
                          form,
                          pieceVersion: piece.version,
                          scopes:
                            scopesList.length > 0 ? scopesList : undefined,
                          setLoading,
                          onDiscoveryFailed: () => setDiscoveryFailed(true),
                        });
                      } else {
                        field.onChange('');
                        form.setValue('request.value.code_challenge', '', {
                          shouldValidate: true,
                        });
                      }
                    }}
                  >
                    {hasCode ? t('Disconnect') : t('Connect')}
                  </Button>
                </div>
                <FormMessage />
              </FormItem>
            );
          }}
        />
      )}
    </div>
  );
}

OAuth2ConnectionSettings.displayName = 'OAuth2ConnectionSettings';
export { OAuth2ConnectionSettings };

function parseScopeString(value: string | undefined): string[] {
  if (!value) {
    return [];
  }
  return value.split(' ').filter((scope) => scope.length > 0);
}

function discoveredPropNames(
  discovery: OAuth2Property<OAuth2Props>['discovery'],
): string[] {
  if (isNil(discovery)) {
    return [];
  }
  return [
    discovery.authUrlProp,
    discovery.tokenUrlProp,
    ...(isNil(discovery.scopesProp) ? [] : [discovery.scopesProp]),
  ];
}

async function openPopup({
  redirectUrl,
  oauth2Type,
  clientId,
  props,
  pieceName,
  pieceVersion,
  form,
  scopes,
  setLoading,
  onDiscoveryFailed,
}: OpenPopupParams) {
  let authorizationUrl, codeVerifier;
  try {
    setLoading(true);
    const formProjectId = form.getValues().request.projectId;
    const result = await appConnectionsApi.getOAuth2AuthorizationUrl({
      pieceName,
      clientId,
      redirectUrl,
      pieceVersion,
      props,
      projectId: formProjectId,
      scopes,
    });
    authorizationUrl = result.authorizationUrl;
    codeVerifier = result.codeVerifier;
    if (!isNil(result.discovered)) {
      form.setValue('request.value.client_id', result.discovered.client_id, {
        shouldValidate: true,
      });
      form.setValue(
        'request.value.client_secret',
        result.discovered.client_secret,
        { shouldValidate: true },
      );
      form.setValue(
        'request.value.props',
        { ...props, ...result.discovered.props },
        { shouldValidate: true },
      );
      form.setValue('request.value.resource', result.discovered.resource, {
        shouldValidate: true,
      });
      form.setValue(
        'request.value.authorization_method',
        result.discovered.authorization_method,
        { shouldValidate: true },
      );
    }
  } catch (error: unknown) {
    const apError = api.isError(error)
      ? (error.response?.data as ApErrorParams | undefined)
      : undefined;
    // Only a rejection by the server itself means discovery can't work here; a
    // transient failure should leave the Connect button able to try again.
    if (apError?.code === ErrorCode.INVALID_APP_CONNECTION) {
      onDiscoveryFailed();
    }
    form.setError('request.value.code', {
      type: 'manual',
      message:
        apError?.code === ErrorCode.INVALID_APP_CONNECTION
          ? t('Connection failed with error {msg}', {
              msg: apError.params.error,
            })
          : api.extractServerErrorMessage(
              error,
              'Failed to initiate OAuth2 authentication',
            ),
    });
    setLoading(false);
    return;
  }
  setLoading(false);
  const { code } = await oauth2Utils.openOAuth2Popup({
    authorizationUrl,
    redirectUrl,
    oauth2Type,
    codeVerifier,
  });
  form.setValue('request.value.code', code, { shouldValidate: true });
  form.setValue('request.value.code_challenge', codeVerifier ?? '', {
    shouldValidate: true,
  });
}

type OAuth2ConnectionSettingsProps = {
  piece: PieceMetadataModelSummary | PieceMetadataModel;
  authProperty: OAuth2Property<OAuth2Props>;
  oauth2App: OAuth2App;
  grantType: OAuth2GrantType;
};

type OpenPopupParams = {
  redirectUrl: string;
  oauth2Type: OAuth2App['oauth2Type'];
  clientId: string;
  props: Record<string, unknown> | undefined;
  pieceName: string;
  pieceVersion: string;
  scopes: string[] | undefined;
  form: UseFormReturn<{
    request:
      | UpsertCloudOAuth2Request
      | UpsertOAuth2Request
      | UpsertPlatformOAuth2Request;
  }>;
  setLoading: Dispatch<SetStateAction<boolean>>;
  onDiscoveryFailed: () => void;
};