EspoCRM – Open Source CRM Application
PHP calendarcontactscrmcrm-platformcrm-systemcustomer-portalcustomer-supportcustomizabledocumentsemail-marketingkanbanleadsopen-sourcephpplatformsales-automationsingle-page-applicationsupport
OAuth server (#3788)
Yurii Kuznietsov1b920adf68da
diff --git a/application/Espo/Classes/Acl/Common/Pipeline/PipelineLinkChecker.php b/application/Espo/Classes/Acl/Common/Pipeline/PipelineLinkChecker.phpindex 2d8980ae70..1a2e172941 100644--- a/application/Espo/Classes/Acl/Common/Pipeline/PipelineLinkChecker.php+++ b/application/Espo/Classes/Acl/Common/Pipeline/PipelineLinkChecker.php@@ -41,7 +41,7 @@ class PipelineLinkChecker implements LinkChecker{public function check(User $user, Entity $entity, Entity $foreignEntity): bool{- if ($user->isAdmin()) {+ if ($user->isEffectiveAdmin()) {return true;}diff --git a/application/Espo/Classes/Acl/Email/AccessChecker.php b/application/Espo/Classes/Acl/Email/AccessChecker.phpindex 2904ff1a2c..40c20d875d 100644--- a/application/Espo/Classes/Acl/Email/AccessChecker.php+++ b/application/Espo/Classes/Acl/Email/AccessChecker.php@@ -84,7 +84,7 @@ class AccessChecker implements AccessEntityCREDSChecker{/** @var Email $entity */- if ($user->isAdmin()) {+ if ($user->isEffectiveAdmin()) {return true;}diff --git a/application/Espo/Classes/Acl/Import/AccessChecker.php b/application/Espo/Classes/Acl/Import/AccessChecker.phpindex bcf0af1798..60985fccd3 100644--- a/application/Espo/Classes/Acl/Import/AccessChecker.php+++ b/application/Espo/Classes/Acl/Import/AccessChecker.php@@ -59,7 +59,7 @@ class AccessChecker implements AccessEntityReadChecker, AccessEntityDeleteCheckepublic function checkEntityRead(User $user, Entity $entity, ScopeData $data): bool{- if ($user->isAdmin()) {+ if ($user->isEffectiveAdmin()) {return true;}@@ -72,7 +72,7 @@ class AccessChecker implements AccessEntityReadChecker, AccessEntityDeleteCheckepublic function checkEntityDelete(User $user, Entity $entity, ScopeData $data): bool{- if ($user->isAdmin()) {+ if ($user->isEffectiveAdmin()) {return true;}diff --git a/application/Espo/Classes/Acl/Note/AccessChecker.php b/application/Espo/Classes/Acl/Note/AccessChecker.phpindex 48760b8c9e..ee28660243 100644--- a/application/Espo/Classes/Acl/Note/AccessChecker.php+++ b/application/Espo/Classes/Acl/Note/AccessChecker.php@@ -99,7 +99,7 @@ class AccessChecker implements AccessEntityCREDChecker*/public function checkEntityRead(User $user, Entity $entity, ScopeData $data): bool{- if ($user->isAdmin()) {+ if ($user->isEffectiveAdmin()) {return true;}@@ -156,7 +156,7 @@ class AccessChecker implements AccessEntityCREDChecker*/public function checkEntityEdit(User $user, Entity $entity, ScopeData $data): bool{- if ($user->isAdmin()) {+ if ($user->isEffectiveAdmin()) {return true;}@@ -197,7 +197,7 @@ class AccessChecker implements AccessEntityCREDChecker*/public function checkEntityDelete(User $user, Entity $entity, ScopeData $data): bool{- if ($user->isAdmin()) {+ if ($user->isEffectiveAdmin()) {return true;}diff --git a/application/Espo/Classes/Acl/Pipeline/AccessChecker.php b/application/Espo/Classes/Acl/Pipeline/AccessChecker.phpindex a06a68fddb..6e15ab5c61 100644--- a/application/Espo/Classes/Acl/Pipeline/AccessChecker.php+++ b/application/Espo/Classes/Acl/Pipeline/AccessChecker.php@@ -52,7 +52,7 @@ class AccessChecker implements AccessEntityCREDCheckerpublic function checkCreate(User $user, ScopeData $data): bool{- return $user->isAdmin();+ return $user->isEffectiveAdmin();}public function checkRead(User $user, ScopeData $data): bool@@ -62,32 +62,32 @@ class AccessChecker implements AccessEntityCREDCheckerpublic function checkEdit(User $user, ScopeData $data): bool{- return $user->isAdmin();+ return $user->isEffectiveAdmin();}public function checkDelete(User $user, ScopeData $data): bool{- return $user->isAdmin();+ return $user->isEffectiveAdmin();}public function checkEntityCreate(User $user, Entity $entity, ScopeData $data): bool{- return $user->isAdmin();+ return $user->isEffectiveAdmin();}public function checkEntityDelete(User $user, Entity $entity, ScopeData $data): bool{- return $user->isAdmin();+ return $user->isEffectiveAdmin();}public function checkEntityEdit(User $user, Entity $entity, ScopeData $data): bool{- return $user->isAdmin();+ return $user->isEffectiveAdmin();}public function checkEntityRead(User $user, Entity $entity, ScopeData $data): bool{- if ($user->isAdmin()) {+ if ($user->isEffectiveAdmin()) {return true;}diff --git a/application/Espo/Classes/Acl/PipelineStage/AccessChecker.php b/application/Espo/Classes/Acl/PipelineStage/AccessChecker.phpindex e250b0f6c6..bbed1d10d4 100644--- a/application/Espo/Classes/Acl/PipelineStage/AccessChecker.php+++ b/application/Espo/Classes/Acl/PipelineStage/AccessChecker.php@@ -52,7 +52,7 @@ class AccessChecker implements AccessEntityCREDCheckerpublic function checkCreate(User $user, ScopeData $data): bool{- return $user->isAdmin();+ return $user->isEffectiveAdmin();}public function checkRead(User $user, ScopeData $data): bool@@ -62,32 +62,32 @@ class AccessChecker implements AccessEntityCREDCheckerpublic function checkEdit(User $user, ScopeData $data): bool{- return $user->isAdmin();+ return $user->isEffectiveAdmin();}public function checkDelete(User $user, ScopeData $data): bool{- return $user->isAdmin();+ return $user->isEffectiveAdmin();}public function checkEntityCreate(User $user, Entity $entity, ScopeData $data): bool{- return $user->isAdmin();+ return $user->isEffectiveAdmin();}public function checkEntityDelete(User $user, Entity $entity, ScopeData $data): bool{- return $user->isAdmin();+ return $user->isEffectiveAdmin();}public function checkEntityEdit(User $user, Entity $entity, ScopeData $data): bool{- return $user->isAdmin();+ return $user->isEffectiveAdmin();}public function checkEntityRead(User $user, Entity $entity, ScopeData $data): bool{- if ($user->isAdmin()) {+ if ($user->isEffectiveAdmin()) {return true;}diff --git a/application/Espo/Classes/Acl/User/AccessChecker.php b/application/Espo/Classes/Acl/User/AccessChecker.phpindex 727492fff0..c98be6f9fc 100644--- a/application/Espo/Classes/Acl/User/AccessChecker.php+++ b/application/Espo/Classes/Acl/User/AccessChecker.php@@ -53,7 +53,7 @@ class AccessChecker implements AccessEntityCREDSCheckerpublic function checkEntityCreate(User $user, Entity $entity, ScopeData $data): bool{- if (!$user->isAdmin()) {+ if (!$user->isEffectiveAdmin()) {return false;}@@ -66,7 +66,7 @@ class AccessChecker implements AccessEntityCREDSCheckerpublic function checkEntityRead(User $user, Entity $entity, ScopeData $data): bool{- if (!$user->isAdmin() && !$entity->isActive()) {+ if (!$user->isEffectiveAdmin() && !$entity->isActive()) {return false;}@@ -91,7 +91,7 @@ class AccessChecker implements AccessEntityCREDSCheckerreturn false;}- if (!$user->isAdmin()) {+ if (!$user->isEffectiveAdmin()) {if ($user->getId() !== $entity->getId()) {return false;}@@ -106,7 +106,7 @@ class AccessChecker implements AccessEntityCREDSCheckerpublic function checkEntityDelete(User $user, Entity $entity, ScopeData $data): bool{- if (!$user->isAdmin()) {+ if (!$user->isEffectiveAdmin()) {return false;}diff --git a/application/Espo/Classes/Acl/Webhook/AccessChecker.php b/application/Espo/Classes/Acl/Webhook/AccessChecker.phpindex 0df6fde5dd..4d2db0bc22 100644--- a/application/Espo/Classes/Acl/Webhook/AccessChecker.php+++ b/application/Espo/Classes/Acl/Webhook/AccessChecker.php@@ -51,7 +51,7 @@ class AccessChecker implements AccessEntityCREDCheckerpublic function check(User $user, ScopeData $data): bool{- if ($user->isAdmin()) {+ if ($user->isEffectiveAdmin()) {return true;}@@ -88,7 +88,7 @@ class AccessChecker implements AccessEntityCREDCheckerprivate function checkEntityInternal(User $user, Entity $entity, ScopeData $data): bool{- if ($user->isAdmin()) {+ if ($user->isEffectiveAdmin()) {return true;}diff --git a/application/Espo/Classes/AppParams/Extensions.php b/application/Espo/Classes/AppParams/Extensions.phpindex 80026e8d1f..a339ecddf0 100644--- a/application/Espo/Classes/AppParams/Extensions.php+++ b/application/Espo/Classes/AppParams/Extensions.php@@ -53,7 +53,7 @@ class Extensions implements AppParam*/public function get(): array{- if (!$this->user->isRegular() && !$this->user->isAdmin()) {+ if (!$this->user->isRegular() && !$this->user->isEffectiveAdmin()) {return [];}diff --git a/application/Espo/Classes/FieldValidators/OAuthClient/Scopes/Valid.php b/application/Espo/Classes/FieldValidators/OAuthClient/Scopes/Valid.phpnew file mode 100644index 0000000000..32899fd860--- /dev/null+++ b/application/Espo/Classes/FieldValidators/OAuthClient/Scopes/Valid.php@@ -0,0 +1,60 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Classes\FieldValidators\OAuthClient\Scopes;++use Espo\Core\FieldValidation\Validator;+use Espo\Core\FieldValidation\Validator\Data;+use Espo\Core\FieldValidation\Validator\Failure;+use Espo\Tools\OAuthServer\Entities\Client;+use Espo\ORM\Entity;+use Espo\Tools\OAuthServer\Scope\ScopesProvider;++/**+ * @implements Validator<Client>+ */+class Valid implements Validator+{+ public function __construct(+ private ScopesProvider $scopesProvider,+ ) {}++ public function validate(Entity $entity, string $field, Data $data): ?Failure+ {+ $scopes = $this->scopesProvider->get();++ foreach ($entity->getScopes() as $scope) {+ if (!in_array($scope, $scopes)) {+ return Failure::create();+ }+ }++ return null;+ }+}diff --git a/application/Espo/Classes/MassAction/User/MassUpdate.php b/application/Espo/Classes/MassAction/User/MassUpdate.phpindex 195df40069..0c723226d5 100644--- a/application/Espo/Classes/MassAction/User/MassUpdate.php+++ b/application/Espo/Classes/MassAction/User/MassUpdate.php@@ -82,7 +82,7 @@ class MassUpdate implements MassAction{$entityType = $params->getEntityType();- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden("Only admin can mass-update users.");}diff --git a/application/Espo/Classes/Record/User/InputFilter.php b/application/Espo/Classes/Record/User/InputFilter.phpindex 7c67c4dfd7..b96ca15681 100644--- a/application/Espo/Classes/Record/User/InputFilter.php+++ b/application/Espo/Classes/Record/User/InputFilter.php@@ -51,7 +51,7 @@ class InputFilter implements Filter$data->clear('isSuperAdmin');}- if (!$this->user->isAdmin() && !$this->acl->checkScope(TeamEntity::ENTITY_TYPE)) {+ if (!$this->user->isEffectiveAdmin() && !$this->acl->checkScope(TeamEntity::ENTITY_TYPE)) {$data->clear('defaultTeamId');}}diff --git a/application/Espo/Classes/Record/User/OutputFilter.php b/application/Espo/Classes/Record/User/OutputFilter.phpindex 599b860dc7..76411ed978 100644--- a/application/Espo/Classes/Record/User/OutputFilter.php+++ b/application/Espo/Classes/Record/User/OutputFilter.php@@ -58,7 +58,7 @@ class OutputFilter implements Filterreturn;}- if ($this->user->isAdmin()) {+ if ($this->user->isEffectiveAdmin()) {if ($entity->getAuthMethod() === Hmac::NAME) {$secretKey = $this->apiKey->getSecretKeyForUserId($entity->getId());diff --git a/application/Espo/Classes/Record/Webhook/UpdateInputFilter.php b/application/Espo/Classes/Record/Webhook/UpdateInputFilter.phpindex 50de9005b1..76ba1ad4d0 100644--- a/application/Espo/Classes/Record/Webhook/UpdateInputFilter.php+++ b/application/Espo/Classes/Record/Webhook/UpdateInputFilter.php@@ -44,7 +44,7 @@ class UpdateInputFilter implements Filterpublic function filter(Data $data): void{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {$data->clear('event');}}diff --git a/application/Espo/Classes/RecordHooks/Email/BeforeUpdate.php b/application/Espo/Classes/RecordHooks/Email/BeforeUpdate.phpindex f9a1804e08..d2048f21c1 100644--- a/application/Espo/Classes/RecordHooks/Email/BeforeUpdate.php+++ b/application/Espo/Classes/RecordHooks/Email/BeforeUpdate.php@@ -64,7 +64,7 @@ class BeforeUpdate implements SaveHook{$skipFilter = false;- if ($this->user->isAdmin()) {+ if ($this->user->isEffectiveAdmin()) {$skipFilter = true;}diff --git a/application/Espo/Classes/RecordHooks/Email/CheckFromAddress.php b/application/Espo/Classes/RecordHooks/Email/CheckFromAddress.phpindex 747a30daca..41a0cdf1a4 100644--- a/application/Espo/Classes/RecordHooks/Email/CheckFromAddress.php+++ b/application/Espo/Classes/RecordHooks/Email/CheckFromAddress.php@@ -53,7 +53,7 @@ class CheckFromAddress implements SaveHookpublic function process(Entity $entity): void{- if ($this->user->isAdmin()) {+ if ($this->user->isEffectiveAdmin()) {return;}diff --git a/application/Espo/Classes/RecordHooks/EmailAccount/BeforeCreate.php b/application/Espo/Classes/RecordHooks/EmailAccount/BeforeCreate.phpindex b0f3aee114..ae9a4d81fa 100644--- a/application/Espo/Classes/RecordHooks/EmailAccount/BeforeCreate.php+++ b/application/Espo/Classes/RecordHooks/EmailAccount/BeforeCreate.php@@ -51,7 +51,7 @@ class BeforeCreate implements SaveHookpublic function process(Entity $entity): void{- if ($this->user->isAdmin()) {+ if ($this->user->isEffectiveAdmin()) {return;}diff --git a/application/Espo/Classes/RecordHooks/EmailFolder/BeforeCreate.php b/application/Espo/Classes/RecordHooks/EmailFolder/BeforeCreate.phpindex 3dba49223a..eb59b19a77 100644--- a/application/Espo/Classes/RecordHooks/EmailFolder/BeforeCreate.php+++ b/application/Espo/Classes/RecordHooks/EmailFolder/BeforeCreate.php@@ -48,7 +48,7 @@ class BeforeCreate implements SaveHookpublic function process(Entity $entity): void{- if (!$this->user->isAdmin() || !$entity->get('assignedUserId')) {+ if (!$this->user->isEffectiveAdmin() || !$entity->get('assignedUserId')) {$entity->set('assignedUserId', $this->user->getId());}diff --git a/application/Espo/Classes/RecordHooks/Note/BeforeCreate.php b/application/Espo/Classes/RecordHooks/Note/BeforeCreate.phpindex bb406857c9..6cf2f12b43 100644--- a/application/Espo/Classes/RecordHooks/Note/BeforeCreate.php+++ b/application/Espo/Classes/RecordHooks/Note/BeforeCreate.php@@ -58,7 +58,7 @@ class BeforeCreate implements SaveHook{$this->checkParent($entity);- if (!$entity->isPost() && !$this->user->isAdmin()) {+ if (!$entity->isPost() && !$this->user->isEffectiveAdmin()) {throw new Forbidden("Only 'Post' type allowed.");}diff --git a/application/Espo/Classes/RecordHooks/Webhook/BeforeSave.php b/application/Espo/Classes/RecordHooks/Webhook/BeforeSave.phpindex 4f85cc7356..61df14b5b1 100644--- a/application/Espo/Classes/RecordHooks/Webhook/BeforeSave.php+++ b/application/Espo/Classes/RecordHooks/Webhook/BeforeSave.php@@ -71,7 +71,7 @@ class BeforeSave implements SaveHook$this->checkEntityUserIsApi($entity);$this->processEntityEventData($entity);- if ($entity->isNew() && !$this->user->isAdmin()) {+ if ($entity->isNew() && !$this->user->isEffectiveAdmin()) {$this->checkMaxCount();}}diff --git a/application/Espo/Classes/Select/EmailAccount/AccessControlFilters/Mandatory.php b/application/Espo/Classes/Select/EmailAccount/AccessControlFilters/Mandatory.phpindex 9355196a35..9743096ea5 100644--- a/application/Espo/Classes/Select/EmailAccount/AccessControlFilters/Mandatory.php+++ b/application/Espo/Classes/Select/EmailAccount/AccessControlFilters/Mandatory.php@@ -40,7 +40,7 @@ class Mandatory implements Filterpublic function apply(QueryBuilder $queryBuilder): void{- if ($this->user->isAdmin()) {+ if ($this->user->isEffectiveAdmin()) {return;}diff --git a/application/Espo/Classes/Select/EmailFolder/AccessControlFilters/Mandatory.php b/application/Espo/Classes/Select/EmailFolder/AccessControlFilters/Mandatory.phpindex cf61b9a62b..a1e29190de 100644--- a/application/Espo/Classes/Select/EmailFolder/AccessControlFilters/Mandatory.php+++ b/application/Espo/Classes/Select/EmailFolder/AccessControlFilters/Mandatory.php@@ -40,7 +40,7 @@ class Mandatory implements Filterpublic function apply(SelectBuilder $queryBuilder): void{- if ($this->user->isAdmin()) {+ if ($this->user->isEffectiveAdmin()) {return;}diff --git a/application/Espo/Classes/Select/Import/AccessControlFilters/Mandatory.php b/application/Espo/Classes/Select/Import/AccessControlFilters/Mandatory.phpindex 503596a6d3..034a063eb5 100644--- a/application/Espo/Classes/Select/Import/AccessControlFilters/Mandatory.php+++ b/application/Espo/Classes/Select/Import/AccessControlFilters/Mandatory.php@@ -42,7 +42,7 @@ class Mandatory implements Filterpublic function apply(SelectBuilder $queryBuilder): void{- if ($this->user->isAdmin()) {+ if ($this->user->isEffectiveAdmin()) {return;}diff --git a/application/Espo/Classes/Select/OAuthClient/PrimaryFilters/Active.php b/application/Espo/Classes/Select/OAuthClient/PrimaryFilters/Active.phpnew file mode 100644index 0000000000..0e51259d17--- /dev/null+++ b/application/Espo/Classes/Select/OAuthClient/PrimaryFilters/Active.php@@ -0,0 +1,44 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Classes\Select\OAuthClient\PrimaryFilters;++use Espo\Core\Select\Primary\Filter;+use Espo\Tools\OAuthServer\Entities\Client;+use Espo\ORM\Query\SelectBuilder;++class Active implements Filter+{+ public function apply(SelectBuilder $queryBuilder): void+ {+ $queryBuilder->where([+ Client::FIELD_STATUS => Client::STATUS_ACTIVE,+ ]);+ }+}diff --git a/application/Espo/Classes/Select/OAuthClientSecret/PrimaryFilters/Active.php b/application/Espo/Classes/Select/OAuthClientSecret/PrimaryFilters/Active.phpnew file mode 100644index 0000000000..18a671f10b--- /dev/null+++ b/application/Espo/Classes/Select/OAuthClientSecret/PrimaryFilters/Active.php@@ -0,0 +1,44 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Classes\Select\OAuthClientSecret\PrimaryFilters;++use Espo\Core\Select\Primary\Filter;+use Espo\Tools\OAuthServer\Entities\ClientSecret;+use Espo\ORM\Query\SelectBuilder;++class Active implements Filter+{+ public function apply(SelectBuilder $queryBuilder): void+ {+ $queryBuilder->where([+ ClientSecret::FIELD_STATUS => ClientSecret::STATUS_ACTIVE,+ ]);+ }+}diff --git a/application/Espo/Classes/Select/Pipeline/AccessControlFilters/Mandatory.php b/application/Espo/Classes/Select/Pipeline/AccessControlFilters/Mandatory.phpindex 1a598eaacf..da579c38b6 100644--- a/application/Espo/Classes/Select/Pipeline/AccessControlFilters/Mandatory.php+++ b/application/Espo/Classes/Select/Pipeline/AccessControlFilters/Mandatory.php@@ -47,7 +47,7 @@ class Mandatory implements Filterpublic function apply(SelectBuilder $queryBuilder): void{- if ($this->user->isAdmin()) {+ if ($this->user->isEffectiveAdmin()) {return;}diff --git a/application/Espo/Classes/Select/PipelineStage/AccessControlFilters/Mandatory.php b/application/Espo/Classes/Select/PipelineStage/AccessControlFilters/Mandatory.phpindex 0eabdb19dd..19cc9ed993 100644--- a/application/Espo/Classes/Select/PipelineStage/AccessControlFilters/Mandatory.php+++ b/application/Espo/Classes/Select/PipelineStage/AccessControlFilters/Mandatory.php@@ -48,7 +48,7 @@ class Mandatory implements Filterpublic function apply(SelectBuilder $queryBuilder): void{- if ($this->user->isAdmin()) {+ if ($this->user->isEffectiveAdmin()) {return;}diff --git a/application/Espo/Classes/Select/Template/AccessControlFilters/Mandatory.php b/application/Espo/Classes/Select/Template/AccessControlFilters/Mandatory.phpindex 0865769492..f814ffbdb9 100644--- a/application/Espo/Classes/Select/Template/AccessControlFilters/Mandatory.php+++ b/application/Espo/Classes/Select/Template/AccessControlFilters/Mandatory.php@@ -46,7 +46,7 @@ class Mandatory implements Filterpublic function apply(SelectBuilder $queryBuilder): void{- if ($this->user->isAdmin()) {+ if ($this->user->isEffectiveAdmin()) {return;}diff --git a/application/Espo/Classes/Select/User/AccessControlFilters/Mandatory.php b/application/Espo/Classes/Select/User/AccessControlFilters/Mandatory.phpindex 14c6c8821e..faf9a3211c 100644--- a/application/Espo/Classes/Select/User/AccessControlFilters/Mandatory.php+++ b/application/Espo/Classes/Select/User/AccessControlFilters/Mandatory.php@@ -45,7 +45,7 @@ class Mandatory implements Filterpublic function apply(SelectBuilder $queryBuilder): void{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {$queryBuilder->where(['isActive' => true,'type!=' => User::TYPE_API,diff --git a/application/Espo/Classes/Select/Webhook/AccessControlFilters/Mandatory.php b/application/Espo/Classes/Select/Webhook/AccessControlFilters/Mandatory.phpindex 95fef15fc8..d4b33d27ca 100644--- a/application/Espo/Classes/Select/Webhook/AccessControlFilters/Mandatory.php+++ b/application/Espo/Classes/Select/Webhook/AccessControlFilters/Mandatory.php@@ -46,7 +46,7 @@ class Mandatory implements Filterpublic function apply(SelectBuilder $queryBuilder): void{- if ($this->user->isAdmin()) {+ if ($this->user->isEffectiveAdmin()) {return;}diff --git a/application/Espo/Controllers/AddressCountry.php b/application/Espo/Controllers/AddressCountry.phpindex 3167853384..f5bad85dae 100644--- a/application/Espo/Controllers/AddressCountry.php+++ b/application/Espo/Controllers/AddressCountry.php@@ -36,7 +36,7 @@ class AddressCountry extends RecordBase{protected function checkAccess(): bool{- return $this->user->isAdmin();+ return $this->user->isEffectiveAdmin();}public function postActionPopulateDefaults(): booldiff --git a/application/Espo/Controllers/Admin.php b/application/Espo/Controllers/Admin.phpindex 1676ee454a..320630b976 100644--- a/application/Espo/Controllers/Admin.php+++ b/application/Espo/Controllers/Admin.php@@ -57,7 +57,7 @@ class Adminprivate DataManager $dataManager,private Config\SystemConfig $systemConfig,) {- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}}diff --git a/application/Espo/Controllers/AppLogRecord.php b/application/Espo/Controllers/AppLogRecord.phpindex debe5f8436..29cc51da7c 100644--- a/application/Espo/Controllers/AppLogRecord.php+++ b/application/Espo/Controllers/AppLogRecord.php@@ -39,7 +39,7 @@ class AppLogRecord extends Record{protected function checkAccess(): bool{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {return false;}diff --git a/application/Espo/Controllers/AppSecret.php b/application/Espo/Controllers/AppSecret.phpindex 5c35cf10cc..ed3dbae7b1 100644--- a/application/Espo/Controllers/AppSecret.php+++ b/application/Espo/Controllers/AppSecret.php@@ -38,6 +38,6 @@ class AppSecret extends Record{protected function checkAccess(): bool{- return $this->user->isAdmin();+ return $this->user->isEffectiveAdmin();}}diff --git a/application/Espo/Controllers/Attachment.php b/application/Espo/Controllers/Attachment.phpindex 2f92e56327..24800f63e0 100644--- a/application/Espo/Controllers/Attachment.php+++ b/application/Espo/Controllers/Attachment.php@@ -40,7 +40,7 @@ class Attachment extends RecordBase{public function getActionList(Request $request, Response $response): stdClass{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Controllers/AuthLogRecord.php b/application/Espo/Controllers/AuthLogRecord.phpindex 89a9331c30..132676c301 100644--- a/application/Espo/Controllers/AuthLogRecord.php+++ b/application/Espo/Controllers/AuthLogRecord.php@@ -40,7 +40,7 @@ class AuthLogRecord extends Record{protected function checkAccess(): bool{- return $this->user->isAdmin();+ return $this->user->isEffectiveAdmin();}public function postActionCreate(Request $request, Response $response): stdClassdiff --git a/application/Espo/Controllers/AuthToken.php b/application/Espo/Controllers/AuthToken.phpindex 90bde2b642..2783a36243 100644--- a/application/Espo/Controllers/AuthToken.php+++ b/application/Espo/Controllers/AuthToken.php@@ -37,7 +37,7 @@ class AuthToken extends Record{protected function checkAccess(): bool{- return $this->user->isAdmin();+ return $this->user->isEffectiveAdmin();}public function postActionCreateLink(Request $request): booldiff --git a/application/Espo/Controllers/AuthenticationProvider.php b/application/Espo/Controllers/AuthenticationProvider.phpindex 21342826e7..1e712ef87b 100644--- a/application/Espo/Controllers/AuthenticationProvider.php+++ b/application/Espo/Controllers/AuthenticationProvider.php@@ -35,7 +35,7 @@ class AuthenticationProvider extends RecordBase{protected function checkAccess(): bool{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {return false;}diff --git a/application/Espo/Controllers/DashboardTemplate.php b/application/Espo/Controllers/DashboardTemplate.phpindex 301fb6b5c1..8758b065fe 100644--- a/application/Espo/Controllers/DashboardTemplate.php+++ b/application/Espo/Controllers/DashboardTemplate.php@@ -42,7 +42,7 @@ class DashboardTemplate extends Record{protected function checkAccess(): bool{- return $this->user->isAdmin();+ return $this->user->isEffectiveAdmin();}/**diff --git a/application/Espo/Controllers/EntityManager.php b/application/Espo/Controllers/EntityManager.phpindex 01162fad89..bcb1e75bcf 100644--- a/application/Espo/Controllers/EntityManager.php+++ b/application/Espo/Controllers/EntityManager.php@@ -55,7 +55,7 @@ class EntityManagerprivate LinkManager $linkManager,private InjectableFactory $injectableFactory) {- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}}diff --git a/application/Espo/Controllers/Extension.php b/application/Espo/Controllers/Extension.phpindex 2c7b86b3f1..ae4292d3da 100644--- a/application/Espo/Controllers/Extension.php+++ b/application/Espo/Controllers/Extension.php@@ -43,7 +43,7 @@ class Extension extends RecordBase{protected function checkAccess(): bool{- return $this->user->isAdmin();+ return $this->user->isEffectiveAdmin();}/**diff --git a/application/Espo/Controllers/FieldManager.php b/application/Espo/Controllers/FieldManager.phpindex f2e402edbe..598b1e7e28 100644--- a/application/Espo/Controllers/FieldManager.php+++ b/application/Espo/Controllers/FieldManager.php@@ -59,7 +59,7 @@ class FieldManager*/protected function checkControllerAccess(): void{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}}diff --git a/application/Espo/Controllers/Formula.php b/application/Espo/Controllers/Formula.phpindex 1c26ed5770..9dc44b1fac 100644--- a/application/Espo/Controllers/Formula.php+++ b/application/Espo/Controllers/Formula.php@@ -49,7 +49,7 @@ class Formulaprivate Service $service,User $user,) {- if (!$user->isAdmin()) {+ if (!$user->isEffectiveAdmin()) {throw new ForbiddenSilent();}}diff --git a/application/Espo/Controllers/InboundEmail.php b/application/Espo/Controllers/InboundEmail.phpindex 394936af88..de2a3cb210 100644--- a/application/Espo/Controllers/InboundEmail.php+++ b/application/Espo/Controllers/InboundEmail.php@@ -42,7 +42,7 @@ class InboundEmail extends Record{protected function checkAccess(): bool{- return $this->user->isAdmin();+ return $this->user->isEffectiveAdmin();}/**diff --git a/application/Espo/Controllers/Integration.php b/application/Espo/Controllers/Integration.phpindex deac5ac36e..522c8b3e00 100644--- a/application/Espo/Controllers/Integration.php+++ b/application/Espo/Controllers/Integration.php@@ -48,7 +48,7 @@ class Integrationprivate User $user,) {- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}}diff --git a/application/Espo/Controllers/Job.php b/application/Espo/Controllers/Job.phpindex 790057fd02..ecb80c1b09 100644--- a/application/Espo/Controllers/Job.php+++ b/application/Espo/Controllers/Job.php@@ -40,7 +40,7 @@ class Job extends RecordBase{protected function checkAccess(): bool{- return $this->user->isAdmin();+ return $this->user->isEffectiveAdmin();}public function postActionCreate(Request $request, Response $response): stdClassdiff --git a/application/Espo/Controllers/LabelManager.php b/application/Espo/Controllers/LabelManager.phpindex fd7020be77..2f3925830b 100644--- a/application/Espo/Controllers/LabelManager.php+++ b/application/Espo/Controllers/LabelManager.php@@ -52,7 +52,7 @@ class LabelManagerprivate DataManager $dataManager,private LabelManagerTool $labelManagerTool) {- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}}diff --git a/application/Espo/Controllers/Layout.php b/application/Espo/Controllers/Layout.phpindex a34b556aa2..76c4222f48 100644--- a/application/Espo/Controllers/Layout.php+++ b/application/Espo/Controllers/Layout.php@@ -88,7 +88,7 @@ class Layout$data = get_object_vars($data);}- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}@@ -114,7 +114,7 @@ class Layout{$data = $request->getParsedBody();- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}@@ -134,7 +134,7 @@ class Layout*/public function getActionGetOriginal(Request $request){- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}@@ -156,7 +156,7 @@ class Layout*/public function postActionCreate(Request $request): bool{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}@@ -195,7 +195,7 @@ class Layout*/public function postActionDelete(Request $request): bool{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Controllers/LayoutSet.php b/application/Espo/Controllers/LayoutSet.phpindex f86a99df12..07a6d4f852 100644--- a/application/Espo/Controllers/LayoutSet.php+++ b/application/Espo/Controllers/LayoutSet.php@@ -35,6 +35,6 @@ class LayoutSet extends Record{protected function checkAccess(): bool{- return $this->user->isAdmin();+ return $this->user->isEffectiveAdmin();}}diff --git a/application/Espo/Controllers/Ldap.php b/application/Espo/Controllers/Ldap.phpindex 7f8b7d082b..f385fc845e 100644--- a/application/Espo/Controllers/Ldap.php+++ b/application/Espo/Controllers/Ldap.php@@ -58,7 +58,7 @@ class Ldap*/public function postActionTestConnection(Request $request): bool{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Controllers/LeadCapture.php b/application/Espo/Controllers/LeadCapture.phpindex ae377510cc..74df029894 100644--- a/application/Espo/Controllers/LeadCapture.php+++ b/application/Espo/Controllers/LeadCapture.php@@ -134,7 +134,7 @@ class LeadCapture extends Record*/public function getActionSmtpAccountDataList(): array{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Controllers/Metadata.php b/application/Espo/Controllers/Metadata.phpindex d62e67b558..59ca7ee106 100644--- a/application/Espo/Controllers/Metadata.php+++ b/application/Espo/Controllers/Metadata.php@@ -71,7 +71,7 @@ class Metadata*/public function getActionGet(Request $request, Response $response): void{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Controllers/OAuthAccessToken.php b/application/Espo/Controllers/OAuthAccessToken.phpnew file mode 100644index 0000000000..9b1cf2ea30--- /dev/null+++ b/application/Espo/Controllers/OAuthAccessToken.php@@ -0,0 +1,52 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Controllers;++use Espo\Core\Api\Request;+use Espo\Core\Api\Response;+use Espo\Core\Controllers\RecordBase;+use Espo\Core\Exceptions\Forbidden;+use stdClass;++/**+ * @noinspection PhpUnused+ */+class OAuthAccessToken extends RecordBase+{+ protected function checkAccess(): bool+ {+ return $this->user->isEffectiveAdmin();+ }++ public function postActionCreate(Request $request, Response $response): stdClass+ {+ throw new Forbidden();+ }+}diff --git a/application/Espo/Controllers/OAuthAccount.php b/application/Espo/Controllers/OAuthAccount.phpindex 2f0b2536a6..d6d8e39667 100644--- a/application/Espo/Controllers/OAuthAccount.php+++ b/application/Espo/Controllers/OAuthAccount.php@@ -38,7 +38,7 @@ class OAuthAccount extends RecordBase{protected function checkAccess(): bool{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {return false;}diff --git a/application/Espo/Controllers/OAuthAuthorizationCode.php b/application/Espo/Controllers/OAuthAuthorizationCode.phpnew file mode 100644index 0000000000..1c2c0d7a87--- /dev/null+++ b/application/Espo/Controllers/OAuthAuthorizationCode.php@@ -0,0 +1,52 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Controllers;++use Espo\Core\Api\Request;+use Espo\Core\Api\Response;+use Espo\Core\Controllers\RecordBase;+use Espo\Core\Exceptions\Forbidden;+use stdClass;++/**+ * @noinspection PhpUnused+ */+class OAuthAuthorizationCode extends RecordBase+{+ protected function checkAccess(): bool+ {+ return $this->user->isEffectiveAdmin();+ }++ public function postActionCreate(Request $request, Response $response): stdClass+ {+ throw new Forbidden();+ }+}diff --git a/public/oauth/callback/index.php b/application/Espo/Controllers/OAuthClient.phpsimilarity index 82%rename from public/oauth/callback/index.phprename to application/Espo/Controllers/OAuthClient.phpindex c5263c4361..36851d8e27 100644--- a/public/oauth/callback/index.php+++ b/application/Espo/Controllers/OAuthClient.php@@ -27,15 +27,17 @@* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.************************************************************************/-include "../../../bootstrap.php";+namespace Espo\Controllers;-use Espo\Core\Application;-use Espo\Core\Application\Runner\Params;-use Espo\Core\ApplicationRunners\EntryPoint;+use Espo\Core\Controllers\Record;-$app = new Application();--$app->run(- EntryPoint::class,- Params::create()->with(EntryPoint::PARAM_ENTRY_POINT, 'oauthCallback')-);+/**+ * @noinspection PhpUnused+ */+class OAuthClient extends Record+{+ protected function checkAccess(): bool+ {+ return $this->user->isEffectiveAdmin();+ }+}diff --git a/application/Espo/Controllers/OAuthClientSecret.php b/application/Espo/Controllers/OAuthClientSecret.phpnew file mode 100644index 0000000000..30b3e8c131--- /dev/null+++ b/application/Espo/Controllers/OAuthClientSecret.php@@ -0,0 +1,43 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Controllers;++use Espo\Core\Controllers\RecordBase;++/**+ * @noinspection PhpUnused+ */+class OAuthClientSecret extends RecordBase+{+ protected function checkAccess(): bool+ {+ return $this->user->isEffectiveAdmin();+ }+}diff --git a/application/Espo/Controllers/OAuthProvider.php b/application/Espo/Controllers/OAuthProvider.phpindex 1f20d2dcbe..c89135bb44 100644--- a/application/Espo/Controllers/OAuthProvider.php+++ b/application/Espo/Controllers/OAuthProvider.php@@ -38,7 +38,7 @@ class OAuthProvider extends Record{protected function checkAccess(): bool{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {return false;}diff --git a/application/Espo/Controllers/OAuthRefreshToken.php b/application/Espo/Controllers/OAuthRefreshToken.phpnew file mode 100644index 0000000000..2cc5ebf4ae--- /dev/null+++ b/application/Espo/Controllers/OAuthRefreshToken.php@@ -0,0 +1,52 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Controllers;++use Espo\Core\Api\Request;+use Espo\Core\Api\Response;+use Espo\Core\Controllers\RecordBase;+use Espo\Core\Exceptions\Forbidden;+use stdClass;++/**+ * @noinspection PhpUnused+ */+class OAuthRefreshToken extends RecordBase+{+ protected function checkAccess(): bool+ {+ return $this->user->isEffectiveAdmin();+ }++ public function postActionCreate(Request $request, Response $response): stdClass+ {+ throw new Forbidden();+ }+}diff --git a/application/Espo/Controllers/ScheduledJob.php b/application/Espo/Controllers/ScheduledJob.phpindex 2b62264dce..923bc0247d 100644--- a/application/Espo/Controllers/ScheduledJob.php+++ b/application/Espo/Controllers/ScheduledJob.php@@ -35,6 +35,6 @@ class ScheduledJob extends Record{protected function checkAccess(): bool{- return $this->user->isAdmin();+ return $this->user->isEffectiveAdmin();}}diff --git a/application/Espo/Controllers/ScheduledJobLogRecord.php b/application/Espo/Controllers/ScheduledJobLogRecord.phpindex 05da8871bb..d76a1f5287 100644--- a/application/Espo/Controllers/ScheduledJobLogRecord.php+++ b/application/Espo/Controllers/ScheduledJobLogRecord.php@@ -33,6 +33,6 @@ class ScheduledJobLogRecord extends \Espo\Core\Controllers\Record{protected function checkAccess(): bool{- return $this->user->isAdmin();+ return $this->user->isEffectiveAdmin();}}diff --git a/application/Espo/Controllers/Settings.php b/application/Espo/Controllers/Settings.phpindex 61e9df161e..c4e46c6dc3 100644--- a/application/Espo/Controllers/Settings.php+++ b/application/Espo/Controllers/Settings.php@@ -57,7 +57,7 @@ class Settings*/public function putActionUpdate(Request $request): stdClass{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Controllers/TemplateManager.php b/application/Espo/Controllers/TemplateManager.phpindex 2955dfdc5a..0602b5ae80 100644--- a/application/Espo/Controllers/TemplateManager.php+++ b/application/Espo/Controllers/TemplateManager.php@@ -29,6 +29,7 @@namespace Espo\Controllers;+use Espo\Core\Acl;use Espo\Core\Exceptions\Forbidden;use Espo\Core\Exceptions\BadRequest;use Espo\Core\Utils\Config;@@ -52,10 +53,11 @@ class TemplateManagerprivate Metadata $metadata,private TemplateFileManager $templateFileManager,private ApplicationState $applicationState,- private Config $config+ private Config $config,+ private Acl $acl,) {- if (!$this->applicationState->isAdmin()) {+ if (!$this->acl->checkAdmin()) {throw new Forbidden();}}diff --git a/application/Espo/Controllers/TwoFactorEmail.php b/application/Espo/Controllers/TwoFactorEmail.phpindex 611e161b4b..0f0428d1c9 100644--- a/application/Espo/Controllers/TwoFactorEmail.php+++ b/application/Espo/Controllers/TwoFactorEmail.php@@ -83,7 +83,7 @@ class TwoFactorEmailthrow new BadRequest("No 'emailAddress'.");}- if (!$this->user->isAdmin() && $id !== $this->user->getId()) {+ if (!$this->user->isEffectiveAdmin() && $id !== $this->user->getId()) {throw new Forbidden();}diff --git a/application/Espo/Controllers/TwoFactorSms.php b/application/Espo/Controllers/TwoFactorSms.phpindex cddb641eef..4e11ef34c2 100644--- a/application/Espo/Controllers/TwoFactorSms.php+++ b/application/Espo/Controllers/TwoFactorSms.php@@ -83,7 +83,7 @@ class TwoFactorSmsthrow new BadRequest("No 'phoneNumber'.");}- if (!$this->user->isAdmin() && $id !== $this->user->getId()) {+ if (!$this->user->isEffectiveAdmin() && $id !== $this->user->getId()) {throw new Forbidden();}diff --git a/application/Espo/Controllers/User.php b/application/Espo/Controllers/User.phpindex ff9481fe91..273195f118 100644--- a/application/Espo/Controllers/User.php+++ b/application/Espo/Controllers/User.php@@ -51,7 +51,7 @@ class User extends Recordpublic function postActionCreateLink(Request $request): bool{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}@@ -60,7 +60,7 @@ class User extends Recordpublic function deleteActionRemoveLink(Request $request): bool{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Controllers/UserSecurity.php b/application/Espo/Controllers/UserSecurity.phpindex 314ec9f963..929c0cbf26 100644--- a/application/Espo/Controllers/UserSecurity.php+++ b/application/Espo/Controllers/UserSecurity.php@@ -77,7 +77,7 @@ class UserSecuritythrow new BadRequest();}- if (!$this->user->isAdmin() && $id !== $this->user->getId()) {+ if (!$this->user->isEffectiveAdmin() && $id !== $this->user->getId()) {throw new Forbidden();}@@ -100,7 +100,7 @@ class UserSecuritythrow new BadRequest("No 'id'.");}- if (!$this->user->isAdmin() && $id !== $this->user->getId()) {+ if (!$this->user->isEffectiveAdmin() && $id !== $this->user->getId()) {throw new Forbidden();}@@ -122,7 +122,7 @@ class UserSecuritythrow new BadRequest();}- if (!$this->user->isAdmin() && $id !== $this->user->getId()) {+ if (!$this->user->isEffectiveAdmin() && $id !== $this->user->getId()) {throw new Forbidden();}diff --git a/application/Espo/Controllers/Webhook.php b/application/Espo/Controllers/Webhook.phpindex d3f5b6870a..c51f6cca06 100644--- a/application/Espo/Controllers/Webhook.php+++ b/application/Espo/Controllers/Webhook.php@@ -38,7 +38,7 @@ class Webhook extends Record{protected function checkAccess(): bool{- if (!$this->user->isAdmin() && !$this->user->isApi()) {+ if (!$this->user->isEffectiveAdmin() && !$this->user->isApi()) {return false;}diff --git a/application/Espo/Controllers/WebhookEventQueueItem.php b/application/Espo/Controllers/WebhookEventQueueItem.phpindex fa3f338297..146033dc5b 100644--- a/application/Espo/Controllers/WebhookEventQueueItem.php+++ b/application/Espo/Controllers/WebhookEventQueueItem.php@@ -42,7 +42,7 @@ class WebhookEventQueueItem extends RecordBase{protected function checkAccess(): bool{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {return false;}diff --git a/application/Espo/Controllers/WebhookQueueItem.php b/application/Espo/Controllers/WebhookQueueItem.phpindex ddd360a535..e42f997a14 100644--- a/application/Espo/Controllers/WebhookQueueItem.php+++ b/application/Espo/Controllers/WebhookQueueItem.php@@ -42,7 +42,7 @@ class WebhookQueueItem extends RecordBase{protected function checkAccess(): bool{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {return false;}diff --git a/application/Espo/Core/Acl.php b/application/Espo/Core/Acl.phpindex f380270c83..4c1c00a835 100644--- a/application/Espo/Core/Acl.php+++ b/application/Espo/Core/Acl.php@@ -393,4 +393,14 @@ class Acl/** @noinspection PhpDeprecationInspection */return $this->aclManager->checkUser($this->user, $permission, $entity);}++ /**+ * Whether the user is admin and has admin capabilities.+ *+ * @since 10.1.0+ */+ public function checkAdmin(): bool+ {+ return $this->aclManager->checkAdmin($this->user);+ }}diff --git a/application/Espo/Core/Acl/AccessChecker/AccessCheckers/Foreign.php b/application/Espo/Core/Acl/AccessChecker/AccessCheckers/Foreign.phpindex 01f8f15fa5..645a72660e 100644--- a/application/Espo/Core/Acl/AccessChecker/AccessCheckers/Foreign.php+++ b/application/Espo/Core/Acl/AccessChecker/AccessCheckers/Foreign.php@@ -29,6 +29,7 @@namespace Espo\Core\Acl\AccessChecker\AccessCheckers;+use Espo\Core\AclManager;use Espo\Entities\User;use Espo\ORM\Entity;use Espo\Core\Utils\Metadata;@@ -67,7 +68,8 @@ class Foreign implementspublic function __construct(private Metadata $metadata,DefaultAccessChecker $defaultAccessChecker,- private EntityManager $entityManager+ private EntityManager $entityManager,+ private AclManager $aclManager,) {$this->defaultAccessChecker = $defaultAccessChecker;}@@ -145,7 +147,7 @@ class Foreign implements$foreign = $this->getForeignEntity($entity);if (!$foreign) {- if ($user->isAdmin()) {+ if ($this->aclManager->checkAdmin($user)) {return true;}diff --git a/application/Espo/Core/Acl/Cache/Clearer.php b/application/Espo/Core/Acl/Cache/Clearer.phpindex d819727246..4f68e528f6 100644--- a/application/Espo/Core/Acl/Cache/Clearer.php+++ b/application/Espo/Core/Acl/Cache/Clearer.php@@ -72,10 +72,13 @@ class Clearerreturn;}- $part = basename($user->getId() . '.php');+ $file = basename($user->getId() . '.php');+ $dir = basename($user->getId());- $this->fileManager->remove('data/cache/application/acl/' . $part);- $this->fileManager->remove('data/cache/application/aclMap/' . $part);+ $this->fileManager->remove('data/cache/application/acl/' . $file);+ $this->fileManager->remove('data/cache/application/aclMap/' . $file);+ $this->fileManager->removeInDir('data/cache/application/acl/' . $dir, true);+ $this->fileManager->removeInDir('data/cache/application/aclMap/' . $dir, true);$this->eventDispatcher->dispatch(new UserRoleUpdate($user->getId()));}diff --git a/application/Espo/Core/Acl/Map/DefaultCacheKeyProvider.php b/application/Espo/Core/Acl/Map/DefaultCacheKeyProvider.phpindex 5d241e2208..e59ca7f162 100644--- a/application/Espo/Core/Acl/Map/DefaultCacheKeyProvider.php+++ b/application/Espo/Core/Acl/Map/DefaultCacheKeyProvider.php@@ -31,13 +31,25 @@ namespace Espo\Core\Acl\Map;use Espo\Entities\User;-class DefaultCacheKeyProvider implements CacheKeyProvider+final class DefaultCacheKeyProvider implements CacheKeyProvider{public function __construct(private User $user){}public function get(): string{- return 'aclMap/' . $this->user->getId();+ $key = 'aclMap/' . $this->user->getId();++ $scopes = $this->user->getScopes();++ if ($scopes === null) {+ return $key;+ }++ $hash = hash('xxh128', implode(' ', $scopes));++ $key .= '/' . $hash;++ return $key;}}diff --git a/application/Espo/Core/Acl/Scope.php b/application/Espo/Core/Acl/Scope.phpnew file mode 100644index 0000000000..b49c91800e--- /dev/null+++ b/application/Espo/Core/Acl/Scope.php@@ -0,0 +1,46 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Core\Acl;++/**+ * @since 10.1.0+ */+class Scope+{+ /**+ * Access to admin capabilities.+ */+ public const string ADMIN = 'Admin';++ /**+ * Reserved scope used for OAuth. If Global is present, the current user's scopes are not stripped.+ */+ public const string GLOBAL = 'Global';+}diff --git a/application/Espo/Core/Acl/Table/DefaultCacheKeyProvider.php b/application/Espo/Core/Acl/Table/DefaultCacheKeyProvider.phpindex 954aa65a17..65334f91a3 100644--- a/application/Espo/Core/Acl/Table/DefaultCacheKeyProvider.php+++ b/application/Espo/Core/Acl/Table/DefaultCacheKeyProvider.php@@ -31,17 +31,25 @@ namespace Espo\Core\Acl\Table;use Espo\Entities\User;-class DefaultCacheKeyProvider implements CacheKeyProvider+final class DefaultCacheKeyProvider implements CacheKeyProvider{- private $user;-- public function __construct(User $user)- {- $this->user = $user;- }+ public function __construct(private User $user)+ {}public function get(): string{- return 'acl/' . $this->user->getId();+ $key = 'acl/' . $this->user->getId();++ $scopes = $this->user->getScopes();++ if ($scopes === null) {+ return $key;+ }++ $hash = hash('xxh128', implode(' ', $scopes));++ $key .= '/' . $hash;++ return $key;}}diff --git a/application/Espo/Core/Acl/Table/DefaultTable.php b/application/Espo/Core/Acl/Table/DefaultTable.phpindex d1d1d9bbf3..935d9b7e9c 100644--- a/application/Espo/Core/Acl/Table/DefaultTable.php+++ b/application/Espo/Core/Acl/Table/DefaultTable.php@@ -29,6 +29,7 @@namespace Espo\Core\Acl\Table;+use Espo\Core\Acl\Scope;use Espo\Core\Utils\Config\SystemConfig;use Espo\Entities\User;@@ -193,7 +194,7 @@ class DefaultTable implements Table$aclTable = (object) [];$fieldTable = (object) [];- if (!$this->user->isAdmin()) {+ if (!$this->isAdmin()) {$roleList = $this->roleListProvider->get();foreach ($roleList as $role) {@@ -212,16 +213,18 @@ class DefaultTable implements Table$this->applyDefault($aclTable, $fieldTable);$this->applyDisabled($aclTable, $fieldTable);+ $this->stripScopes($aclTable, $fieldTable);$this->applyMandatory($aclTable, $fieldTable);}- if ($this->user->isAdmin()) {+ if ($this->isAdmin()) {$aclTable = (object) [];$fieldTable = (object) [];$this->applyHighest($aclTable);$this->applyDisabled($aclTable, $fieldTable);- $this->applyAdminMandatory($aclTable, $fieldTable);+ $this->stripScopes($aclTable, $fieldTable);+ $this->applyAdminMandatoryGeneral($aclTable, $fieldTable);}foreach (get_object_vars($aclTable) as $scope => $data) {@@ -233,7 +236,7 @@ class DefaultTable implements Table$this->data->scopes = $aclTable;$this->data->fields = $fieldTable;- if (!$this->user->isAdmin()) {+ if (!$this->isAdmin()) {foreach ($this->valuePermissionList as $permissionKey) {$permission = $this->normalizePermissionName($permissionKey);@@ -254,7 +257,7 @@ class DefaultTable implements Table}}- if ($this->user->isAdmin()) {+ if ($this->isAdmin()) {foreach ($this->valuePermissionList as $permissionKey) {$permission = $this->normalizePermissionName($permissionKey);@@ -286,7 +289,7 @@ class DefaultTable implements Tableprivate function applyHighest(stdClass $table): void{foreach ($this->getScopeList() as $scope) {- if ($this->metadata->get(['scopes', $scope, $this->type]) === ScopeDataType::BOOLEAN) {+ if ($this->getAclMetaValue($scope) === ScopeDataType::BOOLEAN) {$table->$scope = true;continue;@@ -320,7 +323,7 @@ class DefaultTable implements Tableprotected function applyDefault(stdClass &$table, stdClass &$fieldTable): void{- if ($this->user->isAdmin()) {+ if ($this->isAdmin()) {return;}@@ -393,7 +396,7 @@ class DefaultTable implements Tablecontinue;}- $aclType = $this->metadata->get(['scopes', $scope, $this->type]);+ $aclType = $this->getAclMetaValue($scope);if (empty($aclType)) {continue;@@ -706,4 +709,57 @@ class DefaultTable implements Tablereturn $data;}++ private function getAclMetaValue(string $scope): mixed+ {+ return $this->metadata->get("scopes.$scope.$this->type");+ }++ private function applyAdminMandatoryGeneral(stdClass $aclTable, stdClass $fieldTable): void+ {+ $isAllowedAdmin = $this->user->getScopes() === null || in_array(Scope::ADMIN, $this->user->getScopes());++ if ($isAllowedAdmin) {+ $this->applyAdminMandatory($aclTable, $fieldTable);+ } else {+ $this->applyMandatory($aclTable, $fieldTable);+ }+ }++ protected function stripScopes(stdClass $table, stdClass $fieldTable): void+ {+ if ($this->user->getScopes() === null) {+ return;+ }++ $map = array_fill_keys($this->user->getScopes(), true);++ if (array_key_exists(Scope::GLOBAL, $map)) {+ return;+ }++ if ($this->isAdmin() && array_key_exists(Scope::ADMIN, $map)) {+ // Grant an effective admin access to everything.+ return;+ }++ foreach ($this->getScopeList() as $scope) {+ $value = $this->getAclMetaValue($scope);++ if (!$value || array_key_exists($scope, $map)) {+ continue;+ }++ if (isset($table->$scope)) {+ $table->$scope = false;+ }++ unset($fieldTable->$scope);+ }+ }++ private function isAdmin(): bool+ {+ return $this->user->isAdmin();+ }}diff --git a/application/Espo/Core/AclManager.php b/application/Espo/Core/AclManager.phpindex f132700f72..bd159cd5cc 100644--- a/application/Espo/Core/AclManager.php+++ b/application/Espo/Core/AclManager.php@@ -32,6 +32,7 @@ namespace Espo\Core;use Espo\Core\Acl\Events\UserRoleUpdate;use Espo\Core\Acl\OwnershipSharedChecker;use Espo\Core\Acl\Permission;+use Espo\Core\Acl\Scope;use Espo\Core\Name\Field;use Espo\Core\Utils\Event\EventDispatcher;use Espo\ORM\Entity;@@ -472,14 +473,14 @@ class AclManager$typeList[] = GlobalRestriction::TYPE_INTERNAL;}- if (!$user->isAdmin()) {+ if (!$this->checkAdmin($user)) {$typeList[] = GlobalRestriction::TYPE_ONLY_ADMIN;}if ($action === Table::ACTION_EDIT) {$typeList[] = GlobalRestriction::TYPE_READ_ONLY;- if (!$user->isAdmin()) {+ if (!$this->checkAdmin($user)) {$typeList[] = GlobalRestriction::TYPE_NON_ADMIN_READ_ONLY;}}@@ -797,4 +798,14 @@ class AclManagerunset($this->mapHashMap[$userId]);});}++ /**+ * Whether the user is admin and has admin capabilities.+ *+ * @since 10.1.0+ */+ public function checkAdmin(User $user): bool+ {+ return $user->isEffectiveAdmin() && $this->checkScope($user, Scope::ADMIN);+ }}diff --git a/application/Espo/Core/Api/Auth.php b/application/Espo/Core/Api/Auth.phpindex a5892474a5..67f4d6a03a 100644--- a/application/Espo/Core/Api/Auth.php+++ b/application/Espo/Core/Api/Auth.php@@ -30,10 +30,10 @@namespace Espo\Core\Api;use Espo\Core\Authentication\HeaderKey;+use Espo\Core\Authentication\Login\MethodResolver;use Espo\Core\Exceptions\BadRequest;use Espo\Core\Exceptions\ServiceUnavailable;use Espo\Core\Exceptions\Forbidden;-use Espo\Core\Authentication\ConfigDataProvider;use Espo\Core\Authentication\Authentication;use Espo\Core\Authentication\AuthenticationData;use Espo\Core\Authentication\Result;@@ -51,9 +51,9 @@ class Authpublic function __construct(private Log $log,private Authentication $authentication,- private ConfigDataProvider $configDataProvider,+ private MethodResolver $methodResolver,private bool $authRequired = true,- private bool $isEntryPoint = false+ private bool $isEntryPoint = false,) {}/**@@ -65,7 +65,7 @@ class Auth$username = null;$password = null;- $authenticationMethod = $this->obtainAuthenticationMethodFromRequest($request);+ $authenticationMethod = $this->methodResolver->resolve($request);if (!$authenticationMethod) {[$username, $password] = $this->obtainUsernamePasswordFromRequest($request);@@ -271,32 +271,6 @@ class Authreturn false;}- private function obtainAuthenticationMethodFromRequest(Request $request): ?string- {- if ($request->hasHeader(HeaderKey::AUTHORIZATION)) {- return null;- }-- $paramsList = array_values(array_filter(- $this->configDataProvider->getLoginMetadataParamsList(),- function ($params) use ($request): bool {- $header = $params->getCredentialsHeader();-- if (!$header || !$params->isApi()) {- return false;- }-- return $request->hasHeader($header);- }- ));-- if (count($paramsList)) {- return $paramsList[0]->getMethod();- }-- return null;- }-/*** @return array{?string, ?string}* @throws BadRequest@@ -309,6 +283,11 @@ class Authreturn $this->decodeAuthorizationString($headerValue);}+ // Bypass as the Authorization header may be used for OAuth.+ if (!$this->authRequired) {+ return [null, null];+ }+if ($request->getServerParam('PHP_AUTH_USER') &&$request->getServerParam('PHP_AUTH_PW')@@ -327,8 +306,7 @@ class Authreturn [$username, $password];}- $cgiAuthString = $request->getHeader('Http-Espo-Cgi-Auth') ??- $request->getHeader('Redirect-Http-Espo-Cgi-Auth');+ $cgiAuthString = $this->getCgiAuthString($request);if ($cgiAuthString) {[$username, $password] = $this->decodeAuthorizationString(substr($cgiAuthString, 6));@@ -343,4 +321,11 @@ class Auth{return $request->getCookieParam('auth-token');}++ private function getCgiAuthString(Request $request): ?string+ {+ return+ $request->getHeader('Http-Espo-Cgi-Auth') ??+ $request->getHeader('Redirect-Http-Espo-Cgi-Auth');+ }}diff --git a/application/Espo/Core/ApplicationState.php b/application/Espo/Core/ApplicationState.phpindex 7e2d458e09..e557c46081 100644--- a/application/Espo/Core/ApplicationState.php+++ b/application/Espo/Core/ApplicationState.php@@ -132,7 +132,7 @@ class ApplicationStatereturn false;}- return $this->getUser()->isAdmin();+ return $this->getUser()->isEffectiveAdmin();}diff --git a/application/Espo/Core/Authentication/Authentication.php b/application/Espo/Core/Authentication/Authentication.phpindex 6ca04caea0..fa6c8fdbf0 100644--- a/application/Espo/Core/Authentication/Authentication.php+++ b/application/Espo/Core/Authentication/Authentication.php@@ -157,7 +157,7 @@ class Authentication$this->createAuthLogRecord($username, $user, $request, $method) : null;if ($result->isFail()) {- return $this->processFail($result, $data, $request);+ return $this->processFail($result, $data, $request, $response);}if (!$user) {@@ -165,7 +165,7 @@ class Authenticationreturn $this->processFail(Result::fail(FailReason::USER_NOT_FOUND), $data, $request);}- if (!$user->isAdmin() && $this->configDataProvider->isMaintenanceMode()) {+ if (!$user->isEffectiveAdmin() && $this->configDataProvider->isMaintenanceMode()) {$this->throwMaintenanceModeException();}@@ -584,10 +584,19 @@ class Authenticationreturn false;}- private function processFail(Result $result, AuthenticationData $data, Request $request): Result- {+ private function processFail(+ Result $result,+ AuthenticationData $data,+ Request $request,+ ?Response $response = null,+ ): Result {+$this->hookManager->processOnFail($result, $data, $request);+ if ($result->getResponse() && $response) {+ $response->applyPsr7($result->getResponse()->toPsr7());+ }+return $result;}@@ -643,7 +652,7 @@ class Authentication}// Important check.- if (!$user->isAdmin()) {+ if (!$user->isEffectiveAdmin()) {return [null, FailReason::ANOTHER_USER_NOT_ALLOWED];}diff --git a/application/Espo/Core/Authentication/Login/MetadataParams.php b/application/Espo/Core/Authentication/Login/MetadataParams.phpindex ff5645a235..e60daa490c 100644--- a/application/Espo/Core/Authentication/Login/MetadataParams.php+++ b/application/Espo/Core/Authentication/Login/MetadataParams.php@@ -34,19 +34,15 @@ namespace Espo\Core\Authentication\Login;*/class MetadataParams{- private string $method;- private ?string $credentialsHeader;- private bool $api;-+ /**+ * @internal+ */public function __construct(- string $method,- ?string $credentialsHeader = null,- bool $api = false- ) {- $this->method = $method;- $this->credentialsHeader = $credentialsHeader;- $this->api = $api;- }+ private string $method,+ private bool $api = false,+ private ?string $credentialsHeader = null,+ private ?string $credentialsHeaderScheme = null,+ ) {}/*** @param array<string, mixed> $data@@ -54,9 +50,10 @@ class MetadataParamspublic static function fromRaw(string $method, array $data): self{return new self(- $method,- $data['credentialsHeader'] ?? null,- $data['api'] ?? false,+ method: $method,+ api: $data['api'] ?? false,+ credentialsHeader: $data['credentialsHeader'] ?? null,+ credentialsHeaderScheme: $data['credentialsHeaderScheme'] ?? null,);}@@ -74,4 +71,9 @@ class MetadataParams{return $this->api;}++ public function getCredentialsHeaderScheme(): ?string+ {+ return $this->credentialsHeaderScheme;+ }}diff --git a/application/Espo/Core/Authentication/Login/MethodResolver.php b/application/Espo/Core/Authentication/Login/MethodResolver.phpnew file mode 100644index 0000000000..755b8952d8--- /dev/null+++ b/application/Espo/Core/Authentication/Login/MethodResolver.php@@ -0,0 +1,85 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Core\Authentication\Login;++use Espo\Core\Api\Request;+use Espo\Core\Authentication\ConfigDataProvider;+use Espo\Core\Authentication\HeaderKey;++/**+ * @internal+ */+class MethodResolver+{+ public function __construct(+ private ConfigDataProvider $configDataProvider,+ ) {}++ public function resolve(Request $request): ?string+ {+ if ($request->hasHeader(HeaderKey::AUTHORIZATION)) {+ return null;+ }++ $paramsList = $this->configDataProvider->getLoginMetadataParamsList();++ $paramsList = array_filter($paramsList, fn ($it) => $it->isApi());++ usort($paramsList, function (MetadataParams $a, MetadataParams $b) {+ return ($b->getCredentialsHeaderScheme() !== null) <=> ($a->getCredentialsHeaderScheme() !== null);+ });++ $paramsList = array_filter($paramsList, function ($params) use ($request): bool {+ $headerName = $params->getCredentialsHeader();++ if (!$headerName || !$request->hasHeader($headerName)) {+ return false;+ }++ $headerValue = $request->getHeader($headerName) ?? '';++ $scheme = $params->getCredentialsHeaderScheme();++ if ($scheme !== null && !str_starts_with($headerValue, $scheme . ' ')) {+ return false;+ }++ return true;+ });++ $paramsList = array_values($paramsList);++ if (count($paramsList)) {+ return $paramsList[0]->getMethod();+ }++ return null;+ }+}diff --git a/application/Espo/Core/Authentication/Oidc/UserProvider/DefaultUserProvider.php b/application/Espo/Core/Authentication/Oidc/UserProvider/DefaultUserProvider.phpindex 50f435c8ea..117440d4be 100644--- a/application/Espo/Core/Authentication/Oidc/UserProvider/DefaultUserProvider.php+++ b/application/Espo/Core/Authentication/Oidc/UserProvider/DefaultUserProvider.php@@ -99,7 +99,7 @@ class DefaultUserProvider implements UserProvider$isPortal = $this->applicationState->isPortal();- if (!$isPortal && !$user->isRegular() && !$user->isAdmin()) {+ if (!$isPortal && !$user->isRegular() && !$user->isEffectiveAdmin()) {$this->log->info("Oidc: User $userId found but it's neither regular user nor admin.");return false;diff --git a/application/Espo/Core/Authentication/Result.php b/application/Espo/Core/Authentication/Result.phpindex ea94ed5b3a..2829f7c3b2 100644--- a/application/Espo/Core/Authentication/Result.php+++ b/application/Espo/Core/Authentication/Result.php@@ -29,6 +29,7 @@namespace Espo\Core\Authentication;+use Espo\Core\Api\Response;use Espo\Core\Authentication\Result\Data;use Espo\Entities\User;@@ -52,6 +53,7 @@ class Resultprivate ?string $failReason = null;private bool $bypassSecondStep = false;private ?Data $data;+ private ?Response $response = null;private function __construct(string $status, ?User $user = null, ?Data $data = null){@@ -77,14 +79,24 @@ class Result/*** Create an instance for a failed login.+ *+ * @param ?string $reason A fail reason.+ * @param ?Response $response An error response.*/- public static function fail(?string $reason = null): self+ public static function fail(?string $reason = null, ?Response $response = null): self{$data = $reason ?Data::createWithFailReason($reason) :Data::create();- return new self(self::STATUS_FAIL, null, $data);+ $object = new self(+ status: self::STATUS_FAIL,+ data: $data,+ );++ $object->response = $response;++ return $object;}/**@@ -197,4 +209,14 @@ class Resultreturn $obj;}++ /**+ * An error response.+ *+ * @since 10.1.0+ */+ public function getResponse(): ?Response+ {+ return $this->response;+ }}diff --git a/application/Espo/Core/Controllers/RecordBase.php b/application/Espo/Core/Controllers/RecordBase.phpindex f652593002..f81404e2aa 100644--- a/application/Espo/Core/Controllers/RecordBase.php+++ b/application/Espo/Core/Controllers/RecordBase.php@@ -301,7 +301,7 @@ class RecordBase*/public function postActionRestoreDeleted(Request $request): bool{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Core/Mail/Account/PersonalAccount/Service.php b/application/Espo/Core/Mail/Account/PersonalAccount/Service.phpindex b0bdea9701..bed86d9f34 100644--- a/application/Espo/Core/Mail/Account/PersonalAccount/Service.php+++ b/application/Espo/Core/Mail/Account/PersonalAccount/Service.php@@ -173,7 +173,7 @@ class Serviceif ($userId &&- !$this->user->isAdmin() &&+ !$this->user->isEffectiveAdmin() &&$userId !== $this->user->getId()) {throw new Forbidden();@@ -195,7 +195,7 @@ class Service$account = $this->accountFactory->create($params->getId());if (- !$this->user->isAdmin() &&+ !$this->user->isEffectiveAdmin() &&$account->getUser()->getId() !== $this->user->getId()) {throw new Forbidden();diff --git a/application/Espo/Core/MassAction/Actions/MassFollow.php b/application/Espo/Core/MassAction/Actions/MassFollow.phpindex e496b669f2..c5f747048e 100644--- a/application/Espo/Core/MassAction/Actions/MassFollow.php+++ b/application/Espo/Core/MassAction/Actions/MassFollow.php@@ -68,7 +68,7 @@ class MassFollow implements MassAction$passedUserId = $data->get('userId');- if ($passedUserId && !$this->user->isAdmin()) {+ if ($passedUserId && !$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Core/MassAction/Actions/MassRecalculateFormula.php b/application/Espo/Core/MassAction/Actions/MassRecalculateFormula.phpindex be05a69c30..3b50ffdadb 100644--- a/application/Espo/Core/MassAction/Actions/MassRecalculateFormula.php+++ b/application/Espo/Core/MassAction/Actions/MassRecalculateFormula.php@@ -29,7 +29,7 @@namespace Espo\Core\MassAction\Actions;-use Espo\Core\ApplicationUser;+use Espo\Core\Acl;use Espo\Core\Exceptions\Forbidden;use Espo\Core\MassAction\Data;use Espo\Core\MassAction\MassAction;@@ -38,20 +38,19 @@ use Espo\Core\MassAction\QueryBuilder;use Espo\Core\MassAction\Result;use Espo\Core\ORM\EntityManager;use Espo\Core\Utils\SystemUser;-use Espo\Entities\User;class MassRecalculateFormula implements MassAction{public function __construct(private QueryBuilder $queryBuilder,private EntityManager $entityManager,- private User $user,- private SystemUser $systemUser+ private SystemUser $systemUser,+ private Acl $acl,) {}public function process(Params $params, Data $data): Result{- if (!$this->user->isAdmin()) {+ if (!$this->acl->checkAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Core/MassAction/Actions/MassUnfollow.php b/application/Espo/Core/MassAction/Actions/MassUnfollow.phpindex 7c55a4d8e7..a1778f29c9 100644--- a/application/Espo/Core/MassAction/Actions/MassUnfollow.php+++ b/application/Espo/Core/MassAction/Actions/MassUnfollow.php@@ -54,7 +54,7 @@ class MassUnfollow implements MassAction$passedUserId = $data->get('userId');- if ($passedUserId && !$this->user->isAdmin()) {+ if ($passedUserId && !$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Core/MassAction/Jobs/Process.php b/application/Espo/Core/MassAction/Jobs/Process.phpindex f86d97a353..b808caada0 100644--- a/application/Espo/Core/MassAction/Jobs/Process.php+++ b/application/Espo/Core/MassAction/Jobs/Process.php@@ -29,7 +29,6 @@namespace Espo\Core\MassAction\Jobs;-use Espo\Core\Exceptions\Error;use Espo\Core\Job\Job;use Espo\Core\Job\Job\Data as JobData;use Espo\Core\MassAction\MassActionFactory;@@ -40,40 +39,34 @@ use Espo\Entities\MassAction as MassActionEntity;use Espo\Entities\Notification;use Espo\Entities\User;+use RuntimeException;use Throwable;class Process implements Job{+ public const string PARAM_USER_SCOPES = 'userScopes';+public function __construct(private EntityManager $entityManager,private MassActionFactory $factory,private Language $language) {}- /**- * @throws Error- */public function run(JobData $data): void{$id = $data->getTargetId();if ($id === null) {- throw new Error("ID not passed to the mass action job.");+ throw new RuntimeException("ID not passed to the mass action job.");}- /** @var MassActionEntity|null $entity */- $entity = $this->entityManager->getEntityById(MassActionEntity::ENTITY_TYPE, $id);+ $entity = $this->entityManager->getRDBRepositoryByClass(MassActionEntity::class)->getById($id);- if ($entity === null) {- throw new Error("MassAction '$id' not found.");+ if (!$entity) {+ throw new RuntimeException("MassAction '$id' not found.");}- /** @var User|null $user */- $user = $this->entityManager->getEntityById(User::ENTITY_TYPE, $entity->getCreatedBy()->getId());-- if (!$user) {- throw new Error("MassAction '$id', user not found.");- }+ $user = $this->getUser($entity, $data);$params = $entity->getParams();@@ -89,7 +82,7 @@ class Process implements Job} catch (Throwable $e) {$this->setFailed($entity);- throw new Error("Mass action job error: " . $e->getMessage());+ throw new RuntimeException("Mass action job error: " . $e->getMessage());}$this->setSuccess($entity, $result);@@ -137,4 +130,21 @@ class Process implements Job$this->entityManager->saveEntity($entity);}++ private function getUser(MassActionEntity $entity, JobData $data): User+ {+ $user = $this->entityManager->getRDBRepositoryByClass(User::class)->getById($entity->getCreatedBy()->getId());++ if (!$user) {+ throw new RuntimeException("MassAction '{$entity->getId()}', user not found.");+ }++ $userScopes = $data->get(self::PARAM_USER_SCOPES);++ if (is_array($userScopes)) {+ $user->setScopes($userScopes);+ }++ return $user;+ }}diff --git a/application/Espo/Core/MassAction/Service.php b/application/Espo/Core/MassAction/Service.phpindex 5fd8b51e27..9af0d95b71 100644--- a/application/Espo/Core/MassAction/Service.php+++ b/application/Espo/Core/MassAction/Service.php@@ -156,7 +156,7 @@ class Service->create()->setClassName(Process::class)->setData(- JobData::create()+ JobData::create([Process::PARAM_USER_SCOPES => $this->user->getScopes()])->withTargetId($entity->getId())->withTargetType($entity->getEntityType()))diff --git a/application/Espo/Core/Portal/Acl/Table.php b/application/Espo/Core/Portal/Acl/Table.phpindex d9f48d7c6a..78baea3d08 100644--- a/application/Espo/Core/Portal/Acl/Table.php+++ b/application/Espo/Core/Portal/Acl/Table.php@@ -31,6 +31,7 @@ namespace Espo\Core\Portal\Acl;use Espo\Core\Acl\Table\DefaultTable as BaseTable;+use RuntimeException;use stdClass;class Table extends BaseTable@@ -99,4 +100,11 @@ class Table extends BaseTable}}}++ protected function stripScopes(stdClass $table, stdClass $fieldTable): void+ {+ if ($this->user->getScopes() !== null) {+ throw new RuntimeException("Unexpected having scopes in portal user.");+ }+ }}diff --git a/application/Espo/Core/Record/Service.php b/application/Espo/Core/Record/Service.phpindex 348e9fd66d..64afeaebcf 100644--- a/application/Espo/Core/Record/Service.php+++ b/application/Espo/Core/Record/Service.php@@ -265,7 +265,7 @@ class Service implements Crud,->where([Attribute::ID => $id])->findOne();- if (!$entity && $this->user->isAdmin()) {+ if (!$entity && $this->user->isEffectiveAdmin()) {$entity = $this->getEntityEvenDeleted($id);}@@ -932,7 +932,7 @@ class Service implements Crud,*/public function restoreDeleted(string $id): void{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden("Only admin can restore.");}diff --git a/application/Espo/Core/Select/AccessControl/FilterResolvers/BooleanOwn.php b/application/Espo/Core/Select/AccessControl/FilterResolvers/BooleanOwn.phpindex 22f28bd56e..34473de69c 100644--- a/application/Espo/Core/Select/AccessControl/FilterResolvers/BooleanOwn.php+++ b/application/Espo/Core/Select/AccessControl/FilterResolvers/BooleanOwn.php@@ -52,7 +52,7 @@ class BooleanOwn implements FilterResolverreturn 'no';}- if ($this->user->isAdmin()) {+ if ($this->user->isEffectiveAdmin()) {return 'all';}diff --git a/application/Espo/Core/Utils/Config/ApplicationConfig.php b/application/Espo/Core/Utils/Config/ApplicationConfig.phpindex 168f7bec1d..9a2ecb5802 100644--- a/application/Espo/Core/Utils/Config/ApplicationConfig.php+++ b/application/Espo/Core/Utils/Config/ApplicationConfig.php@@ -72,4 +72,12 @@ class ApplicationConfig{return (int) $this->config->get('recordsPerPage');}++ /**+ * @since 10.1.0+ */+ public function getApplicationName(): string+ {+ return $this->config->get('applicationName', 'EspoCRM');+ }}diff --git a/application/Espo/Core/Utils/OAuth/OAuthRouteUtil.php b/application/Espo/Core/Utils/OAuth/OAuthRouteUtil.phpnew file mode 100644index 0000000000..859f3c3b9a--- /dev/null+++ b/application/Espo/Core/Utils/OAuth/OAuthRouteUtil.php@@ -0,0 +1,132 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Core\Utils\OAuth;++use RuntimeException;++class OAuthRouteUtil+{+ private static function detectBasePath(): string+ {+ /** @var string $serverScriptName */+ $serverScriptName = $_SERVER['SCRIPT_NAME'];++ /** @var string $serverRequestUri */+ $serverRequestUri = $_SERVER['REQUEST_URI'];++ /** @var string $scriptName */+ $scriptName = parse_url($serverScriptName , PHP_URL_PATH);++ $scriptNameModified = str_replace('public/oauth/', 'oauth/', $scriptName);++ $scriptDir = dirname($scriptNameModified);++ $uri = parse_url('https://any.com' . $serverRequestUri, PHP_URL_PATH);++ if (!is_string($uri)) {+ throw new RuntimeException();+ }++ if (stripos($uri, $scriptName) === 0) {+ return $scriptName;+ }++ if ($scriptDir !== '/' && stripos($uri, $scriptDir) === 0) {+ return $scriptDir;+ }++ return '';+ }++ public static function detectPath(): string+ {+ $requestPath = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH);++ if (!is_string($requestPath)) {+ throw new RuntimeException();+ }++ $basePath = self::detectBasePath();++ $path = substr($requestPath, strlen($basePath));++ return trim($path, '/');+ }++ public static function detectBasePast(): string+ {+ $hasTrailingSlash = self::isTrailingSlash();++ $levels = substr_count(self::detectPath(), '/') + 1;++ if ($hasTrailingSlash) {+ $levels ++;+ }++ return str_repeat('../', $levels);+ }++ private static function isTrailingSlash(): bool+ {+ $requestUri = $_SERVER['REQUEST_URI'] ?? '';++ $requestPath = parse_url($requestUri, PHP_URL_PATH);++ if (!is_string($requestPath)) {+ throw new RuntimeException();+ }++ return ($requestPath !== '/' && str_ends_with($requestPath, '/'));+ }++ public static function getRedirectUrlWithTrailingSlash(): ?string+ {+ if ($_SERVER['REQUEST_METHOD'] !== 'GET') {+ return null;+ }++ $uri = $_SERVER['REQUEST_URI'] ?? '';+ $path = explode('?', $uri, 2)[0];++ if ($path === '' || $path === '/' || str_ends_with($path, '/')) {+ return null;+ }++ $output = $path . '/';++ $queryString = $_SERVER['QUERY_STRING'] ?? null;++ if ($queryString !== null && $queryString !== '') {+ $output .= '?' . $queryString;+ }++ return $output;+ }+}diff --git a/application/Espo/Entities/User.php b/application/Espo/Entities/User.phpindex a786b7f54f..59378102cf 100644--- a/application/Espo/Entities/User.php+++ b/application/Espo/Entities/User.php@@ -29,11 +29,13 @@namespace Espo\Entities;+use Espo\Core\Acl\Scope;use Espo\Core\Entities\Person;use Espo\Core\Field\Link;use Espo\Core\Field\LinkMultiple;use Espo\Core\Name\Field;use Espo\Modules\Crm\Entities\Contact;+use LogicException;use RuntimeException;class User extends Person@@ -79,6 +81,12 @@ class User extends Person/** @since 10.0.4 */public const string FIELD_AUTH_METHOD = 'authMethod';+ /**+ * @internal+ * @since 10.1.0+ */+ public const string FIELD_SCOPES = 'scopes';+/*** @internal* @since 10.1.0@@ -172,6 +180,8 @@ class User extends Person/*** Is admin, super-admin or system user.+ *+ * Do not use for access check for the current user. Use Acl::checkAdmin instead.*/public function isAdmin(): bool{@@ -180,6 +190,30 @@ class User extends Person$this->isSuperAdmin();}+ /**+ * Is admin and is not stripped of admin capabilities.+ *+ * Prefer using Acl::checkAdmin instead.+ *+ * @since 10.1.0+ */+ public function isEffectiveAdmin(): bool+ {+ if (!$this->isAdmin()) {+ return false;+ }++ if ($this->getScopes() === null) {+ return true;+ }++ if (!in_array(Scope::ADMIN, $this->getScopes())) {+ return false;+ }++ return true;+ }+/*** Is portal user.*/@@ -440,4 +474,30 @@ class User extends Person{return $this->get(self::FIELD_PASSWORD_VERSION);}++ /**+ * @internal+ * @param string[] $scopes+ * @since 10.1.0+ */+ public function setScopes(array $scopes): self+ {+ if ($this->get(self::FIELD_SCOPES) !== null) {+ throw new LogicException("Scopes are already set.");+ }++ return $this->set(self::FIELD_SCOPES, $scopes);+ }++ /**+ * Get access scopes. If not set, no additional restrictions.+ * Only for the current user.+ *+ * @return ?string[]+ * @since 10.1.0+ */+ public function getScopes(): ?array+ {+ return $this->get(self::FIELD_SCOPES);+ }}diff --git a/application/Espo/Hooks/OAuthClient/SetFields.php b/application/Espo/Hooks/OAuthClient/SetFields.phpnew file mode 100644index 0000000000..c748cc8729--- /dev/null+++ b/application/Espo/Hooks/OAuthClient/SetFields.php@@ -0,0 +1,60 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Hooks\OAuthClient;++use Espo\Core\Utils\Util;+use Espo\Tools\OAuthServer\Entities\Client;+use Espo\Core\Hook\Hook\BeforeSave;+use Espo\ORM\Entity;+use Espo\ORM\Repository\Option\SaveOptions;+use Espo\Tools\OAuthServer\Scope\ScopeSorter;++/**+ * @implements BeforeSave<Client>+ */+class SetFields implements BeforeSave+{+ public function __construct(+ private ScopeSorter $scopeSorter,+ ) {}++ public function beforeSave(Entity $entity, SaveOptions $options): void+ {+ if ($entity->isNew()) {+ $entity->setIdentifier(Util::generateUuid4());+ }++ if ($entity->isAttributeChanged(Client::FIELD_SCOPES)) {+ $scopes = $this->scopeSorter->sort($entity->getScopes());++ $entity->setScopes($scopes);+ }+ }+}diff --git a/application/Espo/Hooks/OAuthClientSecret/SetFields.php b/application/Espo/Hooks/OAuthClientSecret/SetFields.phpnew file mode 100644index 0000000000..3e35c168f5--- /dev/null+++ b/application/Espo/Hooks/OAuthClientSecret/SetFields.php@@ -0,0 +1,76 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Hooks\OAuthClientSecret;++use Espo\Core\Hook\Hook\BeforeSave;+use Espo\Core\Utils\PasswordHash;+use Espo\Core\Utils\Util;+use Espo\Tools\OAuthServer\Entities\ClientSecret;+use Espo\ORM\Entity;+use Espo\ORM\Exceptions\PersistenceException;+use Espo\ORM\Repository\Option\SaveOptions;+use Espo\Tools\OAuthServer\ClientType;++/**+ * @implements BeforeSave<ClientSecret>+ */+class SetFields implements BeforeSave+{++ public function __construct(+ private PasswordHash $passwordHash,+ ) {}++ public function beforeSave(Entity $entity, SaveOptions $options): void+ {+ if ($entity->isNew()) {+ $this->setForNew($entity);+ }+ }++ private function prepareName(string $secret): string+ {+ return '...' . substr($secret, - 6);+ }++ private function setForNew(ClientSecret $entity): void+ {+ if ($entity->getClient()->getClientType() !== ClientType::Confidential) {+ throw new PersistenceException("Cannot create secret for Confidential client.");+ }++ $secret = Util::generateSecretKey();+ $hash = $this->passwordHash->hash($secret);++ $entity->setName($this->prepareName($secret));+ $entity->setHash($hash);+ $entity->setValue($secret);+ }+}diff --git a/application/Espo/Modules/Crm/Controllers/EmailQueueItem.php b/application/Espo/Modules/Crm/Controllers/EmailQueueItem.phpindex 29f85a5ab6..0d46c3602e 100644--- a/application/Espo/Modules/Crm/Controllers/EmailQueueItem.php+++ b/application/Espo/Modules/Crm/Controllers/EmailQueueItem.php@@ -33,6 +33,6 @@ class EmailQueueItem extends \Espo\Core\Controllers\Record{protected function checkAccess(): bool{- return $this->user->isAdmin();+ return $this->user->isEffectiveAdmin();}}diff --git a/application/Espo/Modules/Crm/Tools/Activities/Service.php b/application/Espo/Modules/Crm/Tools/Activities/Service.phpindex 6001213865..e886dfa949 100644--- a/application/Espo/Modules/Crm/Tools/Activities/Service.php+++ b/application/Espo/Modules/Crm/Tools/Activities/Service.php@@ -1146,7 +1146,7 @@ class Service'id' => $id,]);- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {$builder->where(['userId' => $this->user->getId(),]);diff --git a/application/Espo/Resources/defaults/systemConfig.php b/application/Espo/Resources/defaults/systemConfig.phpindex 0890e17a6a..92eda39adc 100644--- a/application/Espo/Resources/defaults/systemConfig.php+++ b/application/Espo/Resources/defaults/systemConfig.php@@ -124,6 +124,8 @@ return ['redis','eventTransport','apiExposeExceptions',+ 'oAuthServerCryptKey',+ 'oAuthServer',],'adminItems' => ['devMode',diff --git a/application/Espo/Resources/i18n/en_US/Admin.json b/application/Espo/Resources/i18n/en_US/Admin.jsonindex 3673891783..12c53ba90a 100644--- a/application/Espo/Resources/i18n/en_US/Admin.json+++ b/application/Espo/Resources/i18n/en_US/Admin.json@@ -332,7 +332,8 @@"formulaSandbox": "Write and test formula scripts.","addressCountries": "Countries available for address fields.","oAuthProviders": "OAuth providers for integrations.",- "pipelines": "Configure multiple pipelines."+ "pipelines": "Configure multiple pipelines.",+ "oAuthClients": "Register applications for API access via OAuth."},"keywords": {"settings": "system",@@ -347,7 +348,8 @@"jobs": "cron","labelManager": "language,translation","appSecrets": "key,keys,password",- "leadCapture": "web forms"+ "leadCapture": "web forms",+ "oauthClients": "oauth,api,authentication"},"options": {"previewSize": {diff --git a/application/Espo/Resources/i18n/en_US/Global.json b/application/Espo/Resources/i18n/en_US/Global.jsonindex 4833878c0c..56fa0a4ec9 100644--- a/application/Espo/Resources/i18n/en_US/Global.json+++ b/application/Espo/Resources/i18n/en_US/Global.json@@ -72,7 +72,12 @@"CurrencyRecord": "Currency Record","CurrencyRecordRate": "Currency Rate","Pipeline": "Pipeline",- "PipelineStage": "Pipeline Stage"+ "PipelineStage": "Pipeline Stage",+ "OAuthClient": "OAuth Client",+ "OAuthClientSecret": "OAuth Client Secret",+ "OAuthAuthorizationCode": "OAuth Authorization Code",+ "OAuthAccessToken": "OAuth Access Token",+ "OAuthRefreshToken": "OAuth Refresh Token"},"scopeNamesPlural": {"Note": "Notes",@@ -135,9 +140,15 @@"CurrencyRecord": "Currencies","CurrencyRecordRate": "Currency Rates","Pipeline": "Pipelines",- "PipelineStage": "Pipeline Stages"+ "PipelineStage": "Pipeline Stages",+ "OAuthClient": "OAuth Clients",+ "OAuthClientSecret": "OAuth Client Secrets",+ "OAuthAuthorizationCode": "OAuth Authorization Codes",+ "OAuthAccessToken": "OAuth Access Tokens",+ "OAuthRefreshToken": "OAuth Refresh Tokens"},"labels": {+ "Disconnect": "Disconnect","Previous Page": "Previous Page","Next Page": "Next Page","First Page": "First Page",diff --git a/application/Espo/Resources/i18n/en_US/OAuthAccessToken.json b/application/Espo/Resources/i18n/en_US/OAuthAccessToken.jsonnew file mode 100644index 0000000000..2692e5a290--- /dev/null+++ b/application/Espo/Resources/i18n/en_US/OAuthAccessToken.json@@ -0,0 +1,27 @@+{+ "fields": {+ "identifier": "Identifier",+ "status": "Status",+ "client": "Client",+ "user": "User",+ "expiresAt": "Expires At",+ "scopes": "Scopes"+ },+ "links": {+ "client": "Client",+ "user": "User"+ },+ "options": {+ "status": {+ "Active": "Active",+ "Revoked": "Revoked",+ "Expired": "Expired"+ }+ },+ "massActions": {+ "revoke": "Revoke"+ },+ "messages": {+ "massRevokeDone": "{count} revoked"+ }+}diff --git a/application/Espo/Resources/i18n/en_US/OAuthAuthorizationCode.json b/application/Espo/Resources/i18n/en_US/OAuthAuthorizationCode.jsonnew file mode 100644index 0000000000..67007f541e--- /dev/null+++ b/application/Espo/Resources/i18n/en_US/OAuthAuthorizationCode.json@@ -0,0 +1,25 @@+{+ "fields": {+ "hash": "Hash",+ "status": "Status",+ "client": "Client",+ "user": "User",+ "expiresAt": "Expires At",+ "redirectUri": "Redirect URI",+ "scopes": "Scopes"+ },+ "links": {+ "client": "Client",+ "user": "User"+ },+ "options": {+ "status": {+ "Active": "Active",+ "Revoked": "Revoked",+ "Expired": "Expired"+ }+ },+ "massActions": {+ "revoke": "Revoke"+ }+}diff --git a/application/Espo/Resources/i18n/en_US/OAuthClient.json b/application/Espo/Resources/i18n/en_US/OAuthClient.jsonnew file mode 100644index 0000000000..6217f42594--- /dev/null+++ b/application/Espo/Resources/i18n/en_US/OAuthClient.json@@ -0,0 +1,43 @@+{+ "labels": {+ "Create OAuthClient": "Register OAuth Client"+ },+ "fields": {+ "status": "Status",+ "clientType": "Client Type",+ "identifier": "Client ID",+ "redirectUris": "Redirect URIs",+ "scopes": "Scopes"+ },+ "links": {+ "secrets": "Client Secrets"+ },+ "options": {+ "clientType": {+ "Confidential": "Confidential",+ "Public": "Public"+ },+ "status": {+ "Active": "Active",+ "Inactive": "Inactive"+ }+ },+ "strings": {+ "allow": "Allow Access",+ "authorizationCodes": "Authorization Codes",+ "accessTokens": "Access Tokens",+ "refreshTokens": "Refresh Tokens",+ "revoke": "Revoke"+ },+ "scopeDescriptions": {+ "Global": "Access to everything.",+ "GlobalAdmin": "Access to everything (except administrative capabilities).",+ "Admin": "Access to administrative capabilities."+ },+ "tooltips": {+ "scopes": "Special scopes:\n\n- `Global` – Grants all possible scopes except Admin.\n- `Admin` – Administrative capabilities. Applicable only for admin users. If an admin user does not have this scope, their admin capabilities will be removed."+ },+ "messages": {+ "allowAccessInfo": "**{clientName}** would like to access **{applicationName}** as *{username}*. By granting access, you will allow {clientName} to access the scopes listed below."+ }+}diff --git a/application/Espo/Resources/i18n/en_US/OAuthClientSecret.json b/application/Espo/Resources/i18n/en_US/OAuthClientSecret.jsonnew file mode 100644index 0000000000..671ef9525b--- /dev/null+++ b/application/Espo/Resources/i18n/en_US/OAuthClientSecret.json@@ -0,0 +1,23 @@+{+ "labels": {+ "Create OAuthClientSecret": "Create Secret"+ },+ "fields": {+ "name": "Name",+ "value": "Value",+ "hash": "Hash",+ "status": "Status",+ "client": "Client",+ "expirationDate": "Expiration Date"+ },+ "links": {+ "client": "Client"+ },+ "options": {+ "status": {+ "Active": "Active",+ "Revoked": "Revoked",+ "Expired": "Expired"+ }+ }+}diff --git a/application/Espo/Resources/i18n/en_US/OAuthRefreshToken.json b/application/Espo/Resources/i18n/en_US/OAuthRefreshToken.jsonnew file mode 100644index 0000000000..591661573a--- /dev/null+++ b/application/Espo/Resources/i18n/en_US/OAuthRefreshToken.json@@ -0,0 +1,25 @@+{+ "fields": {+ "hash": "Hash",+ "status": "Status",+ "client": "Client",+ "user": "User",+ "accessToken": "Access Token",+ "expiresAt": "Expires At"+ },+ "links": {+ "accessToken": "Access Token",+ "client": "Client",+ "user": "User"+ },+ "options": {+ "status": {+ "Active": "Active",+ "Revoked": "Revoked",+ "Expired": "Expired"+ }+ },+ "massActions": {+ "revoke": "Revoke"+ }+}diff --git a/application/Espo/Resources/i18n/en_US/User.json b/application/Espo/Resources/i18n/en_US/User.jsonindex f157df2d53..908f0ac361 100644--- a/application/Espo/Resources/i18n/en_US/User.json+++ b/application/Espo/Resources/i18n/en_US/User.json@@ -86,7 +86,8 @@"Code": "Code","Secret": "Secret","Send Code": "Send Code",- "Login Link": "Login Link"+ "Login Link": "Login Link",+ "Connected Apps": "Connected Apps"},"tooltips": {"defaultTeam": "All records created by this user will be related to this team by default.",diff --git a/application/Espo/Resources/layouts/OAuthAccessToken/detail.json b/application/Espo/Resources/layouts/OAuthAccessToken/detail.jsonnew file mode 100644index 0000000000..ea9f34a1ec--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthAccessToken/detail.json@@ -0,0 +1,30 @@+[+ {+ "rows": [+ [+ {+ "name": "id"+ },+ {+ "name": "status"+ }+ ],+ [+ {+ "name": "client"+ },+ {+ "name": "expiresAt"+ }+ ],+ [+ {+ "name": "user"+ },+ {+ "name": "scopes"+ }+ ]+ ]+ }+]diff --git a/application/Espo/Resources/layouts/OAuthAccessToken/detailSmall.json b/application/Espo/Resources/layouts/OAuthAccessToken/detailSmall.jsonnew file mode 100644index 0000000000..ea9f34a1ec--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthAccessToken/detailSmall.json@@ -0,0 +1,30 @@+[+ {+ "rows": [+ [+ {+ "name": "id"+ },+ {+ "name": "status"+ }+ ],+ [+ {+ "name": "client"+ },+ {+ "name": "expiresAt"+ }+ ],+ [+ {+ "name": "user"+ },+ {+ "name": "scopes"+ }+ ]+ ]+ }+]diff --git a/application/Espo/Resources/layouts/OAuthAccessToken/filters.json b/application/Espo/Resources/layouts/OAuthAccessToken/filters.jsonnew file mode 100644index 0000000000..f1a676b6d8--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthAccessToken/filters.json@@ -0,0 +1,7 @@+[+ "status",+ "client",+ "user",+ "createdAt",+ "expiresAt"+]diff --git a/application/Espo/Resources/layouts/OAuthAccessToken/list.json b/application/Espo/Resources/layouts/OAuthAccessToken/list.jsonnew file mode 100644index 0000000000..3b2abc1ece--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthAccessToken/list.json@@ -0,0 +1,26 @@+[+ {+ "name": "id",+ "link": true+ },+ {+ "name": "client",+ "width": 18+ },+ {+ "name": "status",+ "width": 13+ },+ {+ "name": "user",+ "width": 17+ },+ {+ "name": "createdAt",+ "width": 14+ },+ {+ "name": "expiresAt",+ "width": 14+ }+]diff --git a/application/Espo/Resources/layouts/OAuthAccessToken/listSmall.json b/application/Espo/Resources/layouts/OAuthAccessToken/listSmall.jsonnew file mode 100644index 0000000000..4e3c9acf28--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthAccessToken/listSmall.json@@ -0,0 +1,18 @@+[+ {+ "name": "id",+ "link": true+ },+ {+ "name": "client",+ "width": 25+ },+ {+ "name": "status",+ "width": 20+ },+ {+ "name": "user",+ "width": 20+ }+]diff --git a/application/Espo/Resources/layouts/OAuthAuthorizationCode/detail.json b/application/Espo/Resources/layouts/OAuthAuthorizationCode/detail.jsonnew file mode 100644index 0000000000..ea9f34a1ec--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthAuthorizationCode/detail.json@@ -0,0 +1,30 @@+[+ {+ "rows": [+ [+ {+ "name": "id"+ },+ {+ "name": "status"+ }+ ],+ [+ {+ "name": "client"+ },+ {+ "name": "expiresAt"+ }+ ],+ [+ {+ "name": "user"+ },+ {+ "name": "scopes"+ }+ ]+ ]+ }+]diff --git a/application/Espo/Resources/layouts/OAuthAuthorizationCode/detailSmall.json b/application/Espo/Resources/layouts/OAuthAuthorizationCode/detailSmall.jsonnew file mode 100644index 0000000000..ea9f34a1ec--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthAuthorizationCode/detailSmall.json@@ -0,0 +1,30 @@+[+ {+ "rows": [+ [+ {+ "name": "id"+ },+ {+ "name": "status"+ }+ ],+ [+ {+ "name": "client"+ },+ {+ "name": "expiresAt"+ }+ ],+ [+ {+ "name": "user"+ },+ {+ "name": "scopes"+ }+ ]+ ]+ }+]diff --git a/application/Espo/Resources/layouts/OAuthAuthorizationCode/filters.json b/application/Espo/Resources/layouts/OAuthAuthorizationCode/filters.jsonnew file mode 100644index 0000000000..f1a676b6d8--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthAuthorizationCode/filters.json@@ -0,0 +1,7 @@+[+ "status",+ "client",+ "user",+ "createdAt",+ "expiresAt"+]diff --git a/application/Espo/Resources/layouts/OAuthAuthorizationCode/list.json b/application/Espo/Resources/layouts/OAuthAuthorizationCode/list.jsonnew file mode 100644index 0000000000..2ba72344c0--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthAuthorizationCode/list.json@@ -0,0 +1,26 @@+[+ {+ "name": "id",+ "link": true+ },+ {+ "name": "client",+ "width": 19+ },+ {+ "name": "status",+ "width": 13+ },+ {+ "name": "user",+ "width": 17+ },+ {+ "name": "createdAt",+ "width": 14+ },+ {+ "name": "expiresAt",+ "width": 14+ }+]diff --git a/application/Espo/Resources/layouts/OAuthAuthorizationCode/listSmall.json b/application/Espo/Resources/layouts/OAuthAuthorizationCode/listSmall.jsonnew file mode 100644index 0000000000..4e3c9acf28--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthAuthorizationCode/listSmall.json@@ -0,0 +1,18 @@+[+ {+ "name": "id",+ "link": true+ },+ {+ "name": "client",+ "width": 25+ },+ {+ "name": "status",+ "width": 20+ },+ {+ "name": "user",+ "width": 20+ }+]diff --git a/application/Espo/Resources/layouts/OAuthClient/bottomPanelsDetail.json b/application/Espo/Resources/layouts/OAuthClient/bottomPanelsDetail.jsonnew file mode 100644index 0000000000..e2025afc71--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthClient/bottomPanelsDetail.json@@ -0,0 +1,5 @@+{+ "secrets": {+ "index": 0+ }+}diff --git a/application/Espo/Resources/layouts/OAuthClient/detail.json b/application/Espo/Resources/layouts/OAuthClient/detail.jsonnew file mode 100644index 0000000000..66e9358309--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthClient/detail.json@@ -0,0 +1,35 @@+[+ {+ "rows": [+ [+ {+ "name": "name"+ },+ {+ "name": "status"+ }+ ],+ [+ {+ "name": "clientType"+ },+ {+ "name": "identifier"+ }+ ],+ [+ {+ "name": "redirectUris"+ },+ {+ "name": "scopes"+ }+ ],+ [+ {+ "name": "description"+ }+ ]+ ]+ }+]diff --git a/application/Espo/Resources/layouts/OAuthClient/detailSmall.json b/application/Espo/Resources/layouts/OAuthClient/detailSmall.jsonnew file mode 100644index 0000000000..66e9358309--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthClient/detailSmall.json@@ -0,0 +1,35 @@+[+ {+ "rows": [+ [+ {+ "name": "name"+ },+ {+ "name": "status"+ }+ ],+ [+ {+ "name": "clientType"+ },+ {+ "name": "identifier"+ }+ ],+ [+ {+ "name": "redirectUris"+ },+ {+ "name": "scopes"+ }+ ],+ [+ {+ "name": "description"+ }+ ]+ ]+ }+]diff --git a/application/Espo/Resources/layouts/OAuthClient/filters.json b/application/Espo/Resources/layouts/OAuthClient/filters.jsonnew file mode 100644index 0000000000..954e3be40e--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthClient/filters.json@@ -0,0 +1,6 @@+[+ "status",+ "clientType",+ "identifier",+ "scopes"+]diff --git a/application/Espo/Resources/layouts/OAuthClient/list.json b/application/Espo/Resources/layouts/OAuthClient/list.jsonnew file mode 100644index 0000000000..fb28e0f7d7--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthClient/list.json@@ -0,0 +1,18 @@+[+ {+ "name": "name",+ "link": true+ },+ {+ "name": "status",+ "width": 15+ },+ {+ "name": "clientType",+ "width": 15+ },+ {+ "name": "identifier",+ "width": 26+ }+]diff --git a/application/Espo/Resources/layouts/OAuthClient/listSmall.json b/application/Espo/Resources/layouts/OAuthClient/listSmall.jsonnew file mode 100644index 0000000000..8e547e14f8--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthClient/listSmall.json@@ -0,0 +1,14 @@+[+ {+ "name": "name",+ "link": true+ },+ {+ "name": "status",+ "width": 20+ },+ {+ "name": "clientType",+ "width": 20+ }+]diff --git a/application/Espo/Resources/layouts/OAuthClient/massUpdate.json b/application/Espo/Resources/layouts/OAuthClient/massUpdate.jsonnew file mode 100644index 0000000000..361e8f16fa--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthClient/massUpdate.json@@ -0,0 +1,3 @@+[+ "status"+]diff --git a/application/Espo/Resources/layouts/OAuthClientSecret/detail.json b/application/Espo/Resources/layouts/OAuthClientSecret/detail.jsonnew file mode 100644index 0000000000..a9b4ffc0f9--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthClientSecret/detail.json@@ -0,0 +1,27 @@+[+ {+ "rows": [+ [+ {+ "name": "value"+ },+ {+ "name": "status"+ }+ ],+ [+ {+ "name": "client"+ },+ {+ "name": "expirationDate"+ }+ ],+ [+ {+ "name": "description"+ }+ ]+ ]+ }+]diff --git a/application/Espo/Resources/layouts/OAuthClientSecret/detailSmall.json b/application/Espo/Resources/layouts/OAuthClientSecret/detailSmall.jsonnew file mode 100644index 0000000000..a9b4ffc0f9--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthClientSecret/detailSmall.json@@ -0,0 +1,27 @@+[+ {+ "rows": [+ [+ {+ "name": "value"+ },+ {+ "name": "status"+ }+ ],+ [+ {+ "name": "client"+ },+ {+ "name": "expirationDate"+ }+ ],+ [+ {+ "name": "description"+ }+ ]+ ]+ }+]diff --git a/application/Espo/Resources/layouts/OAuthClientSecret/filters.json b/application/Espo/Resources/layouts/OAuthClientSecret/filters.jsonnew file mode 100644index 0000000000..9e2e4a2e81--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthClientSecret/filters.json@@ -0,0 +1,6 @@+[+ "status",+ "client",+ "expirationDate",+ "createdAt"+]diff --git a/application/Espo/Resources/layouts/OAuthClientSecret/list.json b/application/Espo/Resources/layouts/OAuthClientSecret/list.jsonnew file mode 100644index 0000000000..a6defbf937--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthClientSecret/list.json@@ -0,0 +1,22 @@+[+ {+ "name": "value",+ "link": true+ },+ {+ "name": "client",+ "width": 20+ },+ {+ "name": "status",+ "width": 15+ },+ {+ "name": "expirationDate",+ "width": 15+ },+ {+ "name": "createdAt",+ "width": 18+ }+]diff --git a/application/Espo/Resources/layouts/OAuthClientSecret/listForApp.json b/application/Espo/Resources/layouts/OAuthClientSecret/listForApp.jsonnew file mode 100644index 0000000000..dcaa81a704--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthClientSecret/listForApp.json@@ -0,0 +1,16 @@+[+ {+ "name": "value",+ "link": true+ },+ {+ "name": "status",+ "width": 25,+ "notSortable": true+ },+ {+ "name": "expirationDate",+ "width": 25,+ "notSortable": true+ }+]diff --git a/application/Espo/Resources/layouts/OAuthClientSecret/listSmall.json b/application/Espo/Resources/layouts/OAuthClientSecret/listSmall.jsonnew file mode 100644index 0000000000..bfa1f63829--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthClientSecret/listSmall.json@@ -0,0 +1,18 @@+[+ {+ "name": "value",+ "link": true+ },+ {+ "name": "client",+ "width": 25+ },+ {+ "name": "status",+ "width": 20+ },+ {+ "name": "expirationDate",+ "width": 20+ }+]diff --git a/application/Espo/Resources/layouts/OAuthRefreshToken/detail.json b/application/Espo/Resources/layouts/OAuthRefreshToken/detail.jsonnew file mode 100644index 0000000000..e13593315b--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthRefreshToken/detail.json@@ -0,0 +1,30 @@+[+ {+ "rows": [+ [+ {+ "name": "id"+ },+ {+ "name": "status"+ }+ ],+ [+ {+ "name": "client"+ },+ {+ "name": "expiresAt"+ }+ ],+ [+ {+ "name": "user"+ },+ {+ "name": "accessToken"+ }+ ]+ ]+ }+]diff --git a/application/Espo/Resources/layouts/OAuthRefreshToken/detailSmall.json b/application/Espo/Resources/layouts/OAuthRefreshToken/detailSmall.jsonnew file mode 100644index 0000000000..e13593315b--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthRefreshToken/detailSmall.json@@ -0,0 +1,30 @@+[+ {+ "rows": [+ [+ {+ "name": "id"+ },+ {+ "name": "status"+ }+ ],+ [+ {+ "name": "client"+ },+ {+ "name": "expiresAt"+ }+ ],+ [+ {+ "name": "user"+ },+ {+ "name": "accessToken"+ }+ ]+ ]+ }+]diff --git a/application/Espo/Resources/layouts/OAuthRefreshToken/filters.json b/application/Espo/Resources/layouts/OAuthRefreshToken/filters.jsonnew file mode 100644index 0000000000..ff44ea408f--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthRefreshToken/filters.json@@ -0,0 +1,8 @@+[+ "status",+ "client",+ "user",+ "accessToken",+ "createdAt",+ "expiresAt"+]diff --git a/application/Espo/Resources/layouts/OAuthRefreshToken/list.json b/application/Espo/Resources/layouts/OAuthRefreshToken/list.jsonnew file mode 100644index 0000000000..54b460c04e--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthRefreshToken/list.json@@ -0,0 +1,26 @@+[+ {+ "name": "id",+ "link": true+ },+ {+ "name": "client",+ "width": 17+ },+ {+ "name": "status",+ "width": 13+ },+ {+ "name": "user",+ "width": 17+ },+ {+ "name": "createdAt",+ "width": 14+ },+ {+ "name": "expiresAt",+ "width": 14+ }+]diff --git a/application/Espo/Resources/layouts/OAuthRefreshToken/listSmall.json b/application/Espo/Resources/layouts/OAuthRefreshToken/listSmall.jsonnew file mode 100644index 0000000000..4e3c9acf28--- /dev/null+++ b/application/Espo/Resources/layouts/OAuthRefreshToken/listSmall.json@@ -0,0 +1,18 @@+[+ {+ "name": "id",+ "link": true+ },+ {+ "name": "client",+ "width": 25+ },+ {+ "name": "status",+ "width": 20+ },+ {+ "name": "user",+ "width": 20+ }+]diff --git a/application/Espo/Resources/metadata/app/acl.json b/application/Espo/Resources/metadata/app/acl.jsonindex 3c89dcf96e..08d0b14158 100644--- a/application/Espo/Resources/metadata/app/acl.json+++ b/application/Espo/Resources/metadata/app/acl.json@@ -1,6 +1,7 @@{"mandatory": {"scopeLevel": {+ "Admin": false,"Note": {"read": "own","edit": "own",@@ -134,6 +135,7 @@},"adminMandatory": {"scopeLevel": {+ "Admin": true,"User": {"create": "yes","read": "all",diff --git a/application/Espo/Resources/metadata/app/adminPanel.json b/application/Espo/Resources/metadata/app/adminPanel.jsonindex 5aa367b39a..6af13e268d 100644--- a/application/Espo/Resources/metadata/app/adminPanel.json+++ b/application/Espo/Resources/metadata/app/adminPanel.json@@ -310,6 +310,12 @@"label": "Authentication Providers","iconClass": "fas fa-sign-in-alt","description": "authenticationProviders"+ },+ {+ "url": "#Admin/oAuthClients",+ "labelTranslation": "Global.scopeNamesPlural.OAuthClient",+ "iconClass": "fas fa-user-lock",+ "description": "oAuthClients"}],"order": 24diff --git a/application/Espo/Resources/metadata/app/cleanup.json b/application/Espo/Resources/metadata/app/cleanup.jsonindex 99ae71a734..ea717d1e82 100644--- a/application/Espo/Resources/metadata/app/cleanup.json+++ b/application/Espo/Resources/metadata/app/cleanup.json@@ -30,5 +30,8 @@},"appLog": {"className": "Espo\\Classes\\Cleanup\\AppLog"+ },+ "oAuthServer":{+ "className": "Espo\\Tools\\OAuthServer\\Cleanup\\GeneralCleanup"}}diff --git a/application/Espo/Resources/metadata/app/clientRoutes.json b/application/Espo/Resources/metadata/app/clientRoutes.jsonindex 90a8fbbce1..93d66c81f1 100644--- a/application/Espo/Resources/metadata/app/clientRoutes.json+++ b/application/Espo/Resources/metadata/app/clientRoutes.json@@ -18,5 +18,11 @@"action": "page"},"order": 1+ },+ "User/:id/connectedApps": {+ "params": {+ "controller": "User",+ "action": "listConnectedApps"+ }}}diff --git a/application/Espo/Resources/metadata/app/entryPoints.json b/application/Espo/Resources/metadata/app/entryPoints.jsonindex 323ba47d87..d88128bcec 100644--- a/application/Espo/Resources/metadata/app/entryPoints.json+++ b/application/Espo/Resources/metadata/app/entryPoints.json@@ -4,5 +4,26 @@},"oauthCallback": {"className": "Espo\\EntryPoints\\OauthCallback"+ },+ "oAuthAuthorize": {+ "className": "Espo\\Tools\\OAuthServer\\EntryPoints\\Authorize",+ "noAuth": true,+ "notExposed": true+ },+ "oAuthAuthorizeComplete": {+ "className": "Espo\\Tools\\OAuthServer\\EntryPoints\\AuthorizeComplete",+ "allowedMethods": ["post"]+ },+ "oAuthToken": {+ "className": "Espo\\Tools\\OAuthServer\\EntryPoints\\Token",+ "noAuth": true,+ "notExposed": true,+ "allowedMethods": ["post"]+ },+ "oAuthTokenRevoke": {+ "className": "Espo\\Tools\\OAuthServer\\EntryPoints\\TokenRevoke",+ "noAuth": true,+ "notExposed": true,+ "allowedMethods": ["post"]}}diff --git a/application/Espo/Resources/metadata/app/scheduledJobs.json b/application/Espo/Resources/metadata/app/scheduledJobs.jsonindex d0f9da2fec..f1fc9a5aa3 100644--- a/application/Espo/Resources/metadata/app/scheduledJobs.json+++ b/application/Espo/Resources/metadata/app/scheduledJobs.json@@ -47,6 +47,12 @@"scheduling": "2 0 * * *","isSystem": true},+ "OAuthServerControl": {+ "name": "OAuth Server Control",+ "jobClassName": "Espo\\Tools\\OAuthServer\\Jobs\\OAuthServerControl",+ "scheduling": "3 0 * * *",+ "isSystem": true+ },"Cleanup": {"jobClassName": "Espo\\Classes\\Jobs\\Cleanup","scheduling": "1 1 * * 0",diff --git a/application/Espo/Resources/metadata/authenticationMethods/OAuth.json b/application/Espo/Resources/metadata/authenticationMethods/OAuth.jsonnew file mode 100644index 0000000000..64abfad60d--- /dev/null+++ b/application/Espo/Resources/metadata/authenticationMethods/OAuth.json@@ -0,0 +1,6 @@+{+ "api": true,+ "credentialsHeader": "Authorization",+ "credentialsHeaderScheme": "Bearer",+ "implementationClassName": "Espo\\Tools\\OAuthServer\\Login\\OAuthLogin"+}diff --git a/application/Espo/Resources/metadata/clientDefs/OAuthAccessToken.json b/application/Espo/Resources/metadata/clientDefs/OAuthAccessToken.jsonnew file mode 100644index 0000000000..48f4705cc1--- /dev/null+++ b/application/Espo/Resources/metadata/clientDefs/OAuthAccessToken.json@@ -0,0 +1,43 @@+{+ "controller": "controllers/record",+ "textFilterDisabled": true,+ "createDisabled": true,+ "editDisabled": true,+ "massUpdateDisabled": true,+ "rowActionDefs": {+ "revoke": {+ "labelTranslation": "OAuthClient.strings.revoke",+ "handler": "handlers/o-auth-access-token/revoke-row-action",+ "acl": "edit"+ }+ },+ "rowActionList": [+ "revoke"+ ],+ "massActionDefs": {+ "revoke": {+ "acl": "edit",+ "handler": "handlers/o-auth-access-token/revoke-mass-action",+ "actionFunction": "process",+ "groupIndex": 9+ }+ },+ "massActionList": [+ "revoke"+ ],+ "checkAllResultMassActionList": [+ "revoke"+ ],+ "menu": {+ "list": {+ "dropdown": [+ {+ "name": "oAuthClients",+ "labelTranslation": "Global.scopeNamesPlural.OAuthClient",+ "aclScope": "OAuthClient",+ "link": "#Admin/oAuthClients"+ }+ ]+ }+ }+}diff --git a/application/Espo/Resources/metadata/clientDefs/OAuthAuthorizationCode.json b/application/Espo/Resources/metadata/clientDefs/OAuthAuthorizationCode.jsonnew file mode 100644index 0000000000..48f4705cc1--- /dev/null+++ b/application/Espo/Resources/metadata/clientDefs/OAuthAuthorizationCode.json@@ -0,0 +1,43 @@+{+ "controller": "controllers/record",+ "textFilterDisabled": true,+ "createDisabled": true,+ "editDisabled": true,+ "massUpdateDisabled": true,+ "rowActionDefs": {+ "revoke": {+ "labelTranslation": "OAuthClient.strings.revoke",+ "handler": "handlers/o-auth-access-token/revoke-row-action",+ "acl": "edit"+ }+ },+ "rowActionList": [+ "revoke"+ ],+ "massActionDefs": {+ "revoke": {+ "acl": "edit",+ "handler": "handlers/o-auth-access-token/revoke-mass-action",+ "actionFunction": "process",+ "groupIndex": 9+ }+ },+ "massActionList": [+ "revoke"+ ],+ "checkAllResultMassActionList": [+ "revoke"+ ],+ "menu": {+ "list": {+ "dropdown": [+ {+ "name": "oAuthClients",+ "labelTranslation": "Global.scopeNamesPlural.OAuthClient",+ "aclScope": "OAuthClient",+ "link": "#Admin/oAuthClients"+ }+ ]+ }+ }+}diff --git a/application/Espo/Resources/metadata/clientDefs/OAuthClient.json b/application/Espo/Resources/metadata/clientDefs/OAuthClient.jsonnew file mode 100644index 0000000000..cb35bbc2d5--- /dev/null+++ b/application/Espo/Resources/metadata/clientDefs/OAuthClient.json@@ -0,0 +1,38 @@+{+ "controller": "controllers/record",+ "relationshipPanels": {+ "secrets": {+ "filterList": [+ "all",+ "active"+ ],+ "layout": "listForApp",+ "orderBy": "createdAt",+ "orderDirection": "desc"+ }+ },+ "menu": {+ "list": {+ "dropdown": [+ {+ "name": "authorizationCodes",+ "labelTranslation": "OAuthClient.strings.authorizationCodes",+ "aclScope": "OAuthAuthorizationCode",+ "link": "#OAuthAuthorizationCode"+ },+ {+ "name": "accessToken",+ "labelTranslation": "OAuthClient.strings.accessTokens",+ "aclScope": "OAuthAccessToken",+ "link": "#OAuthAccessToken"+ },+ {+ "name": "refreshTokens",+ "labelTranslation": "OAuthClient.strings.refreshTokens",+ "aclScope": "OAuthRefreshToken",+ "link": "#OAuthRefreshToken"+ }+ ]+ }+ }+}diff --git a/application/Espo/Resources/metadata/clientDefs/OAuthClientSecret.json b/application/Espo/Resources/metadata/clientDefs/OAuthClientSecret.jsonnew file mode 100644index 0000000000..940f4290d8--- /dev/null+++ b/application/Espo/Resources/metadata/clientDefs/OAuthClientSecret.json@@ -0,0 +1,18 @@+{+ "controller": "controllers/record",+ "model": "models/o-auth-client-secret",+ "collection": "collections/o-auth-client-secret",+ "textFilterDisabled": true,+ "menu": {+ "list": {+ "dropdown": [+ {+ "name": "oAuthClients",+ "labelTranslation": "Global.scopeNamesPlural.OAuthClient",+ "aclScope": "OAuthClient",+ "link": "#Admin/oAuthClients"+ }+ ]+ }+ }+}diff --git a/application/Espo/Resources/metadata/clientDefs/OAuthRefreshToken.json b/application/Espo/Resources/metadata/clientDefs/OAuthRefreshToken.jsonnew file mode 100644index 0000000000..48f4705cc1--- /dev/null+++ b/application/Espo/Resources/metadata/clientDefs/OAuthRefreshToken.json@@ -0,0 +1,43 @@+{+ "controller": "controllers/record",+ "textFilterDisabled": true,+ "createDisabled": true,+ "editDisabled": true,+ "massUpdateDisabled": true,+ "rowActionDefs": {+ "revoke": {+ "labelTranslation": "OAuthClient.strings.revoke",+ "handler": "handlers/o-auth-access-token/revoke-row-action",+ "acl": "edit"+ }+ },+ "rowActionList": [+ "revoke"+ ],+ "massActionDefs": {+ "revoke": {+ "acl": "edit",+ "handler": "handlers/o-auth-access-token/revoke-mass-action",+ "actionFunction": "process",+ "groupIndex": 9+ }+ },+ "massActionList": [+ "revoke"+ ],+ "checkAllResultMassActionList": [+ "revoke"+ ],+ "menu": {+ "list": {+ "dropdown": [+ {+ "name": "oAuthClients",+ "labelTranslation": "Global.scopeNamesPlural.OAuthClient",+ "aclScope": "OAuthClient",+ "link": "#Admin/oAuthClients"+ }+ ]+ }+ }+}diff --git a/application/Espo/Resources/metadata/entityAcl/OAuthAccessToken.json b/application/Espo/Resources/metadata/entityAcl/OAuthAccessToken.jsonnew file mode 100644index 0000000000..256b084498--- /dev/null+++ b/application/Espo/Resources/metadata/entityAcl/OAuthAccessToken.json@@ -0,0 +1,11 @@+{+ "fields": {+ "identifier": {+ "forbidden": true+ },+ "hash": {+ "forbidden": true+ }+ },+ "systemWriteForbidden": true+}diff --git a/application/Espo/Resources/metadata/entityAcl/OAuthAuthorizationCode.json b/application/Espo/Resources/metadata/entityAcl/OAuthAuthorizationCode.jsonnew file mode 100644index 0000000000..256b084498--- /dev/null+++ b/application/Espo/Resources/metadata/entityAcl/OAuthAuthorizationCode.json@@ -0,0 +1,11 @@+{+ "fields": {+ "identifier": {+ "forbidden": true+ },+ "hash": {+ "forbidden": true+ }+ },+ "systemWriteForbidden": true+}diff --git a/application/Espo/Resources/metadata/entityAcl/OAuthClientSecret.json b/application/Espo/Resources/metadata/entityAcl/OAuthClientSecret.jsonnew file mode 100644index 0000000000..821529e229--- /dev/null+++ b/application/Espo/Resources/metadata/entityAcl/OAuthClientSecret.json@@ -0,0 +1,8 @@+{+ "fields": {+ "hash": {+ "forbidden": true+ }+ },+ "systemWriteForbidden": true+}diff --git a/application/Espo/Resources/metadata/entityAcl/OAuthRefreshToken.json b/application/Espo/Resources/metadata/entityAcl/OAuthRefreshToken.jsonnew file mode 100644index 0000000000..256b084498--- /dev/null+++ b/application/Espo/Resources/metadata/entityAcl/OAuthRefreshToken.json@@ -0,0 +1,11 @@+{+ "fields": {+ "identifier": {+ "forbidden": true+ },+ "hash": {+ "forbidden": true+ }+ },+ "systemWriteForbidden": true+}diff --git a/application/Espo/Resources/metadata/entityDefs/OAuthAccessToken.json b/application/Espo/Resources/metadata/entityDefs/OAuthAccessToken.jsonnew file mode 100644index 0000000000..00df8ac3c8--- /dev/null+++ b/application/Espo/Resources/metadata/entityDefs/OAuthAccessToken.json@@ -0,0 +1,93 @@+{+ "fields": {+ "identifier": {+ "type": "password",+ "notStorable": true,+ "maxLength": 80,+ "readOnly": true,+ "required": true,+ "utility": true+ },+ "hash": {+ "type": "password",+ "maxLength": 64,+ "readOnly": true+ },+ "status": {+ "type": "enum",+ "options": [+ "Active",+ "Revoked",+ "Expired"+ ],+ "default": "Active",+ "maxLength": 7,+ "readOnly": true,+ "style": {+ "Revoked": "info",+ "Expired": "info"+ }+ },+ "expiresAt": {+ "type": "datetime",+ "readOnly": true,+ "required": true+ },+ "scopes": {+ "type": "array",+ "readOnly": true,+ "displayAsList": true,+ "storeArrayValues": false+ },+ "user": {+ "type": "link",+ "readOnly": true+ },+ "client": {+ "type": "link",+ "readOnly": true+ },+ "createdAt": {+ "type": "datetime",+ "readOnly": true+ },+ "modifiedAt": {+ "type": "datetime",+ "readOnly": true+ }+ },+ "links": {+ "user": {+ "type": "belongsTo",+ "entity": "User"+ },+ "client": {+ "type": "belongsTo",+ "entity": "OAuthClient"+ }+ },+ "collection": {+ "orderBy": "createdAt",+ "order": "desc",+ "textFilterFields": []+ },+ "indexes": {+ "hash": {+ "columns": [+ "hash"+ ]+ },+ "createdAt": {+ "columns": [+ "createdAt"+ ]+ },+ "expiresAtStatus": {+ "columns": [+ "expiresAt",+ "status"+ ]+ }+ },+ "entityClassName": "Espo\\Tools\\OAuthServer\\Entities\\AccessToken"+}diff --git a/application/Espo/Resources/metadata/entityDefs/OAuthAuthorizationCode.json b/application/Espo/Resources/metadata/entityDefs/OAuthAuthorizationCode.jsonnew file mode 100644index 0000000000..416bb862aa--- /dev/null+++ b/application/Espo/Resources/metadata/entityDefs/OAuthAuthorizationCode.json@@ -0,0 +1,92 @@+{+ "fields": {+ "hash": {+ "type": "password",+ "maxLength": 64,+ "readOnly": true+ },+ "status": {+ "type": "enum",+ "options": [+ "Active",+ "Revoked",+ "Expired"+ ],+ "default": "Active",+ "maxLength": 7,+ "readOnly": true,+ "style": {+ "Revoked": "info",+ "Expired": "info"+ }+ },+ "redirectUri": {+ "type": "varchar",+ "dbType": "text",+ "maxLength": 1500,+ "readOnly": true,+ "required": true+ },+ "expiresAt": {+ "type": "datetime",+ "readOnly": true,+ "required": true+ },+ "scopes": {+ "type": "multiEnum",+ "readOnly": true,+ "displayAsList": true,+ "storeArrayValues": false+ },+ "user": {+ "type": "link",+ "readOnly": true+ },+ "client": {+ "type": "link",+ "readOnly": true+ },+ "createdAt": {+ "type": "datetime",+ "readOnly": true+ },+ "modifiedAt": {+ "type": "datetime",+ "readOnly": true+ }+ },+ "links": {+ "user": {+ "type": "belongsTo",+ "entity": "User"+ },+ "client": {+ "type": "belongsTo",+ "entity": "OAuthClient"+ }+ },+ "collection": {+ "orderBy": "createdAt",+ "order": "desc",+ "textFilterFields": []+ },+ "indexes": {+ "hash": {+ "columns": [+ "hash"+ ]+ },+ "createdAt": {+ "columns": [+ "createdAt"+ ]+ },+ "expiresAtStatus": {+ "columns": [+ "expiresAt",+ "status"+ ]+ }+ },+ "entityClassName": "Espo\\Tools\\OAuthServer\\Entities\\AuthorizationCode"+}diff --git a/application/Espo/Resources/metadata/entityDefs/OAuthClient.json b/application/Espo/Resources/metadata/entityDefs/OAuthClient.jsonnew file mode 100644index 0000000000..718a0d5272--- /dev/null+++ b/application/Espo/Resources/metadata/entityDefs/OAuthClient.json@@ -0,0 +1,113 @@+{+ "fields": {+ "name": {+ "type": "varchar",+ "maxLength": 100,+ "required": true,+ "index": true,+ "audited": true+ },+ "status": {+ "type": "enum",+ "options": [+ "Active",+ "Inactive"+ ],+ "default": "Active",+ "maxLength": 8,+ "style": {+ "Inactive": "info"+ },+ "duplicateIgnore": true+ },+ "clientType": {+ "type": "enum",+ "options": [+ "Confidential",+ "Public"+ ],+ "default": "Confidential",+ "maxLength": 12,+ "readOnlyAfterCreate": true,+ "audited": true+ },+ "identifier": {+ "type": "varchar",+ "readOnly": true,+ "maxLength": 36,+ "audited": true,+ "copyToClipboard": true,+ "duplicateIgnore": true+ },+ "redirectUris": {+ "type": "urlMultiple",+ "protocolRequired": true,+ "audited": true,+ "maxItemLength": 1500,+ "storeArrayValues": false+ },+ "scopes": {+ "type": "array",+ "audited": true,+ "displayAsList": true,+ "required": true,+ "validatorClassNameList": [+ "Espo\\Classes\\FieldValidators\\OAuthClient\\Scopes\\Valid"+ ],+ "view": "views/o-auth-client/fields/scopes",+ "tooltip": true+ },+ "description": {+ "type": "text"+ },+ "createdAt": {+ "type": "datetime",+ "readOnly": true+ },+ "modifiedAt": {+ "type": "datetime",+ "readOnly": true+ },+ "createdBy": {+ "type": "link",+ "readOnly": true+ },+ "modifiedBy": {+ "type": "link",+ "readOnly": true+ }+ },+ "links": {+ "secrets": {+ "type": "hasMany",+ "entity": "OAuthClientSecret",+ "foreign": "client",+ "orderBy": "createdAt",+ "order": "desc",+ "readOnly": true+ },+ "createdBy": {+ "type": "belongsTo",+ "entity": "User"+ },+ "modifiedBy": {+ "type": "belongsTo",+ "entity": "User"+ }+ },+ "collection": {+ "orderBy": "name",+ "order": "asc",+ "textFilterFields": [+ "name"+ ]+ },+ "indexes": {+ "identifier": {+ "columns": [+ "identifier"+ ]+ }+ },+ "entityClassName": "Espo\\Tools\\OAuthServer\\Entities\\Client"+}diff --git a/application/Espo/Resources/metadata/entityDefs/OAuthClientSecret.json b/application/Espo/Resources/metadata/entityDefs/OAuthClientSecret.jsonnew file mode 100644index 0000000000..6dba25784f--- /dev/null+++ b/application/Espo/Resources/metadata/entityDefs/OAuthClientSecret.json@@ -0,0 +1,108 @@+{+ "fields": {+ "name": {+ "type": "varchar",+ "readOnly": true,+ "orderDisabled": true,+ "duplicateIgnore": true+ },+ "value": {+ "type": "varchar",+ "readOnly": true,+ "notStorable": true,+ "orderDisabled": true,+ "directAccessDisabled": true,+ "duplicateIgnore": true,+ "view": "views/o-auth-client-secret/fields/value"+ },+ "hash": {+ "type": "password",+ "dbType": "text",+ "maxLength": 255,+ "readOnly": true,+ "orderDisabled": true,+ "duplicateIgnore": true+ },+ "client": {+ "type": "link",+ "required": true,+ "readOnlyAfterCreate": true+ },+ "status": {+ "type": "enum",+ "options": [+ "Active",+ "Revoked",+ "Expired"+ ],+ "default": "Active",+ "maxLength": 7,+ "readOnly": true,+ "style": {+ "Revoked": "info",+ "Expired": "info"+ },+ "audited": true,+ "duplicateIgnore": true+ },+ "expirationDate": {+ "type": "date",+ "readOnlyAfterCreate": true+ },+ "description": {+ "type": "text"+ },+ "createdAt": {+ "type": "datetime",+ "readOnly": true+ },+ "modifiedAt": {+ "type": "datetime",+ "readOnly": true+ },+ "createdBy": {+ "type": "link",+ "readOnly": true+ },+ "modifiedBy": {+ "type": "link",+ "readOnly": true+ }+ },+ "links": {+ "client": {+ "type": "belongsTo",+ "entity": "OAuthClient",+ "foreign": "secrets"+ },+ "createdBy": {+ "type": "belongsTo",+ "entity": "User"+ },+ "modifiedBy": {+ "type": "belongsTo",+ "entity": "User"+ }+ },+ "indexes": {+ "statusExpirationDate": {+ "columns": [+ "status",+ "expirationDate"+ ]+ },+ "clientIdStatusCreatedAt": {+ "columns": [+ "clientId",+ "status",+ "createdAt"+ ]+ }+ },+ "collection": {+ "orderBy": "createdAt",+ "order": "desc",+ "textFilterFields": []+ },+ "entityClassName": "Espo\\Tools\\OAuthServer\\Entities\\ClientSecret"+}diff --git a/application/Espo/Resources/metadata/entityDefs/OAuthRefreshToken.json b/application/Espo/Resources/metadata/entityDefs/OAuthRefreshToken.jsonnew file mode 100644index 0000000000..6212f36e6f--- /dev/null+++ b/application/Espo/Resources/metadata/entityDefs/OAuthRefreshToken.json@@ -0,0 +1,88 @@+{+ "fields": {+ "hash": {+ "type": "password",+ "maxLength": 64,+ "readOnly": true+ },+ "status": {+ "type": "enum",+ "options": [+ "Active",+ "Revoked",+ "Expired"+ ],+ "default": "Active",+ "maxLength": 7,+ "readOnly": true,+ "style": {+ "Revoked": "info",+ "Expired": "info"+ }+ },+ "expiresAt": {+ "type": "datetime",+ "readOnly": true,+ "required": true+ },+ "user": {+ "type": "link",+ "readOnly": true+ },+ "client": {+ "type": "link",+ "readOnly": true+ },+ "accessToken": {+ "type": "link",+ "readOnly": true+ },+ "createdAt": {+ "type": "datetime",+ "readOnly": true+ },+ "modifiedAt": {+ "type": "datetime",+ "readOnly": true+ }+ },+ "links": {+ "user": {+ "type": "belongsTo",+ "entity": "User"+ },+ "client": {+ "type": "belongsTo",+ "entity": "OAuthClient"+ },+ "accessToken": {+ "type": "belongsTo",+ "entity": "OAuthAccessToken",+ "foreignName": "id"+ }+ },+ "collection": {+ "orderBy": "createdAt",+ "order": "desc",+ "textFilterFields": []+ },+ "indexes": {+ "hash": {+ "columns": [+ "hash"+ ]+ },+ "createdAt": {+ "columns": [+ "createdAt"+ ]+ },+ "expiresAtStatus": {+ "columns": [+ "expiresAt",+ "status"+ ]+ }+ },+ "entityClassName": "Espo\\Tools\\OAuthServer\\Entities\\RefreshToken"+}diff --git a/application/Espo/Resources/metadata/entityDefs/User.json b/application/Espo/Resources/metadata/entityDefs/User.jsonindex 39988f5aea..f6f14c5527 100644--- a/application/Espo/Resources/metadata/entityDefs/User.json+++ b/application/Espo/Resources/metadata/entityDefs/User.json@@ -462,6 +462,14 @@"customizationDisabled": true,"utility": true},+ "scopes": {+ "type": "array",+ "notStorable": true,+ "readOnly": true,+ "orderDisabled": true,+ "customizationDisabled": true,+ "utility": true+ },"avatar": {"type": "image","view": "views/user/fields/avatar",diff --git a/application/Espo/Resources/metadata/logicDefs/OAuthClient.json b/application/Espo/Resources/metadata/logicDefs/OAuthClient.jsonnew file mode 100644index 0000000000..8053650c50--- /dev/null+++ b/application/Espo/Resources/metadata/logicDefs/OAuthClient.json@@ -0,0 +1,29 @@+{+ "fields": {+ "identifier": {+ "visible": {+ "conditionGroup": [+ {+ "type": "isNotEmpty",+ "attribute": "id"+ }+ ]+ }+ }+ },+ "panels": {+ "secrets": {+ "visible": {+ "conditionGroup": [+ {+ "type": "in",+ "attribute": "clientType",+ "value": [+ "Confidential"+ ]+ }+ ]+ }+ }+ }+}diff --git a/application/Espo/Resources/metadata/logicDefs/OAuthClientSecret.json b/application/Espo/Resources/metadata/logicDefs/OAuthClientSecret.jsonnew file mode 100644index 0000000000..6f4b62df27--- /dev/null+++ b/application/Espo/Resources/metadata/logicDefs/OAuthClientSecret.json@@ -0,0 +1,34 @@+{+ "fields": {+ "name": {+ "visible": {+ "conditionGroup": [+ {+ "type": "isNotEmpty",+ "attribute": "id"+ }+ ]+ }+ },+ "value": {+ "visible": {+ "conditionGroup": [+ {+ "type": "isNotEmpty",+ "attribute": "id"+ }+ ]+ }+ },+ "status": {+ "visible": {+ "conditionGroup": [+ {+ "type": "isNotEmpty",+ "attribute": "id"+ }+ ]+ }+ }+ }+}diff --git a/application/Espo/Resources/metadata/recordDefs/OAuthAccessToken.json b/application/Espo/Resources/metadata/recordDefs/OAuthAccessToken.jsonnew file mode 100644index 0000000000..06c1641d5a--- /dev/null+++ b/application/Espo/Resources/metadata/recordDefs/OAuthAccessToken.json@@ -0,0 +1,11 @@+{+ "massActions": {+ "delete": {+ "allowed": true+ },+ "revoke": {+ "allowed": true,+ "implementationClassName": "Espo\\Tools\\OAuthServer\\Record\\MassActions\\RevokeMassAction"+ }+ }+}diff --git a/application/Espo/Resources/metadata/recordDefs/OAuthAuthorizationCode.json b/application/Espo/Resources/metadata/recordDefs/OAuthAuthorizationCode.jsonnew file mode 100644index 0000000000..06c1641d5a--- /dev/null+++ b/application/Espo/Resources/metadata/recordDefs/OAuthAuthorizationCode.json@@ -0,0 +1,11 @@+{+ "massActions": {+ "delete": {+ "allowed": true+ },+ "revoke": {+ "allowed": true,+ "implementationClassName": "Espo\\Tools\\OAuthServer\\Record\\MassActions\\RevokeMassAction"+ }+ }+}diff --git a/application/Espo/Resources/metadata/recordDefs/OAuthClient.json b/application/Espo/Resources/metadata/recordDefs/OAuthClient.jsonnew file mode 100644index 0000000000..9e77ee7f65--- /dev/null+++ b/application/Espo/Resources/metadata/recordDefs/OAuthClient.json@@ -0,0 +1,10 @@+{+ "massActions": {+ "update": {+ "allowed": true+ },+ "delete": {+ "allowed": true+ }+ }+}diff --git a/application/Espo/Resources/metadata/recordDefs/OAuthClientSecret.json b/application/Espo/Resources/metadata/recordDefs/OAuthClientSecret.jsonnew file mode 100644index 0000000000..c2d3f8a70f--- /dev/null+++ b/application/Espo/Resources/metadata/recordDefs/OAuthClientSecret.json@@ -0,0 +1,10 @@+{+ "massActions": {+ "update": {+ "allowed": false+ },+ "delete": {+ "allowed": true+ }+ }+}diff --git a/application/Espo/Resources/metadata/recordDefs/OAuthRefreshToken.json b/application/Espo/Resources/metadata/recordDefs/OAuthRefreshToken.jsonnew file mode 100644index 0000000000..06c1641d5a--- /dev/null+++ b/application/Espo/Resources/metadata/recordDefs/OAuthRefreshToken.json@@ -0,0 +1,11 @@+{+ "massActions": {+ "delete": {+ "allowed": true+ },+ "revoke": {+ "allowed": true,+ "implementationClassName": "Espo\\Tools\\OAuthServer\\Record\\MassActions\\RevokeMassAction"+ }+ }+}diff --git a/application/Espo/Resources/metadata/scopes/Admin.json b/application/Espo/Resources/metadata/scopes/Admin.jsonnew file mode 100644index 0000000000..7cd2ffe184--- /dev/null+++ b/application/Espo/Resources/metadata/scopes/Admin.json@@ -0,0 +1,3 @@+{+ "acl": false+}diff --git a/application/Espo/Resources/metadata/scopes/OAuthAccessToken.json b/application/Espo/Resources/metadata/scopes/OAuthAccessToken.jsonnew file mode 100644index 0000000000..39c96e7ac2--- /dev/null+++ b/application/Espo/Resources/metadata/scopes/OAuthAccessToken.json@@ -0,0 +1,3 @@+{+ "entity": true+}diff --git a/application/Espo/Resources/metadata/scopes/OAuthAuthorizationCode.json b/application/Espo/Resources/metadata/scopes/OAuthAuthorizationCode.jsonnew file mode 100644index 0000000000..39c96e7ac2--- /dev/null+++ b/application/Espo/Resources/metadata/scopes/OAuthAuthorizationCode.json@@ -0,0 +1,3 @@+{+ "entity": true+}diff --git a/application/Espo/Resources/metadata/scopes/OAuthClient.json b/application/Espo/Resources/metadata/scopes/OAuthClient.jsonnew file mode 100644index 0000000000..39c96e7ac2--- /dev/null+++ b/application/Espo/Resources/metadata/scopes/OAuthClient.json@@ -0,0 +1,3 @@+{+ "entity": true+}diff --git a/application/Espo/Resources/metadata/scopes/OAuthClientSecret.json b/application/Espo/Resources/metadata/scopes/OAuthClientSecret.jsonnew file mode 100644index 0000000000..39c96e7ac2--- /dev/null+++ b/application/Espo/Resources/metadata/scopes/OAuthClientSecret.json@@ -0,0 +1,3 @@+{+ "entity": true+}diff --git a/application/Espo/Resources/metadata/scopes/OAuthRefreshToken.json b/application/Espo/Resources/metadata/scopes/OAuthRefreshToken.jsonnew file mode 100644index 0000000000..39c96e7ac2--- /dev/null+++ b/application/Espo/Resources/metadata/scopes/OAuthRefreshToken.json@@ -0,0 +1,3 @@+{+ "entity": true+}diff --git a/application/Espo/Resources/metadata/selectDefs/OAuthClient.json b/application/Espo/Resources/metadata/selectDefs/OAuthClient.jsonnew file mode 100644index 0000000000..0743de78b4--- /dev/null+++ b/application/Espo/Resources/metadata/selectDefs/OAuthClient.json@@ -0,0 +1,5 @@+{+ "primaryFilterClassNameMap": {+ "active": "Espo\\Classes\\Select\\OAuth\\PrimaryFilters\\Active"+ }+}diff --git a/application/Espo/Resources/metadata/selectDefs/OAuthClientSecret.json b/application/Espo/Resources/metadata/selectDefs/OAuthClientSecret.jsonnew file mode 100644index 0000000000..98fb6d4640--- /dev/null+++ b/application/Espo/Resources/metadata/selectDefs/OAuthClientSecret.json@@ -0,0 +1,10 @@+{+ "primaryFilterClassNameMap": {+ "active": "Espo\\Classes\\Select\\OAuthClientSecret\\PrimaryFilters\\Active"+ },+ "selectAttributesDependencyMap": {+ "value": [+ "name"+ ]+ }+}diff --git a/application/Espo/Resources/routes.json b/application/Espo/Resources/routes.jsonindex 04d2e02515..8df19ffde7 100644--- a/application/Espo/Resources/routes.json+++ b/application/Espo/Resources/routes.json@@ -83,6 +83,11 @@"method": "get","actionClassName": "Espo\\Tools\\GlobalSearch\\Api\\Get"},+ {+ "route": "OAuthServer/consentData",+ "method": "get",+ "actionClassName": "Espo\\Tools\\OAuthServer\\Api\\GetConsentData"+ },{"route": "/LeadCapture/form/:id","method": "post",@@ -455,6 +460,16 @@"method": "get","actionClassName": "Espo\\Tools\\UserSecurity\\Api\\GetUserAcl"},+ {+ "route": "/User/:id/connectedApps",+ "method": "get",+ "actionClassName": "Espo\\Tools\\UserSecurity\\Api\\GetConnectedApps"+ },+ {+ "route": "/User/:id/connectedApps/:appId",+ "method": "delete",+ "actionClassName": "Espo\\Tools\\UserSecurity\\Api\\DeleteConnectedApp"+ },{"route": "/UserSecurity/apiKey/generate","method": "post",@@ -541,6 +556,21 @@"route": "/OAuth/:id/authorizationData","actionClassName": "Espo\\Tools\\OAuth\\Api\\GetAuthorizationData"},+ {+ "method": "post",+ "route": "/OAuthAccessToken/:id/revoke",+ "actionClassName": "Espo\\Tools\\OAuthServer\\Api\\AccessToken\\PostRevoke"+ },+ {+ "method": "post",+ "route": "/OAuthRefreshToken/:id/revoke",+ "actionClassName": "Espo\\Tools\\OAuthServer\\Api\\RefreshToken\\PostRevoke"+ },+ {+ "method": "post",+ "route": "/OAuthAuthorizationCode/:id/revoke",+ "actionClassName": "Espo\\Tools\\OAuthServer\\Api\\AuthorizationCode\\PostRevoke"+ },{"method": "get","route": "/OpenApi",diff --git a/application/Espo/Services/ExternalAccount.php b/application/Espo/Services/ExternalAccount.phpindex 0ea57e98a2..5a708e36ba 100644--- a/application/Espo/Services/ExternalAccount.php+++ b/application/Espo/Services/ExternalAccount.php@@ -72,7 +72,7 @@ class ExternalAccount extends Record{[, $userId] = explode('__', $id);- if ($this->user->getId() !== $userId && !$this->user->isAdmin()) {+ if ($this->user->getId() !== $userId && !$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Services/Integration.php b/application/Espo/Services/Integration.phpindex 5389445319..e01eb71da0 100644--- a/application/Espo/Services/Integration.php+++ b/application/Espo/Services/Integration.php@@ -58,7 +58,7 @@ class Integration*/protected function processAccessCheck(){- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}}diff --git a/application/Espo/Tools/App/AppService.php b/application/Espo/Tools/App/AppService.phpindex f950819e84..b9137c1076 100644--- a/application/Espo/Tools/App/AppService.php+++ b/application/Espo/Tools/App/AppService.php@@ -248,7 +248,7 @@ class AppService{$data = $this->acl->getMapData();- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {$data = unserialize(serialize($data));/** @var string[] $scopeList */diff --git a/application/Espo/Tools/App/LanguageService.php b/application/Espo/Tools/App/LanguageService.phpindex 8df46cb533..8e10367917 100644--- a/application/Espo/Tools/App/LanguageService.php+++ b/application/Espo/Tools/App/LanguageService.php@@ -96,7 +96,7 @@ class LanguageServiceunset($data['Campaign']['options']);unset($data['Campaign']['tooltips']);unset($data['Campaign']['presetFilters']);- } else if (!$this->user->isAdmin()) {+ } else if (!$this->user->isEffectiveAdmin()) {/** @var string[] $scopeList */$scopeList = array_keys($this->metadata->get(['scopes'], []));@@ -136,7 +136,7 @@ class LanguageService}}- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {$this->prepareDataNonAdmin($data, $language);}}diff --git a/application/Espo/Tools/App/MetadataService.php b/application/Espo/Tools/App/MetadataService.phpindex 2643125c18..222d4ddb5a 100644--- a/application/Espo/Tools/App/MetadataService.php+++ b/application/Espo/Tools/App/MetadataService.php@@ -59,7 +59,7 @@ class MetadataService$this->removeDataByPath($row, $data);}- if ($this->user->isAdmin()) {+ if ($this->user->isEffectiveAdmin()) {return $data;}diff --git a/application/Espo/Tools/App/PreferencesService.php b/application/Espo/Tools/App/PreferencesService.phpindex 8fd3ec1d9e..044b92c489 100644--- a/application/Espo/Tools/App/PreferencesService.php+++ b/application/Espo/Tools/App/PreferencesService.php@@ -77,7 +77,7 @@ class PreferencesService*/protected function processAccessCheck(string $userId): void{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {if ($this->user->getId() !== $userId) {throw new Forbidden();}diff --git a/application/Espo/Tools/App/SettingsService.php b/application/Espo/Tools/App/SettingsService.phpindex c239a4c102..1f3849131a 100644--- a/application/Espo/Tools/App/SettingsService.php+++ b/application/Espo/Tools/App/SettingsService.php@@ -220,7 +220,7 @@ class SettingsService{$user = $this->applicationState->getUser();- if (!$user->isAdmin()) {+ if (!$user->isEffectiveAdmin()) {throw new Forbidden();}@@ -309,7 +309,7 @@ class SettingsService$ignoreItemList[] = $item;}- if (!$user->isAdmin() || $user->isSystem()) {+ if (!$user->isEffectiveAdmin() || $user->isSystem()) {foreach ($this->access->getAdminParamList() as $item) {$ignoreItemList[] = $item;}@@ -368,7 +368,7 @@ class SettingsService{$user = $this->applicationState->getUser();- if (!$user->isAdmin() && !$user->isSystem()) {+ if (!$user->isEffectiveAdmin() && !$user->isSystem()) {$this->filterEntityTypeParams($data);}@@ -388,7 +388,7 @@ class SettingsServicereturn;}- if ($user->isAdmin()) {+ if ($user->isEffectiveAdmin()) {return;}diff --git a/application/Espo/Tools/Attachment/AccessChecker.php b/application/Espo/Tools/Attachment/AccessChecker.phpindex 597b2069fe..8bdb85cbb7 100644--- a/application/Espo/Tools/Attachment/AccessChecker.php+++ b/application/Espo/Tools/Attachment/AccessChecker.php@@ -86,7 +86,7 @@ class AccessChecker}if (- $this->user->isAdmin() &&+ $this->user->isEffectiveAdmin() &&$role === Attachment::ROLE_INLINE_ATTACHMENT &&in_array($relatedEntityType, $this->adminOnlyHavingInlineAttachmentsEntityTypeList)) {@@ -107,7 +107,7 @@ class AccessCheckerthrow new Forbidden("Field type '$fieldType' is not allowed for $role.");}- if ($this->user->isAdmin() && $relatedEntityType === Settings::ENTITY_TYPE) {+ if ($this->user->isEffectiveAdmin() && $relatedEntityType === Settings::ENTITY_TYPE) {return;}diff --git a/application/Espo/Tools/Email/InboxService.php b/application/Espo/Tools/Email/InboxService.phpindex d3a77c3078..111ec8e094 100644--- a/application/Espo/Tools/Email/InboxService.php+++ b/application/Espo/Tools/Email/InboxService.php@@ -527,7 +527,7 @@ class InboxService->distinct()->leftJoin(Field::TEAMS)->where(- $this->user->isAdmin() ?+ $this->user->isEffectiveAdmin() ?['id!=' => null] :['teams.id' => $this->user->getTeamIdList()])diff --git a/application/Espo/Tools/Email/SendService.php b/application/Espo/Tools/Email/SendService.phpindex 36dfb40518..024e59e529 100644--- a/application/Espo/Tools/Email/SendService.php+++ b/application/Espo/Tools/Email/SendService.php@@ -410,7 +410,7 @@ class SendServiceif ($userId &&$userId !== $this->user->getId() &&- !$this->user->isAdmin()+ !$this->user->isEffectiveAdmin()) {throw new Forbidden();}@@ -558,7 +558,7 @@ class SendService$personalAccount = $this->personalAccountFactory->create($id);if (- !$this->user->isAdmin() &&+ !$this->user->isEffectiveAdmin() &&$personalAccount->getUser()->getId() !== $this->user->getId()) {throw new Forbidden();@@ -569,7 +569,7 @@ class SendServicereturn $smtpParams?->getPassword();}- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Tools/EmailFolder/Service.php b/application/Espo/Tools/EmailFolder/Service.phpindex 91d18b06b4..f86b9c0582 100644--- a/application/Espo/Tools/EmailFolder/Service.php+++ b/application/Espo/Tools/EmailFolder/Service.php@@ -80,7 +80,7 @@ class Serviceif ($userId &&$userId !== $this->user->getId() &&- !$this->user->isAdmin()+ !$this->user->isEffectiveAdmin()) {throw new ForbiddenSilent();}@@ -110,7 +110,7 @@ class Service->distinct()->leftJoin(Field::TEAMS)->where(- $user->isAdmin() ?+ $user->isEffectiveAdmin() ?['id!=' => null] :['teams.id' => $user->getTeamIdList()])diff --git a/application/Espo/Tools/Export/Jobs/Process.php b/application/Espo/Tools/Export/Jobs/Process.phpindex c2217b624a..38e0441657 100644--- a/application/Espo/Tools/Export/Jobs/Process.php+++ b/application/Espo/Tools/Export/Jobs/Process.php@@ -29,7 +29,6 @@namespace Espo\Tools\Export\Jobs;-use Espo\Core\Exceptions\Error;use Espo\Core\Job\Job;use Espo\Core\Job\Job\Data as JobData;use Espo\Tools\Export\Factory;@@ -40,40 +39,34 @@ use Espo\Entities\Export;use Espo\Entities\Notification;use Espo\Entities\User;+use RuntimeException;use Throwable;class Process implements Job{+ public const string PARAM_USER_SCOPES = 'userScopes';+public function __construct(private EntityManager $entityManager,private Factory $factory,private Language $language,) {}- /**- * @throws Error- */public function run(JobData $data): void{$id = $data->getTargetId();- if ($id === null) {- throw new Error("ID not passed to the mass action job.");+ if (!$id) {+ throw new RuntimeException("ID not passed to the export job.");}- /** @var Export|null $entity */- $entity = $this->entityManager->getEntityById(Export::ENTITY_TYPE, $id);+ $entity = $this->entityManager->getRDBRepositoryByClass(Export::class)->getById($id);- if ($entity === null) {- throw new Error("Export '$id' not found.");+ if (!$entity) {+ throw new RuntimeException("Export '$id' not found.");}- /** @var User|null $user */- $user = $this->entityManager->getEntityById(User::ENTITY_TYPE, $entity->getCreatedBy()->getId());-- if (!$user) {- throw new Error("Export entity '$id', user not found.");- }+ $user = $this->getUser($entity, $data);try {$export = $this->factory->createForUser($user);@@ -86,7 +79,7 @@ class Process implements Job} catch (Throwable $e) {$this->setFailed($entity);- throw new Error("Export job error: " . $e->getMessage());+ throw new RuntimeException("Export job error: " . $e->getMessage());}$this->setSuccess($entity, $result);@@ -140,4 +133,21 @@ class Process implements Job$this->entityManager->saveEntity($entity);}++ private function getUser(Export $entity, JobData $data): User+ {+ $user = $this->entityManager->getRDBRepositoryByClass(User::class)->getById($entity->getCreatedBy()->getId());++ if (!$user) {+ throw new RuntimeException("Export entity '{$entity->getId()}', user not found.");+ }++ $userScopes = $data->get(self::PARAM_USER_SCOPES);++ if (is_array($userScopes)) {+ $user->setScopes($userScopes);+ }++ return $user;+ }}diff --git a/application/Espo/Tools/Export/Service.php b/application/Espo/Tools/Export/Service.phpindex 36ea17bd1d..9c27719d0a 100644--- a/application/Espo/Tools/Export/Service.php+++ b/application/Espo/Tools/Export/Service.php@@ -63,7 +63,7 @@ class Service*/public function process(Params $params, ServiceParams $serviceParams): ServiceResult{- if ($this->config->get('exportDisabled') && !$this->user->isAdmin()) {+ if ($this->config->get('exportDisabled') && !$this->user->isEffectiveAdmin()) {throw new ForbiddenSilent("Export disabled for non-admin users.");}@@ -154,7 +154,7 @@ class Service->create()->setClassName(Process::class)->setData(- JobData::create()+ JobData::create([Process::PARAM_USER_SCOPES => $this->user->getScopes()])->withTargetId($entity->getId())->withTargetType($entity->getEntityType()))diff --git a/application/Espo/Tools/ExternalAccount/Service.php b/application/Espo/Tools/ExternalAccount/Service.phpindex a24cfb79a2..4ecb8aa60a 100644--- a/application/Espo/Tools/ExternalAccount/Service.php+++ b/application/Espo/Tools/ExternalAccount/Service.php@@ -100,7 +100,7 @@ class Service{[$integration, $userId] = explode('__', $id);- if ($this->user->getId() != $userId && !$this->user->isAdmin()) {+ if ($this->user->getId() != $userId && !$this->user->isEffectiveAdmin()) {throw new Forbidden();}@@ -125,7 +125,7 @@ class Service{[, $userId] = explode('__', $id);- if ($this->user->getId() !== $userId && !$this->user->isAdmin()) {+ if ($this->user->getId() !== $userId && !$this->user->isEffectiveAdmin()) {throw new Forbidden();}@@ -156,7 +156,7 @@ class Service{[$integration, $userId] = explode('__', $id);- if ($this->user->getId() !== $userId && !$this->user->isAdmin()) {+ if ($this->user->getId() !== $userId && !$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Tools/Import/Import.php b/application/Espo/Tools/Import/Import.phpindex 68e248e1b6..8280187cae 100644--- a/application/Espo/Tools/Import/Import.php+++ b/application/Espo/Tools/Import/Import.php@@ -271,6 +271,7 @@ class Import'importAttributeList' => $attributeList,'importId' => $import->getId(),'userId' => $this->user->getId(),+ RunIdle::PARAM_USER_SCOPES => $this->user->getScopes(),])->schedule();@@ -1602,7 +1603,7 @@ class Import}if (- !$this->user->isAdmin() &&+ !$this->user->isEffectiveAdmin() &&!$this->user->isSystem() &&$attachment->getCreatedBy()?->getId() !== $this->user->getId()) {diff --git a/application/Espo/Tools/Import/Jobs/RunIdle.php b/application/Espo/Tools/Import/Jobs/RunIdle.phpindex fb6b19541b..1f7b1543cb 100644--- a/application/Espo/Tools/Import/Jobs/RunIdle.php+++ b/application/Espo/Tools/Import/Jobs/RunIdle.php@@ -29,57 +29,73 @@namespace Espo\Tools\Import\Jobs;+use Espo\Core\Exceptions\Error;use Espo\Core\Exceptions\Forbidden;use Espo\Core\Job\Job;use Espo\Core\Job\Job\Data;-use Espo\Core\Exceptions\Error;use Espo\Tools\Import\ImportFactory;use Espo\Tools\Import\Params as ImportParams;use Espo\ORM\EntityManager;use Espo\Entities\User;+use RuntimeException;class RunIdle implements Job{+ public const string PARAM_USER_SCOPES = 'userScopes';+public function __construct(private ImportFactory $factory,- private EntityManager $entityManager+ private EntityManager $entityManager,) {}- /**- * @throws Forbidden- * @throws Error- */public function run(Data $data): void{$raw = $data->getRaw();- $entityType = $raw->entityType;- $attachmentId = $raw->attachmentId;- $importId = $raw->importId;- $importAttributeList = $raw->importAttributeList;- $userId = $raw->userId;+ $entityType = $raw->entityType ?? throw new RuntimeException();+ $attachmentId = $raw->attachmentId ?? throw new RuntimeException();+ $importId = $raw->importId ?? throw new RuntimeException();+ $importAttributeList = $raw->importAttributeList ?? throw new RuntimeException();+ $userId = $raw->userId ?? throw new RuntimeException();$params = ImportParams::fromRaw($raw->params);- /** @var ?User $user */- $user = $this->entityManager->getEntityById(User::ENTITY_TYPE, $userId);-- if (!$user) {- throw new Error("Import: User not found.");- }-- if (!$user->isActive()) {- throw new Error("Import: User is not active.");- }+ $user = $this->getUser($userId, $data);- $this->factory+ $import = $this->factory->create()->setEntityType($entityType)->setAttributeList($importAttributeList)->setAttachmentId($attachmentId)->setParams($params)->setId($importId)- ->setUser($user)- ->run();+ ->setUser($user);++ try {+ $import->run();+ } catch (Error|Forbidden $e) {+ throw new RuntimeException("Import error: " . $e->getMessage(), previous: $e);+ }+ }++ private function getUser(string $userId, Data $data): User+ {+ $user = $this->entityManager->getRDBRepositoryByClass(User::class)->getById($userId);++ if (!$user) {+ throw new RuntimeException("Import: User not found.");+ }++ if (!$user->isActive()) {+ throw new RuntimeException("Import: User is not active.");+ }++ $userScopes = $data->get(self::PARAM_USER_SCOPES);++ if (is_array($userScopes)) {+ $user->setScopes($userScopes);+ }++ return $user;}}diff --git a/application/Espo/Tools/Layout/Service.php b/application/Espo/Tools/Layout/Service.phpindex cb577e57e4..c376b6926f 100644--- a/application/Espo/Tools/Layout/Service.php+++ b/application/Espo/Tools/Layout/Service.php@@ -137,7 +137,7 @@ class Service}if (- !$this->user->isAdmin() &&+ !$this->user->isEffectiveAdmin() &&$name === 'relationships' &&is_array($data)) {diff --git a/application/Espo/Tools/LeadCapture/Service.php b/application/Espo/Tools/LeadCapture/Service.phpindex 9cb79dc89c..4f226716e9 100644--- a/application/Espo/Tools/LeadCapture/Service.php+++ b/application/Espo/Tools/LeadCapture/Service.php@@ -131,7 +131,7 @@ class Service*/public function getSmtpAccountDataList(): array{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Tools/OAuthServer/Api/AccessToken/PostRevoke.php b/application/Espo/Tools/OAuthServer/Api/AccessToken/PostRevoke.phpnew file mode 100644index 0000000000..4d57163a1e--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Api/AccessToken/PostRevoke.php@@ -0,0 +1,61 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Api\AccessToken;++use Espo\Core\Api\Action;+use Espo\Core\Api\Request;+use Espo\Core\Api\Response;+use Espo\Core\Api\ResponseComposer;+use Espo\Core\Exceptions\BadRequest;+use Espo\Core\Record\EntityProvider;+use Espo\Tools\OAuthServer\Entities\AccessToken;+use Espo\Tools\OAuthServer\Record\TokenService;++/**+ * @noinspection PhpUnused+ */+class PostRevoke implements Action+{+ public function __construct(+ private EntityProvider $entityProvider,+ private TokenService $service,+ ) {}++ public function process(Request $request): Response+ {+ $id = $request->getRouteParam('id') ?? throw new BadRequest();++ $entity = $this->entityProvider->getByClass(AccessToken::class, $id);++ $this->service->revoke($entity);++ return ResponseComposer::json(true);+ }+}diff --git a/application/Espo/Tools/OAuthServer/Api/AuthorizationCode/PostRevoke.php b/application/Espo/Tools/OAuthServer/Api/AuthorizationCode/PostRevoke.phpnew file mode 100644index 0000000000..5ffe104d5b--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Api/AuthorizationCode/PostRevoke.php@@ -0,0 +1,61 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Api\AuthorizationCode;++use Espo\Core\Api\Action;+use Espo\Core\Api\Request;+use Espo\Core\Api\Response;+use Espo\Core\Api\ResponseComposer;+use Espo\Core\Exceptions\BadRequest;+use Espo\Core\Record\EntityProvider;+use Espo\Tools\OAuthServer\Entities\AuthorizationCode;+use Espo\Tools\OAuthServer\Record\TokenService;++/**+ * @noinspection PhpUnused+ */+class PostRevoke implements Action+{+ public function __construct(+ private EntityProvider $entityProvider,+ private TokenService $service,+ ) {}++ public function process(Request $request): Response+ {+ $id = $request->getRouteParam('id') ?? throw new BadRequest();++ $entity = $this->entityProvider->getByClass(AuthorizationCode::class, $id);++ $this->service->revoke($entity);++ return ResponseComposer::json(true);+ }+}diff --git a/application/Espo/Tools/OAuthServer/Api/GetConsentData.php b/application/Espo/Tools/OAuthServer/Api/GetConsentData.phpnew file mode 100644index 0000000000..119638b371--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Api/GetConsentData.php@@ -0,0 +1,56 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Api;++use Espo\Core\Api\Action;+use Espo\Core\Api\Request;+use Espo\Core\Api\Response;+use Espo\Core\Api\ResponseComposer;+use Espo\Core\Exceptions\BadRequest;+use Espo\Tools\OAuthServer\ConsentDataService;++/**+ * @noinspection PhpUnused+ */+class GetConsentData implements Action+{+ public function __construct(+ private ConsentDataService $service,+ ) {}++ public function process(Request $request): Response+ {+ $clientId = $request->getQueryParam('clientId') ?? throw new BadRequest("No clientId.");++ $data = $this->service->getData($clientId);++ return ResponseComposer::json($data);+ }+}diff --git a/application/Espo/Tools/OAuthServer/Api/RefreshToken/PostRevoke.php b/application/Espo/Tools/OAuthServer/Api/RefreshToken/PostRevoke.phpnew file mode 100644index 0000000000..46ad7b81f6--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Api/RefreshToken/PostRevoke.php@@ -0,0 +1,61 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Api\RefreshToken;++use Espo\Core\Api\Action;+use Espo\Core\Api\Request;+use Espo\Core\Api\Response;+use Espo\Core\Api\ResponseComposer;+use Espo\Core\Exceptions\BadRequest;+use Espo\Core\Record\EntityProvider;+use Espo\Tools\OAuthServer\Entities\RefreshToken;+use Espo\Tools\OAuthServer\Record\TokenService;++/**+ * @noinspection PhpUnused+ */+class PostRevoke implements Action+{+ public function __construct(+ private EntityProvider $entityProvider,+ private TokenService $service,+ ) {}++ public function process(Request $request): Response+ {+ $id = $request->getRouteParam('id') ?? throw new BadRequest();++ $entity = $this->entityProvider->getByClass(RefreshToken::class, $id);++ $this->service->revoke($entity);++ return ResponseComposer::json(true);+ }+}diff --git a/application/Espo/Tools/OAuthServer/AuthorizationService.php b/application/Espo/Tools/OAuthServer/AuthorizationService.phpnew file mode 100644index 0000000000..8fbc5679ff--- /dev/null+++ b/application/Espo/Tools/OAuthServer/AuthorizationService.php@@ -0,0 +1,185 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer;++use Espo\Core\ApplicationState;+use Espo\Core\Exceptions\BadRequest;+use Espo\Core\Exceptions\Error;+use Espo\Core\Exceptions\Forbidden;+use Espo\Core\Exceptions\NotFound;+use Espo\Entities\User;+use Espo\Tools\OAuthServer\League\AuthorizationRequestStorage;+use Espo\Tools\OAuthServer\League\AuthorizationServerFactory;+use Espo\Tools\OAuthServer\League\Entities\ScopeEntity;+use Espo\Tools\OAuthServer\League\Entities\UserEntity;+use Espo\Tools\OAuthServer\Scope\ScopeSorter;+use Espo\Tools\OAuthServer\Utils\UriUtil;+use League\OAuth2\Server\Exception\OAuthServerException;+use League\OAuth2\Server\RequestTypes\AuthorizationRequest;+use Psr\Http\Message\ResponseInterface;+use Psr\Http\Message\ServerRequestInterface;++class AuthorizationService+{+ public function __construct(+ private AuthorizationServerFactory $authorizationServerFactory,+ private ApplicationState $applicationState,+ private AuthorizationRequestStorage $authorizationRequestStorage,+ private ScopeSorter $scopeSorter,+ ) {}++ /**+ * @throws Error+ */+ public function authorizeStart(ServerRequestInterface $request, ResponseInterface $response): ?ResponseInterface+ {+ $server = $this->authorizationServerFactory->create();++ try {+ $authRequest = $server->validateAuthorizationRequest($request);+ } catch (OAuthServerException $e) {+ return $e->generateHttpResponse($response);+ }++ $clientId = $authRequest->getClient()->getIdentifier();++ $this->authorizationRequestStorage->store($clientId, $authRequest);++ return null;+ }++ /**+ * @param non-empty-string[] $scopes+ * @throws NotFound+ * @throws Error+ * @throws Forbidden+ * @throws BadRequest+ * @noinspection PhpRedundantCatchClauseInspection+ */+ public function authorizeComplete(+ string $clientId,+ ResponseInterface $response,+ bool $approved,+ array $scopes,+ ): ResponseInterface {++ $scopes = $this->scopeSorter->sort($scopes);++ $authorizationRequest = $this->getAuthRequestFromSession($clientId);++ $this->validateScopesOnCompletion($authorizationRequest, $scopes);++ $authorizationRequest->setScopes(array_map(fn ($it) => new ScopeEntity($it), $scopes));++ $user = $this->applicationState->getUser();++ try {+ $this->assertUser($user, $authorizationRequest);+ } catch (OAuthServerException $e) {+ return $e->generateHttpResponse($response);+ }++ $authorizationRequest->setUser(new UserEntity($user));+ $authorizationRequest->setAuthorizationApproved($approved);++ $server = $this->authorizationServerFactory->create();++ try {+ return $server->completeAuthorizationRequest($authorizationRequest, $response);+ } catch (OAuthServerException $e) {+ return $e->generateHttpResponse($response);+ }+ }++ /**+ * @throws Error+ */+ public function token(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface+ {+ $server = $this->authorizationServerFactory->create();++ try {+ return $server->respondToAccessTokenRequest($request, $response);+ } catch (OAuthServerException $e) {+ return $e->generateHttpResponse($response);+ }+ }++ /**+ * @throws NotFound+ */+ private function getAuthRequestFromSession(string $clientId): AuthorizationRequest+ {+ $authRequest = $this->authorizationRequestStorage->get($clientId, clear: true);++ if (!$authRequest) {+ throw new NotFound("Session not found.");+ }++ return $authRequest;+ }++ /**+ * @throws Error+ * @throws OAuthServerException+ */+ private function assertUser(User $user, AuthorizationRequest $authorizationRequest): void+ {+ if ($user->isRegular() || $user->getType() === User::TYPE_ADMIN) {+ return;+ }++ $redirectUri = $authorizationRequest->getRedirectUri();++ if ($redirectUri && $authorizationRequest->getState()) {+ $redirectUri = UriUtil::makeRedirectUri($redirectUri, $authorizationRequest->getState());+ }++ throw OAuthServerException::accessDenied("User is not allowed.", $redirectUri);+ }++ /**+ * @param string[] $scopes+ * @throws Forbidden+ * @throws BadRequest+ */+ private function validateScopesOnCompletion(AuthorizationRequest $authorizationRequest, array $scopes): void+ {+ if (count(array_unique($scopes)) !== count($scopes)) {+ throw new BadRequest("Duplicate scopes.");+ }++ $storedScopes = array_map(fn ($it) => $it->getIdentifier(), $authorizationRequest->getScopes());++ if (array_diff($scopes, $storedScopes)) {+ throw new Forbidden("Scope mismatch.");+ }+ }+}diff --git a/application/Espo/Tools/OAuthServer/Cleanup/GeneralCleanup.php b/application/Espo/Tools/OAuthServer/Cleanup/GeneralCleanup.phpnew file mode 100644index 0000000000..39de11f2aa--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Cleanup/GeneralCleanup.php@@ -0,0 +1,165 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Cleanup;++use Espo\Core\Cleanup\Cleanup;+use Espo\Core\Name\Field;+use Espo\Core\Utils\Config;+use Espo\Core\Utils\DateTime;+use Espo\ORM\EntityManager;+use Espo\ORM\Name\Attribute;+use Espo\ORM\Query\Part\Condition as Cond;+use Espo\ORM\Query\Part\Expression as Expr;+use Espo\ORM\Query\SelectBuilder;+use Espo\Tools\OAuthServer\Entities\AccessToken;+use Espo\Tools\OAuthServer\Entities\AuthorizationCode;+use Espo\Tools\OAuthServer\Entities\RefreshToken;++/**+ * @noinspection PhpUnused+ */+class GeneralCleanup implements Cleanup+{+ private const string PERIOD_AUTHORIZATION_CODE = '15 days';+ private const string PERIOD_ACCESS_TOKEN = '15 days';+ private const string PERIOD_REFRESH_TOKEN = '15 days';++ public function __construct(+ private Config $config,+ private EntityManager $entityManager,+ private DateTime $dateTime,+ ) {}++ public function process(): void+ {+ $this->processAuthorizationCodes();+ $this->processRefreshTokens();+ $this->processAccessTokens();+ }++ private function getAuthorizationCodePeriod(): string+ {+ return $this->config->get('oAuthServer.cleanup.authorizationCodePeriod') ?? self::PERIOD_AUTHORIZATION_CODE;+ }++ private function getAccessTokenPeriod(): string+ {+ return $this->config->get('oAuthServer.cleanup.accessTokenPeriod') ?? self::PERIOD_ACCESS_TOKEN;+ }++ private function getRefreshTokenPeriod(): string+ {+ return $this->config->get('oAuthServer.cleanup.refreshTokenPeriod') ?? self::PERIOD_REFRESH_TOKEN;+ }++ private function processAuthorizationCodes(): void+ {+ $time = $this->dateTime->getNow()+ ->modify('-' . $this->getAuthorizationCodePeriod());++ $entries = $this->entityManager+ ->getRDBRepositoryByClass(AuthorizationCode::class)+ ->sth()+ ->where([+ AuthorizationCode::FIELD_EXPIRES_AT . '<=' => $time->toString(),+ ])+ ->find();++ foreach ($entries as $entry) {+ $this->entityManager->removeEntity($entry);+ }+ }++ private function processAccessTokens(): void+ {+ $time = $this->dateTime->getNow()+ ->modify('-' . $this->getAccessTokenPeriod());++ $entries = $this->entityManager+ ->getRDBRepositoryByClass(AccessToken::class)+ ->sth()+ ->where([+ AccessToken::FIELD_EXPIRES_AT . '<=' => $time->toString(),+ ])+ ->where(+ Cond::not(+ Cond::exists(+ SelectBuilder::create()+ ->from(RefreshToken::ENTITY_TYPE, 'r')+ ->select(Attribute::ID)+ ->where([+ 'r.' . RefreshToken::FIELD_STATUS => RefreshToken::STATUS_ACTIVE,+ ])+ ->where(+ Cond::equal(+ Expr::column(lcfirst(AccessToken::ENTITY_TYPE) . '.' . Attribute::ID),+ Expr::column('r.' . RefreshToken::FIELD_ACCESS_TOKEN . 'Id'),+ )+ )+ ->build()+ )+ )+ )+ ->find();++ foreach ($entries as $entry) {+ $this->entityManager->removeEntity($entry);+ }+ }++ private function processRefreshTokens(): void+ {+ $time = $this->dateTime->getNow()+ ->modify('-' . $this->getRefreshTokenPeriod());++ $entries = $this->entityManager+ ->getRDBRepositoryByClass(RefreshToken::class)+ ->sth()+ ->where([+ 'OR' => [+ [+ RefreshToken::FIELD_EXPIRES_AT . '<=' => $time->toString(),+ ],+ [+ RefreshToken::FIELD_STATUS => [+ RefreshToken::STATUS_REVOKED,+ RefreshToken::STATUS_EXPIRED,+ ],+ Field::MODIFIED_AT . '<=' => $time->toString(),+ ],+ ],+ ])+ ->find();++ foreach ($entries as $entry) {+ $this->entityManager->removeEntity($entry);+ }+ }+}diff --git a/application/Espo/Tools/OAuthServer/ClientType.php b/application/Espo/Tools/OAuthServer/ClientType.phpnew file mode 100644index 0000000000..4a98c60a98--- /dev/null+++ b/application/Espo/Tools/OAuthServer/ClientType.php@@ -0,0 +1,36 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer;++enum ClientType: string+{+ case Confidential = 'Confidential';+ case Public = 'Public';+}diff --git a/application/Espo/Tools/OAuthServer/ClientValidator.php b/application/Espo/Tools/OAuthServer/ClientValidator.phpnew file mode 100644index 0000000000..4753f8d39e--- /dev/null+++ b/application/Espo/Tools/OAuthServer/ClientValidator.php@@ -0,0 +1,50 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer;++use Espo\Tools\OAuthServer\Entities\Client;+use Espo\Tools\OAuthServer\Secret\SecretValidator;+use SensitiveParameter;++class ClientValidator+{+ public function __construct(+ private SecretValidator $secretValidator,+ ) {}++ public function validate(Client $client, #[SensitiveParameter] ?string $secret): bool+ {+ if (!$secret) {+ return $client->getClientType() === ClientType::Public;+ }++ return $this->secretValidator->validate($client, $secret);+ }+}diff --git a/application/Espo/Tools/OAuthServer/ConnectedApp/AppData.php b/application/Espo/Tools/OAuthServer/ConnectedApp/AppData.phpnew file mode 100644index 0000000000..39fe59f2a7--- /dev/null+++ b/application/Espo/Tools/OAuthServer/ConnectedApp/AppData.php@@ -0,0 +1,48 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\ConnectedApp;++use stdClass;++readonly class AppData+{+ public function __construct(+ public string $id,+ public ?string $name,+ ) {}++ public function toApiOutput(): stdClass+ {+ return (object) [+ 'id' => $this->id,+ 'name' => $this->name,+ ];+ }+}diff --git a/application/Espo/Tools/OAuthServer/ConnectedApp/ConnectedAppService.php b/application/Espo/Tools/OAuthServer/ConnectedApp/ConnectedAppService.phpnew file mode 100644index 0000000000..846ccaaabe--- /dev/null+++ b/application/Espo/Tools/OAuthServer/ConnectedApp/ConnectedAppService.php@@ -0,0 +1,96 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\ConnectedApp;++use Espo\Core\Exceptions\NotFound;+use Espo\Entities\User;+use Espo\ORM\EntityManager;+use Espo\Tools\OAuthServer\Entities\Client;+use Espo\Tools\OAuthServer\Repository\AccessTokenRepository;+use Espo\Tools\OAuthServer\Repository\ClientRepository;+use Espo\Tools\OAuthServer\Repository\RefreshTokenRepository;+use RuntimeException;++class ConnectedAppService+{+ private const int LIMIT = 50;++ public function __construct(+ private ClientRepository $clientRepository,+ private RefreshTokenRepository $refreshTokenRepository,+ private AccessTokenRepository $accessTokenRepository,+ private EntityManager $entityManager,+ ) {}++ /**+ * @return AppData[]+ */+ public function getList(User $user): array+ {+ $clients = $this->clientRepository->findConnectedForUser($user->getId(), self::LIMIT);++ return array_map(function (Client $it) {+ $id = $it->getIdentifier() ?? throw new RuntimeException();++ return new AppData(+ id: $id,+ name: $it->getName() ?? $id,+ );+ }, iterator_to_array($clients));+ }++ /**+ * @throws NotFound+ */+ public function disconnect(User $user, string $clientId): void+ {+ $client = $this->clientRepository->getByIdentifier($clientId);++ if (!$client) {+ throw new NotFound("Client not found.");+ }++ $refreshTokens = $this->refreshTokenRepository->findActiveForClientIdAndUser($client->getId(), $user->getId());++ foreach ($refreshTokens as $refreshToken) {+ $refreshToken->setRevoked();++ $this->entityManager->saveEntity($refreshToken);+ }++ $accessTokens = $this->accessTokenRepository->findActiveForClientIdAndUser($client->getId(), $user->getId());++ foreach ($accessTokens as $accessToken) {+ $accessToken->setRevoked();++ $this->entityManager->saveEntity($accessToken);+ }+ }+}diff --git a/application/Espo/Tools/OAuthServer/ConnectedApp/UserCheck.php b/application/Espo/Tools/OAuthServer/ConnectedApp/UserCheck.phpnew file mode 100644index 0000000000..3a00ba5c71--- /dev/null+++ b/application/Espo/Tools/OAuthServer/ConnectedApp/UserCheck.php@@ -0,0 +1,46 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\ConnectedApp;++use Espo\Core\Exceptions\Forbidden;+use Espo\Entities\User;++class UserCheck+{+ /**+ * @throws Forbidden+ */+ public function assert(User $user): void+ {+ if ($user->getType() !== User::TYPE_ADMIN && !$user->isRegular()) {+ throw new Forbidden("Only regular users and admins are allowed.");+ }+ }+}diff --git a/application/Espo/Tools/OAuthServer/ConsentDataService.php b/application/Espo/Tools/OAuthServer/ConsentDataService.phpnew file mode 100644index 0000000000..ae5165c6a5--- /dev/null+++ b/application/Espo/Tools/OAuthServer/ConsentDataService.php@@ -0,0 +1,165 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer;++use Espo\Core\Acl\Scope;+use Espo\Core\Exceptions\Error;+use Espo\Core\Exceptions\NotFound;+use Espo\Core\Utils\Config\ApplicationConfig;+use Espo\Core\Utils\Language;+use Espo\Entities\User;+use Espo\Tools\OAuthServer\Entities\Client;+use Espo\Tools\OAuthServer\League\AuthorizationRequestStorage;+use Espo\Tools\OAuthServer\Repository\ClientRepository;+use Espo\Tools\OAuthServer\Scope\ScopeSorter;+use Espo\Tools\OAuthServer\Scope\UserAvailableScopesFilter;+use InvalidArgumentException;+use stdClass;++class ConsentDataService+{+ public function __construct(+ private ClientRepository $clientRepository,+ private User $user,+ private Language $language,+ private ApplicationConfig $applicationConfig,+ private AuthorizationRequestStorage $authorizationRequestStorage,+ private UserAvailableScopesFilter $userAvailableScopesFilter,+ private ScopeSorter $scopeSorter,+ ) {}++ /**+ * @throws NotFound+ * @throws Error+ */+ public function getData(string $clientId): stdClass+ {+ $client = $this->getClient($clientId);++ return (object) [+ 'scopeDataList' => $this->getScopeDataList($client),+ 'labels' => (object) [+ 'allow' => $this->language->translateLabel('allow', 'strings', Client::ENTITY_TYPE),+ 'cancel' => $this->language->translateLabel('Cancel'),+ 'info' => $this->composeInfoText($client),+ ],+ ];+ }++ /**+ * @throws NotFound+ */+ private function getClient(string $clientId): Entities\Client+ {+ $client = $this->clientRepository->getActiveByIdentifier($clientId);++ if (!$client) {+ throw new NotFound("Client not found.");+ }++ return $client;+ }++ private function translateScope(string $scope): string+ {+ $appScope = $scope;+ $actionLabel = null;++ if (str_contains($scope, ':')) {+ [$appScope, $action] = explode(':', $appScope, 2);++ $actionLabel = $this->language->translateOption($action, 'levelList', 'Role');+ }++ $scopeLabel = $this->language->translateLabel($appScope, 'scopeNames');++ $label = $scopeLabel;++ if ($actionLabel) {+ $label .= ' . ' . $actionLabel;+ }++ return $label;+ }++ private function composeInfoText(Client $client): string+ {+ return strtr($this->language->translateLabel('allowAccessInfo', 'messages', Client::ENTITY_TYPE), [+ '{clientName}' => $client->getName(),+ '{applicationName}' => $this->applicationConfig->getApplicationName(),+ '{username}' => $this->user->getUserName(),+ ]);+ }++ /**+ * @return stdClass[]+ * @throws Error+ */+ private function getScopeDataList(Client $client): array+ {+ $clientId = $client->getIdentifier() ?? throw new InvalidArgumentException("No client identifier.");++ $request = $this->authorizationRequestStorage->get($clientId);++ if (!$request) {+ throw new Error("No session data.");+ }++ $scopes = array_map(fn ($it) => $it->getIdentifier(), $request->getScopes());++ $scopes = $this->userAvailableScopesFilter->filter($this->user->getId(), $scopes);++ /** @var (stdClass & object{name: string, label: string})[] $scopeDataList */+ $scopeDataList = array_map(function ($scope) {+ return (object) [+ 'name' => $scope,+ 'label' => $this->translateScope($scope),+ 'description' => $this->getScopeDescription($scope),+ ];+ }, $scopes);++ return $this->scopeSorter->sortDataItems($scopeDataList);+ }++ private function getScopeDescription(string $scope): ?string+ {+ if (!in_array($scope, [Scope::ADMIN, Scope::GLOBAL])) {+ return null;+ }++ $key = $scope;++ if ($scope === Scope::GLOBAL && $this->user->isAdmin()) {+ $key = 'GlobalAdmin';+ }++ return $this->language->translateLabel($key, 'scopeDescriptions', Client::ENTITY_TYPE);+ }+}diff --git a/application/Espo/Tools/OAuthServer/Entities/AccessToken.php b/application/Espo/Tools/OAuthServer/Entities/AccessToken.phpnew file mode 100644index 0000000000..7e617b5c99--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Entities/AccessToken.php@@ -0,0 +1,163 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Entities;++use Espo\Core\Field\DateTime;+use Espo\Core\Field\Link;+use Espo\Core\ORM\Entity;+use Espo\Entities\User;+use SensitiveParameter;+use UnexpectedValueException;++class AccessToken extends Entity+{+ public const string ENTITY_TYPE = 'OAuthAccessToken';++ public const string FIELD_STATUS = 'status';+ public const string FIELD_CLIENT = 'client';+ public const string FIELD_IDENTIFIER = 'identifier';+ public const string FIELD_EXPIRES_AT = 'expiresAt';+ public const string FIELD_SCOPES = 'scopes';+ public const string FIELD_USER = 'user';+ public const string FIELD_HASH = 'hash';++ public const string STATUS_ACTIVE = 'Active';+ public const string STATUS_REVOKED = 'Revoked';+ public const string STATUS_EXPIRED = 'Expired';++ public function isActive(): bool+ {+ return $this->get(self::FIELD_STATUS) === self::STATUS_ACTIVE;+ }++ public function isRevoked(): bool+ {+ return $this->get(self::FIELD_STATUS) === self::STATUS_REVOKED;+ }++ public function getClient(): Client+ {+ $client = $this->relations->getOne(self::FIELD_CLIENT);++ if (!$client instanceof Client) {+ throw new UnexpectedValueException("No client.");+ }++ return $client;+ }++ public function setClient(Client|Link $client): self+ {+ return $this->setRelatedLinkOrEntity(self::FIELD_CLIENT, $client);+ }++ public function setRevoked(): self+ {+ return $this->set(self::FIELD_STATUS, self::STATUS_REVOKED);+ }++ public function setExpired(): self+ {+ return $this->set(self::FIELD_STATUS, self::STATUS_EXPIRED);+ }++ public function setHash(string $hash): self+ {+ return $this->set(self::FIELD_HASH, $hash);+ }++ public function setIdentifier(#[SensitiveParameter] string $identifier): self+ {+ return $this->set(self::FIELD_IDENTIFIER, $identifier);+ }++ /**+ * @return non-empty-string+ */+ public function getIdentifier(): string+ {+ /** @var non-empty-string */+ return $this->get(self::FIELD_IDENTIFIER) ?? throw new UnexpectedValueException("No identifier.");+ }++ public function getExpiresAt(): DateTime+ {+ $value = $this->getValueObject(self::FIELD_EXPIRES_AT);++ if (!$value instanceof DateTime) {+ throw new UnexpectedValueException("No expiresAt.");+ }++ return $value;+ }++ public function setExpiresAt(DateTime $expiresAt): self+ {+ return $this->setValueObject(self::FIELD_EXPIRES_AT, $expiresAt);+ }++ public function isExpired(): bool+ {+ return $this->get(self::FIELD_STATUS) === self::STATUS_EXPIRED;+ }++ /**+ * @return non-empty-string[]+ */+ public function getScopes(): array+ {+ /** @var non-empty-string[] */+ return $this->get(self::FIELD_SCOPES) ?? [];+ }++ /**+ * @param string[] $scopes+ */+ public function setScopes(array $scopes): self+ {+ return $this->set(self::FIELD_SCOPES, $scopes);+ }++ public function getUser(): Link+ {+ $user = $this->getValueObject(self::FIELD_USER);++ if (!$user instanceof Link) {+ throw new UnexpectedValueException("No user.");+ }++ return $user;+ }++ public function setUser(Link|User $user): self+ {+ return $this->setRelatedLinkOrEntity(self::FIELD_USER, $user);+ }+}diff --git a/application/Espo/Tools/OAuthServer/Entities/AuthorizationCode.php b/application/Espo/Tools/OAuthServer/Entities/AuthorizationCode.phpnew file mode 100644index 0000000000..1b861fb21a--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Entities/AuthorizationCode.php@@ -0,0 +1,157 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Entities;++use Espo\Core\Field\DateTime;+use Espo\Core\Field\Link;+use Espo\Core\ORM\Entity;+use Espo\Entities\User;+use UnexpectedValueException;++class AuthorizationCode extends Entity+{+ public const string ENTITY_TYPE = 'OAuthAuthorizationCode';++ public const string FIELD_STATUS = 'status';+ public const string FILED_CLIENT = 'client';+ public const string FIELD_HASH = 'hash';+ public const string FIELD_EXPIRES_AT = 'expiresAt';+ public const string FIELD_REDIRECT_URI = 'redirectUri';+ public const string FIELD_SCOPES = 'scopes';+ public const string FIELD_USER = 'user';++ public const string STATUS_ACTIVE = 'Active';+ public const string STATUS_REVOKED = 'Revoked';+ public const string STATUS_EXPIRED = 'Expired';++ public function isActive(): bool+ {+ return $this->get(self::FIELD_STATUS) === self::STATUS_ACTIVE;+ }++ public function isRevoked(): bool+ {+ return $this->get(self::FIELD_STATUS) === self::STATUS_REVOKED;+ }++ public function getClient(): Client+ {+ $client = $this->relations->getOne(self::FILED_CLIENT);++ if (!$client instanceof Client) {+ throw new UnexpectedValueException("No client.");+ }++ return $client;+ }++ public function setClient(Client|Link $client): self+ {+ return $this->setRelatedLinkOrEntity(self::FILED_CLIENT, $client);+ }++ public function setRevoked(): self+ {+ return $this->set(self::FIELD_STATUS, self::STATUS_REVOKED);+ }++ public function setExpired(): self+ {+ return $this->set(self::FIELD_STATUS, self::STATUS_EXPIRED);+ }++ public function setHash(string $hash): self+ {+ return $this->set(self::FIELD_HASH, $hash);+ }++ public function getExpiresAt(): DateTime+ {+ $value = $this->getValueObject(self::FIELD_EXPIRES_AT);++ if (!$value instanceof DateTime) {+ throw new UnexpectedValueException("No expiresAt.");+ }++ return $value;+ }++ public function setExpiresAt(DateTime $expiresAt): self+ {+ return $this->setValueObject(self::FIELD_EXPIRES_AT, $expiresAt);+ }++ public function getRedirectUri(): string+ {+ return $this->get(self::FIELD_REDIRECT_URI) ?? throw new UnexpectedValueException("No redirectUri.");+ }++ public function setRedirectUri(string $redirectUri): self+ {+ return $this->set(self::FIELD_REDIRECT_URI, $redirectUri);+ }++ public function isExpired(): bool+ {+ return $this->get(self::FIELD_STATUS) === self::STATUS_EXPIRED;+ }++ /**+ * @return string[]+ */+ public function getScopes(): array+ {+ return $this->get(self::FIELD_SCOPES);+ }++ /**+ * @param string[] $scopes+ */+ public function setScopes(array $scopes): self+ {+ return $this->set(self::FIELD_SCOPES, $scopes);+ }++ public function getUser(): Link+ {+ $user = $this->getValueObject(self::FIELD_USER);++ if (!$user instanceof Link) {+ throw new UnexpectedValueException("No user.");+ }++ return $user;+ }++ public function setUser(Link|User $user): self+ {+ return $this->setRelatedLinkOrEntity(self::FIELD_USER, $user);+ }+}diff --git a/application/Espo/Tools/OAuthServer/Entities/Client.php b/application/Espo/Tools/OAuthServer/Entities/Client.phpnew file mode 100644index 0000000000..29081bcf02--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Entities/Client.php@@ -0,0 +1,142 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Entities;++use Espo\Core\Name\Field;+use Espo\Core\ORM\Entity;+use Espo\Tools\OAuthServer\ClientType;+use UnexpectedValueException;++class Client extends Entity+{+ public const string ENTITY_TYPE = 'OAuthClient';++ public const string FIELD_STATUS = 'status';+ public const string FIELD_IDENTIFIER = 'identifier';+ public const string FIELD_CLIENT_TYPE = 'clientType';+ public const string FIELD_SCOPES = 'scopes';+ public const string FIELD_REDIRECT_URIS = 'redirectUris';++ public const string LINK_SECRETS = 'secrets';++ public const string STATUS_ACTIVE = 'Active';+ public const string STATUS_INACTIVE = 'Inactive';++ public function getName(): ?string+ {+ return $this->get(Field::NAME);+ }++ public function setName(string $name): self+ {+ return $this->set(Field::NAME, $name);+ }++ public function getClientType(): ClientType+ {+ $raw = $this->get(self::FIELD_CLIENT_TYPE) ?? throw new UnexpectedValueException("No client type.");++ return ClientType::tryFrom($raw) ?? throw new UnexpectedValueException("Bad client type.");+ }++ public function setClientType(ClientType $clientType): self+ {+ return $this->set(self::FIELD_CLIENT_TYPE, $clientType->value);+ }++ /**+ * @return ?non-empty-string+ */+ public function getIdentifier(): ?string+ {+ /** @var ?non-empty-string */+ return $this->get(self::FIELD_IDENTIFIER);+ }++ public function setIdentifier(?string $clientId): self+ {+ return $this->set(self::FIELD_IDENTIFIER, $clientId);+ }++ public function isActive(): bool+ {+ return $this->get(self::FIELD_STATUS) === self::STATUS_ACTIVE;+ }++ public function setActive(): self+ {+ return $this->set(self::FIELD_STATUS, self::STATUS_ACTIVE);+ }++ public function setInactive(): self+ {+ return $this->set(self::FIELD_STATUS, self::STATUS_INACTIVE);+ }++ /**+ * @return non-empty-string[]+ */+ public function getScopes(): array+ {+ $scopes = $this->get(self::FIELD_SCOPES) ?? [];++ foreach ($scopes as $scope) {+ if (!$scope) {+ throw new UnexpectedValueException("Empty scope.");+ }+ }++ return $scopes;+ }++ /**+ * @param string[] $scopes+ */+ public function setScopes(array $scopes): self+ {+ return $this->set(self::FIELD_SCOPES, $scopes);+ }++ /**+ * @return string[]+ */+ public function getRedirectUris(): array+ {+ return $this->get(self::FIELD_REDIRECT_URIS) ?? [];+ }++ /**+ * @param string[] $redirectUris+ */+ public function setRedirectUris(array $redirectUris): self+ {+ return $this->set(self::FIELD_REDIRECT_URIS, $redirectUris);+ }+}diff --git a/application/Espo/Tools/OAuthServer/Entities/ClientSecret.php b/application/Espo/Tools/OAuthServer/Entities/ClientSecret.phpnew file mode 100644index 0000000000..992a7c66bf--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Entities/ClientSecret.php@@ -0,0 +1,135 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Entities;++use Espo\Core\Field\Date;+use Espo\Core\Name\Field;+use Espo\Core\ORM\Entity;+use SensitiveParameter;+use UnexpectedValueException;++class ClientSecret extends Entity+{+ public const string ENTITY_TYPE = 'OAuthClientSecret';++ public const string FIELD_STATUS = 'status';+ public const string FIELD_HASH = 'hash';+ public const string FIELD_CLIENT = 'client';+ public const string FIELD_EXPIRATION_DATE = 'expirationDate';+ public const string FIELD_VALUE = 'value';++ public const string STATUS_ACTIVE = 'Active';+ public const string STATUS_REVOKED = 'Revoked';+ public const string STATUS_EXPIRED = 'Expired';++ public const string ATTR_CLIENT_ID = 'clientId';++ public function setName(string $name): self+ {+ return $this->set(Field::NAME, $name);+ }++ public function getName(): ?string+ {+ return $this->get(Field::NAME);+ }++ public function getHash(): string+ {+ return $this->get(self::FIELD_HASH) ?? throw new UnexpectedValueException("No hash.");+ }++ public function setHash(string $value): self+ {+ return $this->set(self::FIELD_HASH, $value);+ }++ public function isActive(): bool+ {+ return $this->get(self::FIELD_STATUS) === self::STATUS_ACTIVE;+ }++ public function isExpired(): bool+ {+ return $this->get(self::FIELD_STATUS) === self::STATUS_EXPIRED;+ }++ public function isRevoked(): bool+ {+ return $this->get(self::FIELD_STATUS) === self::STATUS_REVOKED;+ }++ public function setRevoked(): self+ {+ return $this->set(self::FIELD_STATUS, self::STATUS_REVOKED);+ }++ public function setExpired(): self+ {+ return $this->set(self::FIELD_STATUS, self::STATUS_EXPIRED);+ }++ public function getExpirationDate(): ?Date+ {+ /** @var ?Date */+ return $this->getValueObject(self::FIELD_EXPIRATION_DATE);+ }++ public function setExpirationDate(?Date $date): self+ {+ return $this->setValueObject(self::FIELD_EXPIRATION_DATE, $date);+ }++ public function getClient(): Client+ {+ $client = $this->relations->getOne(self::FIELD_CLIENT);++ if (!$client instanceof Client) {+ throw new UnexpectedValueException("No client.");+ }++ return $client;+ }++ public function setClient(Client $client): self+ {+ return $this->setRelatedLinkOrEntity(self::FIELD_CLIENT, $client);+ }++ public function setValue(#[SensitiveParameter] string $value): self+ {+ return $this->set(self::FIELD_VALUE, $value);+ }++ public function getValue(): string+ {+ return $this->get(self::FIELD_VALUE) ?? throw new UnexpectedValueException("No value.");+ }+}diff --git a/application/Espo/Tools/OAuthServer/Entities/RefreshToken.php b/application/Espo/Tools/OAuthServer/Entities/RefreshToken.phpnew file mode 100644index 0000000000..d75c362408--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Entities/RefreshToken.php@@ -0,0 +1,146 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Entities;++use Espo\Core\Field\DateTime;+use Espo\Core\Field\Link;+use Espo\Core\ORM\Entity;+use Espo\Entities\User;+use UnexpectedValueException;++class RefreshToken extends Entity+{+ public const string ENTITY_TYPE = 'OAuthRefreshToken';++ public const string FIELD_STATUS = 'status';+ public const string FIELD_CLIENT = 'client';+ public const string FIELD_EXPIRES_AT = 'expiresAt';+ public const string FIELD_USER = 'user';+ public const string FIELD_ACCESS_TOKEN = 'accessToken';+ public const string FIELD_HASH = 'hash';++ public const string STATUS_ACTIVE = 'Active';+ public const string STATUS_REVOKED = 'Revoked';+ public const string STATUS_EXPIRED = 'Expired';++ public function setHash(string $value): self+ {+ return $this->set(self::FIELD_HASH, $value);+ }++ public function isActive(): bool+ {+ return $this->get(self::FIELD_STATUS) === self::STATUS_ACTIVE;+ }++ public function isRevoked(): bool+ {+ return $this->get(self::FIELD_STATUS) === self::STATUS_REVOKED;+ }++ public function setStatus(string $status): self+ {+ return $this->set(self::FIELD_STATUS, $status);+ }++ public function getClient(): Client+ {+ $client = $this->relations->getOne(self::FIELD_CLIENT);++ if (!$client instanceof Client) {+ throw new UnexpectedValueException("No client.");+ }++ return $client;+ }++ public function setAccessToken(AccessToken $accessToken): self+ {+ return $this->setRelatedLinkOrEntity(self::FIELD_ACCESS_TOKEN, $accessToken);+ }++ public function setClient(Client $client): self+ {+ return $this->setRelatedLinkOrEntity(self::FIELD_CLIENT, $client);+ }++ public function isExpired(): bool+ {+ return $this->get(self::FIELD_STATUS) === self::STATUS_EXPIRED;+ }++ public function setRevoked(): self+ {+ return $this->set(self::FIELD_STATUS, self::STATUS_REVOKED);+ }++ public function setExpired(): self+ {+ return $this->set(self::FIELD_STATUS, self::STATUS_EXPIRED);+ }++ public function getExpiresAt(): DateTime+ {+ $value = $this->getValueObject(self::FIELD_EXPIRES_AT);++ if (!$value instanceof DateTime) {+ throw new UnexpectedValueException("No expiresAt.");+ }++ return $value;+ }++ public function setExpiresAt(DateTime $expiresAt): self+ {+ return $this->setValueObject(self::FIELD_EXPIRES_AT, $expiresAt);+ }++ public function getUser(): Link+ {+ $user = $this->getValueObject(self::FIELD_USER);++ if (!$user instanceof Link) {+ throw new UnexpectedValueException("No user.");+ }++ return $user;+ }++ public function setUser(Link|User $user): self+ {+ return $this->setRelatedLinkOrEntity(self::FIELD_USER, $user);+ }++ public function getAccessToken(): ?AccessToken+ {+ /** @var ?AccessToken */+ return $this->relations->getOne(self::FIELD_ACCESS_TOKEN);+ }+}diff --git a/application/Espo/Tools/OAuthServer/EntryPoints/Authorize.php b/application/Espo/Tools/OAuthServer/EntryPoints/Authorize.phpnew file mode 100644index 0000000000..47ac67958f--- /dev/null+++ b/application/Espo/Tools/OAuthServer/EntryPoints/Authorize.php@@ -0,0 +1,74 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\EntryPoints;++use Espo\Core\Api\Request;+use Espo\Core\Api\Response;+use Espo\Core\EntryPoint\EntryPoint;+use Espo\Core\Utils\Client\ActionRenderer;+use Espo\Core\Utils\Client\SecurityParams;+use Espo\Tools\OAuthServer\AuthorizationService;++/**+ * @noinspection PhpUnused+ */+class Authorize implements EntryPoint+{+ public function __construct(+ private ActionRenderer $actionRenderer,+ private AuthorizationService $service,+ ) {}++ public function run(Request $request, Response $response): void+ {+ $psr7Response = $this->service->authorizeStart($request->toPsr7(), $response->toPsr7());++ if ($psr7Response) {+ $response->applyPsr7($psr7Response);++ return;+ }++ $params = new ActionRenderer\Params(+ controller: 'controllers/o-auth-authorize',+ action: 'show',+ );++ $params = $params+ ->withLogin()+ ->withSecurityParams(+ new SecurityParams(+ formAction: [],+ )+ );++ $this->actionRenderer->write($response, $params);+ }+}diff --git a/application/Espo/Tools/OAuthServer/EntryPoints/AuthorizeComplete.php b/application/Espo/Tools/OAuthServer/EntryPoints/AuthorizeComplete.phpnew file mode 100644index 0000000000..3f12693a21--- /dev/null+++ b/application/Espo/Tools/OAuthServer/EntryPoints/AuthorizeComplete.php@@ -0,0 +1,93 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\EntryPoints;++use Espo\Core\Api\Request;+use Espo\Core\Api\Response;+use Espo\Core\EntryPoint\EntryPoint;+use Espo\Core\Exceptions\BadRequest;+use Espo\Tools\OAuthServer\AuthorizationService;++/**+ * @noinspection PhpUnused+ */+class AuthorizeComplete implements EntryPoint+{+ public function __construct(+ private AuthorizationService $service,+ ) {}++ public function run(Request $request, Response $response): void+ {+ $body = $request->getParsedBody();++ $clientId = $body->clientId ?? throw new BadRequest("No 'clientId'.");+ $approved = ($body->approved ?? null) === 'true';++ if (!is_string($clientId)) {+ throw new BadRequest();+ }++ $scopes = $this->fetchScopes($request);++ $psr7Response = $this->service->authorizeComplete(+ clientId: $clientId,+ response: $response->toPsr7(),+ approved: $approved,+ scopes: $scopes,+ );++ $response->applyPsr7($psr7Response);+ }++ /**+ * @return non-empty-string[]+ * @throws BadRequest+ */+ private function fetchScopes(Request $request): array+ {+ $scopesRaw = $request->getParsedBody()->scopes ?? throw new BadRequest("No 'scopes'.");++ $scopes = explode(' ', $scopesRaw);++ foreach ($scopes as $scope) {+ if (!$scope) {+ throw new BadRequest("Bad 'scopes' item values.");+ }++ if ($scope !== trim($scope)) {+ throw new BadRequest("Bad scope.");+ }+ }++ /** @var non-empty-string[] */+ return $scopes;+ }+}diff --git a/application/Espo/Tools/OAuthServer/EntryPoints/Token.php b/application/Espo/Tools/OAuthServer/EntryPoints/Token.phpnew file mode 100644index 0000000000..73f7ef9d30--- /dev/null+++ b/application/Espo/Tools/OAuthServer/EntryPoints/Token.php@@ -0,0 +1,49 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\EntryPoints;++use Espo\Core\Api\Request;+use Espo\Core\Api\Response;+use Espo\Core\EntryPoint\EntryPoint;+use Espo\Tools\OAuthServer\AuthorizationService;++class Token implements EntryPoint+{+ public function __construct(+ private AuthorizationService $service,+ ) {}++ public function run(Request $request, Response $response): void+ {+ $psr7Response = $this->service->token($request->toPsr7(), $response->toPsr7());++ $response->applyPsr7($psr7Response);+ }+}diff --git a/application/Espo/Tools/OAuthServer/EntryPoints/TokenRevoke.php b/application/Espo/Tools/OAuthServer/EntryPoints/TokenRevoke.phpnew file mode 100644index 0000000000..29b9e5898e--- /dev/null+++ b/application/Espo/Tools/OAuthServer/EntryPoints/TokenRevoke.php@@ -0,0 +1,173 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\EntryPoints;++use Espo\Core\Api\Request;+use Espo\Core\Api\Response;+use Espo\Core\EntryPoint\EntryPoint;+use Espo\Core\Exceptions\BadRequest;+use Espo\Core\Exceptions\Unauthorized;+use Espo\Tools\OAuthServer\Revoke\Data;+use Espo\Tools\OAuthServer\Revoke\TokenRevokeService;+use Espo\Tools\OAuthServer\Utils\ErrorResponseComposer;++/**+ * @noinspection PhpUnused+ */+class TokenRevoke implements EntryPoint+{+ private const string HEADER_AUTHORIZATION = 'Authorization';++ public function __construct(+ private TokenRevokeService $service,+ ) {}++ public function run(Request $request, Response $response): void+ {+ $token = $request->getParsedBody()->token ?? throw new BadRequest("No 'token'.");+ $tokenTypeHint = $request->getParsedBody()->token_type_hint ?? null;++ [$clientId, $clientSecret] = $this->obtainAuthorizationFromHeader($request);++ $clientId ??= $request->getParsedBody()->client_id ?? throw new BadRequest("No client ID.");+ $clientSecret ??= $request->getParsedBody()->client_secret ?? null;++ if (!is_string($clientId)) {+ throw new BadRequest("Bad 'client_id' value");+ }++ if ($clientSecret !== null && !is_string($clientSecret)) {+ throw new BadRequest("Bad 'client_secret' value");+ }++ if (!is_string($token)) {+ throw new BadRequest("Bad 'token' value.");+ }++ if ($tokenTypeHint !== null && !is_string($tokenTypeHint)) {+ throw new BadRequest("Bad 'token_type_hint' value.");+ }++ if (!$this->isTokenTypeValid($tokenTypeHint)) {+ $response->applyPsr7(+ ErrorResponseComposer::compose(+ error: 'unsupported_token_type',+ errorDescription: 'Token type is not supported.',+ statusCode: 400,+ )->toPsr7()+ );++ return;+ }++ $data = new Data(+ clientId: $clientId,+ clientSecret: $clientSecret,+ token: $token,+ tokenTypeHint: $tokenTypeHint,+ );++ try {+ $this->service->revoke($data);+ } catch (Unauthorized) {+ $response->applyPsr7(+ ErrorResponseComposer::compose(+ error: 'invalid_client',+ errorDescription: 'Invalid client credentials.',+ statusCode: 401,+ )->toPsr7()+ );+ }+ }++ private function isTokenTypeValid(?string $tokenTypeHint): bool+ {+ return+ $tokenTypeHint === null ||+ in_array($tokenTypeHint, [+ TokenRevokeService::TYPE_ACCESS_TOKEN,+ TokenRevokeService::TYPE_REFRESH_TOKEN,+ ]);+ }++ /**+ * @return array{?string, ?string}+ * @throws BadRequest+ */+ private function obtainAuthorizationFromHeader(Request $request): array+ {+ $headerValue = $request->getHeader(self::HEADER_AUTHORIZATION);++ if (!$headerValue) {+ return [null, null];+ }++ $prefix = 'Basic ';++ if (!str_starts_with($headerValue, $prefix)) {+ return [null, null];+ }++ $string = substr($headerValue, strlen($prefix));++ [$clientId, $clientSecret] = self::decodeAuthorizationString($string);++ if (!$clientId) {+ $clientId = null;+ }++ if (!$clientSecret) {+ $clientSecret = null;+ }++ return [$clientId, $clientSecret];+ }++ /**+ * @return array{string, string}+ * @throws BadRequest+ */+ private function decodeAuthorizationString(string $string): array+ {+ /** @var string $stringDecoded */+ $stringDecoded = base64_decode($string);++ if (!str_contains($stringDecoded, ':')) {+ throw new BadRequest("Bad authorization string.");+ }++ [$username, $password] = explode(':', $stringDecoded, 2);++ $username = trim($username);+ $password = trim($password);++ return [$username, $password];+ }+}diff --git a/application/Espo/Tools/OAuthServer/ExpireService.php b/application/Espo/Tools/OAuthServer/ExpireService.phpnew file mode 100644index 0000000000..2d18fdb79c--- /dev/null+++ b/application/Espo/Tools/OAuthServer/ExpireService.php@@ -0,0 +1,115 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer;++use Espo\Core\Utils\DateTime;+use Espo\ORM\EntityManager;+use Espo\ORM\Query\UpdateBuilder;+use Espo\Tools\OAuthServer\Entities\AccessToken;+use Espo\Tools\OAuthServer\Entities\AuthorizationCode;+use Espo\Tools\OAuthServer\Entities\ClientSecret;+use Espo\Tools\OAuthServer\Entities\RefreshToken;++/**+ * Sets status Expired. Note that even Active status with the expiration date in past+ * renders the token/secret inactive. Expired status serves an information purpose.+ */+class ExpireService+{+ public function __construct(+ private DateTime $dateTime,+ private EntityManager $entityManager,+ ) {}++ public function expireClientSecrets(): void+ {+ $secrets = $this->entityManager+ ->getRDBRepositoryByClass(ClientSecret::class)+ ->where([+ ClientSecret::FIELD_STATUS => ClientSecret::STATUS_ACTIVE,+ ClientSecret::FIELD_EXPIRATION_DATE . '<=' => $this->dateTime->getToday()->toString(),+ ])+ ->find();++ foreach ($secrets as $secret) {+ $secret->setExpired();++ $this->entityManager->saveEntity($secret);+ }+ }++ public function expireAccessTokens(): void+ {+ $query = UpdateBuilder::create()+ ->in(AccessToken::ENTITY_TYPE)+ ->set([+ AccessToken::FIELD_STATUS => AccessToken::STATUS_EXPIRED,+ ])+ ->where([+ AccessToken::FIELD_STATUS => AccessToken::STATUS_ACTIVE,+ AccessToken::FIELD_EXPIRES_AT . '<=' => $this->dateTime->getNow()->toString(),+ ])+ ->build();++ $this->entityManager->getQueryExecutor()->execute($query);+ }++ public function expireRefreshTokens(): void+ {+ $query = UpdateBuilder::create()+ ->in(RefreshToken::ENTITY_TYPE)+ ->set([+ RefreshToken::FIELD_STATUS => RefreshToken::STATUS_EXPIRED,+ ])+ ->where([+ RefreshToken::FIELD_STATUS => RefreshToken::STATUS_ACTIVE,+ RefreshToken::FIELD_EXPIRES_AT . '<=' => $this->dateTime->getNow()->toString(),+ ])+ ->build();++ $this->entityManager->getQueryExecutor()->execute($query);+ }++ public function expireAuthorizationCodes(): void+ {+ $query = UpdateBuilder::create()+ ->in(AuthorizationCode::ENTITY_TYPE)+ ->set([+ AuthorizationCode::FIELD_STATUS => AuthorizationCode::STATUS_EXPIRED,+ ])+ ->where([+ AuthorizationCode::FIELD_STATUS => AuthorizationCode::STATUS_ACTIVE,+ AuthorizationCode::FIELD_EXPIRES_AT . '<=' => $this->dateTime->getNow()->toString(),+ ])+ ->build();++ $this->entityManager->getQueryExecutor()->execute($query);+ }+}diff --git a/application/Espo/Tools/OAuthServer/Jobs/OAuthServerControl.php b/application/Espo/Tools/OAuthServer/Jobs/OAuthServerControl.phpnew file mode 100644index 0000000000..20c8c17054--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Jobs/OAuthServerControl.php@@ -0,0 +1,51 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Jobs;++use Espo\Core\Job\JobDataLess;+use Espo\Tools\OAuthServer\ExpireService;++/**+ * @noinspection PhpUnused+ */+class OAuthServerControl implements JobDataLess+{+ public function __construct(+ private ExpireService $clientSecretExpireService,+ ) {}++ public function run(): void+ {+ $this->clientSecretExpireService->expireClientSecrets();+ $this->clientSecretExpireService->expireAccessTokens();+ $this->clientSecretExpireService->expireRefreshTokens();+ $this->clientSecretExpireService->expireAuthorizationCodes();+ }+}diff --git a/application/Espo/Tools/OAuthServer/League/AuthorizationRequestStorage.php b/application/Espo/Tools/OAuthServer/League/AuthorizationRequestStorage.phpnew file mode 100644index 0000000000..d372e362cd--- /dev/null+++ b/application/Espo/Tools/OAuthServer/League/AuthorizationRequestStorage.php@@ -0,0 +1,91 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\League;++use Espo\Core\Session\Session;+use Espo\Tools\OAuthServer\League\Entities\AuthCodeEntity;+use Espo\Tools\OAuthServer\League\Entities\ClientEntity;+use Espo\Tools\OAuthServer\League\Entities\ScopeEntity;+use InvalidArgumentException;+use League\OAuth2\Server\RequestTypes\AuthorizationRequest;+use League\OAuth2\Server\RequestTypes\AuthorizationRequestInterface;+use RuntimeException;++class AuthorizationRequestStorage+{+ public function __construct(+ private Session $session,+ ) {}++ public function store(string $clientId, AuthorizationRequestInterface $request): void+ {+ /** @noinspection PhpConditionAlreadyCheckedInspection */+ if (!$request instanceof AuthorizationRequest) {+ throw new InvalidArgumentException("Unsupported authorization request instance.");+ }++ $this->session->set(self::composeSessionKey($clientId), serialize($request));+ }++ public function get(string $clientId, bool $clear = false): ?AuthorizationRequest+ {+ $key = self::composeSessionKey($clientId);++ $raw = $this->session->get($key);++ if (!$raw) {+ return null;+ }++ if ($clear) {+ $this->session->clear($key);+ }++ $request = unserialize($raw, [+ 'allowed_classes' => [+ AuthorizationRequest::class,+ ClientEntity::class,+ ScopeEntity::class,+ AuthCodeEntity::class,+ ]+ ]);++ if (!$request instanceof AuthorizationRequest) {+ throw new RuntimeException("Unserialization error.");+ }++ return $request;+ }++ public static function composeSessionKey(string $clientId): string+ {+ return "oAuthServerAuthorizeRequest_" . $clientId;+ }+}diff --git a/application/Espo/Tools/OAuthServer/League/AuthorizationServerFactory.php b/application/Espo/Tools/OAuthServer/League/AuthorizationServerFactory.phpnew file mode 100644index 0000000000..9108743c3b--- /dev/null+++ b/application/Espo/Tools/OAuthServer/League/AuthorizationServerFactory.php@@ -0,0 +1,132 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\League;++use Espo\Core\Exceptions\Error;+use Espo\Tools\OAuthServer\League\Repositories\AccessTokenRepository;+use Espo\Tools\OAuthServer\League\Repositories\AuthCodeRepository;+use Espo\Tools\OAuthServer\League\Repositories\ClientRepository;+use Espo\Tools\OAuthServer\League\Repositories\RefreshTokenRepository;+use Espo\Tools\OAuthServer\League\Repositories\ScopeRepository;+use Espo\Tools\OAuthServer\Utils\CryptKeyProvider;+use Exception;++use League\OAuth2\Server\AuthorizationServer;+use League\OAuth2\Server\CryptKey;+use League\OAuth2\Server\Grant\AuthCodeGrant;+use League\OAuth2\Server\Grant\RefreshTokenGrant;++class AuthorizationServerFactory+{+ public function __construct(+ private ClientRepository $clientRepository,+ private AccessTokenRepository $accessTokenRepository,+ private ScopeRepository $scopeRepository,+ private AuthCodeRepository $authCodeRepository,+ private RefreshTokenRepository $refreshTokenRepository,+ private CryptKeyProvider $cryptKeyProvider,+ private ConfigDataProvider $configDataProvider,+ ) {}++ /**+ * @throws Error+ */+ public function create(): AuthorizationServer+ {+ $server = new AuthorizationServer(+ clientRepository: $this->clientRepository,+ accessTokenRepository: $this->accessTokenRepository,+ scopeRepository: $this->scopeRepository,+ privateKey: $this->createPrivateKeyStub(),+ encryptionKey: $this->cryptKeyProvider->getCryptKey(),+ );++ $server->revokeRefreshTokens(true);++ $this->enableAuthorizationCodeGrant($server);+ $this->enableRefreshTokenGrant($server);++ return $server;+ }++ /**+ * @throws Error+ */+ private function enableAuthorizationCodeGrant(AuthorizationServer $server): void+ {+ try {+ $grant = new AuthCodeGrant(+ authCodeRepository: $this->authCodeRepository,+ refreshTokenRepository: $this->refreshTokenRepository,+ authCodeTTL: $this->configDataProvider->getAuthorizationCodeTtl(),+ );+ } catch (Exception $e) {+ throw new Error("Error occurred.", previous: $e);+ }++ $server->enableGrantType(+ grantType: $grant,+ accessTokenTTL: $this->configDataProvider->getAccessTokenTtl(),+ );+ }++ /**+ * @throws Error+ */+ private function enableRefreshTokenGrant(AuthorizationServer $server): void+ {+ try {+ $grant = new RefreshTokenGrant($this->refreshTokenRepository);+ } catch (Exception $e) {+ throw new Error("Error occurred.", previous: $e);+ }++ $grant->setRefreshTokenTTL($this->configDataProvider->getRefreshTokenTtl());++ $server->enableGrantType(+ grantType: $grant,+ accessTokenTTL: $this->configDataProvider->getAccessTokenTtl(),+ );+ }++ /**+ * Access token encryption is not used. Opaque tokens are used.+ */+ private function createPrivateKeyStub(): CryptKey+ {+ return new class() extends CryptKey {++ /**+ * @noinspection PhpMissingParentConstructorInspection+ */+ public function __construct() {}+ };+ }+}diff --git a/application/Espo/Tools/OAuthServer/League/ConfigDataProvider.php b/application/Espo/Tools/OAuthServer/League/ConfigDataProvider.phpnew file mode 100644index 0000000000..459358c1d9--- /dev/null+++ b/application/Espo/Tools/OAuthServer/League/ConfigDataProvider.php@@ -0,0 +1,78 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\League;++use Espo\Core\Utils\Config;+use DateInterval;+use DateMalformedIntervalStringException;+use RuntimeException;++class ConfigDataProvider+{+ private const string AUTHORIZATION_CODE_TTL = 'PT10M';+ private const string ACCESS_TOKEN_TTL = 'PT1H';+ private const string REFRESH_TOKEN_TTL = 'P1M';++ public function __construct(+ private Config $config,+ ) {}++ public function getAuthorizationCodeTtl(): DateInterval+ {+ $interval = $this->config->get('oAuthServer.ttl.authorizationCode') ?? self::AUTHORIZATION_CODE_TTL;++ return self::convertIntervalToDateInterval($interval);+ }++ public function getAccessTokenTtl(): DateInterval+ {+ $interval = $this->config->get('oAuthServer.ttl.accessToken') ?? self::ACCESS_TOKEN_TTL;++ return self::convertIntervalToDateInterval($interval);+ }++ public function getRefreshTokenTtl(): DateInterval+ {+ $interval = $this->config->get('oAuthServer.ttl.refreshToken') ?? self::REFRESH_TOKEN_TTL;++ return self::convertIntervalToDateInterval($interval);+ }++ private static function convertIntervalToDateInterval(mixed $interval): DateInterval+ {+ try {+ $value = new DateInterval($interval);+ } catch (DateMalformedIntervalStringException $e) {+ throw new RuntimeException("Bad interval '$interval'.", previous: $e);+ }++ return $value;+ }+}diff --git a/application/Espo/Tools/OAuthServer/League/Entities/AccessTokenEntity.php b/application/Espo/Tools/OAuthServer/League/Entities/AccessTokenEntity.phpnew file mode 100644index 0000000000..67ee8bcf9c--- /dev/null+++ b/application/Espo/Tools/OAuthServer/League/Entities/AccessTokenEntity.php@@ -0,0 +1,146 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\League\Entities;++use DateTimeImmutable;+use Espo\Core\Field\DateTime;+use Espo\Core\Field\Link;+use Espo\Tools\OAuthServer\Entities\AccessToken;+use Espo\Tools\OAuthServer\Utils\IdentifierHasher;+use InvalidArgumentException;+use League\OAuth2\Server\CryptKeyInterface;+use League\OAuth2\Server\Entities\AccessTokenEntityInterface;+use League\OAuth2\Server\Entities\ClientEntityInterface;+use League\OAuth2\Server\Entities\ScopeEntityInterface;++class AccessTokenEntity implements AccessTokenEntityInterface+{+ public function __construct(+ private AccessToken $entity,+ private IdentifierHasher $hasher,+ ) {}++ public function toString(): string+ {+ return $this->entity->getIdentifier();+ }++ /**+ * @inheritDoc+ * @return void+ */+ public function setPrivateKey(CryptKeyInterface $privateKey): void+ {}++ public function __toString()+ {+ return $this->toString();+ }++ public function getIdentifier(): string+ {+ return $this->entity->getIdentifier();+ }++ public function setIdentifier(string $identifier): void+ {+ $this->entity->setIdentifier($identifier);++ $hash = $this->hasher->hash($identifier);++ $this->entity->setHash($hash);+ }++ public function getExpiryDateTime(): DateTimeImmutable+ {+ return $this->entity->getExpiresAt()->toDateTime();+ }++ public function setExpiryDateTime(DateTimeImmutable $dateTime): void+ {+ $this->entity->setExpiresAt(DateTime::fromDateTime($dateTime));+ }++ public function setUserIdentifier(string $identifier): void+ {+ $link = Link::create($identifier);++ $this->entity->setUser($link);+ }++ public function getUserIdentifier(): ?string+ {+ /** @var non-empty-string */+ return $this->entity->getUser()->getId();+ }++ public function getClient(): ClientEntityInterface+ {+ return ClientEntity::fromEntity($this->entity->getClient());+ }+++ public function setClient(ClientEntityInterface $client): void+ {+ /** @noinspection PhpConditionAlreadyCheckedInspection */+ if (!$client instanceof ClientEntity) {+ throw new InvalidArgumentException("Not supported client entity.");+ }++ $this->entity->setClient(Link::create($client->entityId));+ }+++ public function addScope(ScopeEntityInterface $scope): void+ {+ $scopes = $this->entity->getScopes();++ if (!in_array($scope->getIdentifier(), $scopes)) {+ $scopes[] = $scope->getIdentifier();+ }++ $this->entity->setScopes($scopes);+ }++ /**+ * @return ScopeEntityInterface[]+ */+ public function getScopes(): array+ {+ $scopes = $this->entity->getScopes();++ return array_map(fn ($scope) => new ScopeEntity($scope), $scopes);+ }++ public function getEntity(): AccessToken+ {+ return $this->entity;+ }+}diff --git a/application/Espo/Tools/OAuthServer/League/Entities/AuthCodeEntity.php b/application/Espo/Tools/OAuthServer/League/Entities/AuthCodeEntity.phpnew file mode 100644index 0000000000..7df3048bf3--- /dev/null+++ b/application/Espo/Tools/OAuthServer/League/Entities/AuthCodeEntity.php@@ -0,0 +1,42 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\League\Entities;++use League\OAuth2\Server\Entities\AuthCodeEntityInterface;+use League\OAuth2\Server\Entities\Traits\AuthCodeTrait;+use League\OAuth2\Server\Entities\Traits\EntityTrait;+use League\OAuth2\Server\Entities\Traits\TokenEntityTrait;++class AuthCodeEntity implements AuthCodeEntityInterface+{+ use EntityTrait;+ use AuthCodeTrait;+ use TokenEntityTrait;+}diff --git a/application/Espo/Tools/OAuthServer/League/Entities/ClientEntity.php b/application/Espo/Tools/OAuthServer/League/Entities/ClientEntity.phpnew file mode 100644index 0000000000..750f3bdd69--- /dev/null+++ b/application/Espo/Tools/OAuthServer/League/Entities/ClientEntity.php@@ -0,0 +1,87 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\League\Entities;++use Espo\Tools\OAuthServer\ClientType;+use Espo\Tools\OAuthServer\Entities\Client;+use League\OAuth2\Server\Entities\ClientEntityInterface;+use UnexpectedValueException;++class ClientEntity implements ClientEntityInterface+{+ /**+ * @param non-empty-string $identifier+ * @param string[] $redirectUri+ */+ public function __construct(+ public string $entityId,+ private string $identifier,+ private string $name,+ private array $redirectUri,+ private bool $isConfidential,+ ) {}++ public static function fromEntity(Client $entity): self+ {+ return new self(+ entityId: $entity->getId(),+ identifier: $entity->getIdentifier() ?? throw new UnexpectedValueException("No client identifier."),+ name: $entity->getName() ?? $entity->getId(),+ redirectUri: $entity->getRedirectUris(),+ isConfidential: $entity->getClientType() === ClientType::Confidential,+ );+ }++ /**+ * @return non-empty-string+ */+ public function getIdentifier(): string+ {+ return $this->identifier;+ }++ public function getName(): string+ {+ return $this->name;+ }++ /**+ * @return string[]+ */+ public function getRedirectUri(): array+ {+ return $this->redirectUri;+ }++ public function isConfidential(): bool+ {+ return $this->isConfidential;+ }+}diff --git a/application/Espo/Tools/OAuthServer/League/Entities/RefreshTokenEntity.php b/application/Espo/Tools/OAuthServer/League/Entities/RefreshTokenEntity.phpnew file mode 100644index 0000000000..a22212cf40--- /dev/null+++ b/application/Espo/Tools/OAuthServer/League/Entities/RefreshTokenEntity.php@@ -0,0 +1,40 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\League\Entities;++use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;+use League\OAuth2\Server\Entities\Traits\EntityTrait;+use League\OAuth2\Server\Entities\Traits\RefreshTokenTrait;++class RefreshTokenEntity implements RefreshTokenEntityInterface+{+ use RefreshTokenTrait;+ use EntityTrait;+}diff --git a/application/Espo/Tools/OAuthServer/League/Entities/ScopeEntity.php b/application/Espo/Tools/OAuthServer/League/Entities/ScopeEntity.phpnew file mode 100644index 0000000000..256f7a665b--- /dev/null+++ b/application/Espo/Tools/OAuthServer/League/Entities/ScopeEntity.php@@ -0,0 +1,53 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\League\Entities;++use League\OAuth2\Server\Entities\ScopeEntityInterface;+use League\OAuth2\Server\Entities\Traits\ScopeTrait;++class ScopeEntity implements ScopeEntityInterface+{+ use ScopeTrait;++ /**+ * @param non-empty-string $identifier+ */+ public function __construct(+ private string $identifier,+ ) {}++ /**+ * @return non-empty-string+ */+ public function getIdentifier(): string+ {+ return $this->identifier;+ }+}diff --git a/application/Espo/Tools/OAuthServer/League/Entities/UserEntity.php b/application/Espo/Tools/OAuthServer/League/Entities/UserEntity.phpnew file mode 100644index 0000000000..e0b3708fa6--- /dev/null+++ b/application/Espo/Tools/OAuthServer/League/Entities/UserEntity.php@@ -0,0 +1,55 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\League\Entities;++use Espo\Entities\User;+use League\OAuth2\Server\Entities\UserEntityInterface;+use LogicException;++class UserEntity implements UserEntityInterface+{+ public function __construct(+ private User $user,+ ) {+ if ($user->isSystem()) {+ // Extra safety measure.+ throw new LogicException();+ }+ }++ /**+ * @return non-empty-string+ */+ public function getIdentifier(): string+ {+ /** @var non-empty-string */+ return $this->user->getId();+ }+}diff --git a/application/Espo/Tools/OAuthServer/League/Repositories/AccessTokenRepository.php b/application/Espo/Tools/OAuthServer/League/Repositories/AccessTokenRepository.phpnew file mode 100644index 0000000000..f4011de86a--- /dev/null+++ b/application/Espo/Tools/OAuthServer/League/Repositories/AccessTokenRepository.php@@ -0,0 +1,124 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\League\Repositories;++use Espo\Core\Field\Link;+use Espo\ORM\EntityManager;+use Espo\Tools\OAuthServer\Entities\AccessToken;+use Espo\Tools\OAuthServer\League\Entities\AccessTokenEntity;+use Espo\Tools\OAuthServer\League\Entities\ClientEntity;+use Espo\Tools\OAuthServer\Repository\AccessTokenRepository as Repository;+use Espo\Tools\OAuthServer\Utils\IdentifierHasher;+use InvalidArgumentException;+use League\OAuth2\Server\Entities\AccessTokenEntityInterface;+use League\OAuth2\Server\Entities\ClientEntityInterface;+use League\OAuth2\Server\Entities\ScopeEntityInterface;+use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;+use SensitiveParameter;++class AccessTokenRepository implements AccessTokenRepositoryInterface+{+ public function __construct(+ private EntityManager $entityManager,+ private Repository $repository,+ private IdentifierHasher $hasher,+ ) {}++ /**+ * @param ScopeEntityInterface[] $scopes+ */+ public function getNewToken(+ ClientEntityInterface $clientEntity,+ array $scopes,+ ?string $userIdentifier = null,+ ): AccessTokenEntityInterface {++ $entity = $this->entityManager->getRDBRepositoryByClass(AccessToken::class)->getNew();++ /** @noinspection PhpConditionAlreadyCheckedInspection */+ if (!$clientEntity instanceof ClientEntity) {+ throw new InvalidArgumentException("Bad client.");+ }++ if (!$userIdentifier) {+ throw new InvalidArgumentException('No user ID.');+ }++ $entity->setClient(Link::create($clientEntity->entityId));++ $accessToken = new AccessTokenEntity($entity, $this->hasher);++ foreach ($scopes as $scope) {+ $accessToken->addScope($scope);+ }++ $accessToken->setUserIdentifier($userIdentifier);++ return $accessToken;+ }++ public function persistNewAccessToken(AccessTokenEntityInterface $accessTokenEntity): void+ {+ /** @noinspection PhpConditionAlreadyCheckedInspection */+ if (!$accessTokenEntity instanceof AccessTokenEntity) {+ throw new InvalidArgumentException("Not supported access token entity.");+ }++ $this->entityManager->saveEntity($accessTokenEntity->getEntity());+ }++ public function revokeAccessToken(#[SensitiveParameter] string $tokenId): void+ {+ $entity = $this->repository->getActiveByIdentifier($tokenId);++ if (!$entity || $entity->isRevoked()) {+ return;+ }++ $entity->setRevoked();++ $this->entityManager->saveEntity($entity);+ }++ /**+ * Not existent or inactive token is treated as revoked intentionally.+ */+ public function isAccessTokenRevoked(#[SensitiveParameter] string $tokenId): bool+ {+ $entity = $this->repository->getActiveByIdentifier($tokenId);++ if (!$entity) {+ return true;+ }++ // Intentionally.+ return !$entity->isActive();+ }+}diff --git a/application/Espo/Tools/OAuthServer/League/Repositories/AuthCodeRepository.php b/application/Espo/Tools/OAuthServer/League/Repositories/AuthCodeRepository.phpnew file mode 100644index 0000000000..12fdfc24bb--- /dev/null+++ b/application/Espo/Tools/OAuthServer/League/Repositories/AuthCodeRepository.php@@ -0,0 +1,119 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\League\Repositories;++use Espo\Core\Field\DateTime;+use Espo\Core\Field\Link;+use Espo\ORM\EntityManager;+use Espo\Tools\OAuthServer\Entities\AuthorizationCode;+use Espo\Tools\OAuthServer\League\Entities\AuthCodeEntity;+use Espo\Tools\OAuthServer\Repository\AuthorizationCodeRepository;+use Espo\Tools\OAuthServer\Repository\ClientRepository as ClientRepository;+use Espo\Tools\OAuthServer\Utils\IdentifierHasher;+use InvalidArgumentException;+use League\OAuth2\Server\Entities\AuthCodeEntityInterface;+use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface;+use RuntimeException;+use SensitiveParameter;++class AuthCodeRepository implements AuthCodeRepositoryInterface+{+ public function __construct(+ private EntityManager $entityManager,+ private AuthorizationCodeRepository $repository,+ private ClientRepository $clientRepository,+ private IdentifierHasher $hasher,+ ) {}++ public function getNewAuthCode(): AuthCodeEntity+ {+ return new AuthCodeEntity();+ }++ public function persistNewAuthCode(AuthCodeEntityInterface $authCodeEntity): void+ {+ $entity = $this->entityManager->getRDBRepositoryByClass(AuthorizationCode::class)->getNew();++ $userId = $authCodeEntity->getUserIdentifier();++ if (!is_string($userId)) {+ throw new InvalidArgumentException("User ID must be string.");+ }++ $scopes = array_map(fn ($scope) => $scope->getIdentifier(), $authCodeEntity->getScopes());++ $redirectUri = $authCodeEntity->getRedirectUri() ?? throw new InvalidArgumentException("No redirect URI");++ $clientId = $authCodeEntity->getClient()->getIdentifier();++ $client = $this->clientRepository->getActiveByIdentifier($clientId);++ if (!$client) {+ throw new RuntimeException("Client not found.");+ }++ $hash = $this->hasher->hash($authCodeEntity->getIdentifier());++ $entity+ ->setClient($client)+ ->setHash($hash)+ ->setUser(Link::create($userId))+ ->setScopes($scopes)+ ->setRedirectUri($redirectUri)+ ->setExpiresAt(DateTime::fromDateTime($authCodeEntity->getExpiryDateTime()));++ $this->entityManager->saveEntity($entity);+ }++ public function revokeAuthCode(#[SensitiveParameter] string $codeId): void+ {+ $code = $this->repository->getActiveByIdentifier($codeId);++ if (!$code || $code->isRevoked()) {+ return;+ }++ $code->setRevoked();++ $this->entityManager->saveEntity($code);+ }++ public function isAuthCodeRevoked(#[SensitiveParameter] string $codeId): bool+ {+ $entity = $this->repository->getActiveByIdentifier($codeId);++ if (!$entity) {+ return true;+ }++ // Intentionally.+ return !$entity->isActive();+ }+}diff --git a/application/Espo/Tools/OAuthServer/League/Repositories/ClientRepository.php b/application/Espo/Tools/OAuthServer/League/Repositories/ClientRepository.phpnew file mode 100644index 0000000000..6bf5f8347a--- /dev/null+++ b/application/Espo/Tools/OAuthServer/League/Repositories/ClientRepository.php@@ -0,0 +1,70 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\League\Repositories;++use Espo\Tools\OAuthServer\ClientValidator;+use Espo\Tools\OAuthServer\League\Entities\ClientEntity;+use Espo\Tools\OAuthServer\Repository\ClientRepository as Repository;+use League\OAuth2\Server\Repositories\ClientRepositoryInterface;+use SensitiveParameter;++class ClientRepository implements ClientRepositoryInterface+{+ public function __construct(+ private Repository $repository,+ private ClientValidator $clientValidator,+ ) {}++ public function getClientEntity(string $clientIdentifier): ?ClientEntity+ {+ $client = $this->repository->getActiveByIdentifier($clientIdentifier);++ if (!$client) {+ return null;+ }++ return ClientEntity::fromEntity($client);+ }++ public function validateClient(+ string $clientIdentifier,+ #[SensitiveParameter] ?string $clientSecret,+ ?string $grantType,+ ): bool {++ $client = $this->repository->getActiveByIdentifier($clientIdentifier);++ if (!$client) {+ return false;+ }++ return $this->clientValidator->validate($client, $clientSecret);+ }+}diff --git a/application/Espo/Tools/OAuthServer/League/Repositories/RefreshTokenRepository.php b/application/Espo/Tools/OAuthServer/League/Repositories/RefreshTokenRepository.phpnew file mode 100644index 0000000000..1d469a08e5--- /dev/null+++ b/application/Espo/Tools/OAuthServer/League/Repositories/RefreshTokenRepository.php@@ -0,0 +1,122 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\League\Repositories;++use Espo\Core\Field\DateTime;+use Espo\Core\Field\Link;+use Espo\ORM\EntityManager;+use Espo\Tools\OAuthServer\Entities\RefreshToken;+use Espo\Tools\OAuthServer\League\Entities\AccessTokenEntity;+use Espo\Tools\OAuthServer\League\Entities\RefreshTokenEntity;+use Espo\Tools\OAuthServer\Repository\ClientRepository as ClientRepositoryInternal;+use Espo\Tools\OAuthServer\Repository\RefreshTokenRepository as RefreshTokenRepositoryInternal;+use Espo\Tools\OAuthServer\Utils\IdentifierHasher;+use InvalidArgumentException;+use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;+use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;+use RuntimeException;+use SensitiveParameter;++class RefreshTokenRepository implements RefreshTokenRepositoryInterface+{+ public function __construct(+ private EntityManager $entityManager,+ private RefreshTokenRepositoryInternal $repository,+ private ClientRepositoryInternal $clientRepository,+ private IdentifierHasher $hasher,+ ) {}++ public function getNewRefreshToken(): RefreshTokenEntity+ {+ return new RefreshTokenEntity();+ }++ public function persistNewRefreshToken(RefreshTokenEntityInterface $refreshTokenEntity): void+ {+ $entity = $this->entityManager->getRDBRepositoryByClass(RefreshToken::class)->getNew();++ $userId = $refreshTokenEntity->getAccessToken()->getUserIdentifier();++ if (!is_string($userId)) {+ throw new InvalidArgumentException("User ID must be string.");+ }++ $clientId = $refreshTokenEntity->getAccessToken()->getClient()->getIdentifier();++ $client = $this->clientRepository->getActiveByIdentifier($clientId) ??+ throw new RuntimeException("Client not found.");++ $accessToken = $refreshTokenEntity->getAccessToken();++ /** @noinspection PhpConditionAlreadyCheckedInspection */+ if (!$accessToken instanceof AccessTokenEntity) {+ throw new InvalidArgumentException("Not supported access token implementation.");+ }++ $hash = $this->hasher->hash($refreshTokenEntity->getIdentifier());++ $entity+ ->setClient($client)+ ->setAccessToken($accessToken->getEntity())+ ->setHash($hash)+ ->setUser(Link::create($userId))+ ->setExpiresAt(DateTime::fromDateTime($refreshTokenEntity->getExpiryDateTime()));++ $this->entityManager->saveEntity($entity);+ }++ /**+ * @todo Delay?+ */+ public function revokeRefreshToken(#[SensitiveParameter] string $tokenId): void+ {+ $token = $this->repository->getActiveByIdentifier($tokenId);++ if (!$token || $token->isRevoked()) {+ return;+ }++ $token->setRevoked();++ $this->entityManager->saveEntity($token);+ }++ public function isRefreshTokenRevoked(#[SensitiveParameter] string $tokenId): bool+ {+ $entity = $this->repository->getActiveByIdentifier($tokenId);++ if (!$entity) {+ return true;+ }++ // Intentionally.+ return !$entity->isActive();+ }+}diff --git a/application/Espo/Tools/OAuthServer/League/Repositories/ScopeRepository.php b/application/Espo/Tools/OAuthServer/League/Repositories/ScopeRepository.phpnew file mode 100644index 0000000000..91a6bd98d8--- /dev/null+++ b/application/Espo/Tools/OAuthServer/League/Repositories/ScopeRepository.php@@ -0,0 +1,82 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\League\Repositories;++use Espo\Tools\OAuthServer\League\Entities\ScopeEntity;+use Espo\Tools\OAuthServer\Scope\UserAvailableScopesFilter;+use Espo\Tools\OAuthServer\Scope\ScopeValidator;+use League\OAuth2\Server\Entities\ClientEntityInterface;+use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;++class ScopeRepository implements ScopeRepositoryInterface+{+ public function __construct(+ private ScopeValidator $scopeValidator,+ private UserAvailableScopesFilter $userAvailableScopesProvider,+ ) {}++ /**+ * @param non-empty-string $identifier+ */+ public function getScopeEntityByIdentifier(string $identifier): ?ScopeEntity+ {+ if (!$this->scopeValidator->validate($identifier)) {+ return null;+ }++ return new ScopeEntity($identifier);+ }++ /**+ * @inheritDoc+ */+ public function finalizeScopes(+ array $scopes,+ ?string $grantType,+ ClientEntityInterface $clientEntity,+ ?string $userIdentifier = null,+ ?string $authCodeId = null,+ ): array {++ if (!$userIdentifier) {+ return $scopes;+ }++ $ids = array_map(fn ($it) => $it->getIdentifier(), $scopes);++ $availableIds = $this->userAvailableScopesProvider->filter($userIdentifier, $ids);++ $scopes = array_filter($scopes, function ($scope) use ($availableIds) {+ return in_array($scope->getIdentifier(), $availableIds);+ });++ return array_values($scopes);+ }+}diff --git a/application/Espo/Tools/OAuthServer/Login/OAuthLogin.php b/application/Espo/Tools/OAuthServer/Login/OAuthLogin.phpnew file mode 100644index 0000000000..8f8fa78e4d--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Login/OAuthLogin.php@@ -0,0 +1,116 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Login;++use Espo\Core\Api\Request;+use Espo\Core\Authentication\Login;+use Espo\Core\Authentication\Login\Data;+use Espo\Core\Authentication\Repository\UserRepository;+use Espo\Core\Authentication\Result;+use Espo\Core\Field\DateTime;+use Espo\Core\Utils\DateTime\Clock;+use Espo\Tools\OAuthServer\Repository\AccessTokenRepository;+use Espo\Tools\OAuthServer\Utils\ErrorResponseComposer;++/**+ * @noinspection PhpUnused+ */+class OAuthLogin implements Login+{+ private const string HEADER_AUTHORIZATION = 'Authorization';+ private const string SCHEME = 'Bearer';++ public function __construct(+ private AccessTokenRepository $repository,+ private Clock $clock,+ private UserRepository $userRepository,+ ) {}++ public function login(Data $data, Request $request): Result+ {+ $header = $request->getHeader(self::HEADER_AUTHORIZATION);++ $prefix = self::SCHEME . ' ';++ if (!$header || !str_starts_with($header, $prefix)) {+ return Result::fail(Result\FailReason::ERROR);+ }++ $opaqueToken = substr($header, strlen($prefix));++ $accessToken = $this->repository->getActiveByIdentifier($opaqueToken);++ if (!$accessToken) {+ $response = ErrorResponseComposer::compose(+ error: 'access_denied',+ errorDescription: 'Invalid access token.',+ );++ return Result::fail(Result\FailReason::WRONG_CREDENTIALS, $response);+ }++ $now = DateTime::fromDateTime($this->clock->now());++ if ($accessToken->getExpiresAt()->isLessThanOrEqualTo($now)) {+ $response = ErrorResponseComposer::compose(+ error: 'access_denied',+ errorDescription: 'The access token expired.',+ );++ return Result::fail(Result\FailReason::DENIED, $response);+ }++ if (!$accessToken->getClient()->isActive()) {+ $response = ErrorResponseComposer::compose(+ error: 'access_denied',+ errorDescription: 'The client is not active.',+ );++ return Result::fail(Result\FailReason::DENIED, $response);+ }++ $userLink = $accessToken->getUser();++ $user = $this->userRepository->findOneById($userLink->getId());++ if (!$user) {+ $response = ErrorResponseComposer::compose(+ error: 'access_denied',+ errorDescription: 'User not found.',+ );++ return Result::fail(Result\FailReason::DENIED, $response);+ }++ $user->setScopes($accessToken->getScopes());++ return Result::success($user);+ }+}diff --git a/application/Espo/Tools/OAuthServer/Record/MassActions/RevokeMassAction.php b/application/Espo/Tools/OAuthServer/Record/MassActions/RevokeMassAction.phpnew file mode 100644index 0000000000..3fd1de6159--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Record/MassActions/RevokeMassAction.php@@ -0,0 +1,136 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Record\MassActions;++use Espo\Core\Acl;+use Espo\Core\Exceptions\BadRequest;+use Espo\Core\Exceptions\Conflict;+use Espo\Core\Exceptions\Forbidden;+use Espo\Core\MassAction\Data;+use Espo\Core\MassAction\MassAction;+use Espo\Core\MassAction\Params;+use Espo\Core\MassAction\QueryBuilder;+use Espo\Core\MassAction\Result;+use Espo\Entities\User;+use Espo\ORM\Entity;+use Espo\ORM\EntityManager;+use Espo\Tools\OAuthServer\Entities\AccessToken;+use Espo\Tools\OAuthServer\Entities\AuthorizationCode;+use Espo\Tools\OAuthServer\Entities\RefreshToken;+use Espo\Tools\OAuthServer\Record\TokenService;+use RuntimeException;++/**+ * @noinspection PhpUnused+ */+class RevokeMassAction implements MassAction+{+ /**+ * @var string[]+ */+ private array $entityTypes = [+ AccessToken::ENTITY_TYPE,+ RefreshToken::ENTITY_TYPE,+ AuthorizationCode::ENTITY_TYPE,+ ];++ public function __construct(+ private TokenService $service,+ private User $user,+ private QueryBuilder $queryBuilder,+ private Acl $acl,+ private EntityManager $entityManager,+ ) {}++ public function process(Params $params, Data $data): Result+ {+ $entityType = $params->getEntityType();++ if (!in_array($entityType, $this->entityTypes)) {+ throw new BadRequest();+ }++ $this->assertAccess($entityType);++ $query = $this->queryBuilder->build($params);++ $collection = $this->entityManager->getRDBRepository($entityType)+ ->clone($query)+ ->sth()+ ->find();++ $ids = [];+ $count = 0;++ foreach ($collection as $entity) {+ try {+ $this->assertEntity($entity);++ /** @noinspection PhpParamsInspection */+ $this->service->revoke($entity);++ $ids[] = $entity->getId();+ $count ++;+ } catch (Conflict|Forbidden) {+ continue;+ }+ }++ return new Result($count, $ids);+ }++ /**+ * @throws Forbidden+ */+ private function assertAccess(string $entityType): void+ {+ if (!$this->user->isEffectiveAdmin()) {+ throw new Forbidden();+ }++ if (!$this->acl->check($entityType, Acl\Table::ACTION_EDIT)) {+ throw new Forbidden("No edit access.");+ }+ }++ /**+ * @phpstan-assert AccessToken|RefreshToken|AuthorizationCode $entity+ */+ private function assertEntity(Entity $entity): void+ {+ if (+ !$entity instanceof AccessToken &&+ !$entity instanceof RefreshToken &&+ !$entity instanceof AuthorizationCode+ ) {+ throw new RuntimeException();+ }+ }+}diff --git a/application/Espo/Tools/OAuthServer/Record/TokenService.php b/application/Espo/Tools/OAuthServer/Record/TokenService.phpnew file mode 100644index 0000000000..1dcc137346--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Record/TokenService.php@@ -0,0 +1,65 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Record;++use Espo\Core\Acl;+use Espo\Core\Exceptions\Conflict;+use Espo\Core\Exceptions\Forbidden;+use Espo\ORM\EntityManager;+use Espo\Tools\OAuthServer\Entities\AccessToken;+use Espo\Tools\OAuthServer\Entities\AuthorizationCode;+use Espo\Tools\OAuthServer\Entities\RefreshToken;++class TokenService+{+ public function __construct(+ private Acl $acl,+ private EntityManager $entityManager,+ ) {}++ /**+ * @throws Forbidden+ * @throws Conflict+ */+ public function revoke(AccessToken|RefreshToken|AuthorizationCode $token): void+ {+ if (!$this->acl->checkEntityEdit($token)) {+ throw new Forbidden("No edit access.");+ }++ if (!$token->isActive()) {+ throw new Conflict("Token is not active.");+ }++ $token->setRevoked();++ $this->entityManager->saveEntity($token);+ }+}diff --git a/application/Espo/Tools/OAuthServer/Repository/AccessTokenRepository.php b/application/Espo/Tools/OAuthServer/Repository/AccessTokenRepository.phpnew file mode 100644index 0000000000..380d8643da--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Repository/AccessTokenRepository.php@@ -0,0 +1,84 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Repository;++use Espo\ORM\SthCollection;+use Espo\Tools\OAuthServer\Utils\IdentifierHasher;+use Espo\ORM\EntityManager;+use Espo\Tools\OAuthServer\Entities\AccessToken;+use SensitiveParameter;++class AccessTokenRepository+{+ public function __construct(+ private EntityManager $entityManager,+ private IdentifierHasher $hasher,+ ) {}++ public function getActiveByIdentifier(#[SensitiveParameter] string $identifier): ?AccessToken+ {+ $hash = $this->hasher->hash($identifier);++ return $this->entityManager+ ->getRDBRepositoryByClass(AccessToken::class)+ ->where([+ AccessToken::FIELD_HASH => $hash,+ AccessToken::FIELD_STATUS => AccessToken::STATUS_ACTIVE,+ ])+ ->findOne();+ }++ public function getByIdentifier(#[SensitiveParameter] string $identifier): ?AccessToken+ {+ $hash = $this->hasher->hash($identifier);++ return $this->entityManager+ ->getRDBRepositoryByClass(AccessToken::class)+ ->where([+ AccessToken::FIELD_HASH => $hash,+ ])+ ->findOne();+ }++ /**+ * @return SthCollection<AccessToken>+ */+ public function findActiveForClientIdAndUser(string $clientId, string $userId): SthCollection+ {+ return $this->entityManager->getRDBRepositoryByClass(AccessToken::class)+ ->where([+ AccessToken::FIELD_STATUS => AccessToken::STATUS_ACTIVE,+ AccessToken::FIELD_CLIENT . 'Id' => $clientId,+ AccessToken::FIELD_USER . 'Id' => $userId,+ ])+ ->sth()+ ->find();+ }+}diff --git a/application/Espo/Tools/OAuthServer/Repository/AuthorizationCodeRepository.php b/application/Espo/Tools/OAuthServer/Repository/AuthorizationCodeRepository.phpnew file mode 100644index 0000000000..d660b1f3c8--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Repository/AuthorizationCodeRepository.php@@ -0,0 +1,56 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Repository;++use Espo\Tools\OAuthServer\Utils\IdentifierHasher;+use Espo\ORM\EntityManager;+use Espo\Tools\OAuthServer\Entities\AuthorizationCode;+use SensitiveParameter;++class AuthorizationCodeRepository+{+ public function __construct(+ private EntityManager $entityManager,+ private IdentifierHasher $hasher,+ ) {}++ public function getActiveByIdentifier(#[SensitiveParameter] string $identifier): ?AuthorizationCode+ {+ $hash = $this->hasher->hash($identifier);++ return $this->entityManager+ ->getRDBRepositoryByClass(AuthorizationCode::class)+ ->where([+ AuthorizationCode::FIELD_HASH => $hash,+ AuthorizationCode::FIELD_STATUS => AuthorizationCode::STATUS_ACTIVE,+ ])+ ->findOne();+ }+}diff --git a/application/Espo/Tools/OAuthServer/Repository/ClientRepository.php b/application/Espo/Tools/OAuthServer/Repository/ClientRepository.phpnew file mode 100644index 0000000000..ea01e3159f--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Repository/ClientRepository.php@@ -0,0 +1,109 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Repository;++use Espo\Core\Name\Field;+use Espo\ORM\EntityCollection;+use Espo\ORM\EntityManager;+use Espo\ORM\Name\Attribute;+use Espo\ORM\Query\Part\Condition as Cond;+use Espo\ORM\Query\Part\Expression as Expr;+use Espo\ORM\Query\SelectBuilder;+use Espo\Tools\OAuthServer\Entities\AccessToken;+use Espo\Tools\OAuthServer\Entities\Client;+use Espo\Tools\OAuthServer\Entities\RefreshToken;++class ClientRepository+{+ public function __construct(+ private EntityManager $entityManager,+ ) {}++ public function getActiveByIdentifier(string $identifier): ?Client+ {+ return $this->entityManager+ ->getRDBRepositoryByClass(Client::class)+ ->where([+ Client::FIELD_IDENTIFIER => $identifier,+ Client::FIELD_STATUS => Client::STATUS_ACTIVE,+ ])+ ->findOne();+ }++ public function getByIdentifier(string $identifier): ?Client+ {+ return $this->entityManager+ ->getRDBRepositoryByClass(Client::class)+ ->where([+ Client::FIELD_IDENTIFIER => $identifier,+ ])+ ->findOne();+ }++ /**+ * @return EntityCollection<Client>+ */+ public function findConnectedForUser(string $userId, int $limit): EntityCollection+ {+ return $this->entityManager->getRDBRepositoryByClass(Client::class)+ ->where(+ Cond::or(+ Cond::in(+ Expr::column(Attribute::ID),+ SelectBuilder::create()+ ->from(RefreshToken::ENTITY_TYPE)+ ->select([RefreshToken::FIELD_CLIENT . 'Id'])+ ->where([+ RefreshToken::FIELD_STATUS => RefreshToken::STATUS_ACTIVE,+ RefreshToken::FIELD_USER . 'Id' => $userId,+ ])+ ->build()+ ),+ Cond::in(+ Expr::column(Attribute::ID),+ SelectBuilder::create()+ ->from(AccessToken::ENTITY_TYPE)+ ->select([RefreshToken::FIELD_CLIENT . 'Id'])+ ->where([+ AccessToken::FIELD_STATUS => RefreshToken::STATUS_ACTIVE,+ AccessToken::FIELD_USER . 'Id' => $userId,+ ])+ ->build()+ ),+ )+ )+ ->where([+ Client::FIELD_IDENTIFIER . '!=' => null,+ ])+ ->order(Field::NAME)+ ->limit(0, $limit)+ ->find();+ }+}diff --git a/application/Espo/Tools/OAuthServer/Repository/RefreshTokenRepository.php b/application/Espo/Tools/OAuthServer/Repository/RefreshTokenRepository.phpnew file mode 100644index 0000000000..d8314f72b7--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Repository/RefreshTokenRepository.php@@ -0,0 +1,72 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Repository;++use Espo\ORM\SthCollection;+use Espo\Tools\OAuthServer\Utils\IdentifierHasher;+use Espo\ORM\EntityManager;+use Espo\Tools\OAuthServer\Entities\RefreshToken;+use SensitiveParameter;++class RefreshTokenRepository+{+ public function __construct(+ private EntityManager $entityManager,+ private IdentifierHasher $hasher,+ ) {}++ public function getActiveByIdentifier(#[SensitiveParameter] string $identifier): ?RefreshToken+ {+ $hash = $this->hasher->hash($identifier);++ return $this->entityManager+ ->getRDBRepositoryByClass(RefreshToken::class)+ ->where([+ RefreshToken::FIELD_HASH => $hash,+ RefreshToken::FIELD_STATUS => RefreshToken::STATUS_ACTIVE,+ ])+ ->findOne();+ }++ /**+ * @return SthCollection<RefreshToken>+ */+ public function findActiveForClientIdAndUser(string $clientId, string $userId): SthCollection+ {+ return $this->entityManager->getRDBRepositoryByClass(RefreshToken::class)+ ->where([+ RefreshToken::FIELD_STATUS => RefreshToken::STATUS_ACTIVE,+ RefreshToken::FIELD_CLIENT . 'Id' => $clientId,+ RefreshToken::FIELD_USER . 'Id' => $userId,+ ])+ ->sth()+ ->find();+ }+}diff --git a/application/Espo/Tools/OAuthServer/Revoke/Data.php b/application/Espo/Tools/OAuthServer/Revoke/Data.phpnew file mode 100644index 0000000000..56877fb3bc--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Revoke/Data.php@@ -0,0 +1,43 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Revoke;++use SensitiveParameter;++readonly class Data+{+ public function __construct(+ public string $clientId,+ #[SensitiveParameter]+ public ?string $clientSecret,+ public string $token,+ public ?string $tokenTypeHint,+ ) {}+}diff --git a/application/Espo/Tools/OAuthServer/Revoke/TokenRevokeService.php b/application/Espo/Tools/OAuthServer/Revoke/TokenRevokeService.phpnew file mode 100644index 0000000000..473df30b1e--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Revoke/TokenRevokeService.php@@ -0,0 +1,125 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Revoke;++use Espo\Core\Exceptions\Unauthorized;+use Espo\ORM\EntityManager;+use Espo\Tools\OAuthServer\ClientValidator;+use Espo\Tools\OAuthServer\Entities\Client;+use Espo\Tools\OAuthServer\Repository\AccessTokenRepository;+use Espo\Tools\OAuthServer\Repository\ClientRepository;+use Espo\Tools\OAuthServer\Repository\RefreshTokenRepository;+use Espo\Tools\OAuthServer\Utils\RefreshTokenDataExtractor;+use Exception;+use SensitiveParameter;++class TokenRevokeService+{+ public const string TYPE_ACCESS_TOKEN = 'access_token';+ public const string TYPE_REFRESH_TOKEN = 'refresh_token';++ public function __construct(+ private AccessTokenRepository $accessTokenRepository,+ private RefreshTokenRepository $refreshTokenRepository,+ private ClientRepository $clientRepository,+ private ClientValidator $clientValidator,+ private EntityManager $entityManager,+ private RefreshTokenDataExtractor $refreshTokenDataExtractor,+ ) {}++ /**+ * @throws Unauthorized+ */+ public function revoke(#[SensitiveParameter] Data $data): void+ {+ $tokenTypeHint = $data->tokenTypeHint;+ $token = $data->token;++ $client = $this->clientRepository->getActiveByIdentifier($data->clientId);++ if (!$client || !$this->clientValidator->validate($client, $data->clientSecret)) {+ throw new Unauthorized();+ }++ if (!$tokenTypeHint || $tokenTypeHint === self::TYPE_ACCESS_TOKEN) {+ $this->revokeAccessToken($token, $client);+ }++ if (!$tokenTypeHint || $tokenTypeHint === self::TYPE_REFRESH_TOKEN) {+ $this->revokeRefreshToken($token, $client);+ }+ }++ private function revokeAccessToken(#[SensitiveParameter] string $token, Client $client): void+ {+ $accessToken = $this->accessTokenRepository->getActiveByIdentifier($token);++ if (+ !$accessToken ||+ $accessToken->getClient()->getId() !== $client->getId()+ ) {+ return;+ }++ $accessToken->setRevoked();++ $this->entityManager->saveEntity($accessToken);+ }++ private function revokeRefreshToken(#[SensitiveParameter] string $token, Client $client): void+ {+ try {+ $identifier = $this->refreshTokenDataExtractor->extractIdentifier($token);+ } catch (Exception) {+ return;+ }++ $refreshToken = $this->refreshTokenRepository->getActiveByIdentifier($identifier);++ if (+ !$refreshToken ||+ $refreshToken->getClient()->getId() !== $client->getId()+ ) {+ return;+ }++ $accessToken = $refreshToken->getAccessToken();++ $refreshToken->setRevoked();++ $this->entityManager->saveEntity($refreshToken);++ if ($accessToken) {+ $accessToken->setRevoked();++ $this->entityManager->saveEntity($accessToken);+ }+ }+}diff --git a/application/Espo/Tools/OAuthServer/Scope/ScopeSorter.php b/application/Espo/Tools/OAuthServer/Scope/ScopeSorter.phpnew file mode 100644index 0000000000..61158349c4--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Scope/ScopeSorter.php@@ -0,0 +1,76 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Scope;++use Espo\Core\Acl\Scope;+use stdClass;++class ScopeSorter+{+ /**+ * @var array<string, int>+ */+ private array $priority = [+ Scope::GLOBAL => 0,+ Scope::ADMIN => 1,+ ];++ /**+ * @param (stdClass & object{name: string, label: string})[] $items+ * @return (stdClass & object{name: string, label: string})[]+ */+ public function sortDataItems(array $items): array+ {+ usort($items, function ($a, $b) {+ $aPriority = $this->priority[$a->name] ?? PHP_INT_MAX;+ $bPriority = $this->priority[$b->name] ?? PHP_INT_MAX;++ return $aPriority <=> $bPriority ?: strcasecmp($a->label, $b->label);+ });++ return $items;+ }++ /**+ * @param non-empty-string[] $scopes+ * @return non-empty-string[]+ */+ public function sort(array $scopes): array+ {+ usort($scopes, function ($a, $b) {+ $aPriority = $this->priority[$a] ?? PHP_INT_MAX;+ $bPriority = $this->priority[$b] ?? PHP_INT_MAX;++ return $aPriority <=> $bPriority ?: strcmp($a, $b);+ });++ return $scopes;+ }+}diff --git a/application/Espo/Tools/OAuthServer/Scope/ScopeValidator.php b/application/Espo/Tools/OAuthServer/Scope/ScopeValidator.phpnew file mode 100644index 0000000000..361ff37a98--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Scope/ScopeValidator.php@@ -0,0 +1,42 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Scope;++class ScopeValidator+{+ public function __construct(+ private ScopesProvider $scopesProvider,+ ) {}++ public function validate(string $scope): bool+ {+ return in_array($scope, $this->scopesProvider->get());+ }+}diff --git a/application/Espo/Tools/OAuthServer/Scope/ScopesProvider.php b/application/Espo/Tools/OAuthServer/Scope/ScopesProvider.phpnew file mode 100644index 0000000000..5975cb11af--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Scope/ScopesProvider.php@@ -0,0 +1,94 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Scope;++use Espo\Core\Acl\Scope;+use Espo\Core\Utils\Metadata;++/**+ * @since 10.1.0+ */+class ScopesProvider+{+ /**+ * @var string[]+ */+ private array $commonScopes = [+ Scope::ADMIN,+ Scope::GLOBAL,+ ];++ public function __construct(+ private Metadata $metadata,+ ) {}++ /**+ * @return string[]+ */+ public function get(): array+ {+ return [+ ...$this->commonScopes,+ ...$this->getAclScopes(),+ ];+ }++ /**+ * @return string[]+ */+ private function getAclScopes(): array+ {+ /**+ * @var array<string, array{+ * disabled?: bool,+ * acl?: mixed,+ * }> $scopesDefs+ */+ $scopesDefs = $this->metadata->get("scopes", []);++ $list = [];++ foreach ($scopesDefs as $scope => $defs) {+ if (+ ($defs['disabled'] ?? false) ||+ !($defs['acl'] ?? false) ||+ in_array($scope, $this->commonScopes)+ ) {+ continue;+ }++ $list[] = $scope;+ }++ sort($list);++ return $list;+ }+}diff --git a/application/Espo/Tools/OAuthServer/Scope/UserAvailableScopesFilter.php b/application/Espo/Tools/OAuthServer/Scope/UserAvailableScopesFilter.phpnew file mode 100644index 0000000000..946522bc53--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Scope/UserAvailableScopesFilter.php@@ -0,0 +1,68 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Scope;++use Espo\Core\Acl\Scope;+use Espo\Core\Utils\Acl\UserAclManagerProvider;+use Espo\Entities\User;+use Espo\ORM\EntityManager;++class UserAvailableScopesFilter+{+ public function __construct(+ private EntityManager $entityManager,+ private UserAclManagerProvider $aclManagerProvider,+ ) {}++ /**+ * @param string[] $scopes+ * @return string[]+ */+ public function filter(string $userId, array $scopes): array+ {+ $user = $this->entityManager->getRDBRepositoryByClass(User::class)->getById($userId);++ if (!$user) {+ return [];+ }++ $aclManager = $this->aclManagerProvider->get($user);++ $scopes = array_filter($scopes, function ($scope) use ($aclManager, $user) {+ if ($scope === Scope::GLOBAL) {+ return true;+ }++ return $aclManager->tryCheck($user, $scope);+ });++ return array_values($scopes);+ }+}diff --git a/application/Espo/Tools/OAuthServer/Secret/SecretValidator.php b/application/Espo/Tools/OAuthServer/Secret/SecretValidator.phpnew file mode 100644index 0000000000..d7212fcb66--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Secret/SecretValidator.php@@ -0,0 +1,79 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Secret;++use Espo\Core\Name\Field;+use Espo\Core\Utils\DateTime;+use Espo\Core\Utils\PasswordHash;+use Espo\ORM\EntityManager;+use Espo\ORM\Query\Part\Order;+use Espo\Tools\OAuthServer\Entities\Client;+use Espo\Tools\OAuthServer\Entities\ClientSecret;+use SensitiveParameter;++class SecretValidator+{+ public function __construct(+ private EntityManager $entityManager,+ private DateTime $dateTime,+ private PasswordHash $passwordHash,+ ) {}++ public function validate(Client $client, #[SensitiveParameter] string $secret): bool+ {+ $secrets = $this->entityManager+ ->getRDBRepositoryByClass(ClientSecret::class)+ ->sth()+ ->where([+ ClientSecret::ATTR_CLIENT_ID => $client->getId(),+ ClientSecret::FIELD_STATUS => ClientSecret::STATUS_ACTIVE,+ ])+ ->order(Field::CREATED_AT, Order::DESC)+ ->find();++ foreach ($secrets as $entry) {+ /** @noinspection PhpParamsInspection */+ if ($this->match($entry, $secret)) {+ return true;+ }+ }++ return false;+ }++ private function match(ClientSecret $entry, #[SensitiveParameter] string $secret): bool+ {+ if ($entry->getExpirationDate()?->isLessThanOrEqualTo($this->dateTime->getToday())) {+ return false;+ }++ return $this->passwordHash->verify($secret, $entry->getHash());+ }+}diff --git a/application/Espo/Tools/OAuthServer/Utils/Crypt.php b/application/Espo/Tools/OAuthServer/Utils/Crypt.phpnew file mode 100644index 0000000000..a20eb3e4d5--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Utils/Crypt.php@@ -0,0 +1,54 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Utils;++use Defuse\Crypto\Crypto;+use Defuse\Crypto\Exception\EnvironmentIsBrokenException;+use Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException;+use RuntimeException;+use SensitiveParameter;++class Crypt+{+ public function __construct(+ private CryptKeyProvider $keyProvider,+ ) {}++ public function decrypt(#[SensitiveParameter] string $value): string+ {+ $key = $this->keyProvider->getCryptKey();++ try {+ return Crypto::decryptWithPassword($value, $key);+ } catch (EnvironmentIsBrokenException|WrongKeyOrModifiedCiphertextException $e) {+ throw new RuntimeException(previous: $e);+ }+ }+}diff --git a/application/Espo/Tools/OAuthServer/Utils/CryptKeyProvider.php b/application/Espo/Tools/OAuthServer/Utils/CryptKeyProvider.phpnew file mode 100644index 0000000000..1950ae5f41--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Utils/CryptKeyProvider.php@@ -0,0 +1,65 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Utils;++use Espo\Core\Utils\Config;+use Random\RandomException;+use RuntimeException;++class CryptKeyProvider+{+ private const string PARAM_CRYPT_KEY = 'oAuthServerCryptKey';++ public function __construct(+ private Config $config,+ private Config\ConfigWriter $configWriter,+ ) {}++ public function getCryptKey(): string+ {+ if (!$this->config->has(self::PARAM_CRYPT_KEY)) {+ $this->configWriter->set(self::PARAM_CRYPT_KEY, $this->generateKey());+ $this->configWriter->save();+ }++ return $this->config->get(self::PARAM_CRYPT_KEY) ?? throw new RuntimeException("No crypt key.");+ }++ private function generateKey(): string+ {+ try {+ $key = bin2hex(random_bytes(32));+ } catch (RandomException $e) {+ throw new RuntimeException(previous: $e);+ }++ return $key;+ }+}diff --git a/application/Espo/Tools/OAuthServer/Utils/ErrorResponseComposer.php b/application/Espo/Tools/OAuthServer/Utils/ErrorResponseComposer.phpnew file mode 100644index 0000000000..23e1c02121--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Utils/ErrorResponseComposer.php@@ -0,0 +1,61 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Utils;++use Espo\Core\Api\Response;+use Espo\Core\Api\ResponseComposer;++class ErrorResponseComposer+{+ /**+ * @param ?int<400, 499> $statusCode+ */+ public static function compose(+ string $error,+ string $errorDescription,+ ?int $statusCode = null,+ ): Response {++ $header = "Bearer error=\"$error\", error_description=\"$errorDescription\"";++ $response = ResponseComposer::json([+ 'error' => $error,+ 'error_description' => $errorDescription,+ ]);++ if ($statusCode) {+ $response->setStatus($statusCode);+ }++ $response->setHeader('WWW-Authenticate', $header);++ return $response;+ }+}diff --git a/application/Espo/Tools/OAuthServer/Utils/IdentifierHasher.php b/application/Espo/Tools/OAuthServer/Utils/IdentifierHasher.phpnew file mode 100644index 0000000000..1b79147191--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Utils/IdentifierHasher.php@@ -0,0 +1,40 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Utils;++use SensitiveParameter;++class IdentifierHasher+{+ public function hash(#[SensitiveParameter] string $value): string+ {+ return hash('sha256', $value);+ }+}diff --git a/application/Espo/Tools/OAuthServer/Utils/RefreshTokenDataExtractor.php b/application/Espo/Tools/OAuthServer/Utils/RefreshTokenDataExtractor.phpnew file mode 100644index 0000000000..d75c1403bb--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Utils/RefreshTokenDataExtractor.php@@ -0,0 +1,66 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Utils;++use Espo\Core\Utils\Json;+use Exception;+use InvalidArgumentException;+use JsonException;+use SensitiveParameter;++class RefreshTokenDataExtractor+{+ public function __construct(+ private Crypt $crypt,+ ) {}++ public function extractIdentifier(#[SensitiveParameter] string $token): string+ {+ try {+ $decrypted = $this->crypt->decrypt($token);+ } catch (Exception) {+ throw new InvalidArgumentException("Could not decrypt.");+ }++ try {+ $tokenData = Json::decode($decrypted, true);+ } catch (JsonException) {+ throw new InvalidArgumentException("Could not JSON decode.");+ }++ $identifier = $tokenData['refresh_token_id'] ?? null;++ if (!is_string($identifier)) {+ throw new InvalidArgumentException("No identifier.");+ }++ return $identifier;+ }+}diff --git a/application/Espo/Tools/OAuthServer/Utils/UriUtil.php b/application/Espo/Tools/OAuthServer/Utils/UriUtil.phpnew file mode 100644index 0000000000..45e98e05a8--- /dev/null+++ b/application/Espo/Tools/OAuthServer/Utils/UriUtil.php@@ -0,0 +1,43 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\OAuthServer\Utils;++/**+ * @internal+ */+class UriUtil+{+ public static function makeRedirectUri(string $uri, string $state): string+ {+ $uri .= !str_contains($uri, '?') ? '?' : '&';++ return $uri . http_build_query(['state' => $state]);+ }+}diff --git a/application/Espo/Tools/Pipeline/PipelineDataUserFilter.php b/application/Espo/Tools/Pipeline/PipelineDataUserFilter.phpindex 247d5418ac..9232b083b9 100644--- a/application/Espo/Tools/Pipeline/PipelineDataUserFilter.php+++ b/application/Espo/Tools/Pipeline/PipelineDataUserFilter.php@@ -46,7 +46,7 @@ class PipelineDataUserFilter*/public function filter(array $data): array{- if ($this->user->isAdmin()) {+ if ($this->user->isEffectiveAdmin()) {return $data;}diff --git a/application/Espo/Tools/Stream/RecordService.php b/application/Espo/Tools/Stream/RecordService.phpindex df721fdc37..7b0d54c70a 100644--- a/application/Espo/Tools/Stream/RecordService.php+++ b/application/Espo/Tools/Stream/RecordService.php@@ -111,7 +111,7 @@ class RecordServicethrow new Forbidden();}- if ($entity instanceof User && !$this->user->isAdmin()) {+ if ($entity instanceof User && !$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Tools/User/Api/PutTeamUserPosition.php b/application/Espo/Tools/User/Api/PutTeamUserPosition.phpindex 0bd3dcf509..ac11f88342 100644--- a/application/Espo/Tools/User/Api/PutTeamUserPosition.php+++ b/application/Espo/Tools/User/Api/PutTeamUserPosition.php@@ -55,7 +55,7 @@ class PutTeamUserPosition implements Actionpublic function process(Request $request): Response{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Tools/UserSecurity/Api/DeleteConnectedApp.php b/application/Espo/Tools/UserSecurity/Api/DeleteConnectedApp.phpnew file mode 100644index 0000000000..f73e264246--- /dev/null+++ b/application/Espo/Tools/UserSecurity/Api/DeleteConnectedApp.php@@ -0,0 +1,88 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\UserSecurity\Api;++use Espo\Core\Api\Action;+use Espo\Core\Api\Request;+use Espo\Core\Api\Response;+use Espo\Core\Api\ResponseComposer;+use Espo\Core\Exceptions\BadRequest;+use Espo\Core\Exceptions\Forbidden;+use Espo\Core\Exceptions\NotFound;+use Espo\Core\Record\EntityProvider;+use Espo\Entities\User;+use Espo\Tools\OAuthServer\ConnectedApp\ConnectedAppService;+use Espo\Tools\OAuthServer\ConnectedApp\UserCheck;++/**+ * @noinspection PhpUnused+ */+class DeleteConnectedApp implements Action+{+ public function __construct(+ private EntityProvider $entityProvider,+ private User $user,+ private ConnectedAppService $oAuthService,+ private UserCheck $userCheck,+ ) {}++ /**+ * @inheritDoc+ */+ public function process(Request $request): Response+ {+ $user = $this->fetchUser($request);+ $appId = $request->getRouteParam('appId') ?? throw new BadRequest();++ $this->oAuthService->disconnect($user, $appId);++ return ResponseComposer::json(true);+ }++ /**+ * @throws BadRequest+ * @throws Forbidden+ * @throws NotFound+ */+ private function fetchUser(Request $request): User+ {+ $id = $request->getRouteParam('id') ?? throw new BadRequest();++ if ($id !== $this->user->getId() && !$this->user->isEffectiveAdmin()) {+ throw new Forbidden();+ }++ $user = $this->entityProvider->getByClass(User::class, $id);++ $this->userCheck->assert($user);++ return $user;+ }+}diff --git a/application/Espo/Tools/UserSecurity/Api/GetConnectedApps.php b/application/Espo/Tools/UserSecurity/Api/GetConnectedApps.phpnew file mode 100644index 0000000000..027bd4580c--- /dev/null+++ b/application/Espo/Tools/UserSecurity/Api/GetConnectedApps.php@@ -0,0 +1,94 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Tools\UserSecurity\Api;++use Espo\Core\Api\Action;+use Espo\Core\Api\Request;+use Espo\Core\Api\Response;+use Espo\Core\Api\ResponseComposer;+use Espo\Core\Exceptions\BadRequest;+use Espo\Core\Exceptions\Forbidden;+use Espo\Core\Exceptions\NotFound;+use Espo\Core\Record\EntityProvider;+use Espo\Entities\User;+use Espo\Tools\OAuthServer\ConnectedApp\AppData;+use Espo\Tools\OAuthServer\ConnectedApp\ConnectedAppService;+use Espo\Tools\OAuthServer\ConnectedApp\UserCheck;++/**+ * @noinspection PhpUnused+ */+class GetConnectedApps implements Action+{+ public function __construct(+ private EntityProvider $entityProvider,+ private User $user,+ private ConnectedAppService $oAuthService,+ private UserCheck $userCheck,+ ) {}++ /**+ * @inheritDoc+ */+ public function process(Request $request): Response+ {+ $user = $this->fetchUser($request);++ $apps = $this->oAuthService->getList($user);++ return ResponseComposer::json([+ 'list' => array_map(fn (AppData $it) => $it->toApiOutput(), $apps),+ 'user' => [+ 'id' => $user->getId(),+ 'name' => $user->getName() ?? $user->getId(),+ ],+ ]);+ }++ /**+ * @throws BadRequest+ * @throws Forbidden+ * @throws NotFound+ */+ private function fetchUser(Request $request): User+ {+ $id = $request->getRouteParam('id') ?? throw new BadRequest();++ if ($id !== $this->user->getId() && !$this->user->isEffectiveAdmin()) {+ throw new Forbidden();+ }++ $user = $this->entityProvider->getByClass(User::class, $id);++ $this->userCheck->assert($user);++ return $user;+ }+}diff --git a/application/Espo/Tools/UserSecurity/Api/GetUserAcl.php b/application/Espo/Tools/UserSecurity/Api/GetUserAcl.phpindex 0ed13e7096..19c0fcef56 100644--- a/application/Espo/Tools/UserSecurity/Api/GetUserAcl.php+++ b/application/Espo/Tools/UserSecurity/Api/GetUserAcl.php@@ -60,7 +60,7 @@ class GetUserAcl implements Action}if (- !$this->user->isAdmin() &&+ !$this->user->isEffectiveAdmin() &&$this->user->getId() !== $userId) {throw new Forbidden();diff --git a/application/Espo/Tools/UserSecurity/Api/PostApiKeyGenerate.php b/application/Espo/Tools/UserSecurity/Api/PostApiKeyGenerate.phpindex bc7d34960c..06b26e65df 100644--- a/application/Espo/Tools/UserSecurity/Api/PostApiKeyGenerate.php+++ b/application/Espo/Tools/UserSecurity/Api/PostApiKeyGenerate.php@@ -50,7 +50,7 @@ class PostApiKeyGenerate implements Actionpublic function process(Request $request): Response{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Tools/UserSecurity/Api/PostPasswordGenerate.php b/application/Espo/Tools/UserSecurity/Api/PostPasswordGenerate.phpindex f167dea29e..49ebb8152b 100644--- a/application/Espo/Tools/UserSecurity/Api/PostPasswordGenerate.php+++ b/application/Espo/Tools/UserSecurity/Api/PostPasswordGenerate.php@@ -50,7 +50,7 @@ class PostPasswordGenerate implements Actionpublic function process(Request $request): Response{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Tools/UserSecurity/Api/PostPasswordRecovery.php b/application/Espo/Tools/UserSecurity/Api/PostPasswordRecovery.phpindex e6e8ef3026..c022cbe14a 100644--- a/application/Espo/Tools/UserSecurity/Api/PostPasswordRecovery.php+++ b/application/Espo/Tools/UserSecurity/Api/PostPasswordRecovery.php@@ -50,7 +50,7 @@ class PostPasswordRecovery implements Actionpublic function process(Request $request): Response{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Tools/UserSecurity/ApiService.php b/application/Espo/Tools/UserSecurity/ApiService.phpindex 91f4160066..5059c31595 100644--- a/application/Espo/Tools/UserSecurity/ApiService.php+++ b/application/Espo/Tools/UserSecurity/ApiService.php@@ -59,7 +59,7 @@ class ApiService*/public function generateNewApiKey(string $id): User{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Tools/UserSecurity/Password/Service.php b/application/Espo/Tools/UserSecurity/Password/Service.phpindex 52c2bc3d91..965a76344f 100644--- a/application/Espo/Tools/UserSecurity/Password/Service.php+++ b/application/Espo/Tools/UserSecurity/Password/Service.php@@ -75,7 +75,7 @@ class Service*/public function createAndSendPasswordRecovery(string $id): void{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}@@ -260,7 +260,7 @@ class Service*/public function generateAndSendNewPasswordForUser(string $id): void{- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {throw new Forbidden();}diff --git a/application/Espo/Tools/UserSecurity/Service.php b/application/Espo/Tools/UserSecurity/Service.phpindex 6346573dba..5ca2703503 100644--- a/application/Espo/Tools/UserSecurity/Service.php+++ b/application/Espo/Tools/UserSecurity/Service.php@@ -64,7 +64,7 @@ class Service*/public function read(string $id): stdClass{- if (!$this->user->isAdmin() && $id !== $this->user->getId()) {+ if (!$this->user->isEffectiveAdmin() && $id !== $this->user->getId()) {throw new Forbidden();}@@ -104,7 +104,7 @@ class Servicepublic function getTwoFactorUserSetupData(string $id, stdClass $data): stdClass{if (- !$this->user->isAdmin() &&+ !$this->user->isEffectiveAdmin() &&$id !== $this->user->getId()) {throw new Forbidden();@@ -137,11 +137,11 @@ class Servicethrow new Forbidden('Passport required.');}- if (!$this->user->isAdmin()) {+ if (!$this->user->isEffectiveAdmin()) {$this->checkPassword($id, $password);}- if ($this->user->isAdmin()) {+ if ($this->user->isEffectiveAdmin()) {$this->checkPassword($this->user->getId(), $password);}@@ -187,7 +187,7 @@ class Service*/public function update(string $id, stdClass $data): stdClass{- if (!$this->user->isAdmin() && $id !== $this->user->getId()) {+ if (!$this->user->isEffectiveAdmin() && $id !== $this->user->getId()) {throw new Forbidden();}@@ -219,7 +219,7 @@ class Servicethrow new Forbidden('Password required.');}- if (!$this->user->isAdmin() || $this->user->getId() === $id) {+ if (!$this->user->isEffectiveAdmin() || $this->user->getId() === $id) {$this->checkPassword($id, $password);}diff --git a/application/Espo/Tools/UserSecurity/TwoFactor/EmailService.php b/application/Espo/Tools/UserSecurity/TwoFactor/EmailService.phpindex bb4630ba39..4246255553 100644--- a/application/Espo/Tools/UserSecurity/TwoFactor/EmailService.php+++ b/application/Espo/Tools/UserSecurity/TwoFactor/EmailService.php@@ -54,7 +54,7 @@ class EmailService*/public function sendCode(string $userId, string $emailAddress): void{- if (!$this->user->isAdmin() && $userId !== $this->user->getId()) {+ if (!$this->user->isEffectiveAdmin() && $userId !== $this->user->getId()) {throw new Forbidden();}diff --git a/application/Espo/Tools/UserSecurity/TwoFactor/SmsService.php b/application/Espo/Tools/UserSecurity/TwoFactor/SmsService.phpindex fc47cc5082..2a09d5b321 100644--- a/application/Espo/Tools/UserSecurity/TwoFactor/SmsService.php+++ b/application/Espo/Tools/UserSecurity/TwoFactor/SmsService.php@@ -54,7 +54,7 @@ class SmsService*/public function sendCode(string $userId, string $phoneNumber): void{- if (!$this->user->isAdmin() && $userId !== $this->user->getId()) {+ if (!$this->user->isEffectiveAdmin() && $userId !== $this->user->getId()) {throw new Forbidden();}diff --git a/client/src/collections/o-auth-client-secret.ts b/client/src/collections/o-auth-client-secret.tsnew file mode 100644index 0000000000..7fc455b35b--- /dev/null+++ b/client/src/collections/o-auth-client-secret.ts@@ -0,0 +1,50 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++import Collection from 'collection';+import {CreatedSecrets} from 'helpers/misc/o-auth-client-secret';++// noinspection JSUnusedGlobalSymbols+export default class OAuthClientSecretCollection extends Collection {++ protected prepareAttributes(+ response: Record<string, any>[] | Record<string, any>,+ options: Record<string, any>+ ): Record<string, any>[] {++ const items = super.prepareAttributes(response, options);++ for (const item of items) {+ if (item.id && CreatedSecrets[item.id]) {+ item.value = CreatedSecrets[item.id];+ }+ }++ return items;+ }+}diff --git a/client/src/controllers/admin.js b/client/src/controllers/admin.jsindex a7120c0e09..b8fd4a25df 100644--- a/client/src/controllers/admin.js+++ b/client/src/controllers/admin.js@@ -244,6 +244,11 @@ class AdminController extends Controller {this.getRouter().dispatch('AuthenticationProvider', 'list', {fromAdmin: true});}+ // noinspection JSUnusedGlobalSymbols+ actionOAuthClients() {+ this.getRouter().dispatch('OAuthClient', 'list', {fromAdmin: true});+ }+// noinspection JSUnusedGlobalSymbolsactionAddressCountries() {this.getRouter().dispatch('AddressCountry', 'list', {fromAdmin: true});diff --git a/client/src/controllers/o-auth-authorize.js b/client/src/controllers/o-auth-authorize.jsnew file mode 100644index 0000000000..89ee627452--- /dev/null+++ b/client/src/controllers/o-auth-authorize.js@@ -0,0 +1,42 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++import Controller from 'controller';+import AuthorizationConsentView from 'views/o-auth-server/authorization-consent';++// noinspection JSUnusedGlobalSymbols+export default class OAuthAuthorizeController extends Controller {++ // noinspection JSUnusedGlobalSymbols+ actionShow() {+ const view = new AuthorizationConsentView();++ this.entire(view);+ }+}+diff --git a/client/src/controllers/user.js b/client/src/controllers/user.jsindex 2b423b4639..67af2b40ed 100644--- a/client/src/controllers/user.js+++ b/client/src/controllers/user.js@@ -27,6 +27,9 @@************************************************************************/import RecordController from 'controllers/record';+import Ui from 'ui';+import Ajax from 'ajax';+import UserConnectedAppsView from 'views/user/connected-apps';class UserController extends RecordController {@@ -68,6 +71,24 @@ class UserController extends RecordController {super.createViewView(options, model, view);}++ // noinspection JSUnusedGlobalSymbols+ /**+ * @param {{+ * id?: string,+ * }} options+ */+ async actionListConnectedApps(options) {+ if (!options.id) {+ throw new Error("No user ID.");+ }++ const view = new UserConnectedAppsView({+ id: options.id,+ });++ this.main(view);+ }}export default UserController;diff --git a/client/src/handlers/o-auth-access-token/revoke-mass-action.ts b/client/src/handlers/o-auth-access-token/revoke-mass-action.tsnew file mode 100644index 0000000000..f67bb7ddc9--- /dev/null+++ b/client/src/handlers/o-auth-access-token/revoke-mass-action.ts@@ -0,0 +1,74 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++import ActionHandler from 'action-handler';+import MassActionHelper from 'helpers/mass-action';+import ListRecordView from 'views/record/list';+import Ui from 'ui';+import Ajax from 'ajax';++/**+ * Important. Used for AccessToken, RefreshToken, AuthorizationCode.+ */+// noinspection JSUnusedGlobalSymbols+export default class RevokeMassActionHandler extends ActionHandler {++ async process() {+ const view = this.view as ListRecordView;++ const helper = new MassActionHelper(this.view);+ const params = view.getMassActionSelectionPostData();+ const idle = !!params.searchParams && helper.checkIsIdle(view.collection.total);++ const onDone = (count: number) => {+ const msg = this.view.translate('massRevokeDone', 'messages', 'OAuthAccessToken')+ .replace('{count}', count.toString());++ Ui.success(msg);+ };++ Ui.notifyWait();++ const result = await Ajax.postRequest('MassAction', {+ entityType: view.collection.entityType!,+ action: 'revoke',+ params: params,+ idle: idle,+ });++ if (result.id) {+ const view = await helper.process(result.id, 'revoke')++ this.view.listenToOnce(view, 'close:success', result => onDone(result.count));++ return;+ }++ onDone(result.count);+ }+}diff --git a/client/src/handlers/o-auth-access-token/revoke-row-action.ts b/client/src/handlers/o-auth-access-token/revoke-row-action.tsnew file mode 100644index 0000000000..e634bd096d--- /dev/null+++ b/client/src/handlers/o-auth-access-token/revoke-row-action.ts@@ -0,0 +1,58 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++import RowActionHandler from 'handlers/row-action';+import Model from 'model';+import Ajax from 'ajax';+import Ui from 'ui';+import {inject} from 'di';+import Language from 'language';++/**+ * Important. Used for AccessToken, RefreshToken, AuthorizationCode.+ */+// noinspection JSUnusedGlobalSymbols+export default class RevokeRowActionHandler extends RowActionHandler {++ @inject(Language)+ private language: Language++ async process(model: Model, _action: string) {+ Ui.notifyWait();++ await Ajax.postRequest(`${model.entityType}/${model.id}/revoke`);++ await model.fetch();++ Ui.success(this.language.translate('Done'));+ }++ isAvailable(model: Model, _action: string): boolean {+ return model.attributes.status === 'Active';+ }+}diff --git a/client/src/helpers/misc/o-auth-client-secret.ts b/client/src/helpers/misc/o-auth-client-secret.tsnew file mode 100644index 0000000000..17477d56b6--- /dev/null+++ b/client/src/helpers/misc/o-auth-client-secret.ts@@ -0,0 +1,34 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++const values: Record<string, string> = {};++/**+ * @internal+ */+export {values as CreatedSecrets};diff --git a/client/src/models/o-auth-client-secret.ts b/client/src/models/o-auth-client-secret.tsnew file mode 100644index 0000000000..955cf5ed2f--- /dev/null+++ b/client/src/models/o-auth-client-secret.ts@@ -0,0 +1,54 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++import Model from 'model';++import {CreatedSecrets} from 'helpers/misc/o-auth-client-secret';++// noinspection JSUnusedGlobalSymbols+export default class OAuthClientSecretModel extends Model<{+ value: string;+}> {++ prepareAttributes(response: any, options: Record<string, any>): any {+ const attributes = super.prepareAttributes(response, options) as Record<string, any>;++ const id = attributes.id;+ const value = attributes.value as string | undefined;++ if (id) {+ if (value != null) {+ CreatedSecrets[id] = value;+ } else if (id in CreatedSecrets) {+ attributes.value = CreatedSecrets[id];+ }+ }++ return attributes;+ }+}diff --git a/client/src/models/user.js b/client/src/models/user.jsindex 51250abc58..ac5e02b688 100644--- a/client/src/models/user.js+++ b/client/src/models/user.js@@ -92,6 +92,28 @@ class User extends Model {isSuperAdmin() {return this.get('type') === 'super-admin';}++ /**+ * Is admin and is not stripped of admin capabilities.+ *+ * @return {boolean}+ *+ * @since 10.1.0+ */+ isEffectiveAdmin() {+ if (!this.isAdmin()) {+ return false;+ }++ /** @type {string[]|null} */+ const scopes = this.attributes.scopes;++ if (scopes == null) {+ return true;+ }++ return scopes.includes('Admin');+ }}export default User;diff --git a/client/src/views/o-auth-client-secret/fields/value.ts b/client/src/views/o-auth-client-secret/fields/value.tsnew file mode 100644index 0000000000..b18de7c0b5--- /dev/null+++ b/client/src/views/o-auth-client-secret/fields/value.ts@@ -0,0 +1,94 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++import VarcharFieldView from 'views/fields/varchar';+import Model from 'model';++export default class OAuthClientSecretValueField extends VarcharFieldView<{+ model: Model<{+ value: string | null,+ name: string | null,+ }>+}> {++ // noinspection JSUnusedGlobalSymbols+ protected listLinkTemplateContent = `+ {{~#if copyToClipboard~}}+ <a+ role="button"+ data-action="copyToClipboard"+ class="pull-right text-soft"+ title="{{translate 'Copy to Clipboard'}}"+ ><span class="far fa-copy"></span></a>+ {{~/if~}}+ <a+ href="#{{scope}}/view/{{model.id}}"+ class="link"+ data-id="{{model.id}}"+ title="{{value}}"+ >{{#if value}}{{value}}{{else}}{{translate 'None'}}{{/if}}</a>+ `+ protected getAttributeList(): string[] {+ return [+ ...super.getAttributeList(),+ 'name',+ ];+ }++ protected data() {+ const data = super.data();++ return {+ ...data,+ isNotEmpty: data.isNotEmpty || this.model.attributes.name != null,+ valueIsSet: data.valueIsSet || this.model.attributes.name != null,+ };+ }++ protected setup() {+ this.model.onChange({+ owner: this,+ attributes: ['hasValue'],+ callback: () => {+ this.params.copyToClipboard = !!this.model.attributes.value;+ },+ });++ this.params.copyToClipboard = !!this.model.attributes.value;++ super.setup();+ }++ protected getValueForDisplay(): string | null | undefined {+ if (this.model.attributes.value) {+ return this.model.attributes.value;+ }++ return this.model.attributes.name;+ }+}diff --git a/client/src/views/o-auth-client/fields/scopes.ts b/client/src/views/o-auth-client/fields/scopes.tsnew file mode 100644index 0000000000..357908eca3--- /dev/null+++ b/client/src/views/o-auth-client/fields/scopes.ts@@ -0,0 +1,67 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++import ArrayFieldView from 'views/fields/array';++export default class OAuthClientScopesFieldView extends ArrayFieldView {++ private commonScopes = [+ 'Global',+ 'Admin',+ ]++ protected setupOptions() {+ this.params.options = [+ ...this.commonScopes,+ ...this.getAclScopes(),+ ];+ }++ private getAclScopes(): string[] {+ const scopesDefs = this.getMetadata().get('scopes', []) as+ {disabled?: boolean, acl?: any}[];++ const list: string[] = [];++ for (const [scope, defs] of Object.entries(scopesDefs)) {+ if (+ defs.disabled ||+ !defs.acl ||+ this.commonScopes.includes(scope)+ ) {+ continue;+ }++ list.push(scope);+ }++ list.sort((a, b) => a.localeCompare(b));++ return list;+ }+}diff --git a/client/src/views/o-auth-server/authorization-consent.ts b/client/src/views/o-auth-server/authorization-consent.tsnew file mode 100644index 0000000000..2202f2782a--- /dev/null+++ b/client/src/views/o-auth-server/authorization-consent.ts@@ -0,0 +1,161 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++import View from 'view';+import Ajax from 'ajax';+import Ui from 'ui';++// noinspection JSUnusedGlobalSymbols+export default class AuthorizationConsentView extends View<{+ options: {}+}> {++ // language=Handlebars+ protected templateContent = `+ <div class="block-center-5 margin-top">+ <div class="panel panel-default">+ <div class="panel-body">+ <div class="alert alert-info margin-bottom-2x">+ {{complexText labels.info}}+ </div>+ <ul class="list-group">+ {{#each scopeDataList}}+ <li class="list-group-item">+ {{label}}+ {{#if description}}+ <div class="small text-soft">{{description}}</div>+ {{/if}}+ </li>+ {{/each}}+ </ul>+ <div class="margin-top-2x center-align">+ <form+ method="post"+ action="{{actionEndpoint}}"+ >+ <input type="hidden" name="clientId" value="{{clientId}}">+ <input type="hidden" name="approved">+ <input type="hidden" name="scopes" value="{{scopes}}">+ <button+ type="button"+ class="btn btn-danger btn-x-wide pull-left"+ data-action="allow"+ >{{labels.allow}}</button>+ <button+ type="button"+ class="btn btn-default btn-x-wide pull-right"+ data-action="cancel"+ >{{labels.cancel}}</button>+ </form>+ </div>+ </div>+ </div>+ </div>+ `++ params: {+ clientId: string,+ }++ consentData: {+ scopeDataList: {+ name: string,+ label: string,+ description: string | null,+ }[],+ labels: Record<string, string>,+ }++ protected data() {+ const scopes = this.consentData.scopeDataList+ .map(it => it.name)+ .join(' ');++ return {+ ...this.consentData,+ actionEndpoint: this.getBasePath() + '?entryPoint=oAuthAuthorizeComplete',+ clientId: this.params.clientId,+ scopes,+ };+ }++ protected setup() {+ this.addActionHandler('allow', () => this.handleAllow());+ this.addActionHandler('cancel', () => this.handleCancel());++ const params = new URLSearchParams(window.location.search);++ const clientId = params.get('client_id');++ if (!clientId) {+ throw new Error("No client_id.");+ }++ this.params = {+ clientId: clientId,+ };++ this.wait(this.loadData());+ }++ private async loadData() {+ Ui.notifyWait();++ this.consentData = await Ajax.getRequest(`OAuthServer/consentData`, {+ clientId: this.params.clientId,+ }) as AuthorizationConsentView['consentData'];++ Ui.notify();+ }++ private handleAllow() {+ this.handleComplete(true);+ }++ private handleCancel() {+ this.handleComplete(false);+ }++ private handleComplete(approved: boolean) {+ const formElement = this.element.querySelector('form');++ if (!formElement) {+ throw new Error();+ }++ const approvedElement = this.element.querySelector<HTMLInputElement>('input[name="approved"]');++ if (!approvedElement) {+ throw new Error();+ }++ approvedElement.value = approved ? 'true' : 'false';++ formElement.submit();+ }+}diff --git a/client/src/views/user/connected-apps.ts b/client/src/views/user/connected-apps.tsnew file mode 100644index 0000000000..6c72794c1a--- /dev/null+++ b/client/src/views/user/connected-apps.ts@@ -0,0 +1,189 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++import View from 'view';+import Ajax from 'ajax';+import Ui from 'ui';++interface Item {+ id: string;+ name: string;+}++export default class UserConnectedAppsView extends View<{+ options: {+ id: string,+ }+}> {++ // language=Handlebars+ protected templateContent = `+ <div class="header page-header">+ <h3>+ <a href="#User">{{translate 'User' category='scopeNamesPlural'}}</a>+ <span class="breadcrumb-separator"><span></span></span>+ <a href="#User/view/{{user.id}}">{{user.name}}</a>+ <span class="breadcrumb-separator"><span></span></span>+ <span>{{translate 'Connected Apps' scope='User'}}</span>+ </h3>+ </div>+ <div>{{{record}}}</div>+ `++ recordData: {+ user: {+ id: string,+ name: string,+ },+ list: Item[]+ }++ protected data(): {[p: string]: any} {+ return {+ user: this.recordData.user,+ };+ }++ protected setup() {++ this.wait((async () => {+ await this.fetchData();++ const state: {list: Item[]} = {+ list: this.recordData.list,+ };++ const recordView = new RecordView({+ state: state,+ user: {+ id: this.options.id,+ },+ onUpdate: async () => {+ await this.fetchData();++ state.list = this.recordData.list;++ await recordView.reRender();++ Ui.success(this.translate('Done'));+ },+ });++ await this.assignView('record', recordView);+ })());+ }++ private async fetchData() {+ Ui.notifyWait();++ this.recordData = await Ajax.getRequest(`User/${this.options.id}/connectedApps`);++ Ui.notify();+ }+}++class RecordView extends View<{+ options: {+ user: {+ id: string,+ },+ state: {+ list: Item[],+ },+ onUpdate: () => {},+ },+}> {++ // language=Handlebars+ protected templateContent = `+ {{#if list.length}}+ <ul class="list-group list-group-panel" style="max-width: var(--600px)">+ {{#each list}}+ <li class="list-group-item">+ <div style="display: flex;">+ <div class="detail-field-container">{{name}}</div>+ <div style="margin-inline-start: auto;">+ <button+ class="btn btn-default"+ data-action="disconnect"+ data-id="{{id}}"+ {{#if ../isDisabled}}+ disabled="disabled"+ {{/if}}+ >{{translate 'Disconnect'}}</button>+ </div>+ </div>+ </li>+ {{/each}}+ </ul>+ {{else}}+ <div class="no-data">{{translate 'No Data'}}</div>+ {{/if}}+ `++ isDisabled: boolean = false++ protected data(): Record<string, any> {+ return {+ isDisabled: this.isDisabled,+ list: this.options.state.list,+ };+ }++ protected setup() {+ this.addActionHandler('disconnect', (_, target) => {+ const id = target.dataset.id as string;++ this.handleDisconnect(id);+ });+ }++ private async handleDisconnect(id: string) {+ this.isDisabled = true;++ await this.reRender();++ Ui.notifyWait();++ try {+ await Ajax.deleteRequest(`User/${this.options.user.id}/connectedApps/${id}`);+ } catch (e) {+ this.isDisabled = false;+ await this.reRender();++ return;+ }++ Ui.notify();++ this.isDisabled = false;+ await this.reRender();++ this.options.onUpdate();+ }+}diff --git a/client/src/views/user/detail.js b/client/src/views/user/detail.jsindex a8de48033d..ca40909fbe 100644--- a/client/src/views/user/detail.js+++ b/client/src/views/user/detail.js@@ -106,6 +106,18 @@ export default class extends DetailView {hidden: !showActivities,})}++ if (+ (this.getUserModel().isRegular() || this.getUserModel().isAdmin()) &&+ (this.getUser().id === this.getUserModel().id || this.getUser().isAdmin())+ ) {+ this.addMenuItem('dropdown', {+ name: 'connectedApps',+ iconHtml: '<span class="fas fa-user-lock"></span>',+ text: this.translate('Connected Apps', 'labels', 'User'),+ link: `#User/${this.model.id}/connectedApps`,+ });+ }}/**diff --git a/composer.json b/composer.jsonindex 4e7b0f0db4..639052c43b 100644--- a/composer.json+++ b/composer.json@@ -18,7 +18,7 @@"ext-pdo": "*","ext-ctype": "*","psr/log": "~3",- "psr/http-message": "^1.0",+ "psr/http-message": "^2.0","psr/container": "^1.1","slim/slim": "^4.15","slim/psr7": "^1",@@ -59,7 +59,8 @@"devtheorem/php-handlebars": "^1.0","php-amqplib/php-amqplib": "^3.7","predis/predis": "^3.5",- "psr/cache": "^3.0"+ "psr/cache": "^3.0",+ "league/oauth2-server": "^9.4"},"require-dev": {"phpunit/phpunit": "^11.5",diff --git a/composer.lock b/composer.lockindex c146d8b6f5..36808a8fab 100644--- a/composer.lock+++ b/composer.lock@@ -4,7 +4,7 @@"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies","This file is @generated automatically"],- "content-hash": "34ac75e2293db87de4f484db7ff3c921",+ "content-hash": "151386f4ef4eae362df4e7d474ecf2a4","packages": [{"name": "async-aws/core",@@ -634,6 +634,73 @@],"time": "2025-08-20T19:15:30+00:00"},+ {+ "name": "defuse/php-encryption",+ "version": "v2.4.0",+ "source": {+ "type": "git",+ "url": "https://github.com/defuse/php-encryption.git",+ "reference": "f53396c2d34225064647a05ca76c1da9d99e5828"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/defuse/php-encryption/zipball/f53396c2d34225064647a05ca76c1da9d99e5828",+ "reference": "f53396c2d34225064647a05ca76c1da9d99e5828",+ "shasum": ""+ },+ "require": {+ "ext-openssl": "*",+ "paragonie/random_compat": ">= 2",+ "php": ">=5.6.0"+ },+ "require-dev": {+ "phpunit/phpunit": "^5|^6|^7|^8|^9|^10",+ "yoast/phpunit-polyfills": "^2.0.0"+ },+ "bin": [+ "bin/generate-defuse-key"+ ],+ "type": "library",+ "autoload": {+ "psr-4": {+ "Defuse\\Crypto\\": "src"+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "Taylor Hornby",+ "email": "[email protected]",+ "homepage": "https://defuse.ca/"+ },+ {+ "name": "Scott Arciszewski",+ "email": "[email protected]",+ "homepage": "https://paragonie.com"+ }+ ],+ "description": "Secure PHP Encryption Library",+ "keywords": [+ "aes",+ "authenticated encryption",+ "cipher",+ "crypto",+ "cryptography",+ "encrypt",+ "encryption",+ "openssl",+ "security",+ "symmetric key cryptography"+ ],+ "support": {+ "issues": "https://github.com/defuse/php-encryption/issues",+ "source": "https://github.com/defuse/php-encryption/tree/v2.4.0"+ },+ "time": "2023-06-19T06:10:36+00:00"+ },{"name": "devtheorem/php-handlebars","version": "v1.2.3",@@ -2693,6 +2760,138 @@},"time": "2023-07-26T07:23:39+00:00"},+ {+ "name": "lcobucci/jwt",+ "version": "5.6.0",+ "source": {+ "type": "git",+ "url": "https://github.com/lcobucci/jwt.git",+ "reference": "bb3e9f21e4196e8afc41def81ef649c164bca25e"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/lcobucci/jwt/zipball/bb3e9f21e4196e8afc41def81ef649c164bca25e",+ "reference": "bb3e9f21e4196e8afc41def81ef649c164bca25e",+ "shasum": ""+ },+ "require": {+ "ext-openssl": "*",+ "ext-sodium": "*",+ "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0",+ "psr/clock": "^1.0"+ },+ "require-dev": {+ "infection/infection": "^0.29",+ "lcobucci/clock": "^3.2",+ "lcobucci/coding-standard": "^11.0",+ "phpbench/phpbench": "^1.2",+ "phpstan/extension-installer": "^1.2",+ "phpstan/phpstan": "^1.10.7",+ "phpstan/phpstan-deprecation-rules": "^1.1.3",+ "phpstan/phpstan-phpunit": "^1.3.10",+ "phpstan/phpstan-strict-rules": "^1.5.0",+ "phpunit/phpunit": "^11.1"+ },+ "suggest": {+ "lcobucci/clock": ">= 3.2"+ },+ "type": "library",+ "autoload": {+ "psr-4": {+ "Lcobucci\\JWT\\": "src"+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "BSD-3-Clause"+ ],+ "authors": [+ {+ "name": "Luís Cobucci",+ "email": "[email protected]",+ "role": "Developer"+ }+ ],+ "description": "A simple library to work with JSON Web Token and JSON Web Signature",+ "keywords": [+ "JWS",+ "jwt"+ ],+ "support": {+ "issues": "https://github.com/lcobucci/jwt/issues",+ "source": "https://github.com/lcobucci/jwt/tree/5.6.0"+ },+ "funding": [+ {+ "url": "https://github.com/lcobucci",+ "type": "github"+ },+ {+ "url": "https://www.patreon.com/lcobucci",+ "type": "patreon"+ }+ ],+ "time": "2025-10-17T11:30:53+00:00"+ },+ {+ "name": "league/event",+ "version": "3.0.3",+ "source": {+ "type": "git",+ "url": "https://github.com/thephpleague/event.git",+ "reference": "ec38ff7ea10cad7d99a79ac937fbcffb9334c210"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/thephpleague/event/zipball/ec38ff7ea10cad7d99a79ac937fbcffb9334c210",+ "reference": "ec38ff7ea10cad7d99a79ac937fbcffb9334c210",+ "shasum": ""+ },+ "require": {+ "php": ">=7.2.0",+ "psr/event-dispatcher": "^1.0"+ },+ "provide": {+ "psr/event-dispatcher-implementation": "1.0"+ },+ "require-dev": {+ "friendsofphp/php-cs-fixer": "^2.16",+ "phpstan/phpstan": "^0.12.45",+ "phpunit/phpunit": "^8.5"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-master": "3.0-dev"+ }+ },+ "autoload": {+ "psr-4": {+ "League\\Event\\": "src/"+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "Frank de Jonge",+ "email": "[email protected]"+ }+ ],+ "description": "Event package",+ "keywords": [+ "emitter",+ "event",+ "listener"+ ],+ "support": {+ "issues": "https://github.com/thephpleague/event/issues",+ "source": "https://github.com/thephpleague/event/tree/3.0.3"+ },+ "time": "2024-09-04T16:06:53+00:00"+ },{"name": "league/flysystem","version": "3.30.2",@@ -3093,6 +3292,285 @@},"time": "2025-11-25T22:17:17+00:00"},+ {+ "name": "league/oauth2-server",+ "version": "9.4.1",+ "source": {+ "type": "git",+ "url": "https://github.com/thephpleague/oauth2-server.git",+ "reference": "9d2f6fc0a0b5aa1bb02506971d3a4ecff2c6526c"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/thephpleague/oauth2-server/zipball/9d2f6fc0a0b5aa1bb02506971d3a4ecff2c6526c",+ "reference": "9d2f6fc0a0b5aa1bb02506971d3a4ecff2c6526c",+ "shasum": ""+ },+ "require": {+ "defuse/php-encryption": "^2.4",+ "ext-json": "*",+ "ext-openssl": "*",+ "lcobucci/jwt": "^5.6",+ "league/event": "^3.0",+ "league/uri": "^7.8",+ "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0",+ "psr/clock": "^1.0",+ "psr/http-message": "^2.0",+ "psr/http-server-middleware": "^1.0"+ },+ "replace": {+ "league/oauth2server": "*",+ "lncd/oauth2": "*"+ },+ "require-dev": {+ "laminas/laminas-diactoros": "^3.8",+ "paragonie/random_compat": "^9.99.100",+ "php-parallel-lint/php-parallel-lint": "^1.4",+ "phpstan/extension-installer": "^1.4.3",+ "phpstan/phpstan": "^2.1.38",+ "phpstan/phpstan-deprecation-rules": "^2.0",+ "phpstan/phpstan-phpunit": "^2.0.12",+ "phpstan/phpstan-strict-rules": "^2.0",+ "phpunit/phpunit": "^11.5.50",+ "roave/security-advisories": "dev-master",+ "slevomat/coding-standard": "^8.27.1",+ "squizlabs/php_codesniffer": "^4.0"+ },+ "type": "library",+ "autoload": {+ "psr-4": {+ "League\\OAuth2\\Server\\": "src/"+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "Alex Bilbie",+ "email": "[email protected]",+ "homepage": "http://www.alexbilbie.com",+ "role": "Developer"+ },+ {+ "name": "Andy Millington",+ "email": "[email protected]",+ "homepage": "https://www.noexceptions.io",+ "role": "Developer"+ }+ ],+ "description": "A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.",+ "homepage": "https://oauth2.thephpleague.com/",+ "keywords": [+ "Authentication",+ "api",+ "auth",+ "authorisation",+ "authorization",+ "oauth",+ "oauth 2",+ "oauth 2.0",+ "oauth2",+ "protect",+ "resource",+ "secure",+ "server"+ ],+ "support": {+ "issues": "https://github.com/thephpleague/oauth2-server/issues",+ "source": "https://github.com/thephpleague/oauth2-server/tree/9.4.1"+ },+ "funding": [+ {+ "url": "https://github.com/sephster",+ "type": "github"+ }+ ],+ "time": "2026-06-25T15:24:07+00:00"+ },+ {+ "name": "league/uri",+ "version": "7.8.1",+ "source": {+ "type": "git",+ "url": "https://github.com/thephpleague/uri.git",+ "reference": "08cf38e3924d4f56238125547b5720496fac8fd4"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/thephpleague/uri/zipball/08cf38e3924d4f56238125547b5720496fac8fd4",+ "reference": "08cf38e3924d4f56238125547b5720496fac8fd4",+ "shasum": ""+ },+ "require": {+ "league/uri-interfaces": "^7.8.1",+ "php": "^8.1",+ "psr/http-factory": "^1"+ },+ "conflict": {+ "league/uri-schemes": "^1.0"+ },+ "suggest": {+ "ext-bcmath": "to improve IPV4 host parsing",+ "ext-dom": "to convert the URI into an HTML anchor tag",+ "ext-fileinfo": "to create Data URI from file contennts",+ "ext-gmp": "to improve IPV4 host parsing",+ "ext-intl": "to handle IDN host with the best performance",+ "ext-uri": "to use the PHP native URI class",+ "jeremykendall/php-domain-parser": "to further parse the URI host and resolve its Public Suffix and Top Level Domain",+ "league/uri-components": "to provide additional tools to manipulate URI objects components",+ "league/uri-polyfill": "to backport the PHP URI extension for older versions of PHP",+ "php-64bit": "to improve IPV4 host parsing",+ "rowbot/url": "to handle URLs using the WHATWG URL Living Standard specification",+ "symfony/polyfill-intl-idn": "to handle IDN host via the Symfony polyfill if ext-intl is not present"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-master": "7.x-dev"+ }+ },+ "autoload": {+ "psr-4": {+ "League\\Uri\\": ""+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "Ignace Nyamagana Butera",+ "email": "[email protected]",+ "homepage": "https://nyamsprod.com"+ }+ ],+ "description": "URI manipulation library",+ "homepage": "https://uri.thephpleague.com",+ "keywords": [+ "URN",+ "data-uri",+ "file-uri",+ "ftp",+ "hostname",+ "http",+ "https",+ "middleware",+ "parse_str",+ "parse_url",+ "psr-7",+ "query-string",+ "querystring",+ "rfc2141",+ "rfc3986",+ "rfc3987",+ "rfc6570",+ "rfc8141",+ "uri",+ "uri-template",+ "url",+ "ws"+ ],+ "support": {+ "docs": "https://uri.thephpleague.com",+ "forum": "https://thephpleague.slack.com",+ "issues": "https://github.com/thephpleague/uri-src/issues",+ "source": "https://github.com/thephpleague/uri/tree/7.8.1"+ },+ "funding": [+ {+ "url": "https://github.com/sponsors/nyamsprod",+ "type": "github"+ }+ ],+ "time": "2026-03-15T20:22:25+00:00"+ },+ {+ "name": "league/uri-interfaces",+ "version": "7.8.1",+ "source": {+ "type": "git",+ "url": "https://github.com/thephpleague/uri-interfaces.git",+ "reference": "85d5c77c5d6d3af6c54db4a78246364908f3c928"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/thephpleague/uri-interfaces/zipball/85d5c77c5d6d3af6c54db4a78246364908f3c928",+ "reference": "85d5c77c5d6d3af6c54db4a78246364908f3c928",+ "shasum": ""+ },+ "require": {+ "ext-filter": "*",+ "php": "^8.1",+ "psr/http-message": "^1.1 || ^2.0"+ },+ "suggest": {+ "ext-bcmath": "to improve IPV4 host parsing",+ "ext-gmp": "to improve IPV4 host parsing",+ "ext-intl": "to handle IDN host with the best performance",+ "php-64bit": "to improve IPV4 host parsing",+ "rowbot/url": "to handle URLs using the WHATWG URL Living Standard specification",+ "symfony/polyfill-intl-idn": "to handle IDN host via the Symfony polyfill if ext-intl is not present"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-master": "7.x-dev"+ }+ },+ "autoload": {+ "psr-4": {+ "League\\Uri\\": ""+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "Ignace Nyamagana Butera",+ "email": "[email protected]",+ "homepage": "https://nyamsprod.com"+ }+ ],+ "description": "Common tools for parsing and resolving RFC3987/RFC3986 URI",+ "homepage": "https://uri.thephpleague.com",+ "keywords": [+ "data-uri",+ "file-uri",+ "ftp",+ "hostname",+ "http",+ "https",+ "parse_str",+ "parse_url",+ "psr-7",+ "query-string",+ "querystring",+ "rfc3986",+ "rfc3987",+ "rfc6570",+ "uri",+ "url",+ "ws"+ ],+ "support": {+ "docs": "https://uri.thephpleague.com",+ "forum": "https://thephpleague.slack.com",+ "issues": "https://github.com/thephpleague/uri-src/issues",+ "source": "https://github.com/thephpleague/uri-interfaces/tree/7.8.1"+ },+ "funding": [+ {+ "url": "https://github.com/sponsors/nyamsprod",+ "type": "github"+ }+ ],+ "time": "2026-03-08T20:05:35+00:00"+ },{"name": "maennchen/zipstream-php","version": "3.2.1",@@ -4866,16 +5344,16 @@},{"name": "psr/http-message",- "version": "1.1",+ "version": "2.0","source": {"type": "git","url": "https://github.com/php-fig/http-message.git",- "reference": "cb6ce4845ce34a8ad9e68117c10ee90a29919eba"+ "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/php-fig/http-message/zipball/cb6ce4845ce34a8ad9e68117c10ee90a29919eba",- "reference": "cb6ce4845ce34a8ad9e68117c10ee90a29919eba",+ "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71",+ "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71","shasum": ""},"require": {@@ -4884,7 +5362,7 @@"type": "library","extra": {"branch-alias": {- "dev-master": "1.1.x-dev"+ "dev-master": "2.0.x-dev"}},"autoload": {@@ -4899,7 +5377,7 @@"authors": [{"name": "PHP-FIG",- "homepage": "http://www.php-fig.org/"+ "homepage": "https://www.php-fig.org/"}],"description": "Common interface for HTTP messages",@@ -4913,9 +5391,9 @@"response"],"support": {- "source": "https://github.com/php-fig/http-message/tree/1.1"+ "source": "https://github.com/php-fig/http-message/tree/2.0"},- "time": "2023-04-04T09:50:52+00:00"+ "time": "2023-04-04T09:54:51+00:00"},{"name": "psr/http-server-handler",diff --git a/public/oauth/.htaccess b/public/oauth/.htaccessnew file mode 100644index 0000000000..c506092e1b--- /dev/null+++ b/public/oauth/.htaccess@@ -0,0 +1,10 @@+RewriteEngine On++# Some hosts may require you to use the `RewriteBase` directive.+# If you need to use the `RewriteBase` directive, it should be the+# absolute physical path to the directory that contains this htaccess file.+#+# RewriteBase /++RewriteCond %{REQUEST_FILENAME} !-f+RewriteRule ^ index.php [QSA,L]diff --git a/public/oauth/index.php b/public/oauth/index.phpnew file mode 100644index 0000000000..9795ba5e5f--- /dev/null+++ b/public/oauth/index.php@@ -0,0 +1,71 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++require_once('../../bootstrap.php');++use Espo\Core\Application;+use Espo\Core\Application\Runner\Params;+use Espo\Core\ApplicationRunners\EntryPoint;+use Espo\Core\Utils\OAuth\OAuthRouteUtil;++$redirectUrl = OAuthRouteUtil::getRedirectUrlWithTrailingSlash();++if ($redirectUrl) {+ header('Location: ' . $redirectUrl, true, 301);++ exit;+}++$app = new Application();++$map = [+ 'token' => 'oAuthToken',+ 'token/revoke' => 'oAuthTokenRevoke',+ 'authorize' => 'oAuthAuthorize',+ 'callback' => 'oauthCallback',+];++$path = OAuthRouteUtil::detectPath();++$entryPoint = $map[$path] ?? null;++if (!$entryPoint) {+ http_response_code(404);++ exit;+}++$basePath = OAuthRouteUtil::detectBasePast();++$app->setClientBasePath($basePath);++$app->run(+ EntryPoint::class,+ Params::create()->with(EntryPoint::PARAM_ENTRY_POINT, $entryPoint)+);diff --git a/schema/metadata/authenticationMethods.json b/schema/metadata/authenticationMethods.jsonindex b3b5d1938f..fc4825e602 100644--- a/schema/metadata/authenticationMethods.json+++ b/schema/metadata/authenticationMethods.json@@ -15,7 +15,18 @@},"credentialsHeader": {"type": "string",- "description": "A header that is supposed to contain credentials. Actual only for API methods."+ "description": "A header that is supposed to contain credentials. Actual only for API methods.",+ "examples": [+ "Authorization",+ "X-Api-Key"+ ]+ },+ "credentialsHeaderScheme": {+ "type": "string",+ "description": "An authorization header scheme. The header value should start with the specified value for this method to be used. Of omitted, the header is still checked for match. As of v10.1.",+ "examples": [+ "Bearer"+ ]},"login": {"type": "object",diff --git a/tests/integration/Espo/Actions/MassActionTest.php b/tests/integration/Espo/Actions/MassActionTest.phpindex 7d633b1c91..97d71c1efa 100644--- a/tests/integration/Espo/Actions/MassActionTest.php+++ b/tests/integration/Espo/Actions/MassActionTest.php@@ -49,6 +49,7 @@ use Espo\Modules\Crm\Entities\Contact;use Espo\Modules\Crm\Entities\Opportunity;use Espo\Tools\MassUpdate\Data as MassUpdateData;use Espo\Tools\MassUpdate\Processor;+use RuntimeException;use tests\integration\Core\BaseTestCase;class MassActionTest extends BaseTestCase@@ -280,7 +281,7 @@ class MassActionTest extends BaseTestCase$process = $injectableFactory1->create(JobProcess::class);// Mass-update for User entity type is allowed only for admins.- $this->expectException(Error::class);+ $this->expectException(RuntimeException::class);$process->run(JobData::create()->withTargetId($massActionId));}diff --git a/tests/integration/Espo/Core/Acl/AclTest.php b/tests/integration/Espo/Core/Acl/AclTest.phpindex 887201a797..3f25f72b55 100644--- a/tests/integration/Espo/Core/Acl/AclTest.php+++ b/tests/integration/Espo/Core/Acl/AclTest.php@@ -38,6 +38,7 @@ use Espo\Modules\Crm\Entities\Account;use Espo\Modules\Crm\Entities\Call;use Espo\Modules\Crm\Entities\Meeting;use Espo\Modules\Crm\Entities\Task;+use RuntimeException;use tests\integration\Core\BaseTestCase;class AclTest extends BaseTestCase@@ -247,4 +248,62 @@ class AclTest extends BaseTestCase$this->assertTrue($aclManager->checkScope($user, 'Call', Acl\Table::ACTION_CREATE));$this->assertTrue($aclManager->checkScope($user, 'Call', Acl\Table::ACTION_EDIT));}++ public function testCheckAdmin(): void+ {+ $user = $this->createUser(+ userData: [+ User::FIELD_USER_NAME => 'test',+ ],+ );++ $admin = $this->createUser(+ userData: [+ User::FIELD_USER_NAME => 'admin-test',+ User::FIELD_TYPE => User::TYPE_ADMIN,+ ],+ );++ $aclManager = $this->getInjectableFactory()->create(AclManager::class);++ //++ $user = $this->reFetchUser($user);+ $admin = $this->reFetchUser($admin);++ $this->assertFalse($aclManager->checkAdmin($user));+ $this->assertTrue($aclManager->checkAdmin($admin));++ $this->assertFalse($aclManager->createUserAcl($user)->checkAdmin());+ $this->assertTrue($aclManager->createUserAcl($admin)->checkAdmin());++ //++ $user = $this->reFetchUser($user);+ $admin = $this->reFetchUser($admin);++ $user->setScopes([Acl\Scope::ADMIN]);+ $admin->setScopes([Acl\Scope::ADMIN]);++ $this->assertFalse($aclManager->checkAdmin($user));+ $this->assertTrue($aclManager->checkAdmin($admin));++ //++ $user = $this->reFetchUser($user);+ $admin = $this->reFetchUser($admin);++ $user->setScopes([]);+ $admin->setScopes([]);++ $this->assertFalse($aclManager->checkAdmin($user));+ $this->assertFalse($aclManager->checkAdmin($admin));+ }++ private function reFetchUser(User $user): User+ {+ return $this->getEntityManager()+ ->getRDBRepositoryByClass(User::class)+ ->getById($user->getId()) ?? throw new RuntimeException();+ }}diff --git a/tests/integration/Espo/Core/Acl/TableTest.php b/tests/integration/Espo/Core/Acl/TableTest.phpnew file mode 100644index 0000000000..d9398c7512--- /dev/null+++ b/tests/integration/Espo/Core/Acl/TableTest.php@@ -0,0 +1,247 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace integration\Espo\Core\Acl;++use Espo\Core\Acl\Scope;+use Espo\Core\Acl\Table;+use Espo\Entities\Role;+use Espo\Entities\User;+use Espo\Modules\Crm\Entities\Account;+use Espo\Modules\Crm\Entities\Contact;+use Espo\Modules\Crm\Entities\Lead;+use Espo\Tools\Stream\GlobalRecordService;+use RuntimeException;+use tests\integration\Core\BaseTestCase;++class TableTest extends BaseTestCase+{+ public function testScopesRegular(): void+ {+ $roleData = [+ Account::ENTITY_TYPE => [+ Table::ACTION_CREATE => Table::LEVEL_YES,+ Table::ACTION_READ => Table::LEVEL_ALL,+ Table::ACTION_EDIT => Table::LEVEL_ALL,+ Table::ACTION_DELETE => Table::LEVEL_ALL,+ Table::ACTION_STREAM => Table::LEVEL_ALL,+ ],+ Contact::ENTITY_TYPE => false,+ Lead::ENTITY_TYPE => [+ Table::ACTION_CREATE => Table::LEVEL_YES,+ Table::ACTION_READ => Table::LEVEL_ALL,+ Table::ACTION_EDIT => Table::LEVEL_ALL,+ Table::ACTION_DELETE => Table::LEVEL_ALL,+ Table::ACTION_STREAM => Table::LEVEL_ALL,+ ],+ GlobalRecordService::SCOPE_NAME => true,+ ];++ $user = $this->createUser(+ userData: [+ User::FIELD_USER_NAME => 'test',+ ],+ role: [+ Role::FIELD_DATA => $roleData,+ ],+ );++ $factory = $this->getInjectableFactory()->create(Table\DefaultTableFactory::class);++ //++ $user = $this->reFetchUser($user);++ $table = $factory->create($user);++ $this->assertEquals(Table::LEVEL_YES, $table->getScopeData(Account::ENTITY_TYPE)->getCreate());+ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Account::ENTITY_TYPE)->getRead());+ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Account::ENTITY_TYPE)->getEdit());+ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Account::ENTITY_TYPE)->getDelete());+ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Account::ENTITY_TYPE)->getStream());++ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Lead::ENTITY_TYPE)->getRead());++ $this->assertFalse($table->getScopeData(Contact::ENTITY_TYPE)->isTrue());+ $this->assertTrue($table->getScopeData(GlobalRecordService::SCOPE_NAME)->isTrue());++ //++ $user->setScopes([+ Lead::ENTITY_TYPE,+ GlobalRecordService::SCOPE_NAME,+ ]);++ $table = $factory->create($user);++ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Account::ENTITY_TYPE)->getCreate());+ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Account::ENTITY_TYPE)->getRead());+ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Account::ENTITY_TYPE)->getEdit());+ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Account::ENTITY_TYPE)->getDelete());+ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Account::ENTITY_TYPE)->getStream());++ $this->assertEquals(Table::LEVEL_YES, $table->getScopeData(Lead::ENTITY_TYPE)->getCreate());+ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Lead::ENTITY_TYPE)->getRead());+ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Lead::ENTITY_TYPE)->getEdit());+ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Lead::ENTITY_TYPE)->getDelete());+ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Lead::ENTITY_TYPE)->getStream());++ $this->assertTrue($table->getScopeData(GlobalRecordService::SCOPE_NAME)->isTrue());++ //++ $user = $this->reFetchUser($user);++ $user->setScopes([+ Scope::GLOBAL,+ ]);++ $table = $factory->create($user);++ $this->assertEquals(Table::LEVEL_YES, $table->getScopeData(Account::ENTITY_TYPE)->getCreate());+ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Account::ENTITY_TYPE)->getRead());+ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Account::ENTITY_TYPE)->getEdit());+ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Account::ENTITY_TYPE)->getDelete());+ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Account::ENTITY_TYPE)->getStream());++ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Lead::ENTITY_TYPE)->getRead());++ $this->assertFalse($table->getScopeData(Contact::ENTITY_TYPE)->isTrue());+ $this->assertTrue($table->getScopeData(GlobalRecordService::SCOPE_NAME)->isTrue());++ //++ $user = $this->reFetchUser($user);++ $user->setScopes([]);++ $table = $factory->create($user);++ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Account::ENTITY_TYPE)->getCreate());+ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Account::ENTITY_TYPE)->getRead());+ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Account::ENTITY_TYPE)->getEdit());+ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Account::ENTITY_TYPE)->getDelete());+ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Account::ENTITY_TYPE)->getStream());++ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Lead::ENTITY_TYPE)->getCreate());+ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Lead::ENTITY_TYPE)->getRead());+ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Lead::ENTITY_TYPE)->getEdit());+ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Lead::ENTITY_TYPE)->getDelete());+ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Lead::ENTITY_TYPE)->getStream());++ $this->assertFalse($table->getScopeData(Contact::ENTITY_TYPE)->isTrue());+ $this->assertFalse($table->getScopeData(GlobalRecordService::SCOPE_NAME)->isTrue());++ //++ $user = $this->reFetchUser($user);++ $user->setScopes([+ Scope::ADMIN,+ ]);++ $table = $factory->create($user);++ $this->assertFalse($table->getScopeData(Scope::ADMIN)->isTrue());++ $this->assertFalse($user->isEffectiveAdmin());+ }++ public function testScopesAdmin(): void+ {+ $user = $this->createUser(+ userData: [+ User::FIELD_USER_NAME => 'test',+ User::FIELD_TYPE => User::TYPE_ADMIN,+ ]+ );++ $factory = $this->getInjectableFactory()->create(Table\DefaultTableFactory::class);++ //++ $user = $this->reFetchUser($user);++ $table = $factory->create($user);++ $this->assertTrue($table->getScopeData(Scope::ADMIN)->isTrue());++ //++ $user = $this->reFetchUser($user);++ $user->setScopes([+ Scope::ADMIN,+ ]);++ $table = $factory->create($user);++ $this->assertTrue($table->getScopeData(Scope::ADMIN)->isTrue());++ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Account::ENTITY_TYPE)->getRead());+ $this->assertTrue($table->getScopeData(GlobalRecordService::SCOPE_NAME)->isTrue());++ //++ $user = $this->reFetchUser($user);++ $user->setScopes([+ Scope::GLOBAL,+ ]);++ $table = $factory->create($user);++ $this->assertFalse($table->getScopeData(Scope::ADMIN)->isTrue());++ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Account::ENTITY_TYPE)->getRead());+ $this->assertTrue($table->getScopeData(GlobalRecordService::SCOPE_NAME)->isTrue());++ //++ $user = $this->reFetchUser($user);++ $user->setScopes([+ Account::ENTITY_TYPE,+ ]);++ $table = $factory->create($user);++ $this->assertFalse($table->getScopeData(Scope::ADMIN)->isTrue());++ $this->assertEquals(Table::LEVEL_ALL, $table->getScopeData(Account::ENTITY_TYPE)->getRead());+ $this->assertEquals(Table::LEVEL_NO, $table->getScopeData(Lead::ENTITY_TYPE)->getRead());+ }++ private function reFetchUser(User $user): User+ {+ return $this->getEntityManager()+ ->getRDBRepositoryByClass(User::class)+ ->getById($user->getId()) ?? throw new RuntimeException();+ }+}diff --git a/tests/integration/Espo/Tools/OAuthServer/AuthorizationServerTest.php b/tests/integration/Espo/Tools/OAuthServer/AuthorizationServerTest.phpnew file mode 100644index 0000000000..dc9bc24706--- /dev/null+++ b/tests/integration/Espo/Tools/OAuthServer/AuthorizationServerTest.php@@ -0,0 +1,1523 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace tests\integration\Espo\Tools\OAuthServer;++use DateTimeImmutable;+use Espo\Core\Acl\Scope;+use Espo\Core\Acl\Table;+use Espo\Core\Api\Auth;+use Espo\Core\Api\AuthBuilderFactory;+use Espo\Core\Api\Method;+use Espo\Core\Api\ResponseWrapper;+use Espo\Core\ApplicationState;+use Espo\Core\Authentication\Authentication;+use Espo\Core\Authentication\Oidc\PkceUtil;+use Espo\Core\Binding\Binder;+use Espo\Core\Exceptions\Forbidden;+use Espo\Core\Field\Date;+use Espo\Core\Session\Session;+use Espo\Core\Utils\DateTime\Clock;+use Espo\Core\Utils\Json;+use Espo\Entities\Role;+use Espo\Entities\User;+use Espo\Modules\Crm\Entities\Account;+use Espo\Modules\Crm\Entities\Contact;+use Espo\Tools\App\SettingsService;+use Espo\Tools\OAuthServer\ClientType;+use Espo\Tools\OAuthServer\ConsentDataService;+use Espo\Tools\OAuthServer\Entities\Client;+use Espo\Tools\OAuthServer\Entities\ClientSecret;+use Espo\Tools\OAuthServer\Entities\RefreshToken;+use Espo\Tools\OAuthServer\EntryPoints\Authorize;+use Espo\Tools\OAuthServer\EntryPoints\AuthorizeComplete;+use Espo\Tools\OAuthServer\EntryPoints\Token;+use Espo\Tools\OAuthServer\EntryPoints\TokenRevoke;+use Espo\Tools\OAuthServer\Repository\AccessTokenRepository;+use Slim\Psr7\Response;+use tests\integration\Core\BaseTestCase;++class AuthorizationServerTest extends BaseTestCase+{+ private const string REDIRECT_URI = 'http://localhost/oauth/callback';+ private const string USER_USERNAME = 'test';++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testAuthorizeConfidentialSuccess(): void+ {+ $redirectUri = self::REDIRECT_URI;++ $client = $this->createClient();+ $secret = $this->createSecret($client);++ $user = $this->createUserForTest();++ //++ $codeChallenge = PkceUtil::generateCodeVerifier();++ $code = $this->processObtainCode(+ client: $client,+ redirectUri: $redirectUri,+ codeChallenge: $codeChallenge,+ user: $user,+ );++ //++ [$accessToken, $refreshToken] = $this->tokenWithAuthorizationCode(+ client: $client,+ secret: $secret,+ redirectUri: $redirectUri,+ code: $code,+ codeChallenge: $codeChallenge,+ );++ //++ $this->expiredSecret(+ client: $client,+ secret: $secret,+ redirectUri: $redirectUri,+ refreshToken: $refreshToken,+ );++ //++ [$accessToken, $refreshToken] = $this->refreshTokenGrant(+ refreshToken: $refreshToken,+ client: $client,+ secret: $secret,+ redirectUri: $redirectUri,+ accessToken: $accessToken,+ );++ //++ $this->resourceSuccess($accessToken, $user);+ $this->resourceAccessTokenWrong();+ $this->resourceAccessTokenInactive($client, $accessToken);+ $this->resourceAccessTokenExpired($accessToken);++ //++ $this->refreshTokenGrantWrongSecret($client, $redirectUri);++ //++ $this->reCreateApplication(reuse: true, noUser: true);++ //++ $this->revokeAccessTokenWithAuthorizationHeader(+ client: $client,+ secret: $secret,+ accessToken: $accessToken,+ );++ $this->revokeAccessTokenWithPostParameters(+ accessToken: $accessToken,+ client: $client,+ secret: $secret,+ );++ $this->revokeRefreshToken(+ refreshToken: $refreshToken,+ client: $client,+ secret: $secret,+ accessToken: $accessToken,+ );++ $this->revokeRefreshTokenWithoutHint(+ refreshToken: $refreshToken,+ client: $client,+ secret: $secret,+ accessToken: $accessToken,+ );++ $this->revokeFailDueWrongSecret(+ accessToken: $accessToken,+ client: $client,+ );++ $this->revokeFailDueWrongClientId(+ accessToken: $accessToken,+ secret: $secret,+ );+ }++ public function testExtraScopesNotAllowed(): void+ {+ $redirectUri = self::REDIRECT_URI;++ $client = $this->createClient();++ $user = $this->createUserForTest();++ //++ $codeChallenge = PkceUtil::generateCodeVerifier();++ $this->obtainCodeInitital(+ client: $client,+ redirectUri: $redirectUri,+ codeChallenge: $codeChallenge,+ user: $user,+ );++ $this->authorizeCompleteScopeMismatch($client);+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testAuthorizeWrongSecret(): void+ {+ $redirectUri = self::REDIRECT_URI;++ $client = $this->createClient();+ $this->createSecret($client);++ //++ $user = $this->createUser(+ [+ User::FIELD_USER_NAME => self::USER_USERNAME,+ ],+ );++ //++ $codeChallenge = PkceUtil::generateCodeVerifier();++ $code = $this->processObtainCode(+ client: $client,+ redirectUri: $redirectUri,+ codeChallenge: $codeChallenge,+ user: $user,+ );++ //++ $this->setApplication(+ $this->createApplication(+ reuse: true,+ noUser: true,+ )+ );++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'grant_type' => 'authorization_code',+ 'client_id' => $client->getIdentifier(),+ 'client_secret' => 'wrong',+ 'redirect_uri' => $redirectUri,+ 'code' => $code,+ 'code_verifier' => $codeChallenge,+ ]),+ resourcePath: '/oauth/token',+ );++ $response = $this->createResponseWrapper();++ $tokenEntryPoint = $this->getInjectableFactory()->create(Token::class);++ $tokenEntryPoint->run($request, $response);++ $body = Json::decode((string) $response->getBody());++ $this->assertEquals('invalid_client', $body->error);+ $this->assertEquals(401, $response->getStatusCode());+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testAuthorizePublicSuccess(): void+ {+ $em = $this->getEntityManager();++ //++ $redirectUri = self::REDIRECT_URI;++ $client = $this->createClient(ClientType::Public);++ //++ $user = $this->createUser(+ [+ User::FIELD_USER_NAME => self::USER_USERNAME,+ ],+ );++ //++ $codeChallenge = PkceUtil::generateCodeVerifier();++ $code = $this->processObtainCode(+ client: $client,+ redirectUri: $redirectUri,+ codeChallenge: $codeChallenge,+ user: $user,+ );++ //++ $this->setApplication(+ $this->createApplication(+ reuse: true,+ noUser: true,+ )+ );++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'grant_type' => 'authorization_code',+ 'client_id' => $client->getIdentifier(),+ 'redirect_uri' => $redirectUri,+ 'code' => $code,+ 'code_verifier' => $codeChallenge,+ ]),+ resourcePath: '/oauth/token',+ );++ $response = $this->createResponseWrapper();++ $tokenEntryPoint = $this->getInjectableFactory()->create(Token::class);++ $tokenEntryPoint->run($request, $response);++ $body = Json::decode((string) $response->getBody());++ $this->assertEquals('Bearer', $body->token_type);+ $this->assertObjectHasProperty('access_token', $body);+ $this->assertObjectHasProperty('refresh_token', $body);+ $this->assertObjectHasProperty('expires_in', $body);++ $refreshToken = $body->refresh_token;+ $accessToken = $body->access_token;++ //++ // Refresh token grant.++ $this->setApplication(+ $this->createApplication(+ reuse: true,+ noUser: true,+ )+ );++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'grant_type' => 'refresh_token',+ 'refresh_token' => $refreshToken,+ 'client_id' => $client->getIdentifier(),+ 'redirect_uri' => $redirectUri,+ ]),+ resourcePath: '/oauth/token',+ );++ $response = $this->createResponseWrapper();++ $tokenEntryPoint = $this->getInjectableFactory()->create(Token::class);++ $tokenEntryPoint->run($request, $response);++ $body = Json::decode((string) $response->getBody());++ $this->assertObjectHasProperty('access_token', $body);+ $this->assertObjectHasProperty('refresh_token', $body);+ $this->assertObjectHasProperty('expires_in', $body);++ $this->assertNotEquals($accessToken, $body->access_token);+ $this->assertNotEquals($refreshToken, $body->refresh_token);++ $accessTokenRepo = $this->getInjectableFactory()->create(AccessTokenRepository::class);++ $oldAccessToken = $accessTokenRepo->getByIdentifier($accessToken);++ $this->assertNotNull($oldAccessToken);+ $this->assertTrue($oldAccessToken->isRevoked());++ $oldRefreshToken = $em->getRDBRepositoryByClass(RefreshToken::class)+ ->where([RefreshToken::FIELD_ACCESS_TOKEN . 'Id' => $oldAccessToken->getId()])+ ->findOne();++ $this->assertNotNull($oldRefreshToken);+ $this->assertTrue($oldRefreshToken->isRevoked());+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testAuthorizeWrongCodeChallenge(): void+ {+ $redirectUri = self::REDIRECT_URI;++ $client = $this->createClient();+ $secret = $this->createSecret($client);++ //++ $user = $this->createUser(+ [+ User::FIELD_USER_NAME => self::USER_USERNAME,+ ],+ );++ //++ $codeChallenge = PkceUtil::generateCodeVerifier();++ $code = $this->processObtainCode(+ client: $client,+ redirectUri: $redirectUri,+ codeChallenge: $codeChallenge,+ user: $user,+ );++ //++ $this->setApplication(+ $this->createApplication(+ reuse: true,+ noUser: true,+ )+ );++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'grant_type' => 'authorization_code',+ 'client_id' => $client->getIdentifier(),+ 'client_secret' => $secret->getValue(),+ 'redirect_uri' => $redirectUri,+ 'code' => $code,+ 'code_verifier' => 'wrong',+ ]),+ resourcePath: '/oauth/token',+ );++ $response = $this->createResponseWrapper();++ $tokenEntryPoint = $this->getInjectableFactory()->create(Token::class);++ $tokenEntryPoint->run($request, $response);++ $body = Json::decode((string) $response->getBody());++ $this->assertEquals('invalid_request', $body->error);+ $this->assertEquals(400, $response->getStatusCode());+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testAuthorizeWrongRequestUri(): void+ {+ $redirectUri = self::REDIRECT_URI;++ $client = $this->createClient();+ $secret = $this->createSecret($client);++ //++ $user = $this->createUser(+ [+ User::FIELD_USER_NAME => self::USER_USERNAME,+ ],+ );++ //++ $codeChallenge = PkceUtil::generateCodeVerifier();++ $code = $this->processObtainCode(+ client: $client,+ redirectUri: $redirectUri,+ codeChallenge: $codeChallenge,+ user: $user,+ );++ //++ $this->setApplication(+ $this->createApplication(+ reuse: true,+ noUser: true,+ )+ );++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'grant_type' => 'authorization_code',+ 'client_id' => $client->getIdentifier(),+ 'client_secret' => $secret->getValue(),+ 'redirect_uri' => 'wrong',+ 'code' => $code,+ 'code_verifier' => $codeChallenge,+ ]),+ resourcePath: '/oauth/token',+ );++ $response = $this->createResponseWrapper();++ $tokenEntryPoint = $this->getInjectableFactory()->create(Token::class);++ $tokenEntryPoint->run($request, $response);++ $result = Json::decode((string) $response->getBody());++ $this->assertEquals('invalid_request', $result->error);+ $this->assertEquals(400, $response->getStatusCode());+ }++ public function testWrongClientId(): void+ {+ $this->createClient();++ $clientId = 'wrong';+ $redirectUri = self::REDIRECT_URI;+ $scope = $this->getScopesString();++ //++ $response = $this->processCodeRequestError($clientId, $redirectUri, $scope);++ $result = Json::decode((string) $response->getBody());+ $this->assertEquals('invalid_client', $result->error);++ $this->assertEquals(401, $response->getStatusCode());+ }++ public function testWrongRedirectUri(): void+ {+ $client = $this->createClient();++ $clientId = $client->getIdentifier();+ $redirectUri = 'wrong';+ $scope = $this->getScopesString();++ //++ $response = $this->processCodeRequestError($clientId, $redirectUri, $scope);++ $result = Json::decode((string) $response->getBody());+ $this->assertEquals('invalid_client', $result->error);++ $this->assertEquals(401, $response->getStatusCode());+ }++ public function testWrongScope(): void+ {+ $client = $this->createClient();++ $clientId = $client->getIdentifier();+ $redirectUri = self::REDIRECT_URI;+ $scope = 'wrong';++ //++ $response =$this->processCodeRequestError($clientId, $redirectUri, $scope);++ $location = $response->getHeader('Location');+ $this->assertIsString($location);+ $this->assertStringContainsString('error=invalid_scope', $location);+ }++ public function testSettings(): void+ {+ $this->createUser(+ [+ User::FIELD_USER_NAME => 'admin',+ User::FIELD_TYPE => User::TYPE_ADMIN,+ ],+ );++ $this->authenticate('admin');++ $settingsService = $this->getInjectableFactory()->create(SettingsService::class);++ $this->assertObjectNotHasProperty('oAuthServerCryptKey', $settingsService->getConfigData());+ }++ private function createResponseWrapper(): ResponseWrapper+ {+ return new ResponseWrapper(new Response());+ }++ private function createClient(ClientType $type = ClientType::Confidential): Client+ {+ $em = $this->getEntityManager();++ $client = $em->getRDBRepositoryByClass(Client::class)->getNew();+ $client+ ->setScopes($this->getScopes())+ ->setClientType($type)+ ->setRedirectUris([self::REDIRECT_URI]);+ $em->saveEntity($client);++ return $client;+ }++ private function createSecret(Client $client): ClientSecret+ {+ $em = $this->getEntityManager();++ $secret = $em->getRDBRepositoryByClass(ClientSecret::class)->getNew();++ $secret+ ->setClient($client)+ ->setExpirationDate(Date::createToday()->addYears(1));++ $em->saveEntity($secret);++ return $secret;+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function processCodeRequestError(+ string $clientId,+ string $redirectUri,+ string $scope,+ ): ResponseWrapper {++ $this->setApplication(+ $this->createApplication(+ reuse: true,+ noUser: true,+ )+ );++ $codeChallenge = PkceUtil::generateCodeVerifier();++ //++ $request = $this->createRequest(+ method: Method::GET,+ queryParams: [+ 'response_type' => 'code',+ 'client_id' => $clientId,+ 'redirect_uri' => $redirectUri,+ 'scope' => $scope,+ 'code_challenge' => PkceUtil::hashAndEncodeCodeVerifier($codeChallenge),+ 'code_challenge_method' => 'S256',+ ],+ resourcePath: '/oauth/authorize',+ );++ $response = $this->createResponseWrapper();++ $authorizeEntryPoint = $this->getInjectableFactory()->create(Authorize::class);++ $authorizeEntryPoint->run($request, $response);++ return $response;+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function processObtainCode(+ Client $client,+ string $redirectUri,+ string $codeChallenge,+ User $user,+ ): string {++ $this->obtainCodeInitital(+ client: $client,+ redirectUri: $redirectUri,+ codeChallenge: $codeChallenge,+ user: $user,+ );++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'clientId' => $client->getIdentifier(),+ 'approved' => 'true',+ 'scopes' => $this->getScopesString(),+ ]),+ resourcePath: '?entryPoint=oAuthAuthorizeComplete',+ );++ $response = $this->createResponseWrapper();++ $completeEntryPoint = $this->getInjectableFactory()->create(AuthorizeComplete::class);++ $completeEntryPoint->run($request, $response);++ $location = $response->getHeader('Location');++ $this->assertIsString($location);+ $this->assertStringStartsWith($redirectUri, $location);++ $urlData = parse_url($location);+ parse_str($urlData['query'], $queryParams);+ $this->assertIsString($queryParams['code']);++ return $queryParams['code'];+ }++ private function prepareAuth(): Auth+ {+ $authentication = $this->getInjectableFactory()->create(Authentication::class);++ $authBuilderFactory = $this->getInjectableFactory()->create(AuthBuilderFactory::class);++ return $authBuilderFactory->create()+ ->setAuthentication($authentication)+ ->setAuthRequired(true)+ ->build();+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function revokeFailDueWrongClientId(+ string $accessToken,+ ClientSecret $secret,+ ): void {++ $tokenRevokeEntryPoint = $this->getInjectableFactory()->create(TokenRevoke::class);+ $accessTokenRepo = $this->getInjectableFactory()->create(AccessTokenRepository::class);+ $em = $this->getEntityManager();++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'token' => $accessToken,+ 'token_type_hint' => 'access_token',+ 'client_id' => 'wrong',+ 'client_secret' => $secret->getValue(),+ ]),+ resourcePath: '/oauth/token/revoke',+ );++ $response = $this->createResponseWrapper();++ $em->getTransactionManager()->start();++ $tokenRevokeEntryPoint->run($request, $response);++ $this->assertEquals(401, $response->getStatusCode());+ $this->assertFalse($accessTokenRepo->getByIdentifier($accessToken)->isRevoked());++ $em->getTransactionManager()->rollback();+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function revokeAccessTokenWithAuthorizationHeader(+ Client $client,+ ClientSecret $secret,+ string $accessToken,+ ): void {++ $tokenRevokeEntryPoint = $this->getInjectableFactory()->create(TokenRevoke::class);+ $accessTokenRepo = $this->getInjectableFactory()->create(AccessTokenRepository::class);+ $em = $this->getEntityManager();++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ 'Authorization' => 'Basic ' . base64_encode($client->getIdentifier() . ':' . $secret->getValue()),+ ],+ body: http_build_query([+ 'token' => $accessToken,+ 'token_type_hint' => 'access_token',+ ]),+ resourcePath: '/oauth/token/revoke',+ );++ $response = $this->createResponseWrapper();++ $em->getTransactionManager()->start();++ $tokenRevokeEntryPoint->run($request, $response);++ $this->assertEquals(200, $response->getStatusCode());+ $this->assertTrue($accessTokenRepo->getByIdentifier($accessToken)->isRevoked());++ $em->getTransactionManager()->rollback();++ $this->assertFalse($accessTokenRepo->getByIdentifier($accessToken)->isRevoked());+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function revokeAccessTokenWithPostParameters(+ string $accessToken,+ Client $client,+ ClientSecret $secret,+ ): void {++ $tokenRevokeEntryPoint = $this->getInjectableFactory()->create(TokenRevoke::class);+ $accessTokenRepo = $this->getInjectableFactory()->create(AccessTokenRepository::class);+ $em = $this->getEntityManager();++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'token' => $accessToken,+ 'token_type_hint' => 'access_token',+ 'client_id' => $client->getIdentifier(),+ 'client_secret' => $secret->getValue(),+ ]),+ resourcePath: '/oauth/token/revoke',+ );++ $response = $this->createResponseWrapper();++ $em->getTransactionManager()->start();++ $tokenRevokeEntryPoint->run($request, $response);++ $this->assertEquals(200, $response->getStatusCode());+ $this->assertTrue($accessTokenRepo->getByIdentifier($accessToken)->isRevoked());++ $em->getTransactionManager()->rollback();++ //++ $this->assertFalse($accessTokenRepo->getByIdentifier($accessToken)->isRevoked());+ }+++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function revokeRefreshToken(+ string $refreshToken,+ Client $client,+ ClientSecret $secret,+ string $accessToken,+ ): void {++ $accessTokenRepo = $this->getInjectableFactory()->create(AccessTokenRepository::class);+ $em = $this->getEntityManager();++ $tokenRevokeEntryPoint = $this->getInjectableFactory()->create(TokenRevoke::class);++ $this->assertEquals(+ 1,+ $em->getRDBRepositoryByClass(RefreshToken::class)+ ->where([RefreshToken::FIELD_STATUS => RefreshToken::STATUS_ACTIVE])+ ->count()+ );++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'token' => $refreshToken,+ 'token_type_hint' => 'refresh_token',+ 'client_id' => $client->getIdentifier(),+ 'client_secret' => $secret->getValue(),+ ]),+ resourcePath: '/oauth/token/revoke',+ );++ $response = $this->createResponseWrapper();++ $em->getTransactionManager()->start();++ $tokenRevokeEntryPoint->run($request, $response);++ $this->assertEquals(200, $response->getStatusCode());+ $this->assertTrue($accessTokenRepo->getByIdentifier($accessToken)?->isRevoked());+ $this->assertEquals(+ 0,+ $em->getRDBRepositoryByClass(RefreshToken::class)+ ->where([RefreshToken::FIELD_STATUS => RefreshToken::STATUS_ACTIVE])+ ->count()+ );++ $em->getTransactionManager()->rollback();++ //++ $this->assertFalse($accessTokenRepo->getByIdentifier($accessToken)->isRevoked());+ $this->assertEquals(+ 1,+ $em->getRDBRepositoryByClass(RefreshToken::class)+ ->where([RefreshToken::FIELD_STATUS => RefreshToken::STATUS_ACTIVE])+ ->count()+ );+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function revokeRefreshTokenWithoutHint(+ string $refreshToken,+ Client $client,+ ClientSecret $secret,+ string $accessToken,+ ) {++ $tokenRevokeEntryPoint = $this->getInjectableFactory()->create(TokenRevoke::class);+ $accessTokenRepo = $this->getInjectableFactory()->create(AccessTokenRepository::class);+ $em = $this->getEntityManager();++ $this->assertEquals(+ 1,+ $em->getRDBRepositoryByClass(RefreshToken::class)+ ->where([RefreshToken::FIELD_STATUS => RefreshToken::STATUS_ACTIVE])+ ->count()+ );++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'token' => $refreshToken,+ 'client_id' => $client->getIdentifier(),+ 'client_secret' => $secret->getValue(),+ ]),+ resourcePath: '/oauth/token/revoke',+ );++ $response = $this->createResponseWrapper();++ $em->getTransactionManager()->start();++ $tokenRevokeEntryPoint->run($request, $response);++ $this->assertEquals(200, $response->getStatusCode());+ $this->assertTrue($accessTokenRepo->getByIdentifier($accessToken)?->isRevoked());+ $this->assertEquals(+ 0,+ $em->getRDBRepositoryByClass(RefreshToken::class)+ ->where([RefreshToken::FIELD_STATUS => RefreshToken::STATUS_ACTIVE])+ ->count()+ );++ $em->getTransactionManager()->rollback();++ //++ $this->assertFalse($accessTokenRepo->getByIdentifier($accessToken)->isRevoked());+ $this->assertEquals(+ 1,+ $em->getRDBRepositoryByClass(RefreshToken::class)+ ->where([RefreshToken::FIELD_STATUS => RefreshToken::STATUS_ACTIVE])+ ->count()+ );+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function revokeFailDueWrongSecret(+ string $accessToken,+ Client $client,+ ): void {++ $accessTokenRepo = $this->getInjectableFactory()->create(AccessTokenRepository::class);+ $em = $this->getEntityManager();++ $tokenRevokeEntryPoint = $this->getInjectableFactory()->create(TokenRevoke::class);++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'token' => $accessToken,+ 'token_type_hint' => 'access_token',+ 'client_id' => $client->getIdentifier(),+ 'client_secret' => 'wrong',+ ]),+ resourcePath: '/oauth/token/revoke',+ );++ $response = $this->createResponseWrapper();++ $em->getTransactionManager()->start();++ $tokenRevokeEntryPoint->run($request, $response);++ $this->assertEquals(401, $response->getStatusCode());+ $this->assertFalse($accessTokenRepo->getByIdentifier($accessToken)->isRevoked());++ $em->getTransactionManager()->rollback();+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function refreshTokenGrantWrongSecret(Client $client, string $redirectUri): void+ {+ $this->setApplication(+ $this->createApplication(+ reuse: true,+ noUser: true,+ )+ );++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'grant_type' => 'refresh_token',+ 'refresh_token' => 'wrong',+ 'client_id' => $client->getIdentifier(),+ 'client_secret' => 'wrong',+ 'redirect_uri' => $redirectUri,+ ]),+ resourcePath: '/oauth/token',+ );++ $response = $this->createResponseWrapper();++ $tokenEntryPoint = $this->getInjectableFactory()->create(Token::class);++ $tokenEntryPoint->run($request, $response);++ $this->assertEquals(401, $response->getStatusCode());++ $body = Json::decode((string) $response->getBody());+ $this->assertEquals('invalid_client', $body->error);+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function resourceAccessTokenExpired($accessToken): void+ {+ $clock = $this->createMock(Clock::class);+ $clock->expects(self::any())+ ->method('now')+ ->willReturn((new DateTimeImmutable())->modify('+1 day'));++ $this->reCreateApplication(+ reuse: true,+ noUser: true,+ binding: $this->prepareBinding(function ($binder) use ($clock) {+ $binder->bindInstance(Clock::class, $clock);+ }),+ );++ $request = $this->createRequest(+ method::GET,+ headers: [+ 'Authorization' => 'Bearer ' . $accessToken,+ ],+ );++ $auth = $this->prepareAuth();++ $response = $this->createResponse();++ $result = $auth->process($request, $response);++ $this->assertFalse($result->isResolved());+ $this->assertFalse($this->getContainer()->getByClass(ApplicationState::class)->hasUser());++ $body = Json::decode((string) $response->getBody());+ $this->assertEquals('access_denied', $body->error);+ $this->assertStringContainsString('expired', $body->error_description);+ $this->assertEquals(401, $response->getStatusCode());+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function resourceAccessTokenInactive(Client $client, string $accessToken): void+ {+ $em = $this->getEntityManager();++ $client->setInactive();+ $em->saveEntity($client);++ $this->reCreateApplication(reuse: true, noUser: true);++ $request = $this->createRequest(+ method::GET,+ headers: [+ 'Authorization' => 'Bearer ' . $accessToken,+ ],+ );++ $auth = $this->prepareAuth();++ $response = $this->createResponse();++ $result = $auth->process($request, $response);++ $this->assertFalse($result->isResolved());+ $this->assertFalse($this->getContainer()->getByClass(ApplicationState::class)->hasUser());++ $body = Json::decode((string) $response->getBody());+ $this->assertEquals('access_denied', $body->error);+ $this->assertEquals(401, $response->getStatusCode());++ //++ $client->setActive();+ $em->saveEntity($client);+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function resourceAccessTokenWrong(): void+ {+ $this->reCreateApplication(reuse: true, noUser: true);++ $request = $this->createRequest(+ method::GET,+ headers: [+ 'Authorization' => 'Bearer wrong',+ ],+ );++ $auth = $this->prepareAuth();++ $response = $this->createResponse();++ $result = $auth->process($request, $response);++ $this->assertFalse($result->isResolved());+ $this->assertFalse($this->getContainer()->getByClass(ApplicationState::class)->hasUser());++ $this->assertNotNull($response->getHeader('WWW-Authenticate'));++ $body = Json::decode((string) $response->getBody());+ $this->assertObjectHasProperty('error', $body);+ $this->assertEquals('access_denied', $body->error);+ $this->assertEquals(401, $response->getStatusCode());+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function resourceSuccess($accessToken, User $user): void+ {+ $this->reCreateApplication(reuse: true, noUser: true);++ $request = $this->createRequest(+ method::GET,+ headers: [+ 'Authorization' => 'Bearer ' . $accessToken,+ ],+ );++ $auth = $this->prepareAuth();++ $response = $this->createResponse();++ $result = $auth->process($request, $response);++ $this->assertTrue($result->isResolved());+ $this->assertEquals($user->getId(), $this->getContainer()->getByClass(ApplicationState::class)->getUserId());++ $loggedUser = $this->getContainer()->getByClass(ApplicationState::class)->getUser();++ $this->assertEquals([+ Scope::GLOBAL,+ Account::ENTITY_TYPE,+ ], $loggedUser->getScopes());+ }++ /**+ * @return array{string, string}+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function refreshTokenGrant(+ string $refreshToken,+ Client $client,+ ClientSecret $secret,+ string $redirectUri,+ string $accessToken,+ ): array {++ $this->reCreateApplication(reuse: true, noUser: true);++ $em = $this->getEntityManager();++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'grant_type' => 'refresh_token',+ 'refresh_token' => $refreshToken,+ 'client_id' => $client->getIdentifier(),+ 'client_secret' => $secret->getValue(),+ 'redirect_uri' => $redirectUri,+ ]),+ resourcePath: '/oauth/token',+ );++ $response = $this->createResponseWrapper();++ $tokenEntryPoint = $this->getInjectableFactory()->create(Token::class);++ $tokenEntryPoint->run($request, $response);++ $body = Json::decode((string) $response->getBody());++ $this->assertObjectHasProperty('access_token', $body);+ $this->assertObjectHasProperty('refresh_token', $body);+ $this->assertObjectHasProperty('expires_in', $body);++ $this->assertNotEquals($accessToken, $body->access_token);+ $this->assertNotEquals($refreshToken, $body->refresh_token);++ $accessTokenRepo = $this->getInjectableFactory()->create(AccessTokenRepository::class);++ $oldAccessToken = $accessTokenRepo->getByIdentifier($accessToken);++ $this->assertNotNull($oldAccessToken);+ $this->assertTrue($oldAccessToken->isRevoked());++ $oldRefreshToken = $em->getRDBRepositoryByClass(RefreshToken::class)+ ->where([RefreshToken::FIELD_ACCESS_TOKEN . 'Id' => $oldAccessToken->getId()])+ ->findOne();++ $this->assertNotNull($oldRefreshToken);+ $this->assertTrue($oldRefreshToken->isRevoked());++ $accessToken = $body->access_token;+ $refreshToken = $body->refresh_token;++ return [$accessToken, $refreshToken];+ }++ /**+ * @return array{string, string}+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function tokenWithAuthorizationCode(+ Client $client,+ ClientSecret $secret,+ string $redirectUri,+ string $code,+ string $codeChallenge,+ ): array {++ $this->reCreateApplication(reuse: true, noUser: true);++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'grant_type' => 'authorization_code',+ 'client_id' => $client->getIdentifier(),+ 'client_secret' => $secret->getValue(),+ 'redirect_uri' => $redirectUri,+ 'code' => $code,+ 'code_verifier' => $codeChallenge,+ ]),+ resourcePath: '/oauth/token',+ );++ $response = $this->createResponseWrapper();++ $tokenEntryPoint = $this->getInjectableFactory()->create(Token::class);++ $tokenEntryPoint->run($request, $response);++ $body = Json::decode((string) $response->getBody());++ $this->assertEquals('Bearer', $body->token_type);+ $this->assertObjectHasProperty('access_token', $body);+ $this->assertObjectHasProperty('refresh_token', $body);+ $this->assertObjectHasProperty('expires_in', $body);++ $refreshToken = $body->refresh_token;+ $accessToken = $body->access_token;++ return [$accessToken, $refreshToken];+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function expiredSecret(+ Client $client,+ ClientSecret $secret,+ string $redirectUri,+ string $refreshToken,+ ): void {++ $clock = $this->createMock(Clock::class);+ $clock->expects(self::any())+ ->method('now')+ ->willReturn((new DateTimeImmutable())->modify('+1 year'));++ $this->reCreateApplication(+ reuse: true,+ noUser: true,+ binding: $this->prepareBinding(function ($binder) use ($clock) {+ $binder->bindInstance(Clock::class, $clock);+ }),+ );++ $em = $this->getEntityManager();++ $em->getTransactionManager()->start();++ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'grant_type' => 'refresh_token',+ 'refresh_token' => $refreshToken,+ 'client_id' => $client->getIdentifier(),+ 'client_secret' => $secret->getValue(),+ 'redirect_uri' => $redirectUri,+ ]),+ resourcePath: '/oauth/token',+ );++ $response = $this->createResponseWrapper();++ $tokenEntryPoint = $this->getInjectableFactory()->create(Token::class);++ $tokenEntryPoint->run($request, $response);++ $body = Json::decode((string) $response->getBody());++ $this->assertEquals('invalid_client', $body->error);++ $em->getTransactionManager()->rollback();+ }++ /**+ * @return string[]+ */+ private function getScopes(): array+ {+ return [+ Scope::GLOBAL,+ Scope::ADMIN,+ Account::ENTITY_TYPE,+ ];+ }++ private function getScopesString(): string+ {+ return implode(' ', $this->getScopes());+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function authorizeCompleteScopeMismatch(Client $client): void+ {+ $request = $this->createRequest(+ method: Method::POST,+ headers: [+ 'Content-Type' => 'application/x-www-form-urlencoded',+ ],+ body: http_build_query([+ 'clientId' => $client->getIdentifier(),+ 'approved' => 'true',+ 'scopes' => $this->getScopesString() . ' ' . Contact::ENTITY_TYPE,+ ]),+ resourcePath: '?entryPoint=oAuthAuthorizeComplete',+ );++ $response = $this->createResponseWrapper();++ $completeEntryPoint = $this->getInjectableFactory()->create(AuthorizeComplete::class);++ $thrown = false;++ try {+ $completeEntryPoint->run($request, $response);+ } catch (Forbidden) {+ $thrown = true;+ }++ $this->assertTrue($thrown, "Extra scope must not be allowed.");+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ private function obtainCodeInitital(+ Client $client,+ string $redirectUri,+ string $codeChallenge,+ User $user,+ ): void {++ $session = $this->createMock(Session::class);++ $this->reCreateApplication(+ reuse: true,+ noUser: true,+ binding: $this->prepareBinding(function (Binder $binder) use ($session) {+ $binder->bindInstance(Session::class, $session);+ }),+ );++ //++ $request = $this->createRequest(+ method: Method::GET,+ queryParams: [+ 'client_id' => $client->getIdentifier(),+ 'redirect_uri' => $redirectUri,+ 'response_type' => 'code',+ 'scope' => $this->getScopesString(),+ 'code_challenge' => PkceUtil::hashAndEncodeCodeVerifier($codeChallenge),+ 'code_challenge_method' => 'S256',+ ],+ resourcePath: '/oauth/authorize',+ );++ $response = $this->createResponseWrapper();++ $authorizeEntryPoint = $this->getInjectableFactory()->create(Authorize::class);++ $authorizationRequest = null;+ $sessionKey = null;++ $session+ ->expects(self::any())+ ->method('set')+ ->with(+ $this->callback(function ($key) use (&$sessionKey) {+ $sessionKey = $key;++ return true;+ }),+ $this->callback(function ($value) use (&$authorizationRequest) {+ $authorizationRequest = $value;++ return true;+ })+ );++ $authorizeEntryPoint->run($request, $response);++ //++ $session+ ->expects(self::any())+ ->method('get')+ ->with($sessionKey)+ ->willReturn($authorizationRequest);++ $session+ ->expects(self::once())+ ->method('clear')+ ->with($sessionKey);++ //++ $this->auth($user->getUserName());++ $this->reCreateApplication(+ reuse: true,+ binding: $this->prepareBinding(function (Binder $binder) use ($session) {+ $binder->bindInstance(Session::class, $session);+ }),+ );++ //++ $consentDataService = $this->getInjectableFactory()->create(ConsentDataService::class);++ $data = $consentDataService->getData($client->getIdentifier());++ $this->assertIsArray($data->scopeDataList);+ }++ private function createUserForTest(): User+ {+ return $this->createUser(+ userData: [+ User::FIELD_USER_NAME => self::USER_USERNAME,+ ],+ role: [+ Role::FIELD_DATA => [+ Account::ENTITY_TYPE => [+ Table::ACTION_READ => Table::LEVEL_ALL,+ ],+ ],+ ],+ );+ }+}diff --git a/tests/integration/Espo/Tools/OAuthServer/CleanupTest.php b/tests/integration/Espo/Tools/OAuthServer/CleanupTest.phpnew file mode 100644index 0000000000..8d2272ea54--- /dev/null+++ b/tests/integration/Espo/Tools/OAuthServer/CleanupTest.php@@ -0,0 +1,200 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace integration\Espo\Tools\OAuthServer;++use Espo\Core\Field\DateTime;+use Espo\Core\Utils\DateTime\Clock;+use Espo\Tools\OAuthServer\Cleanup\GeneralCleanup;+use Espo\Tools\OAuthServer\Entities\AccessToken;+use Espo\Tools\OAuthServer\Entities\AuthorizationCode;+use Espo\Tools\OAuthServer\Entities\RefreshToken;+use tests\integration\Core\BaseTestCase;++class CleanupTest extends BaseTestCase+{+ public function testCleanupAuthTokens(): void+ {+ $now = DateTime::fromString('2030-01-01 00:00');++ $this->reCreateApplicationWithNow($now);++ $em = $this->getEntityManager();++ $accessToken1 = $em->getRDBRepositoryByClass(AccessToken::class)->getNew();+ $accessToken1->setExpiresAt($now->addHours(1));+ $em->saveEntity($accessToken1);++ $accessToken2 = $em->getRDBRepositoryByClass(AccessToken::class)->getNew();+ $accessToken2->setExpiresAt($now->addHours(1));+ $em->saveEntity($accessToken2);++ $refreshToken = $em->getRDBRepositoryByClass(RefreshToken::class)->getNew();+ $refreshToken+ ->setAccessToken($accessToken2)+ ->setExpiresAt($now->addMonths(3));+ $em->saveEntity($refreshToken);++ //++ $cleanup = $this->getInjectableFactory()->create(GeneralCleanup::class);+ $cleanup->process();++ $this->assertNotNull(+ $em->getRDBRepositoryByClass(AccessToken::class)->getById($accessToken1->getId())+ );++ $this->assertNotNull(+ $em->getRDBRepositoryByClass(AccessToken::class)->getById($accessToken2->getId())+ );++ //++ $now = $now->addDays(15)->addHours(1);++ $this->reCreateApplicationWithNow($now);++ //++ $cleanup = $this->getInjectableFactory()->create(GeneralCleanup::class);+ $cleanup->process();++ $this->assertFalse(+ $em->getRDBRepositoryByClass(AccessToken::class)->getById($accessToken1->getId()) !== null+ );++ $this->assertTrue(+ $em->getRDBRepositoryByClass(AccessToken::class)->getById($accessToken2->getId()) !== null+ );++ //++ $refreshToken->setRevoked();+ $em->saveEntity($refreshToken);++ //++ $cleanup->process();++ $this->assertFalse(+ $em->getRDBRepositoryByClass(AccessToken::class)->getById($accessToken2->getId()) !== null+ );+ }++ public function testCleanupRefreshTokens(): void+ {+ $now = DateTime::fromString('2030-01-01 00:00');++ $this->reCreateApplicationWithNow($now);++ $em = $this->getEntityManager();++ $refreshToken = $em->getRDBRepositoryByClass(RefreshToken::class)->getNew();+ $refreshToken+ ->setExpiresAt($now->addMonths(1));+ $em->saveEntity($refreshToken);++ //++ $cleanup = $this->getInjectableFactory()->create(GeneralCleanup::class);+ $cleanup->process();++ $this->assertNotNull(+ $em->getRDBRepositoryByClass(RefreshToken::class)->getById($refreshToken->getId())+ );++ //++ $now = $now->addMonths(1)->addDays(15);++ $this->reCreateApplicationWithNow($now);++ //++ $cleanup = $this->getInjectableFactory()->create(GeneralCleanup::class);+ $cleanup->process();++ $this->assertFalse(+ $em->getRDBRepositoryByClass(RefreshToken::class)->getById($refreshToken->getId()) !== null+ );+ }++ public function testCleanupAuthorizationCode(): void+ {+ $now = DateTime::fromString('2030-01-01 00:00');++ $this->reCreateApplicationWithNow($now);++ $em = $this->getEntityManager();++ $code = $em->getRDBRepositoryByClass(AuthorizationCode::class)->getNew();+ $code+ ->setExpiresAt($now->addHours(1));+ $em->saveEntity($code);++ //++ $cleanup = $this->getInjectableFactory()->create(GeneralCleanup::class);+ $cleanup->process();++ $this->assertNotNull(+ $em->getRDBRepositoryByClass(AuthorizationCode::class)->getById($code->getId())+ );++ //++ $now = $now->addHours(1)->addDays(15);++ $this->reCreateApplicationWithNow($now);++ //++ $cleanup = $this->getInjectableFactory()->create(GeneralCleanup::class);+ $cleanup->process();++ $this->assertFalse(+ $em->getRDBRepositoryByClass(AuthorizationCode::class)->getById($code->getId()) !== null+ );+ }++ private function reCreateApplicationWithNow(DateTime $now): void+ {+ $clock = $this->createMock(Clock::class);+ $clock->expects(self::any())+ ->method('now')+ ->willReturn($now->toDateTime());++ $this->reCreateApplication(+ reuse: true,+ binding: $this->prepareBinding(function ($binder) use ($clock) {+ $binder->bindInstance(Clock::class, $clock);+ }),+ );+ }+}diff --git a/tests/integration/Espo/Tools/OAuthServer/ConnectedAppTest.php b/tests/integration/Espo/Tools/OAuthServer/ConnectedAppTest.phpnew file mode 100644index 0000000000..14d1532909--- /dev/null+++ b/tests/integration/Espo/Tools/OAuthServer/ConnectedAppTest.php@@ -0,0 +1,167 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace integration\Espo\Tools\OAuthServer;++use Espo\Core\Acl\Scope;+use Espo\Core\Field\DateTime;+use Espo\Tools\OAuthServer\ClientType;+use Espo\Tools\OAuthServer\ConnectedApp\ConnectedAppService;+use Espo\Tools\OAuthServer\Entities\AccessToken;+use Espo\Tools\OAuthServer\Entities\Client;+use Espo\Tools\OAuthServer\Entities\RefreshToken;+use Espo\Tools\OAuthServer\Repository\AccessTokenRepository;+use tests\integration\Core\BaseTestCase;++class ConnectedAppTest extends BaseTestCase+{+ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testListAndDisconnect(): void+ {+ $em = $this->getEntityManager();++ $user1 = $this->createUser('test-1');+ $user2 = $this->createUser('test-2');++ $client1 = $this->createClient('Test 1');+ $client2 = $this->createClient('Test 2');++ //++ $em->saveEntity(+ $em->getRDBRepositoryByClass(RefreshToken::class)+ ->getNew()+ ->setClient($client1)+ ->setExpiresAt(DateTime::createNow()->addHours(1))+ ->setUser($user1)+ );++ $em->saveEntity(+ $em->getRDBRepositoryByClass(RefreshToken::class)+ ->getNew()+ ->setClient($client2)+ ->setExpiresAt(DateTime::createNow()->addHours(1))+ ->setUser($user1)+ );++ $em->saveEntity(+ $em->getRDBRepositoryByClass(RefreshToken::class)+ ->getNew()+ ->setClient($client1)+ ->setExpiresAt(DateTime::createNow()->addHours(1))+ ->setUser($user1)+ );++ $em->saveEntity(+ $em->getRDBRepositoryByClass(AccessToken::class)+ ->getNew()+ ->setClient($client1)+ ->setExpiresAt(DateTime::createNow()->addHours(1))+ ->setUser($user1)+ );++ $em->saveEntity(+ $em->getRDBRepositoryByClass(AccessToken::class)+ ->getNew()+ ->setClient($client2)+ ->setExpiresAt(DateTime::createNow()->addHours(1))+ ->setUser($user1)+ );++ $em->saveEntity(+ $em->getRDBRepositoryByClass(RefreshToken::class)+ ->getNew()+ ->setClient($client1)+ ->setExpiresAt(DateTime::createNow()->addHours(1))+ ->setUser($user2)+ );++ //++ $accessTokenRepo = $this->getInjectableFactory()->create(AccessTokenRepository::class);++ $service = $this->getInjectableFactory()->create(ConnectedAppService::class);++ $apps = $service->getList($user1);++ $this->assertCount(2, $apps);+ $this->assertEquals($client1->getIdentifier(), $apps[0]->id);++ $this->assertEquals(+ 1,+ $accessTokenRepo+ ->findActiveForClientIdAndUser($client1->getId(), $user1->getId())+ ->count(),+ );++ //++ $service->disconnect($user1, $client1->getIdentifier());++ $apps = $service->getList($user1);++ $this->assertCount(1, $apps);++ $this->assertEquals(+ 0,+ $accessTokenRepo+ ->findActiveForClientIdAndUser($client1->getId(), $user1->getId())+ ->count(),+ );++ //++ $apps = $service->getList($user2);++ $this->assertCount(1, $apps);++ //++ $apps = $service->getList($user2);++ $this->assertCount(1, $apps);+ }++ private function createClient(string $name): Client+ {+ $em = $this->getEntityManager();++ $client = $em->getRDBRepositoryByClass(Client::class)->getNew();+ $client+ ->setName($name)+ ->setScopes([Scope::GLOBAL])+ ->setClientType(ClientType::Confidential)+ ->setRedirectUris(['http://localhost/oauth/callback']);+ $em->saveEntity($client);++ return $client;+ }+}diff --git a/tests/integration/Espo/Tools/OAuthServer/ExpirationTest.php b/tests/integration/Espo/Tools/OAuthServer/ExpirationTest.phpnew file mode 100644index 0000000000..e7895095c1--- /dev/null+++ b/tests/integration/Espo/Tools/OAuthServer/ExpirationTest.php@@ -0,0 +1,153 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace integration\Espo\Tools\OAuthServer;++use Espo\Core\Field\Date;+use Espo\Core\Field\DateTime;+use Espo\Core\Utils\DateTime\Clock;+use Espo\Tools\OAuthServer\Entities\AccessToken;+use Espo\Tools\OAuthServer\Entities\AuthorizationCode;+use Espo\Tools\OAuthServer\Entities\Client;+use Espo\Tools\OAuthServer\Entities\ClientSecret;+use Espo\Tools\OAuthServer\Entities\RefreshToken;+use Espo\Tools\OAuthServer\Jobs\OAuthServerControl;+use tests\integration\Core\BaseTestCase;++class ExpirationTest extends BaseTestCase+{+ public function testExpire(): void+ {+ $now = DateTime::fromString('2030-01-01 00:00');++ $clock = $this->createClock($now);++ $this->reCreateApplication(+ reuse: true,+ noUser: true,+ binding: $this->prepareBinding(function ($binder) use ($clock) {+ $binder->bindInstance(Clock::class, $clock);+ }),+ );++ $em = $this->getEntityManager();++ $client = $em->getRDBRepositoryByClass(Client::class)->getNew();+ $em->saveEntity($client);++ //++ $expirationDate = Date::fromDateTime($now->toDateTime())->addMonths(1);+ $expiresAt = DateTime::fromDateTime($now->toDateTime())->addMonths(1);++ $secret = $em->getRDBRepositoryByClass(ClientSecret::class)->getNew();+ $secret+ ->setClient($client)+ ->setExpirationDate($expirationDate);+ $em->saveEntity($secret);++ $code = $em->getRDBRepositoryByClass(AuthorizationCode::class)->getNew();+ $code+ ->setClient($client)+ ->setExpiresAt($expiresAt);+ $em->saveEntity($code);++ $accessToken = $em->getRDBRepositoryByClass(AccessToken::class)->getNew();+ $accessToken+ ->setClient($client)+ ->setExpiresAt($expiresAt);+ $em->saveEntity($accessToken);++ $refreshToken = $em->getRDBRepositoryByClass(RefreshToken::class)->getNew();+ $refreshToken+ ->setClient($client)+ ->setExpiresAt($expiresAt);+ $em->saveEntity($refreshToken);++ //++ $job = $this->getInjectableFactory()->create(OAuthServerControl::class);++ $job->run();++ $em->refreshEntity($secret);+ $em->refreshEntity($code);+ $em->refreshEntity($accessToken);+ $em->refreshEntity($refreshToken);++ $this->assertTrue($secret->isActive());+ $this->assertTrue($code->isActive());+ $this->assertTrue($accessToken->isActive());+ $this->assertTrue($refreshToken->isActive());++ //++ $now = $now->addMonths(1);++ $clock = $this->createClock($now);++ $this->reCreateApplication(+ reuse: true,+ noUser: true,+ binding: $this->prepareBinding(function ($binder) use ($clock) {+ $binder->bindInstance(Clock::class, $clock);+ }),+ );++ //++ $job = $this->getInjectableFactory()->create(OAuthServerControl::class);++ $job->run();++ $em->refreshEntity($secret);+ $em->refreshEntity($code);+ $em->refreshEntity($accessToken);+ $em->refreshEntity($refreshToken);++ $this->assertTrue($secret->isExpired());+ $this->assertFalse($secret->isActive());+ $this->assertFalse($secret->isRevoked());++ $this->assertTrue($code->isExpired());+ $this->assertTrue($accessToken->isExpired());+ $this->assertTrue($refreshToken->isExpired());+ }++ private function createClock(DateTime $now): Clock+ {+ $clock = $this->createMock(Clock::class);++ $clock->expects(self::any())+ ->method('now')+ ->willReturn($now->toDateTime());++ return $clock;+ }+}diff --git a/tests/unit/Espo/Core/Acl/Map/DefaultCacheKeyProviderTest.php b/tests/unit/Espo/Core/Acl/Map/DefaultCacheKeyProviderTest.phpnew file mode 100644index 0000000000..c5b7590e2a--- /dev/null+++ b/tests/unit/Espo/Core/Acl/Map/DefaultCacheKeyProviderTest.php@@ -0,0 +1,65 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace tests\unit\Espo\Core\Acl\Map;++use Espo\Core\Acl\Map\DefaultCacheKeyProvider;+use Espo\Entities\User;+use PHPUnit\Framework\Attributes\DataProvider;+use PHPUnit\Framework\TestCase;++class DefaultCacheKeyProviderTest extends TestCase+{+ #[DataProvider('provider')]+ public function testKey(string $expected, string $userId, ?array $scopes = null): void+ {+ $user = $this->createMock(User::class);++ $user->expects(self::any())+ ->method('getId')+ ->willReturn($userId);++ $user->expects(self::any())+ ->method('getScopes')+ ->willReturn($scopes);++ $provider = new DefaultCacheKeyProvider($user);++ $this->assertEquals($expected, $provider->get());+ }++ public static function provider(): array+ {+ return [+ ['aclMap/01', '01', null],+ ['aclMap/01/37f6e5e382faedc68e0769892e78d8d3', '01', ['Admin', 'Global']],+ ['aclMap/01/99aa06d3014798d86001c324468d497f', '01', []],+ ];+ }+}diff --git a/tests/unit/Espo/Core/Acl/Table/DefaultCacheKeyProviderTest.php b/tests/unit/Espo/Core/Acl/Table/DefaultCacheKeyProviderTest.phpnew file mode 100644index 0000000000..ce96daa2a5--- /dev/null+++ b/tests/unit/Espo/Core/Acl/Table/DefaultCacheKeyProviderTest.php@@ -0,0 +1,65 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace tests\unit\Espo\Core\Acl\Table;++use Espo\Core\Acl\Table\DefaultCacheKeyProvider;+use Espo\Entities\User;+use PHPUnit\Framework\Attributes\DataProvider;+use PHPUnit\Framework\TestCase;++class DefaultCacheKeyProviderTest extends TestCase+{+ #[DataProvider('provider')]+ public function testKey(string $expected, string $userId, ?array $scopes = null): void+ {+ $user = $this->createMock(User::class);++ $user->expects(self::any())+ ->method('getId')+ ->willReturn($userId);++ $user->expects(self::any())+ ->method('getScopes')+ ->willReturn($scopes);++ $provider = new DefaultCacheKeyProvider($user);++ $this->assertEquals($expected, $provider->get());+ }++ public static function provider(): array+ {+ return [+ ['acl/01', '01', null],+ ['acl/01/37f6e5e382faedc68e0769892e78d8d3', '01', ['Admin', 'Global']],+ ['acl/01/99aa06d3014798d86001c324468d497f', '01', []],+ ];+ }+}diff --git a/tests/unit/Espo/Core/Api/AuthTest.php b/tests/unit/Espo/Core/Api/AuthTest.phpindex 9bde0116e6..76026ff9e2 100644--- a/tests/unit/Espo/Core/Api/AuthTest.php+++ b/tests/unit/Espo/Core/Api/AuthTest.php@@ -33,8 +33,8 @@ use Espo\Core\Api\Auth;use Espo\Core\Api\RequestWrapper;use Espo\Core\Api\Response;use Espo\Core\Authentication\Authentication;-use Espo\Core\Authentication\ConfigDataProvider;use Espo\Core\Authentication\HeaderKey;+use Espo\Core\Authentication\Login\MethodResolver;use Espo\Core\Authentication\Result;use Espo\Core\Authentication\Result\Data;use Espo\Core\Utils\Json;@@ -63,12 +63,10 @@ class AuthTest extends TestCaseResult::secondStepRequired($this->createMock(User::class), Data::create()));- $configDataProvider = $this->createConfigDataProvider();-$auth = new Auth(log: $this->createMock(Log::class),authentication: $authentication,- configDataProvider: $configDataProvider,+ methodResolver: $this->createMock(MethodResolver::class),authRequired: false,);@@ -94,12 +92,10 @@ class AuthTest extends TestCaseResult::fail());- $configDataProvider = $this->createConfigDataProvider();-$auth = new Auth(log: $this->createMock(Log::class),authentication: $authentication,- configDataProvider: $configDataProvider,+ methodResolver: $this->createMock(MethodResolver::class),);$result = $auth->process($request, $response);@@ -142,14 +138,4 @@ class AuthTest extends TestCasebody: Json::encode((object) []),);}-- private function createConfigDataProvider(): ConfigDataProvider- {- $configDataProvider = $this->createMock(ConfigDataProvider::class);- $configDataProvider- ->method('getLoginMetadataParamsList')- ->willReturn([]);-- return $configDataProvider;- }}diff --git a/tests/unit/Espo/Core/Authentication/Login/MethodResolverTest.php b/tests/unit/Espo/Core/Authentication/Login/MethodResolverTest.phpnew file mode 100644index 0000000000..13e1b7baa4--- /dev/null+++ b/tests/unit/Espo/Core/Authentication/Login/MethodResolverTest.php@@ -0,0 +1,162 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace tests\unit\Espo\Core\Authentication\Login;++use Espo\Core\Api\Method;+use Espo\Core\Api\RequestWrapper;+use Espo\Core\Authentication\ConfigDataProvider;+use Espo\Core\Authentication\Login\MetadataParams;+use Espo\Core\Authentication\Login\MethodResolver;+use PHPUnit\Framework\Attributes\DataProvider;+use PHPUnit\Framework\TestCase;+use Slim\Psr7\Factory\ServerRequestFactory;++class MethodResolverTest extends TestCase+{++ /**+ * @param MetadataParams[] $paramsList+ * @param array{string, string} $headerPair+ */+ #[DataProvider('provider')]+ public function testResolve(array $paramsList, array $headerPair, ?string $expected): void+ {+ $this->processTest($paramsList, $headerPair, $expected);+ }++ public static function provider(): array+ {+ $paramsList1 = [+ new MetadataParams(+ method: 'Test',+ ),+ new MetadataParams(+ method: 'ApiKey',+ api: true,+ credentialsHeader: 'X-Api-Key',+ ),+ new MetadataParams(+ method: 'OAuth',+ api: true,+ credentialsHeader: 'Authorization',+ credentialsHeaderScheme: 'Bearer',+ ),+ ];++ $paramsList2 = [+ new MetadataParams(+ method: 'Some',+ api: true,+ credentialsHeader: 'Authorization',+ ),+ new MetadataParams(+ method: 'OAuth',+ api: true,+ credentialsHeader: 'Authorization',+ credentialsHeaderScheme: 'Bearer',+ ),+ ];++ $paramsList3 = [+ new MetadataParams(+ method: 'OAuth',+ api: true,+ credentialsHeader: 'Authorization',+ credentialsHeaderScheme: 'Bearer',+ ),+ new MetadataParams(+ method: 'Some',+ api: true,+ credentialsHeader: 'Authorization',+ ),+ ];++ return [+ [+ $paramsList1,+ ['Authorization', 'Bearer test'],+ 'OAuth',+ ],+ [+ $paramsList1,+ ['X-Api-Key', 'test'],+ 'ApiKey',+ ],+ [+ $paramsList1,+ ['Espo-Authorization', 'test'],+ null,+ ],+ [+ $paramsList2,+ ['Authorization', 'Bearer test'],+ 'OAuth',+ ],+ [+ $paramsList3,+ ['Authorization', 'Bearer test'],+ 'OAuth',+ ],+ [+ $paramsList2,+ ['Authorization', 'test'],+ 'Some',+ ],+ [+ $paramsList3,+ ['Authorization', 'test'],+ 'Some',+ ],+ ];+ }++ /**+ * @param MetadataParams[] $paramsList+ * @param array{string, string} $headerPair+ */+ private function processTest(array $paramsList, array $headerPair, ?string $expected): void+ {+ $config = $this->createMock(ConfigDataProvider::class);++ $config+ ->expects(self::any())+ ->method('getLoginMetadataParamsList')+ ->willReturn($paramsList);++ $request = new RequestWrapper(+ psr7Request: (new ServerRequestFactory())->createServerRequest(Method::GET, 'http://localhost')+ ->withHeader($headerPair[0], $headerPair[1]),+ );++ $resolver = new MethodResolver($config);++ $this->assertEquals($expected, $resolver->resolve($request));+ }+}diff --git a/tests/unit/Espo/Tools/OAuthServer/Scope/ScopeSorterTest.php b/tests/unit/Espo/Tools/OAuthServer/Scope/ScopeSorterTest.phpnew file mode 100644index 0000000000..3c9c5baaab--- /dev/null+++ b/tests/unit/Espo/Tools/OAuthServer/Scope/ScopeSorterTest.php@@ -0,0 +1,58 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace tests\unit\Espo\Tools\OAuthServer\Scope;++use Espo\Core\Acl\Scope;+use Espo\Modules\Crm\Entities\Account;+use Espo\Modules\Crm\Entities\Lead;+use Espo\Tools\OAuthServer\Scope\ScopeSorter;+use PHPUnit\Framework\TestCase;++class ScopeSorterTest extends TestCase+{+ public function testSort(): void+ {+ $sorted = (new ScopeSorter())->sort([+ Lead::ENTITY_TYPE,+ Account::ENTITY_TYPE,+ Scope::ADMIN,+ Scope::GLOBAL,+ ]);++ $expected = [+ Scope::GLOBAL,+ Scope::ADMIN,+ Account::ENTITY_TYPE,+ Lead::ENTITY_TYPE,+ ];++ $this->assertEquals($expected, $sorted);+ }+}