Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

feat(plugin-auth): visibility picker for OAuth credentials (#39840)

YungLe219596c4dfc2
diff --git a/api/controllers/console/datasets/rag_pipeline/datasource_auth.py b/api/controllers/console/datasets/rag_pipeline/datasource_auth.py
index df87c4dd2ee..a28b44d0346 100644
--- a/api/controllers/console/datasets/rag_pipeline/datasource_auth.py
+++ b/api/controllers/console/datasets/rag_pipeline/datasource_auth.py
@@ -30,6 +30,7 @@ from graphon.model_runtime.errors.validate import CredentialsValidateFailedError
from libs.helper import dump_response
from libs.login import login_required
from models import Account
+from models.enums import PermissionEnum
from models.provider_ids import DatasourceProviderID
from services.datasource_provider_service import DatasourceProviderService
from services.plugin.oauth_service import OAuthProxyService
@@ -74,6 +75,13 @@ class DatasourceUpdateNamePayload(BaseModel):
class DatasourceOAuthAuthorizationQuery(BaseModel):
credential_id: str | None = Field(default=None, description="Credential ID to reauthorize")
+ visibility: str | None = Field(
+ default=None,
+ description=(
+ "Visibility for the credential to be created. Accepts 'only_me' or 'all_team_members'; "
+ "any other value falls back to 'only_me'. Ignored on reauthorization (credential_id set)."
+ ),
+ )
class DatasourceOAuthCallbackQuery(BaseModel):
@@ -175,12 +183,27 @@ class DatasourcePluginOAuthAuthorizationUrl(Resource):
if not oauth_config:
raise ValueError(f"No OAuth Client Config for {provider_id}")
+ # Visibility is chosen by the user in the frontend before the redirect,
+ # then read back in the callback below when the credential is created.
+ # Only ONLY_ME / ALL_TEAM are accepted; anything else falls back to
+ # ONLY_ME (OAuth tokens are personal by nature).
+ # For reauthorization (credential_id set), visibility is ignored — we
+ # keep whatever the credential was created with.
+ raw_visibility = request.args.get("visibility")
+ try:
+ requested_visibility = PermissionEnum(raw_visibility) if raw_visibility else PermissionEnum.ONLY_ME
+ except ValueError:
+ requested_visibility = PermissionEnum.ONLY_ME
+ if requested_visibility not in (PermissionEnum.ONLY_ME, PermissionEnum.ALL_TEAM):
+ requested_visibility = PermissionEnum.ONLY_ME
+
context_id = OAuthProxyService.create_proxy_context(
user_id=current_user.id,
tenant_id=tenant_id,
plugin_id=plugin_id,
provider=provider_name,
credential_id=credential_id,
+ extra_data={"visibility": requested_visibility.value},
)
oauth_handler = OAuthHandler()
redirect_uri = f"{dify_config.CONSOLE_API_URL}/console/api/oauth/plugin/{provider_id}/datasource/callback"
@@ -253,6 +276,17 @@ class DatasourceOAuthCallback(Resource):
credential_id=credential_id,
)
else:
+ # Visibility was chosen by the user before the redirect and stashed
+ # in the proxy context. Fall back to ONLY_ME for older cookies (or
+ # anything that somehow wrote an unexpected value) — OAuth tokens
+ # are personal by default.
+ stored_visibility = context.get("visibility")
+ try:
+ visibility = PermissionEnum(stored_visibility) if stored_visibility else PermissionEnum.ONLY_ME
+ except ValueError:
+ visibility = PermissionEnum.ONLY_ME
+ if visibility not in (PermissionEnum.ONLY_ME, PermissionEnum.ALL_TEAM):
+ visibility = PermissionEnum.ONLY_ME
datasource_provider_service.add_datasource_oauth_provider(
tenant_id=tenant_id,
provider_id=datasource_provider_id,
@@ -260,6 +294,8 @@ class DatasourceOAuthCallback(Resource):
name=oauth_response.metadata.get("name") or None,
expire_at=oauth_response.expires_at,
credentials=dict(oauth_response.credentials),
+ user_id=user_id,
+ visibility=visibility,
)
return redirect(f"{dify_config.CONSOLE_WEB_URL}/oauth-callback")
@@ -381,11 +417,12 @@ class DatasourceAuthListApi(Resource):
@setup_required
@login_required
@account_initialization_required
+ @with_current_user
@with_current_tenant_id
- def get(self, current_tenant_id: str):
+ def get(self, current_tenant_id: str, user: Account):
datasource_provider_service = DatasourceProviderService()
datasources = datasource_provider_service.get_all_datasource_credentials(
- tenant_id=current_tenant_id, session=db.session()
+ tenant_id=current_tenant_id, session=db.session(), user=user
)
return dump_response(DatasourceProviderAuthListResponse, {"result": datasources}), 200
@@ -400,11 +437,12 @@ class DatasourceHardCodeAuthListApi(Resource):
@setup_required
@login_required
@account_initialization_required
+ @with_current_user
@with_current_tenant_id
- def get(self, current_tenant_id: str):
+ def get(self, current_tenant_id: str, user: Account):
datasource_provider_service = DatasourceProviderService()
datasources = datasource_provider_service.get_hard_code_datasource_credentials(
- tenant_id=current_tenant_id, session=db.session()
+ tenant_id=current_tenant_id, session=db.session(), user=user
)
return dump_response(DatasourceProviderAuthListResponse, {"result": datasources}), 200
diff --git a/api/controllers/console/workspace/tool_providers.py b/api/controllers/console/workspace/tool_providers.py
index badfb21eed6..a02e603373d 100644
--- a/api/controllers/console/workspace/tool_providers.py
+++ b/api/controllers/console/workspace/tool_providers.py
@@ -67,6 +67,7 @@ from fields.base import ResponseModel
from libs.helper import alphanumeric, dump_response, uuid_value
from libs.login import login_required
from models import Account
+from models.enums import PermissionEnum
from models.provider_ids import ToolProviderID
# from models.provider_ids import ToolProviderID
@@ -97,6 +98,13 @@ class ToolProviderListQuery(BaseModel):
type: Literal["builtin", "model", "api", "workflow", "mcp"] | None = None
+class ToolOAuthAuthorizationQuery(BaseModel):
+ visibility: Literal["only_me", "all_team_members"] | None = Field(
+ default=None,
+ description="Visibility for the OAuth credential. Defaults to 'only_me'.",
+ )
+
+
class BuiltinToolCredentialDeletePayload(BaseModel):
credential_id: str
@@ -436,6 +444,7 @@ class WorkflowToolDetailResponse(ResponseModel):
register_schema_models(
console_ns,
ToolProviderListQuery,
+ ToolOAuthAuthorizationQuery,
UrlQuery,
ProviderQuery,
BuiltinCredentialListQuery,
@@ -1107,6 +1116,7 @@ class ToolLabelsApi(Resource):
@console_ns.route("/oauth/plugin/<path:provider>/tool/authorization-url")
class ToolPluginOAuthApi(Resource):
+ @console_ns.doc(params=query_params_from_model(ToolOAuthAuthorizationQuery))
@console_ns.response(
200,
"Tool OAuth authorization URL generated successfully",
@@ -1128,9 +1138,25 @@ class ToolPluginOAuthApi(Resource):
if oauth_client_params is None:
raise Forbidden("no oauth available client config found for this tool provider")
+ # Visibility is chosen by the user in the frontend before the redirect,
+ # then read back in the callback below when the credential is created.
+ # Only ONLY_ME / ALL_TEAM are accepted; anything else falls back to
+ # ONLY_ME (OAuth tokens are personal by nature).
+ raw_visibility = request.args.get("visibility")
+ try:
+ requested_visibility = PermissionEnum(raw_visibility) if raw_visibility else PermissionEnum.ONLY_ME
+ except ValueError:
+ requested_visibility = PermissionEnum.ONLY_ME
+ if requested_visibility not in (PermissionEnum.ONLY_ME, PermissionEnum.ALL_TEAM):
+ requested_visibility = PermissionEnum.ONLY_ME
+
oauth_handler = OAuthHandler()
context_id = OAuthProxyService.create_proxy_context(
- user_id=user.id, tenant_id=tenant_id, plugin_id=plugin_id, provider=provider_name
+ user_id=user.id,
+ tenant_id=tenant_id,
+ plugin_id=plugin_id,
+ provider=provider_name,
+ extra_data={"visibility": requested_visibility.value},
)
redirect_uri = f"{dify_config.CONSOLE_API_URL}/console/api/oauth/plugin/{provider}/tool/callback"
authorization_url_response = oauth_handler.get_authorization_url(
@@ -1194,7 +1220,17 @@ class ToolOAuthCallback(Resource):
if not credentials:
raise Exception("the plugin credentials failed")
- # add credentials to database — OAuth tokens default to only_me since they're personal
+ # Visibility was chosen by the user before the redirect and stashed in
+ # the proxy context. Fall back to ONLY_ME for older cookies (or for
+ # anything that somehow wrote an unexpected value) — OAuth tokens are
+ # personal by default.
+ stored_visibility = context.get("visibility")
+ try:
+ visibility = PermissionEnum(stored_visibility) if stored_visibility else PermissionEnum.ONLY_ME
+ except ValueError:
+ visibility = PermissionEnum.ONLY_ME
+ if visibility not in (PermissionEnum.ONLY_ME, PermissionEnum.ALL_TEAM):
+ visibility = PermissionEnum.ONLY_ME
BuiltinToolManageService.add_builtin_tool_provider(
user_id=user_id,
tenant_id=tenant_id,
@@ -1202,7 +1238,7 @@ class ToolOAuthCallback(Resource):
credentials=dict(credentials),
expires_at=expires_at,
api_type=CredentialType.OAUTH2,
- visibility="only_me",
+ visibility=visibility.value,
)
# response-contract:ignore redirect response
return redirect(f"{dify_config.CONSOLE_WEB_URL}/oauth-callback")
diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md
index 9fff14ab3b1..b403b6713da 100644
--- a/api/openapi/markdown/console-openapi.md
+++ b/api/openapi/markdown/console-openapi.md
@@ -7723,6 +7723,7 @@ Initiate OAuth login process
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ------ |
| credential_id | query | Credential ID to reauthorize | No | string |
+| visibility | query | Visibility for the credential to be created. Accepts 'only_me' or 'all_team_members'; any other value falls back to 'only_me'. Ignored on reauthorization (credential_id set). | No | string |
| provider_id | path | | Yes | string |
#### Responses
@@ -7736,6 +7737,7 @@ Initiate OAuth login process
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ------ |
+| visibility | query | Visibility for the OAuth credential. Defaults to 'only_me'. | No | string, <br>**Available values:** "all_team_members", "only_me" |
| provider | path | | Yes | string |
#### Responses
@@ -17205,6 +17207,7 @@ Model class for provider custom model configuration.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| credential_id | string | Credential ID to reauthorize | No |
+| visibility | string | Visibility for the credential to be created. Accepts 'only_me' or 'all_team_members'; any other value falls back to 'only_me'. Ignored on reauthorization (credential_id set). | No |
#### DatasourceOAuthCallbackQuery
@@ -22580,6 +22583,12 @@ Tool label
| ---- | ---- | ----------- | -------- |
| ToolLabelListResponse | array | | |
+#### ToolOAuthAuthorizationQuery
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| visibility | string | Visibility for the OAuth credential. Defaults to 'only_me'. | No |
+
#### ToolOAuthCustomClientPayload
| Name | Type | Description | Required |
diff --git a/api/services/datasource_provider_service.py b/api/services/datasource_provider_service.py
index 5de194dd262..ed394bd0a29 100644
--- a/api/services/datasource_provider_service.py
+++ b/api/services/datasource_provider_service.py
@@ -22,6 +22,7 @@ from core.tools.utils.encryption import ProviderConfigCache, ProviderConfigEncry
from extensions.ext_database import db
from extensions.ext_redis import redis_client
from graphon.model_runtime.entities.provider_entities import FormType
+from models.enums import PermissionEnum
from models.oauth import DatasourceOauthParamConfig, DatasourceOauthTenantParamConfig, DatasourceProvider
from models.provider_ids import DatasourceProviderID
@@ -642,10 +643,23 @@ class DatasourceProviderService:
avatar_url: str | None,
expire_at: int,
credentials: dict[str, Any],
+ user_id: str | None = None,
+ visibility: PermissionEnum | None = None,
) -> None:
"""
- add datasource oauth provider
+ add datasource oauth provider.
+
+ ``user_id`` is the creator whose visibility choice this credential is
+ scoped to. When ``visibility`` is only_me the row is visible only to
+ this creator; ``all_team_members`` shares it workspace-wide.
+ Callers that omit ``user_id``/``visibility`` fall back to the previous
+ team-wide default (matches how the DB column defaults).
"""
+ # partial_members isn't supported for plugin credentials (matches the
+ # tool + api-key paths); collapse it to ALL_TEAM so we never persist
+ # an unreachable value here.
+ if visibility == PermissionEnum.PARTIAL_TEAM:
+ visibility = PermissionEnum.ALL_TEAM
credential_type = CredentialType.OAUTH2
with sessionmaker(bind=db.engine).begin() as session:
lock = f"datasource_provider_create_lock:{tenant_id}_{provider_id}_{credential_type.value}"
@@ -692,16 +706,21 @@ class DatasourceProviderService:
if key in provider_credential_secret_variables:
credentials[key] = encrypter.encrypt_token(tenant_id, value)
- datasource_provider = DatasourceProvider(
- tenant_id=tenant_id,
- name=db_provider_name,
- provider=provider_id.provider_name,
- plugin_id=provider_id.plugin_id,
- auth_type=credential_type.value,
- encrypted_credentials=credentials,
- avatar_url=avatar_url or "default",
- expires_at=expire_at,
- )
+ datasource_provider_kwargs: dict[str, Any] = {
+ "tenant_id": tenant_id,
+ "name": db_provider_name,
+ "provider": provider_id.provider_name,
+ "plugin_id": provider_id.plugin_id,
+ "auth_type": credential_type.value,
+ "encrypted_credentials": credentials,
+ "avatar_url": avatar_url or "default",
+ "expires_at": expire_at,
+ }
+ if user_id is not None:
+ datasource_provider_kwargs["user_id"] = user_id
+ if visibility is not None:
+ datasource_provider_kwargs["visibility"] = visibility
+ datasource_provider = DatasourceProvider(**datasource_provider_kwargs)
session.add(datasource_provider)
def add_datasource_api_key_provider(
@@ -879,11 +898,17 @@ class DatasourceProviderService:
return copy_credentials_list
- def get_all_datasource_credentials(self, tenant_id: str, *, session: Session) -> list[dict]:
+ def get_all_datasource_credentials(
+ self, tenant_id: str, *, session: Session, user: "Account | None" = None
+ ) -> list[dict]:
"""
get datasource credentials.
- :return:
+ ``user`` is threaded through to ``list_datasource_credentials`` so the
+ embedded ``credentials_list`` per datasource is filtered by
+ per-credential visibility. Callers that omit it (background /
+ maintenance jobs) get the pre-visibility behavior of returning every
+ credential in the workspace.
"""
# get all plugin providers
manager = PluginDatasourceManager()
@@ -895,6 +920,7 @@ class DatasourceProviderService:
tenant_id=tenant_id,
provider=datasource.provider,
plugin_id=datasource.plugin_id,
+ user=user,
session=session,
)
redirect_uri = (
@@ -938,11 +964,14 @@ class DatasourceProviderService:
)
return datasource_credentials
- def get_hard_code_datasource_credentials(self, tenant_id: str, *, session: Session) -> list[dict]:
+ def get_hard_code_datasource_credentials(
+ self, tenant_id: str, *, session: Session, user: "Account | None" = None
+ ) -> list[dict]:
"""
get hard code datasource credentials.
- :return:
+ ``user`` is threaded through to ``list_datasource_credentials`` so
+ credentials in the returned envelope are visibility-filtered.
"""
# get all plugin providers
manager = PluginDatasourceManager()
@@ -960,6 +989,7 @@ class DatasourceProviderService:
tenant_id=tenant_id,
provider=datasource.provider,
plugin_id=datasource.plugin_id,
+ user=user,
session=session,
)
redirect_uri = "{}/console/api/oauth/plugin/{}/datasource/callback".format(
diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_datasource_auth.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_datasource_auth.py
index 4bdc862b651..63a61586ef9 100644
--- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_datasource_auth.py
+++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_datasource_auth.py
@@ -151,6 +151,7 @@ class TestDatasourcePluginOAuthAuthorizationUrl:
plugin_id="langgenius/notion_datasource",
provider="notion",
credential_id="cred-1",
+ extra_data={"visibility": "only_me"},
)
get_authorization_url.assert_called_once()
assert get_authorization_url.call_args.kwargs["tenant_id"] == "tenant-1"
@@ -250,6 +251,10 @@ class TestDatasourceOAuthCallback:
assert response.status_code == 302
assert "/oauth-callback" in response.location
add_oauth_provider.assert_called_once()
+ # Legacy context without a visibility key falls back to ONLY_ME, and
+ # the callback now also propagates the creator's user_id.
+ from models.enums import PermissionEnum
+
assert add_oauth_provider.call_args.kwargs == {
"tenant_id": "tenant-1",
"provider_id": add_oauth_provider.call_args.kwargs["provider_id"],
@@ -257,6 +262,8 @@ class TestDatasourceOAuthCallback:
"name": "Workspace Bot",
"expire_at": expires_at,
"credentials": {"token": "abc"},
+ "user_id": "user-1",
+ "visibility": PermissionEnum.ONLY_ME,
}
assert str(add_oauth_provider.call_args.kwargs["provider_id"]) == _PROVIDER_ID
@@ -645,6 +652,7 @@ class TestDatasourceAuthListApi:
def test_list_success(self, app: Flask):
api = DatasourceAuthListApi()
method = inspect.unwrap(api.get)
+ user = MagicMock(id="user-1")
with (
app.test_request_context("/"),
@@ -652,16 +660,20 @@ class TestDatasourceAuthListApi:
DatasourceProviderService,
"get_all_datasource_credentials",
return_value=[_datasource_auth()],
- ),
+ ) as get_all,
):
- response, status = method(api, "tenant-1")
+ response, status = method(api, "tenant-1", user)
assert status == 200
assert response == {"result": [_datasource_auth()]}
+ # user is threaded through so list_datasource_credentials applies the
+ # visibility filter for the current viewer.
+ assert get_all.call_args.kwargs["user"] is user
def test_auth_list_empty(self, app: Flask):
api = DatasourceAuthListApi()
method = inspect.unwrap(api.get)
+ user = MagicMock(id="user-1")
with (
app.test_request_context("/"),
@@ -671,7 +683,7 @@ class TestDatasourceAuthListApi:
return_value=[],
),
):
- response, status = method(api, "tenant-1")
+ response, status = method(api, "tenant-1", user)
assert status == 200
assert response["result"] == []
@@ -679,6 +691,7 @@ class TestDatasourceAuthListApi:
def test_hardcode_list_empty(self, app: Flask):
api = DatasourceHardCodeAuthListApi()
method = inspect.unwrap(api.get)
+ user = MagicMock(id="user-1")
with (
app.test_request_context("/"),
@@ -688,7 +701,7 @@ class TestDatasourceAuthListApi:
return_value=[],
),
):
- response, status = method(api, "tenant-1")
+ response, status = method(api, "tenant-1", user)
assert status == 200
assert response["result"] == []
@@ -698,6 +711,7 @@ class TestDatasourceHardCodeAuthListApi:
def test_list_success(self, app: Flask):
api = DatasourceHardCodeAuthListApi()
method = inspect.unwrap(api.get)
+ user = MagicMock(id="user-1")
with (
app.test_request_context("/"),
@@ -705,11 +719,12 @@ class TestDatasourceHardCodeAuthListApi:
DatasourceProviderService,
"get_hard_code_datasource_credentials",
return_value=[_datasource_auth()],
- ),
+ ) as get_hardcode,
):
- response, status = method(api, "tenant-1")
+ response, status = method(api, "tenant-1", user)
assert status == 200
+ assert get_hardcode.call_args.kwargs["user"] is user
class TestDatasourceAuthOauthCustomClient:
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_tool_providers.py b/api/tests/unit_tests/controllers/console/workspace/test_tool_providers.py
index 8184adaad97..3e8df467ad1 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_tool_providers.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_tool_providers.py
@@ -764,3 +764,187 @@ def test_resolve_identity_mode_off_is_passthrough_when_not_enterprise(
monkeypatch.setattr(controller_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
assert controller_module._resolve_identity_mode(None, current=identity_mode.OFF) == identity_mode.OFF
+
+
+# --- OAuth start + callback: visibility passthrough (PR #39840 review) ---
+#
+# The OAuth flow stashes the user-chosen visibility in the proxy context on the
+# start endpoint, then reads it back on the callback to persist the credential.
+# These tests pin down: (a) the value round-trips for the two supported levels,
+# and (b) unknown/missing values collapse to ONLY_ME on both ends.
+
+
+_OAUTH_PROVIDER_PATH = "langgenius/github/github"
+
+
+def _invoke_oauth_start(
+ controller_module: ModuleType,
+ app: Flask,
+ user: Account,
+ tenant_id: str,
+ *,
+ query_string: str = "",
+ provider: str = _OAUTH_PROVIDER_PATH,
+):
+ """Call ToolPluginOAuthApi.get bypassing decorators (matches the pattern
+ used by test_builtin_provider_credentials_get_reads_repeated_include_ids)."""
+ api = controller_module.ToolPluginOAuthApi()
+ path = f"/oauth/plugin/{provider}/tool/authorization-url"
+ if query_string:
+ path = f"{path}?{query_string}"
+ with app.test_request_context(path, method="GET"):
+ return unwrap(api.get)(api, tenant_id, user, provider=provider)
+
+
+@contextmanager
+def _mock_oauth_start_deps(controller_module: ModuleType, monkeypatch: pytest.MonkeyPatch):
+ """Mock everything ToolPluginOAuthApi.get calls out to and capture the
+ create_proxy_context kwargs so tests can assert on extra_data."""
+ monkeypatch.setattr(
+ controller_module.BuiltinToolManageService,
+ "get_oauth_client",
+ MagicMock(return_value={"client_id": "abc"}),
+ )
+ create_proxy_context = MagicMock(return_value="ctx-id")
+ monkeypatch.setattr(controller_module.OAuthProxyService, "create_proxy_context", create_proxy_context)
+ auth_response = MagicMock(authorization_url="https://oauth.example.com/authorize", state="s")
+ oauth_handler_instance = MagicMock()
+ oauth_handler_instance.get_authorization_url.return_value = auth_response
+ monkeypatch.setattr(controller_module, "OAuthHandler", MagicMock(return_value=oauth_handler_instance))
+ # dump_response is called with the pydantic response class; short-circuit it.
+ monkeypatch.setattr(
+ controller_module, "dump_response", lambda _cls, obj: {"authorization_url": obj.authorization_url}
+ )
+ yield create_proxy_context
+
+
+ ("query_visibility", "expected_stored"),
+ [
+ ("only_me", "only_me"),
+ ("all_team_members", "all_team_members"),
+ ],
+)
+def test_tool_plugin_oauth_url_stashes_valid_visibility(
+ app: Flask,
+ controller_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+ query_visibility: str,
+ expected_stored: str,
+):
+ user = _mock_account("user-oauth")
+ _set_current_account(monkeypatch, controller_module, user, "tenant-oauth")
+
+ with _mock_oauth_start_deps(controller_module, monkeypatch) as create_proxy_context:
+ _invoke_oauth_start(
+ controller_module,
+ app,
+ user,
+ "tenant-oauth",
+ query_string=f"visibility={query_visibility}",
+ )
+
+ _, kwargs = create_proxy_context.call_args
+ assert kwargs["extra_data"] == {"visibility": expected_stored}
+
+
[email protected]("query_string", ["", "visibility=partial_members", "visibility=nonsense"])
+def test_tool_plugin_oauth_url_unknown_visibility_falls_back_to_only_me(
+ app: Flask,
+ controller_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+ query_string: str,
+):
+ """Missing, partial_members (rejected for plugin creds), and garbage inputs
+ all collapse to only_me — OAuth tokens are personal by default."""
+ user = _mock_account("user-oauth-fallback")
+ _set_current_account(monkeypatch, controller_module, user, "tenant-oauth")
+
+ with _mock_oauth_start_deps(controller_module, monkeypatch) as create_proxy_context:
+ _invoke_oauth_start(
+ controller_module,
+ app,
+ user,
+ "tenant-oauth",
+ query_string=query_string,
+ )
+
+ _, kwargs = create_proxy_context.call_args
+ assert kwargs["extra_data"] == {"visibility": "only_me"}
+
+
+def _invoke_oauth_callback(
+ controller_module: ModuleType,
+ app: Flask,
+ *,
+ stored_visibility: str | None,
+ provider: str = _OAUTH_PROVIDER_PATH,
+):
+ api = controller_module.ToolOAuthCallback()
+ ctx = {"user_id": "user-oauth", "tenant_id": "tenant-oauth"}
+ if stored_visibility is not None:
+ ctx["visibility"] = stored_visibility
+ with app.test_request_context(
+ f"/oauth/plugin/{provider}/tool/callback",
+ method="GET",
+ headers={"Cookie": "context_id=ctx-id"},
+ ):
+ with patch.object(controller_module.OAuthProxyService, "use_proxy_context", return_value=ctx):
+ return unwrap(api.get)(api, provider=provider)
+
+
+@contextmanager
+def _mock_oauth_callback_deps(controller_module: ModuleType, monkeypatch: pytest.MonkeyPatch):
+ """Mock everything ToolOAuthCallback.get calls out to and capture the
+ add_builtin_tool_provider kwargs so tests can assert visibility."""
+ monkeypatch.setattr(
+ controller_module.BuiltinToolManageService,
+ "get_oauth_client",
+ MagicMock(return_value={"client_id": "abc"}),
+ )
+ add_provider = MagicMock()
+ monkeypatch.setattr(controller_module.BuiltinToolManageService, "add_builtin_tool_provider", add_provider)
+ credentials_response = MagicMock(credentials={"access_token": "tok"}, expires_at=-1)
+ oauth_handler_instance = MagicMock()
+ oauth_handler_instance.get_credentials.return_value = credentials_response
+ monkeypatch.setattr(controller_module, "OAuthHandler", MagicMock(return_value=oauth_handler_instance))
+ monkeypatch.setattr(controller_module, "redirect", lambda url: {"redirect": url})
+ yield add_provider
+
+
+ ("stored", "expected"),
+ [
+ ("only_me", "only_me"),
+ ("all_team_members", "all_team_members"),
+ ],
+)
+def test_tool_oauth_callback_persists_stored_visibility(
+ app: Flask,
+ controller_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+ stored: str,
+ expected: str,
+):
+ with _mock_oauth_callback_deps(controller_module, monkeypatch) as add_provider:
+ _invoke_oauth_callback(controller_module, app, stored_visibility=stored)
+
+ _, kwargs = add_provider.call_args
+ assert kwargs["visibility"] == expected
+ assert kwargs["api_type"] == controller_module.CredentialType.OAUTH2
+
+
[email protected]("stored", [None, "partial_members", "garbage"])
+def test_tool_oauth_callback_unknown_stored_visibility_falls_back_to_only_me(
+ app: Flask,
+ controller_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+ stored: str | None,
+):
+ """Older proxy contexts (pre-feature) and anything unexpected must default
+ to only_me — matches the safe-default we apply on the start endpoint."""
+ with _mock_oauth_callback_deps(controller_module, monkeypatch) as add_provider:
+ _invoke_oauth_callback(controller_module, app, stored_visibility=stored)
+
+ _, kwargs = add_provider.call_args
+ assert kwargs["visibility"] == "only_me"
diff --git a/packages/contracts/generated/api/console/oauth/orpc.gen.ts b/packages/contracts/generated/api/console/oauth/orpc.gen.ts
index 31feb8abd4d..e65bb04c043 100644
--- a/packages/contracts/generated/api/console/oauth/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/oauth/orpc.gen.ts
@@ -14,6 +14,7 @@ import {
zGetOauthPluginByProviderIdDatasourceGetAuthorizationUrlQuery,
zGetOauthPluginByProviderIdDatasourceGetAuthorizationUrlResponse,
zGetOauthPluginByProviderToolAuthorizationUrlPath,
+ zGetOauthPluginByProviderToolAuthorizationUrlQuery,
zGetOauthPluginByProviderToolAuthorizationUrlResponse,
zPostOauthProviderAccountBody,
zPostOauthProviderAccountResponse,
@@ -137,7 +138,12 @@ export const get5 = oc
path: '/oauth/plugin/{provider}/tool/authorization-url',
tags: ['console'],
})
- .input(z.object({ params: zGetOauthPluginByProviderToolAuthorizationUrlPath }))
+ .input(
+ z.object({
+ params: zGetOauthPluginByProviderToolAuthorizationUrlPath,
+ query: zGetOauthPluginByProviderToolAuthorizationUrlQuery.optional(),
+ }),
+ )
.output(zGetOauthPluginByProviderToolAuthorizationUrlResponse)
export const authorizationUrl = {
diff --git a/packages/contracts/generated/api/console/oauth/types.gen.ts b/packages/contracts/generated/api/console/oauth/types.gen.ts
index 2108c56280d..2120c2a3283 100644
--- a/packages/contracts/generated/api/console/oauth/types.gen.ts
+++ b/packages/contracts/generated/api/console/oauth/types.gen.ts
@@ -138,6 +138,7 @@ export type GetOauthPluginByProviderIdDatasourceGetAuthorizationUrlData = {
}
query?: {
credential_id?: string
+ visibility?: string
}
url: '/oauth/plugin/{provider_id}/datasource/get-authorization-url'
}
@@ -154,7 +155,9 @@ export type GetOauthPluginByProviderToolAuthorizationUrlData = {
path: {
provider: string
}
- query?: never
+ query?: {
+ visibility?: 'all_team_members' | 'only_me'
+ }
url: '/oauth/plugin/{provider}/tool/authorization-url'
}
diff --git a/packages/contracts/generated/api/console/oauth/zod.gen.ts b/packages/contracts/generated/api/console/oauth/zod.gen.ts
index 960d1e429c3..d96544bcdc0 100644
--- a/packages/contracts/generated/api/console/oauth/zod.gen.ts
+++ b/packages/contracts/generated/api/console/oauth/zod.gen.ts
@@ -134,6 +134,7 @@ export const zGetOauthPluginByProviderIdDatasourceGetAuthorizationUrlPath = z.ob
export const zGetOauthPluginByProviderIdDatasourceGetAuthorizationUrlQuery = z.object({
credential_id: z.string().optional(),
+ visibility: z.string().optional(),
})
/**
@@ -146,6 +147,10 @@ export const zGetOauthPluginByProviderToolAuthorizationUrlPath = z.object({
provider: z.string(),
})
+export const zGetOauthPluginByProviderToolAuthorizationUrlQuery = z.object({
+ visibility: z.enum(['all_team_members', 'only_me']).optional(),
+})
+
/**
* Tool OAuth authorization URL generated successfully
*/
diff --git a/web/app/components/datasets/documents/create-from-pipeline/data-source/base/credential-selector/__tests__/index.spec.tsx b/web/app/components/datasets/documents/create-from-pipeline/data-source/base/credential-selector/__tests__/index.spec.tsx
index b639f7e2f6b..2720b42237d 100644
--- a/web/app/components/datasets/documents/create-from-pipeline/data-source/base/credential-selector/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/documents/create-from-pipeline/data-source/base/credential-selector/__tests__/index.spec.tsx
@@ -12,12 +12,14 @@ const credentials = [
name: 'First credential',
avatar_url: 'https://example.com/first.png',
type: 'oauth2',
+ is_default: false,
},
{
id: 'credential-2',
name: 'Second credential',
avatar_url: 'https://example.com/second.png',
type: 'oauth2',
+ is_default: false,
},
] as DataSourceCredential[]
@@ -51,6 +53,23 @@ describe('CredentialSelector', () => {
await waitFor(() => expect(onCredentialChange).toHaveBeenCalledWith('credential-1'))
})
+ it('selects the visible default credential before falling back to the first one', async () => {
+ const onCredentialChange = vi.fn()
+ const credentialsWithDefault = credentials.map((credential, index) => ({
+ ...credential,
+ is_default: index === 1,
+ }))
+ render(
+ <CredentialSelector
+ currentCredentialId="missing"
+ credentials={credentialsWithDefault}
+ onCredentialChange={onCredentialChange}
+ />,
+ )
+
+ await waitFor(() => expect(onCredentialChange).toHaveBeenCalledWith('credential-2'))
+ })
+
it('does not select a fallback for an empty credential list', () => {
const onCredentialChange = vi.fn()
render(
diff --git a/web/app/components/datasets/documents/create-from-pipeline/data-source/base/credential-selector/index.tsx b/web/app/components/datasets/documents/create-from-pipeline/data-source/base/credential-selector/index.tsx
index ed516f2f52f..c03318af82f 100644
--- a/web/app/components/datasets/documents/create-from-pipeline/data-source/base/credential-selector/index.tsx
+++ b/web/app/components/datasets/documents/create-from-pipeline/data-source/base/credential-selector/index.tsx
@@ -25,8 +25,11 @@ const CredentialSelector = ({
}, [credentials, currentCredentialId])
useEffect(() => {
- if (!currentCredential && credentials.length) onCredentialChange(credentials[0]!.id)
- }, [currentCredential, credentials])
+ if (!currentCredential && credentials.length) {
+ const fallbackCredential = credentials.find((credential) => credential.is_default)
+ onCredentialChange((fallbackCredential ?? credentials[0]!).id)
+ }
+ }, [currentCredential, credentials, onCredentialChange])
const handleCredentialChange = useCallback(
(credentialId: string) => {
diff --git a/web/app/components/header/account-setting/data-source-page-new/__tests__/card.spec.tsx b/web/app/components/header/account-setting/data-source-page-new/__tests__/card.spec.tsx
index fe56ab9dfdd..bc2d337c06d 100644
--- a/web/app/components/header/account-setting/data-source-page-new/__tests__/card.spec.tsx
+++ b/web/app/components/header/account-setting/data-source-page-new/__tests__/card.spec.tsx
@@ -1,4 +1,5 @@
import type { DataSourceAuth } from '../types'
+import type { AddOAuthButtonProps } from '@/app/components/plugins/plugin-auth/types'
import { fireEvent, screen, waitFor, within } from '@testing-library/react'
import { FormTypeEnum } from '@/app/components/base/form/types'
import { usePluginAuthAction } from '@/app/components/plugins/plugin-auth'
@@ -68,11 +69,27 @@ vi.mock('@/app/components/plugins/plugin-auth', () => ({
Add API Key
</button>
),
- AddOAuthButton: ({ onUpdate, disabled }: { onUpdate: () => void; disabled?: boolean }) => (
- <button disabled={disabled} onClick={onUpdate}>
- Add OAuth
- </button>
- ),
+ AddOAuthButton: ({ onUpdate, disabled, renderTrigger }: AddOAuthButtonProps) => {
+ const handleClick = () => onUpdate?.()
+ const trigger = (
+ <button disabled={disabled} onClick={handleClick}>
+ Add OAuth
+ </button>
+ )
+
+ return (
+ <>
+ {renderTrigger
+ ? renderTrigger({
+ disabled,
+ isConfigured: false,
+ onClick: handleClick,
+ trigger,
+ })
+ : trigger}
+ </>
+ )
+ },
}))
vi.mock('@/hooks/use-i18n', () => ({
diff --git a/web/app/components/header/account-setting/data-source-page-new/__tests__/configure.spec.tsx b/web/app/components/header/account-setting/data-source-page-new/__tests__/configure.spec.tsx
index 6109ce80e1b..22a1fe7aa37 100644
--- a/web/app/components/header/account-setting/data-source-page-new/__tests__/configure.spec.tsx
+++ b/web/app/components/header/account-setting/data-source-page-new/__tests__/configure.spec.tsx
@@ -6,6 +6,7 @@ import type {
PluginPayload,
} from '@/app/components/plugins/plugin-auth/types'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import * as React from 'react'
import { FormTypeEnum } from '@/app/components/base/form/types'
import { AuthCategory } from '@/app/components/plugins/plugin-auth/types'
import Configure from '../configure'
@@ -25,11 +26,32 @@ vi.mock('@/app/components/plugins/plugin-auth', () => ({
),
),
AddOAuthButton: vi.fn(
- ({ onUpdate, disabled, buttonText }: AddOAuthButtonProps & { onUpdate: () => void }) => (
- <button data-testid="add-oauth" onClick={onUpdate} disabled={disabled}>
- {buttonText}
- </button>
- ),
+ ({ onUpdate, disabled, buttonText, renderTrigger }: AddOAuthButtonProps) => {
+ const [permissionOpen, setPermissionOpen] = React.useState(false)
+ const handleSaveAndAuthorize = () => {
+ onUpdate?.()
+ setPermissionOpen(true)
+ }
+ const trigger = (
+ <button data-testid="add-oauth" onClick={handleSaveAndAuthorize} disabled={disabled}>
+ {buttonText}
+ </button>
+ )
+
+ return (
+ <>
+ {renderTrigger
+ ? renderTrigger({
+ disabled,
+ isConfigured: false,
+ onClick: handleSaveAndAuthorize,
+ trigger,
+ })
+ : trigger}
+ {permissionOpen && <div role="dialog" aria-label="Who can use" />}
+ </>
+ )
+ },
),
}))
@@ -146,6 +168,29 @@ describe('Configure Component', () => {
})
describe('Update Handling', () => {
+ it('should keep the permission dialog mounted after the OAuth menu closes', () => {
+ const itemWithOAuth: DataSourceAuth = {
+ ...mockItemBase,
+ oauth_schema: {
+ client_schema: [mockFormSchema],
+ },
+ }
+ render(
+ <Configure
+ item={itemWithOAuth}
+ pluginPayload={mockPluginPayload}
+ onUpdate={mockOnUpdate}
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: /dataSource.configure/i }))
+ fireEvent.click(screen.getByTestId('add-oauth'))
+
+ expect(mockOnUpdate).toHaveBeenCalledOnce()
+ expect(screen.queryByTestId('add-oauth')).not.toBeInTheDocument()
+ expect(screen.getByRole('dialog', { name: 'Who can use' })).toBeInTheDocument()
+ })
+
it('should call onUpdate and close the portal when an update is triggered', () => {
// Arrange
const itemWithApiKey: DataSourceAuth = {
diff --git a/web/app/components/header/account-setting/data-source-page-new/configure.tsx b/web/app/components/header/account-setting/data-source-page-new/configure.tsx
index 08c4ab59e55..bc52077891b 100644
--- a/web/app/components/header/account-setting/data-source-page-new/configure.tsx
+++ b/web/app/components/header/account-setting/data-source-page-new/configure.tsx
@@ -1,3 +1,4 @@
+import type { ReactNode } from 'react'
import type { DataSourceAuth } from './types'
import type {
AddApiKeyButtonProps,
@@ -6,7 +7,6 @@ import type {
} from '@/app/components/plugins/plugin-auth/types'
import { Button } from '@langgenius/dify-ui/button'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
-import { RiAddLine } from '@remixicon/react'
import { memo, useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { AddApiKeyButton, AddOAuthButton } from '@/app/components/plugins/plugin-auth'
@@ -42,13 +42,13 @@ const Configure = ({ item, pluginPayload, onUpdate, disabled }: ConfigureProps)
onUpdate?.()
}, [onUpdate])
- return (
- <>
+ const renderConfigurePopover = (oAuthTrigger?: ReactNode) => {
+ return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger
render={
<Button className="h-8" variant="secondary-accent">
- <RiAddLine className="size-4" />
+ <span className="i-ri-add-line size-4" aria-hidden="true" />
{t(($) => $['dataSource.configure'], { ns: 'common' })}
</Button>
}
@@ -60,20 +60,7 @@ const Configure = ({ item, pluginPayload, onUpdate, disabled }: ConfigureProps)
popupClassName="border-none bg-transparent shadow-none"
>
<div className="w-60 space-y-1.5 rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-2 shadow-lg">
- {!!canOAuth && (
- <AddOAuthButton
- {...oAuthButtonProps}
- onUpdate={handleUpdate}
- oAuthData={{
- schema: oAuthData.client_schema || [],
- is_oauth_custom_client_enabled: oAuthData.is_oauth_custom_client_enabled,
- is_system_oauth_params_exists: oAuthData.is_system_oauth_params_exists,
- client_params: oAuthData.oauth_custom_client_params,
- redirect_uri: oAuthData.redirect_uri,
- }}
- disabled={disabled}
- />
- )}
+ {!!canOAuth && oAuthTrigger}
{!!canApiKey && !!canOAuth && (
<div className="flex h-4 items-center p-2 system-2xs-medium-uppercase text-text-quaternary">
<div className="mr-2 h-px grow bg-linear-to-l from-[rgba(16,24,40,0.08)]" />
@@ -92,7 +79,25 @@ const Configure = ({ item, pluginPayload, onUpdate, disabled }: ConfigureProps)
</div>
</PopoverContent>
</Popover>
- </>
+ )
+ }
+
+ if (!canOAuth) return renderConfigurePopover()
+
+ return (
+ <AddOAuthButton
+ {...oAuthButtonProps}
+ onUpdate={handleUpdate}
+ oAuthData={{
+ schema: oAuthData.client_schema || [],
+ is_oauth_custom_client_enabled: oAuthData.is_oauth_custom_client_enabled,
+ is_system_oauth_params_exists: oAuthData.is_system_oauth_params_exists,
+ client_params: oAuthData.oauth_custom_client_params,
+ redirect_uri: oAuthData.redirect_uri,
+ }}
+ disabled={disabled}
+ renderTrigger={({ trigger }) => renderConfigurePopover(trigger)}
+ />
)
}
diff --git a/web/app/components/plugins/plugin-auth/authorize/__tests__/add-oauth-button.spec.tsx b/web/app/components/plugins/plugin-auth/authorize/__tests__/add-oauth-button.spec.tsx
index 75729d8ef75..71f86ff6b93 100644
--- a/web/app/components/plugins/plugin-auth/authorize/__tests__/add-oauth-button.spec.tsx
+++ b/web/app/components/plugins/plugin-auth/authorize/__tests__/add-oauth-button.spec.tsx
@@ -1,8 +1,10 @@
import type { OAuthClientSettingsProps } from '../oauth-client-settings'
import type { FormSchema } from '@/app/components/base/form/types'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { renderWithAccountProfile } from '@/test/console/account-profile'
import { AuthCategory } from '../../types'
const mockGetPluginOAuthUrl = vi
@@ -22,9 +24,21 @@ vi.mock('@/hooks/use-oauth', () => ({
}))
vi.mock('../../hooks/use-credential', () => ({
- useGetPluginOAuthUrlHook: () => ({
- mutateAsync: mockGetPluginOAuthUrl,
- }),
+ useGetPluginOAuthUrlHook: () => {
+ const [isPending, setIsPending] = React.useState(false)
+
+ return {
+ isPending,
+ mutateAsync: async (params?: { visibility?: string }) => {
+ setIsPending(true)
+ try {
+ return await mockGetPluginOAuthUrl(params)
+ } finally {
+ setIsPending(false)
+ }
+ },
+ }
+ },
useGetPluginOAuthClientSchemaHook: () => ({
data: {
schema: [],
@@ -40,7 +54,7 @@ vi.mock('../../hooks/use-credential', () => ({
vi.mock('../oauth-client-settings', () => ({
default: (props: OAuthClientSettingsProps) => {
mockOAuthClientSettingsProps.push(props)
- const { open = true, onClose, onOpenChange, schemas } = props
+ const { open = true, onClose, onOpenChange, onRequestAuthorization, schemas } = props
if (!open) return null
@@ -48,12 +62,19 @@ vi.mock('../oauth-client-settings', () => ({
onOpenChange?.(false)
onClose?.()
}
+ const handleSaveAndAuthorize = async () => {
+ handleClose()
+ await onRequestAuthorization?.()
+ }
return (
<div data-testid="oauth-settings-modal">
<button data-testid="oauth-settings-close" onClick={handleClose}>
Close
</button>
+ <button type="button" onClick={handleSaveAndAuthorize}>
+ plugin.auth.saveAndAuth
+ </button>
{schemas.map((schema) => (
<div key={schema.name} data-testid={`oauth-schema-${schema.name}`}>
<div data-testid={`oauth-schema-label-${schema.name}`}>
@@ -95,13 +116,25 @@ describe('AddOAuthButton', () => {
})
it('should render OAuth button when configured (system params exist)', () => {
- render(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
+ renderWithAccountProfile(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
expect(screen.getByText('Use OAuth')).toBeInTheDocument()
})
+ it('should expose the default trigger to an external overlay owner', () => {
+ renderWithAccountProfile(
+ <AddOAuthButton
+ pluginPayload={basePayload}
+ buttonText="Use OAuth"
+ renderTrigger={({ trigger }) => <div data-testid="external-owner">{trigger}</div>}
+ />,
+ )
+
+ expect(within(screen.getByTestId('external-owner')).getByText('Use OAuth')).toBeInTheDocument()
+ })
+
it('should open OAuth settings modal when settings icon clicked', () => {
- render(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
+ renderWithAccountProfile(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
fireEvent.click(screen.getByRole('button', { name: /plugin\.auth\.oauthClientSettings/i }))
@@ -110,7 +143,7 @@ describe('AddOAuthButton', () => {
})
it('should close OAuth settings modal', () => {
- render(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
+ renderWithAccountProfile(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
fireEvent.click(screen.getByRole('button', { name: /plugin\.auth\.oauthClientSettings/i }))
fireEvent.click(screen.getByTestId('oauth-settings-close'))
@@ -120,13 +153,17 @@ describe('AddOAuthButton', () => {
it('should trigger OAuth flow on main button click', async () => {
const mockOnUpdate = vi.fn()
- render(
+ renderWithAccountProfile(
<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" onUpdate={mockOnUpdate} />,
)
const button = screen.getByText('Use OAuth').closest('button')
if (button) fireEvent.click(button)
+ // Confirm the visibility picker to actually kick off OAuth
+ const confirmButton = await screen.findByText('plugin.auth.authorize')
+ fireEvent.click(confirmButton)
+
await waitFor(() => {
expect(mockOpenOAuthPopup).toHaveBeenCalledWith(
'https://auth.example.com',
@@ -142,27 +179,196 @@ describe('AddOAuthButton', () => {
})
it('should not open OAuth popup when authorization URL is missing', async () => {
+ const user = userEvent.setup()
mockGetPluginOAuthUrl.mockResolvedValueOnce({})
- render(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
+ renderWithAccountProfile(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
- const button = screen.getByText('Use OAuth').closest('button')
- if (button) fireEvent.click(button)
+ await user.click(screen.getByRole('button', { name: 'Use OAuth' }))
+
+ const dialog = await screen.findByRole('dialog', { name: 'plugin.auth.whoCanUse' })
+ expect(dialog).toHaveAccessibleDescription('plugin.auth.oauthCredentialPermissionDescription')
+
+ const confirmButton = within(dialog).getByRole('button', { name: 'plugin.auth.authorize' })
+ await user.click(confirmButton)
await waitFor(() => {
expect(mockGetPluginOAuthUrl).toHaveBeenCalled()
})
expect(mockOpenOAuthPopup).not.toHaveBeenCalled()
+ expect(dialog).toBeInTheDocument()
+ expect(confirmButton).toBeEnabled()
+ })
+
+ it('should lock the visibility dialog while requesting an OAuth URL', async () => {
+ const user = userEvent.setup()
+ let resolveOAuthRequest: ((value: { authorization_url: string }) => void) | undefined
+ mockGetPluginOAuthUrl.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveOAuthRequest = resolve
+ }),
+ )
+ renderWithAccountProfile(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
+
+ await user.click(screen.getByRole('button', { name: 'Use OAuth' }))
+ const dialog = await screen.findByRole('dialog', { name: 'plugin.auth.whoCanUse' })
+ const confirmButton = within(dialog).getByRole('button', { name: 'plugin.auth.authorize' })
+ await user.click(confirmButton)
+
+ await waitFor(() => {
+ expect(confirmButton).toHaveAttribute('aria-disabled', 'true')
+ })
+ expect(confirmButton).toHaveAttribute('aria-busy', 'true')
+ expect(within(dialog).getByRole('button', { name: 'common.operation.cancel' })).toBeDisabled()
+ expect(
+ within(dialog).getByRole('button', {
+ name: /datasetSettings\.form\.permissionsOnlyMe/,
+ }),
+ ).toBeDisabled()
+ expect(within(dialog).getByRole('button', { name: 'Close' })).toBeDisabled()
+
+ await act(async () => {
+ resolveOAuthRequest?.({ authorization_url: 'https://auth.example.com' })
+ })
+
+ await waitFor(() => {
+ expect(
+ screen.queryByRole('dialog', { name: 'plugin.auth.whoCanUse' }),
+ ).not.toBeInTheDocument()
+ })
+ expect(mockOpenOAuthPopup).toHaveBeenCalledWith(
+ 'https://auth.example.com',
+ expect.any(Function),
+ )
+ })
+
+ it('should preserve the visibility selection when the OAuth URL request fails', async () => {
+ const user = userEvent.setup()
+ mockGetPluginOAuthUrl.mockRejectedValueOnce(new Error('OAuth URL request failed'))
+ renderWithAccountProfile(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
+
+ await user.click(screen.getByRole('button', { name: 'Use OAuth' }))
+ const dialog = await screen.findByRole('dialog', { name: 'plugin.auth.whoCanUse' })
+ await user.click(
+ within(dialog).getByRole('button', {
+ name: /datasetSettings\.form\.permissionsOnlyMe/,
+ }),
+ )
+ await user.click(
+ screen.getByRole('menuitemradio', {
+ name: 'datasetSettings.form.permissionsAllMember',
+ }),
+ )
+ const confirmButton = within(dialog).getByRole('button', { name: 'plugin.auth.authorize' })
+ await user.click(confirmButton)
+
+ await waitFor(() => {
+ expect(confirmButton).toBeEnabled()
+ })
+ expect(mockGetPluginOAuthUrl).toHaveBeenCalledWith({ visibility: 'all_team_members' })
+ expect(mockOpenOAuthPopup).not.toHaveBeenCalled()
+ expect(dialog).toBeInTheDocument()
+ expect(
+ within(dialog).getByRole('button', {
+ name: /datasetSettings\.form\.permissionsAllMember/,
+ }),
+ ).toBeEnabled()
+ })
+
+ it('should skip visibility picker for categories without backend visibility support', async () => {
+ // Trigger / model OAuth endpoints don't yet accept a visibility value on
+ // the backend — the picker would let users select "Only me" while the
+ // credential silently defaults to all_team_members. Tool and datasource
+ // are both wired end-to-end so they DO get the picker.
+ const triggerPayload = { category: AuthCategory.trigger, provider: 'test-trigger' }
+ renderWithAccountProfile(
+ <AddOAuthButton pluginPayload={triggerPayload} buttonText="Use OAuth" />,
+ )
+
+ const button = screen.getByText('Use OAuth').closest('button')
+ if (button) fireEvent.click(button)
+
+ await waitFor(() => {
+ expect(mockGetPluginOAuthUrl).toHaveBeenCalledWith(undefined)
+ })
+ // No pre-OAuth visibility modal should ever appear for unsupported categories.
+ expect(screen.queryByText('plugin.auth.authorize')).not.toBeInTheDocument()
+ })
+
+ it('should show visibility picker for datasource category (backend now supports it)', async () => {
+ const datasourcePayload = { category: AuthCategory.datasource, provider: 'test-datasource' }
+ renderWithAccountProfile(
+ <AddOAuthButton pluginPayload={datasourcePayload} buttonText="Use OAuth" />,
+ )
+
+ const button = screen.getByText('Use OAuth').closest('button')
+ if (button) fireEvent.click(button)
+
+ // Visibility picker appears for datasource just like it does for tool.
+ const confirmButton = await screen.findByText('plugin.auth.authorize')
+ fireEvent.click(confirmButton)
+
+ await waitFor(() => {
+ expect(mockGetPluginOAuthUrl).toHaveBeenCalledWith({ visibility: 'only_me' })
+ })
+ })
+
+ it('should pass the selected shared visibility to the OAuth URL request', async () => {
+ const user = userEvent.setup()
+ renderWithAccountProfile(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
+
+ await user.click(screen.getByRole('button', { name: 'Use OAuth' }))
+ await user.click(
+ screen.getByRole('button', { name: /datasetSettings\.form\.permissionsOnlyMe/ }),
+ )
+ await user.click(
+ screen.getByRole('menuitemradio', {
+ name: 'datasetSettings.form.permissionsAllMember',
+ }),
+ )
+ await user.click(screen.getByRole('button', { name: 'plugin.auth.authorize' }))
+
+ await waitFor(() => {
+ expect(mockGetPluginOAuthUrl).toHaveBeenCalledWith({
+ visibility: 'all_team_members',
+ })
+ })
+ })
+
+ it('should discard a cancelled visibility selection before the next OAuth attempt', async () => {
+ const user = userEvent.setup()
+ renderWithAccountProfile(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
+
+ await user.click(screen.getByRole('button', { name: 'Use OAuth' }))
+ await user.click(
+ screen.getByRole('button', { name: /datasetSettings\.form\.permissionsOnlyMe/ }),
+ )
+ await user.click(
+ screen.getByRole('menuitemradio', {
+ name: 'datasetSettings.form.permissionsAllMember',
+ }),
+ )
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+
+ await user.click(screen.getByRole('button', { name: 'Use OAuth' }))
+ await user.click(screen.getByRole('button', { name: 'plugin.auth.authorize' }))
+
+ await waitFor(() => {
+ expect(mockGetPluginOAuthUrl).toHaveBeenCalledWith({ visibility: 'only_me' })
+ })
})
it('should be disabled when disabled prop is true', () => {
- render(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" disabled />)
+ renderWithAccountProfile(
+ <AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" disabled />,
+ )
const button = screen.getByText('Use OAuth').closest('button')
expect(button).toBeDisabled()
})
it('should open OAuth settings from setup entry when OAuth is not configured', () => {
- render(
+ renderWithAccountProfile(
<AddOAuthButton
pluginPayload={basePayload}
oAuthData={{
@@ -182,8 +388,49 @@ describe('AddOAuthButton', () => {
})
})
+ it('should choose visibility after saving custom OAuth settings for authorization', async () => {
+ const user = userEvent.setup()
+ renderWithAccountProfile(
+ <AddOAuthButton
+ pluginPayload={basePayload}
+ oAuthData={{
+ schema: [],
+ is_oauth_custom_client_enabled: false,
+ is_system_oauth_params_exists: false,
+ client_params: {},
+ }}
+ />,
+ )
+
+ await user.click(screen.getByText('plugin.auth.setupOAuth'))
+ await user.click(
+ within(screen.getByTestId('oauth-settings-modal')).getByRole('button', {
+ name: 'plugin.auth.saveAndAuth',
+ }),
+ )
+
+ expect(mockGetPluginOAuthUrl).not.toHaveBeenCalled()
+ expect(screen.getByText('plugin.auth.oauthCredentialPermissionDescription')).toBeInTheDocument()
+
+ await user.click(
+ screen.getByRole('button', { name: /datasetSettings\.form\.permissionsOnlyMe/ }),
+ )
+ await user.click(
+ screen.getByRole('menuitemradio', {
+ name: 'datasetSettings.form.permissionsAllMember',
+ }),
+ )
+ await user.click(screen.getByRole('button', { name: 'plugin.auth.authorize' }))
+
+ await waitFor(() => {
+ expect(mockGetPluginOAuthUrl).toHaveBeenCalledWith({
+ visibility: 'all_team_members',
+ })
+ })
+ })
+
it('should show custom badge when OAuth custom client is enabled', () => {
- render(
+ renderWithAccountProfile(
<AddOAuthButton
pluginPayload={basePayload}
buttonText="Use OAuth"
@@ -210,7 +457,7 @@ describe('AddOAuthButton', () => {
},
] as FormSchema[]
- render(
+ renderWithAccountProfile(
<AddOAuthButton
pluginPayload={basePayload}
buttonText="Use OAuth"
diff --git a/web/app/components/plugins/plugin-auth/authorize/__tests__/api-key-modal.spec.tsx b/web/app/components/plugins/plugin-auth/authorize/__tests__/api-key-modal.spec.tsx
index 4cd02a15d4f..90e8830aa0d 100644
--- a/web/app/components/plugins/plugin-auth/authorize/__tests__/api-key-modal.spec.tsx
+++ b/web/app/components/plugins/plugin-auth/authorize/__tests__/api-key-modal.spec.tsx
@@ -296,29 +296,28 @@ describe('ApiKeyModal', () => {
})
})
- it('selects credential visibility through the native trigger', async () => {
+ it('selects credential visibility through the dropdown menu', async () => {
const user = userEvent.setup()
render(<ApiKeyModal pluginPayload={basePayload} />)
const trigger = screen.getByRole('button', { name: /permissionsAllMember/ })
expect(trigger).toHaveAttribute('type', 'button')
await user.click(trigger)
- const permissionDialog = screen.getByRole('dialog', { name: /auth.whoCanUse/ })
- const permissionGroup = within(permissionDialog).getByRole('radiogroup', {
+ const permissionMenu = screen.getByRole('menu', { name: /auth.whoCanUse/ })
+ const permissionGroup = within(permissionMenu).getByRole('group', {
name: /auth.whoCanUse/,
})
- const allMembers = within(permissionGroup).getByRole('radio', {
+ const allMembers = within(permissionGroup).getByRole('menuitemradio', {
name: /permissionsAllMember/,
})
- const onlyMe = within(permissionGroup).getByRole('radio', { name: /permissionsOnlyMe/ })
- expect(allMembers).toBeChecked()
-
- allMembers.focus()
- await user.keyboard('{ArrowUp}')
- expect(onlyMe).toBeChecked()
- expect(permissionDialog).toBeInTheDocument()
+ const onlyMe = within(permissionGroup).getByRole('menuitemradio', {
+ name: /permissionsOnlyMe/,
+ })
+ expect(allMembers).toHaveAttribute('aria-checked', 'true')
await user.click(onlyMe)
+ expect(screen.queryByRole('menu', { name: /auth.whoCanUse/ })).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /permissionsOnlyMe/ })).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => {
diff --git a/web/app/components/plugins/plugin-auth/authorize/__tests__/authorize-components.spec.tsx b/web/app/components/plugins/plugin-auth/authorize/__tests__/authorize-components.spec.tsx
index c36e6ae58e8..d7cb0c17665 100644
--- a/web/app/components/plugins/plugin-auth/authorize/__tests__/authorize-components.spec.tsx
+++ b/web/app/components/plugins/plugin-auth/authorize/__tests__/authorize-components.spec.tsx
@@ -433,10 +433,14 @@ describe('AddOAuthButton', () => {
wrapper: createWrapper(),
})
- // Click the main button area (left side)
+ // Click the main button area (left side) → opens visibility picker
const buttonText = screen.getByText('use oauth')
fireEvent.click(buttonText)
+ // Confirm the picker to actually kick off OAuth
+ const confirmButton = await screen.findByText('plugin.auth.authorize')
+ fireEvent.click(confirmButton)
+
await waitFor(() => {
expect(mockGetPluginOAuthUrl).toHaveBeenCalled()
})
@@ -474,6 +478,10 @@ describe('AddOAuthButton', () => {
const buttonText = screen.getByText('use oauth')
fireEvent.click(buttonText)
+ // Confirm the visibility picker to kick off the OAuth request
+ const confirmButton = await screen.findByText('plugin.auth.authorize')
+ fireEvent.click(confirmButton)
+
await waitFor(() => {
expect(mockGetPluginOAuthUrl).toHaveBeenCalled()
})
@@ -504,6 +512,10 @@ describe('AddOAuthButton', () => {
const buttonText = screen.getByText('use oauth')
fireEvent.click(buttonText)
+ // Confirm the visibility picker to kick off the OAuth request
+ const confirmButton = await screen.findByText('plugin.auth.authorize')
+ fireEvent.click(confirmButton)
+
await waitFor(() => {
expect(mockOpenOAuthPopup).toHaveBeenCalledWith(
'https://oauth.example.com/auth',
@@ -1333,9 +1345,8 @@ describe('OAuthClientSettings', () => {
it('should render Save and Auth button that is clickable', async () => {
const pluginPayload = createPluginPayload()
- const onAuth = vi.fn().mockResolvedValue(undefined)
- render(<OAuthClientSettings pluginPayload={pluginPayload} schemas={[]} onAuth={onAuth} />, {
+ render(<OAuthClientSettings pluginPayload={pluginPayload} schemas={[]} />, {
wrapper: createWrapper(),
})
@@ -1392,9 +1403,9 @@ describe('OAuthClientSettings', () => {
})
})
- it('should call onAuth after handleConfirmAndAuthorize', async () => {
+ it('should request authorization after handleConfirmAndAuthorize', async () => {
const pluginPayload = createPluginPayload()
- const onAuth = vi.fn().mockResolvedValue(undefined)
+ const onRequestAuthorization = vi.fn().mockResolvedValue(undefined)
const onClose = vi.fn()
mockSetPluginOAuthCustomClient.mockResolvedValue({})
@@ -1402,7 +1413,7 @@ describe('OAuthClientSettings', () => {
<OAuthClientSettings
pluginPayload={pluginPayload}
schemas={defaultSchemas}
- onAuth={onAuth}
+ onRequestAuthorization={onRequestAuthorization}
onClose={onClose}
/>,
{ wrapper: createWrapper() },
@@ -1413,7 +1424,7 @@ describe('OAuthClientSettings', () => {
await waitFor(() => {
expect(mockSetPluginOAuthCustomClient).toHaveBeenCalled()
- expect(onAuth).toHaveBeenCalled()
+ expect(onRequestAuthorization).toHaveBeenCalled()
})
})
@@ -1773,7 +1784,7 @@ describe('OAuthClientSettings', () => {
})
})
- describe('Branch Coverage - onAuth callback', () => {
+ describe('Branch Coverage - authorization request callback', () => {
beforeEach(() => {
mockGetFormValues.mockReturnValue({
isCheckValidated: true,
@@ -1781,16 +1792,16 @@ describe('OAuthClientSettings', () => {
})
})
- it('should call onAuth when provided and Save and Auth is clicked', async () => {
+ it('should request authorization when Save and Auth is clicked', async () => {
const pluginPayload = createPluginPayload()
- const onAuth = vi.fn().mockResolvedValue(undefined)
+ const onRequestAuthorization = vi.fn().mockResolvedValue(undefined)
mockSetPluginOAuthCustomClient.mockResolvedValue({})
render(
<OAuthClientSettings
pluginPayload={pluginPayload}
schemas={defaultSchemas}
- onAuth={onAuth}
+ onRequestAuthorization={onRequestAuthorization}
/>,
{ wrapper: createWrapper() },
)
@@ -1798,29 +1809,23 @@ describe('OAuthClientSettings', () => {
fireEvent.click(screen.getByText('plugin.auth.saveAndAuth'))
await waitFor(() => {
- expect(onAuth).toHaveBeenCalled()
+ expect(onRequestAuthorization).toHaveBeenCalled()
})
})
- it('should not call onAuth when not provided', async () => {
+ it('should save without an authorization request callback', async () => {
const pluginPayload = createPluginPayload()
mockSetPluginOAuthCustomClient.mockResolvedValue({})
- render(
- <OAuthClientSettings
- pluginPayload={pluginPayload}
- schemas={defaultSchemas}
- onAuth={undefined}
- />,
- { wrapper: createWrapper() },
- )
+ render(<OAuthClientSettings pluginPayload={pluginPayload} schemas={defaultSchemas} />, {
+ wrapper: createWrapper(),
+ })
fireEvent.click(screen.getByText('plugin.auth.saveAndAuth'))
await waitFor(() => {
expect(mockSetPluginOAuthCustomClient).toHaveBeenCalled()
})
- // No onAuth to call, but should not throw
})
})
diff --git a/web/app/components/plugins/plugin-auth/authorize/__tests__/oauth-client-settings.spec.tsx b/web/app/components/plugins/plugin-auth/authorize/__tests__/oauth-client-settings.spec.tsx
index cc6d2030545..c71389f0265 100644
--- a/web/app/components/plugins/plugin-auth/authorize/__tests__/oauth-client-settings.spec.tsx
+++ b/web/app/components/plugins/plugin-auth/authorize/__tests__/oauth-client-settings.spec.tsx
@@ -305,21 +305,44 @@ describe('OAuthClientSettings', () => {
})
})
- it('should save and authorize on confirm button click', async () => {
- const mockOnAuth = vi.fn().mockResolvedValue(undefined)
+ it('should request authorization after saving settings', async () => {
+ const user = userEvent.setup()
+ const mockOnRequestAuthorization = vi.fn().mockResolvedValue(undefined)
+ render(
+ <OAuthClientSettings
+ pluginPayload={basePayload}
+ schemas={defaultSchemas}
+ onRequestAuthorization={mockOnRequestAuthorization}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'plugin.auth.saveAndAuth' }))
+
+ await waitFor(() => {
+ expect(mockSetPluginOAuthCustomClient).toHaveBeenCalled()
+ expect(mockOnRequestAuthorization).toHaveBeenCalledOnce()
+ })
+ })
+
+ it('should not request authorization when saving settings fails', async () => {
+ const user = userEvent.setup()
+ const mockOnRequestAuthorization = vi.fn()
+ mockSetPluginOAuthCustomClient.mockRejectedValueOnce(new Error('Save failed'))
render(
<OAuthClientSettings
pluginPayload={basePayload}
schemas={defaultSchemas}
- onAuth={mockOnAuth}
+ onRequestAuthorization={mockOnRequestAuthorization}
/>,
)
- fireEvent.click(screen.getByRole('button', { name: 'plugin.auth.saveAndAuth' }))
+ await user.click(screen.getByRole('button', { name: 'plugin.auth.saveAndAuth' }))
await waitFor(() => {
expect(mockSetPluginOAuthCustomClient).toHaveBeenCalled()
})
+ expect(mockOnRequestAuthorization).not.toHaveBeenCalled()
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
})
it('should remove custom client settings', async () => {
diff --git a/web/app/components/plugins/plugin-auth/authorize/add-oauth-button.tsx b/web/app/components/plugins/plugin-auth/authorize/add-oauth-button.tsx
index 92968eda47d..737df3301ff 100644
--- a/web/app/components/plugins/plugin-auth/authorize/add-oauth-button.tsx
+++ b/web/app/components/plugins/plugin-auth/authorize/add-oauth-button.tsx
@@ -1,6 +1,7 @@
import type { ButtonProps } from '@langgenius/dify-ui/button'
import type { PluginPayload } from '../types'
import type { FormSchema } from '@/app/components/base/form/types'
+import type { CredentialPermission } from '@/models/permission'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { IconButton } from '@langgenius/dify-ui/icon-button'
@@ -10,11 +11,14 @@ import Badge from '@/app/components/base/badge'
import { FormTypeEnum } from '@/app/components/base/form/types'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import { openOAuthPopup } from '@/hooks/use-oauth'
+import { PermissionLevel } from '@/models/permission'
import {
useGetPluginOAuthClientSchemaHook,
useGetPluginOAuthUrlHook,
} from '../hooks/use-credential'
+import { AuthCategory } from '../types'
import OAuthClientSettings from './oauth-client-settings'
+import OAuthVisibilityDialog from './oauth-visibility-dialog'
export type AddOAuthButtonProps = {
pluginPayload: PluginPayload
@@ -30,6 +34,7 @@ export type AddOAuthButtonProps = {
disabled?: boolean
isConfigured: boolean
onClick: () => void
+ trigger: React.ReactNode
}) => React.ReactNode
oAuthData?: {
schema?: FormSchema[]
@@ -58,8 +63,17 @@ const AddOAuthButton = ({
const renderI18nObject = useRenderI18nObject()
const [isOAuthSettingsOpen, setIsOAuthSettingsOpen] = useState(false)
const [isOAuthSettingsMounted, setIsOAuthSettingsMounted] = useState(false)
- const { mutateAsync: getPluginOAuthUrl } = useGetPluginOAuthUrlHook(pluginPayload)
- const { data, isLoading } = useGetPluginOAuthClientSchemaHook(pluginPayload)
+ // Only expose the picker where the OAuth callback persists the selection.
+ const isVisibilityPickerSupported =
+ pluginPayload.category === AuthCategory.tool ||
+ pluginPayload.category === AuthCategory.datasource
+ const [isVisibilityModalOpen, setIsVisibilityModalOpen] = useState(false)
+ const [pendingVisibility, setPendingVisibility] = useState<CredentialPermission>(
+ PermissionLevel.onlyMe,
+ )
+ const { mutateAsync: getPluginOAuthUrl, isPending: isGettingOAuthUrl } =
+ useGetPluginOAuthUrlHook(pluginPayload)
+ const { data, isLoading } = useGetPluginOAuthClientSchemaHook(pluginPayload, !oAuthData)
const mergedOAuthData = useMemo<OAuthData>(() => {
if (oAuthData) return oAuthData
@@ -78,12 +92,50 @@ const AddOAuthButton = ({
setIsOAuthSettingsOpen(true)
}, [])
const handleOAuth = useCallback(async () => {
- const { authorization_url } = await getPluginOAuthUrl()
+ try {
+ const { authorization_url } = await getPluginOAuthUrl(
+ isVisibilityPickerSupported ? { visibility: pendingVisibility } : undefined,
+ )
+
+ if (!authorization_url) return false
- if (authorization_url) {
openOAuthPopup(authorization_url, () => onUpdate?.())
+ return true
+ } catch {
+ // The request layer surfaces the error. Keep the current UI state so the
+ // user can retry without losing their visibility selection.
+ return false
+ }
+ }, [getPluginOAuthUrl, onUpdate, pendingVisibility, isVisibilityPickerSupported])
+ // Providers without a usable OAuth client first open settings. Once those
+ // settings are saved, authorization continues through the same visibility
+ // dialog used by configured providers.
+ const openVisibilityModal = useCallback(() => {
+ if (!isVisibilityPickerSupported) {
+ if (isConfigured) void handleOAuth()
+ else openOAuthSettings()
+ return
+ }
+ if (isConfigured) {
+ setPendingVisibility(PermissionLevel.onlyMe)
+ setIsVisibilityModalOpen(true)
+ } else {
+ openOAuthSettings()
+ }
+ }, [isConfigured, isVisibilityPickerSupported, openOAuthSettings, handleOAuth])
+ const handleAuthorizationRequest = useCallback(async () => {
+ if (!isVisibilityPickerSupported) {
+ await handleOAuth()
+ return
}
- }, [getPluginOAuthUrl, onUpdate])
+
+ setPendingVisibility(PermissionLevel.onlyMe)
+ setIsVisibilityModalOpen(true)
+ }, [handleOAuth, isVisibilityPickerSupported])
+ const handleVisibilityConfirm = useCallback(async () => {
+ const didOpenOAuthPopup = await handleOAuth()
+ if (didOpenOAuthPopup) setIsVisibilityModalOpen(false)
+ }, [handleOAuth])
const renderCustomLabel = useCallback(
(item: FormSchema) => {
@@ -181,71 +233,72 @@ const AddOAuthButton = ({
}
}, [isConfigured, is_oauth_custom_client_enabled, is_system_oauth_params_exists])
- return (
- <>
- {renderTrigger?.({
- disabled,
- isConfigured,
- onClick: isConfigured ? handleOAuth : openOAuthSettings,
- })}
- {!renderTrigger && isConfigured && (
- <div className={cn('flex w-full', className)}>
- <Button
- variant={buttonVariant}
- className={cn(
- 'h-8 min-w-0 flex-1 rounded-r-none p-0 hover:bg-components-button-primary-bg-hover',
- buttonLeftClassName,
- )}
- disabled={disabled}
- onClick={handleOAuth}
- >
- <div className="truncate">{buttonText}</div>
- {is_oauth_custom_client_enabled && (
- <Badge
- className={cn(
- 'mr-0.5',
- buttonVariant === 'primary' &&
- 'border-text-primary-on-surface bg-components-badge-bg-dimm text-text-primary-on-surface',
- )}
- >
- {t(($) => $['auth.custom'], { ns: 'plugin' })}
- </Badge>
- )}
- </Button>
- <div
+ const trigger = isConfigured ? (
+ <div className={cn('flex w-full', className)}>
+ <Button
+ variant={buttonVariant}
+ className={cn(
+ 'h-8 min-w-0 flex-1 rounded-r-none p-0 hover:bg-components-button-primary-bg-hover',
+ buttonLeftClassName,
+ )}
+ disabled={disabled}
+ onClick={openVisibilityModal}
+ >
+ <div className="truncate">{buttonText}</div>
+ {is_oauth_custom_client_enabled && (
+ <Badge
className={cn(
- 'h-4 w-px shrink-0 self-center bg-text-primary-on-surface opacity-[0.15]',
- dividerClassName,
+ 'mr-0.5',
+ buttonVariant === 'primary' &&
+ 'border-text-primary-on-surface bg-components-badge-bg-dimm text-text-primary-on-surface',
)}
- ></div>
- <IconButton
- variant={buttonVariant}
- aria-label={t(($) => $['auth.oauthClientSettings'], { ns: 'plugin' })}
- size="lg"
- className={cn(
- 'shrink-0 rounded-l-none hover:bg-components-button-primary-bg-hover',
- buttonRightClassName,
- )}
- disabled={disabled}
- onClick={() => {
- openOAuthSettings()
- }}
>
- <span className="i-ri-equalizer-2-line size-4" aria-hidden="true" />
- </IconButton>
- </div>
- )}
- {!renderTrigger && !isConfigured && (
- <Button
- variant={buttonVariant}
- onClick={openOAuthSettings}
- disabled={disabled}
- className="w-full"
- >
- <span className="i-ri-equalizer-2-line size-4" />
- {t(($) => $['auth.setupOAuth'], { ns: 'plugin' })}
- </Button>
- )}
+ {t(($) => $['auth.custom'], { ns: 'plugin' })}
+ </Badge>
+ )}
+ </Button>
+ <div
+ className={cn(
+ 'h-4 w-px shrink-0 self-center bg-text-primary-on-surface opacity-[0.15]',
+ dividerClassName,
+ )}
+ ></div>
+ <IconButton
+ variant={buttonVariant}
+ aria-label={t(($) => $['auth.oauthClientSettings'], { ns: 'plugin' })}
+ size="lg"
+ className={cn(
+ 'shrink-0 rounded-l-none hover:bg-components-button-primary-bg-hover',
+ buttonRightClassName,
+ )}
+ disabled={disabled}
+ onClick={openOAuthSettings}
+ >
+ <span className="i-ri-equalizer-2-line size-4" aria-hidden="true" />
+ </IconButton>
+ </div>
+ ) : (
+ <Button
+ variant={buttonVariant}
+ onClick={openVisibilityModal}
+ disabled={disabled}
+ className="w-full"
+ >
+ <span className="i-ri-equalizer-2-line size-4" />
+ {t(($) => $['auth.setupOAuth'], { ns: 'plugin' })}
+ </Button>
+ )
+
+ return (
+ <>
+ {renderTrigger
+ ? renderTrigger({
+ disabled,
+ isConfigured,
+ onClick: openVisibilityModal,
+ trigger,
+ })
+ : trigger}
{isOAuthSettingsMounted && (
<OAuthClientSettings
open={isOAuthSettingsOpen}
@@ -254,7 +307,7 @@ const AddOAuthButton = ({
onClose={() => setIsOAuthSettingsOpen(false)}
disabled={disabled || isLoading}
schemas={memorizedSchemas}
- onAuth={handleOAuth}
+ onRequestAuthorization={handleAuthorizationRequest}
editValues={{
...client_params,
__oauth_client__: __auth_client__,
@@ -263,6 +316,14 @@ const AddOAuthButton = ({
onUpdate={onUpdate}
/>
)}
+ <OAuthVisibilityDialog
+ open={isVisibilityModalOpen}
+ onOpenChange={setIsVisibilityModalOpen}
+ permission={pendingVisibility}
+ onPermissionChange={setPendingVisibility}
+ onConfirm={handleVisibilityConfirm}
+ loading={isGettingOAuthUrl}
+ />
</>
)
}
diff --git a/web/app/components/plugins/plugin-auth/authorize/api-key-modal.tsx b/web/app/components/plugins/plugin-auth/authorize/api-key-modal.tsx
index e03cfcf54c6..1deb3ea3a3c 100644
--- a/web/app/components/plugins/plugin-auth/authorize/api-key-modal.tsx
+++ b/web/app/components/plugins/plugin-auth/authorize/api-key-modal.tsx
@@ -1,6 +1,6 @@
import type { PluginPayload } from '../types'
-import type { CredentialPermission } from './permission-selector'
import type { FormRefObject, FormSchema } from '@/app/components/base/form/types'
+import type { CredentialPermission } from '@/models/permission'
import { Button } from '@langgenius/dify-ui/button'
import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
diff --git a/web/app/components/plugins/plugin-auth/authorize/oauth-client-settings.tsx b/web/app/components/plugins/plugin-auth/authorize/oauth-client-settings.tsx
index acbd5a83995..cb6bcaf4a97 100644
--- a/web/app/components/plugins/plugin-auth/authorize/oauth-client-settings.tsx
+++ b/web/app/components/plugins/plugin-auth/authorize/oauth-client-settings.tsx
@@ -22,7 +22,7 @@ export type OAuthClientSettingsProps = {
editValues?: Record<string, unknown>
disabled?: boolean
schemas: FormSchema[]
- onAuth?: () => Promise<void>
+ onRequestAuthorization?: () => Promise<void> | void
hasOriginalClientParams?: boolean
onUpdate?: () => void
}
@@ -34,7 +34,7 @@ const OAuthClientSettings = ({
editValues,
disabled,
schemas,
- onAuth,
+ onRequestAuthorization,
hasOriginalClientParams,
onUpdate,
}: OAuthClientSettingsProps) => {
@@ -64,7 +64,7 @@ const OAuthClientSettings = ({
const invalidPluginOAuthClientSchema = useInvalidPluginOAuthClientSchemaHook(pluginPayload)
const formRef = useRef<FormRefObject>(null)
const handleConfirm = useCallback(async () => {
- if (doingActionRef.current) return
+ if (doingActionRef.current) return false
try {
const { isCheckValidated, values } = formRef.current?.getFormValues({
@@ -85,6 +85,7 @@ const OAuthClientSettings = ({
onClose?.()
onUpdate?.()
invalidPluginOAuthClientSchema()
+ return true
} finally {
handleSetDoingAction(false)
}
@@ -99,9 +100,14 @@ const OAuthClientSettings = ({
])
const handleConfirmAndAuthorize = useCallback(async () => {
- await handleConfirm()
- if (onAuth) await onAuth()
- }, [handleConfirm, onAuth])
+ try {
+ const isSaved = await handleConfirm()
+ if (isSaved) await onRequestAuthorization?.()
+ } catch {
+ // The request layer reports the save error. Keep settings open and stop
+ // before opening the permission dialog.
+ }
+ }, [handleConfirm, onRequestAuthorization])
const { mutateAsync: deletePluginOAuthCustomClient } =
useDeletePluginOAuthCustomClientHook(pluginPayload)
const handleRemove = useCallback(async () => {
diff --git a/web/app/components/plugins/plugin-auth/authorize/oauth-visibility-dialog.tsx b/web/app/components/plugins/plugin-auth/authorize/oauth-visibility-dialog.tsx
new file mode 100644
index 00000000000..ce892e8609d
--- /dev/null
+++ b/web/app/components/plugins/plugin-auth/authorize/oauth-visibility-dialog.tsx
@@ -0,0 +1,77 @@
+import type { CredentialPermission } from '@/models/permission'
+import { Button } from '@langgenius/dify-ui/button'
+import {
+ Dialog,
+ DialogCloseButton,
+ DialogContent,
+ DialogDescription,
+ DialogTitle,
+} from '@langgenius/dify-ui/dialog'
+import { memo } from 'react'
+import { useTranslation } from 'react-i18next'
+import PermissionSelector from './permission-selector'
+
+type OAuthVisibilityDialogProps = {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ permission: CredentialPermission
+ onPermissionChange: (permission: CredentialPermission) => void
+ onConfirm: () => Promise<void> | void
+ loading?: boolean
+}
+
+const OAuthVisibilityDialog = ({
+ open,
+ onOpenChange,
+ permission,
+ onPermissionChange,
+ onConfirm,
+ loading = false,
+}: OAuthVisibilityDialogProps) => {
+ const { t } = useTranslation()
+ const handleOpenChange = (nextOpen: boolean) => {
+ if (loading && !nextOpen) return
+ onOpenChange(nextOpen)
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={handleOpenChange} disablePointerDismissal={loading}>
+ <DialogContent className="w-120! max-w-[calc(100vw-2rem)]! p-0!">
+ <div className="flex flex-col">
+ <div className="relative shrink-0 p-6 pr-14 pb-3">
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t(($) => $['auth.whoCanUse'], { ns: 'plugin' })}
+ </DialogTitle>
+ <DialogDescription className="mt-1 system-xs-regular text-text-tertiary">
+ {t(($) => $['auth.oauthCredentialPermissionDescription'], { ns: 'plugin' })}
+ </DialogDescription>
+ <DialogCloseButton className="top-5 right-5 size-8 rounded-lg" disabled={loading} />
+ </div>
+ <div className="px-6 py-3">
+ <PermissionSelector
+ disabled={loading}
+ permission={permission}
+ onChange={onPermissionChange}
+ />
+ </div>
+ <div className="flex shrink-0 justify-end p-6 pt-5">
+ <Button disabled={loading} onClick={() => handleOpenChange(false)}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </Button>
+ <Button
+ variant="primary"
+ className="ml-2"
+ loading={loading}
+ aria-busy={loading}
+ onClick={onConfirm}
+ >
+ {t(($) => $['auth.authorize'], { ns: 'plugin' })}
+ </Button>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+export default memo(OAuthVisibilityDialog)
diff --git a/web/app/components/plugins/plugin-auth/authorize/permission-selector.tsx b/web/app/components/plugins/plugin-auth/authorize/permission-selector.tsx
index f38c993bb06..c0f4acc8205 100644
--- a/web/app/components/plugins/plugin-auth/authorize/permission-selector.tsx
+++ b/web/app/components/plugins/plugin-auth/authorize/permission-selector.tsx
@@ -1,31 +1,25 @@
+import type { CredentialPermission } from '@/models/permission'
import { Avatar } from '@langgenius/dify-ui/avatar'
import { cn } from '@langgenius/dify-ui/cn'
import {
- Popover,
- PopoverClose,
- PopoverContent,
- PopoverTitle,
- PopoverTrigger,
-} from '@langgenius/dify-ui/popover'
-import { RadioGroup, RadioItem } from '@langgenius/dify-ui/radio'
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuRadioItemIndicator,
+ DropdownMenuTrigger,
+} from '@langgenius/dify-ui/dropdown-menu'
import { useSuspenseQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { PermissionLevel } from '@/models/permission'
-export type CredentialPermission =
- | typeof PermissionLevel.onlyMe
- | typeof PermissionLevel.allTeamMembers
-
type PermissionSelectorProps = {
disabled?: boolean
permission: CredentialPermission
onChange: (permission: CredentialPermission) => void
}
-const optionClassName =
- 'flex w-full touch-manipulation cursor-pointer items-center gap-x-1 rounded-lg border-none bg-transparent px-2 py-1 text-left outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid'
-
const PermissionSelector = ({ disabled, permission, onChange }: PermissionSelectorProps) => {
const { t } = useTranslation()
const { data: userProfile } = useSuspenseQuery({
@@ -35,10 +29,16 @@ const PermissionSelector = ({ disabled, permission, onChange }: PermissionSelect
const isOnlyMe = permission === PermissionLevel.onlyMe
const isAllTeamMembers = permission === PermissionLevel.allTeamMembers
const permissionLabel = t(($) => $['auth.whoCanUse'], { ns: 'plugin' })
+ const onlyMeLabel = t(($) => $['form.permissionsOnlyMe'], { ns: 'datasetSettings' })
+ const allTeamMembersLabel = t(($) => $['form.permissionsAllMember'], {
+ ns: 'datasetSettings',
+ })
+ const selectedPermissionLabel = isOnlyMe ? onlyMeLabel : allTeamMembersLabel
return (
- <Popover>
- <PopoverTrigger
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ aria-label={`${permissionLabel}: ${selectedPermissionLabel}`}
disabled={disabled}
className={cn(
'group/permission-trigger flex w-full cursor-pointer touch-manipulation items-center gap-x-0.5 rounded-lg bg-components-input-bg-normal px-2 py-1 text-left outline-hidden hover:bg-state-base-hover-alt focus-visible:ring-2 focus-visible:ring-state-accent-solid data-popup-open:bg-state-base-hover-alt',
@@ -51,7 +51,7 @@ const PermissionSelector = ({ disabled, permission, onChange }: PermissionSelect
<Avatar avatar={userProfile.avatar_url} name={userProfile.name} size="xs" />
</div>
<div className="grow p-1 system-sm-regular text-components-input-text-filled">
- {t(($) => $['form.permissionsOnlyMe'], { ns: 'datasetSettings' })}
+ {onlyMeLabel}
</div>
</>
)}
@@ -61,7 +61,7 @@ const PermissionSelector = ({ disabled, permission, onChange }: PermissionSelect
<span aria-hidden="true" className="i-ri-group-2-line size-4 text-text-secondary" />
</div>
<div className="grow p-1 system-sm-regular text-components-input-text-filled">
- {t(($) => $['form.permissionsAllMember'], { ns: 'datasetSettings' })}
+ {allTeamMembersLabel}
</div>
</>
)}
@@ -69,18 +69,22 @@ const PermissionSelector = ({ disabled, permission, onChange }: PermissionSelect
aria-hidden="true"
className="i-ri-arrow-down-s-line size-4 shrink-0 text-text-quaternary group-data-disabled/permission-trigger:text-components-input-text-placeholder! group-data-popup-open/permission-trigger:text-text-secondary"
/>
- </PopoverTrigger>
- <PopoverContent placement="bottom-start" sideOffset={4} popupClassName="w-[480px] p-0">
- <PopoverTitle className="sr-only">{permissionLabel}</PopoverTitle>
- <RadioGroup<CredentialPermission>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ placement="bottom-start"
+ sideOffset={4}
+ popupClassName="w-(--anchor-width) max-w-(--available-width)"
+ >
+ <DropdownMenuRadioGroup<CredentialPermission>
value={permission}
onValueChange={onChange}
aria-label={permissionLabel}
- className="flex-col items-stretch gap-0 p-1"
>
- <PopoverClose
- render={<RadioItem<CredentialPermission> value={PermissionLevel.onlyMe} />}
- className={optionClassName}
+ <DropdownMenuRadioItem<CredentialPermission>
+ aria-label={onlyMeLabel}
+ value={PermissionLevel.onlyMe}
+ closeOnClick
+ className="touch-manipulation"
>
<Avatar
avatar={userProfile.avatar_url}
@@ -88,30 +92,28 @@ const PermissionSelector = ({ disabled, permission, onChange }: PermissionSelect
className="shrink-0"
size="sm"
/>
- <div className="grow px-1 system-md-regular text-text-secondary">
- {t(($) => $['form.permissionsOnlyMe'], { ns: 'datasetSettings' })}
+ <div className="min-w-0 grow px-1 system-md-regular text-text-secondary">
+ {onlyMeLabel}
</div>
- {isOnlyMe && (
- <span aria-hidden="true" className="i-ri-check-line size-4 text-text-accent" />
- )}
- </PopoverClose>
- <PopoverClose
- render={<RadioItem<CredentialPermission> value={PermissionLevel.allTeamMembers} />}
- className={optionClassName}
+ <DropdownMenuRadioItemIndicator />
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem<CredentialPermission>
+ aria-label={allTeamMembersLabel}
+ value={PermissionLevel.allTeamMembers}
+ closeOnClick
+ className="touch-manipulation"
>
<div className="flex size-6 shrink-0 items-center justify-center">
<span aria-hidden="true" className="i-ri-group-2-line size-4 text-text-secondary" />
</div>
- <div className="grow px-1 system-md-regular text-text-secondary">
- {t(($) => $['form.permissionsAllMember'], { ns: 'datasetSettings' })}
+ <div className="min-w-0 grow px-1 system-md-regular text-text-secondary">
+ {allTeamMembersLabel}
</div>
- {isAllTeamMembers && (
- <span aria-hidden="true" className="i-ri-check-line size-4 text-text-accent" />
- )}
- </PopoverClose>
- </RadioGroup>
- </PopoverContent>
- </Popover>
+ <DropdownMenuRadioItemIndicator />
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
)
}
diff --git a/web/app/components/plugins/plugin-auth/hooks/__tests__/use-credential.spec.ts b/web/app/components/plugins/plugin-auth/hooks/__tests__/use-credential.spec.ts
index d364d8f9b5c..f7f65d5a753 100644
--- a/web/app/components/plugins/plugin-auth/hooks/__tests__/use-credential.spec.ts
+++ b/web/app/components/plugins/plugin-auth/hooks/__tests__/use-credential.spec.ts
@@ -159,6 +159,12 @@ describe('use-credential hooks', () => {
`/workspaces/current/tool-provider/builtin/${toolPayload.provider}/oauth/client-schema`,
)
})
+
+ it('should disable the service query when OAuth data is provided by the caller', () => {
+ renderHook(() => useGetPluginOAuthClientSchemaHook(toolPayload, false))
+
+ expect(mockUseGetPluginOAuthClientSchema).toHaveBeenCalledWith('')
+ })
})
describe('useInvalidPluginOAuthClientSchemaHook', () => {
diff --git a/web/app/components/plugins/plugin-auth/hooks/use-credential.ts b/web/app/components/plugins/plugin-auth/hooks/use-credential.ts
index 3c82daf5141..80e7151ab21 100644
--- a/web/app/components/plugins/plugin-auth/hooks/use-credential.ts
+++ b/web/app/components/plugins/plugin-auth/hooks/use-credential.ts
@@ -83,10 +83,10 @@ export const useGetPluginOAuthUrlHook = (pluginPayload: PluginPayload) => {
return useGetPluginOAuthUrl(apiMap.getOauthUrl)
}
-export const useGetPluginOAuthClientSchemaHook = (pluginPayload: PluginPayload) => {
+export const useGetPluginOAuthClientSchemaHook = (pluginPayload: PluginPayload, enabled = true) => {
const apiMap = useGetApi(pluginPayload)
- return useGetPluginOAuthClientSchema(apiMap.getOauthClientSchema)
+ return useGetPluginOAuthClientSchema(enabled ? apiMap.getOauthClientSchema : '')
}
export const useInvalidPluginOAuthClientSchemaHook = (pluginPayload: PluginPayload) => {
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/index.spec.tsx
index c9f3a0b812a..54e9e1452c5 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/index.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/index.spec.tsx
@@ -107,18 +107,21 @@ vi.mock('@/utils/get-icon', () => ({
vi.mock('@/app/components/plugins/plugin-auth/authorize/add-oauth-button', () => ({
default: ({ buttonText, onUpdate, renderTrigger }: AddOAuthButtonProps) => {
+ const trigger = (
+ <button type="button" onClick={onUpdate}>
+ {buttonText}
+ </button>
+ )
+
if (renderTrigger) {
return renderTrigger({
isConfigured: false,
onClick: () => onUpdate?.(),
+ trigger,
})
}
- return (
- <button type="button" onClick={onUpdate}>
- {buttonText}
- </button>
- )
+ return trigger
},
}))
diff --git a/web/i18n/ar-TN/plugin.json b/web/i18n/ar-TN/plugin.json
index ae3788e19b9..4d6627fbcbf 100644
--- a/web/i18n/ar-TN/plugin.json
+++ b/web/i18n/ar-TN/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "تفويض",
"auth.authorizationName": "اسم التفويض",
"auth.authorizations": "تفويضات",
+ "auth.authorize": "تفويض",
"auth.clientInfo": "نظرًا لعدم العثور على أسرار عميل النظام لمزود الأداة هذا، فإن إعداده يدويًا مطلوب، بالنسبة لـ redirect_uri، يرجى الاستخدام",
"auth.connectedWorkspace": "مساحة العمل المتصلة",
"auth.credentialUnavailable": "بيانات الاعتماد غير متوفرة حاليًا. يرجى الاتصال بالمسؤول.",
@@ -24,6 +25,7 @@
"auth.enterprise": "المؤسسة",
"auth.oauthClient": "عميل OAuth",
"auth.oauthClientSettings": "إعدادات عميل OAuth",
+ "auth.oauthCredentialPermissionDescription": "اختر ما إذا كانت بيانات اعتماد OAuth الجديدة خاصة بك فقط أم مشتركة مع جميع أعضاء مساحة العمل. ينطبق هذا الإعداد على بيانات الاعتماد، وليس على عميل OAuth، ولا يمكن تغييره بعد التفويض.",
"auth.onlyAtCreationHint": "لا يمكن تحديده مرة أخرى بعد التبديل",
"auth.onlyAtCreationHintTooltip": "تم تكوينه بواسطة أعضاء آخرين · لا يمكن اختياره مرة أخرى بعد التبديل.",
"auth.permissionHint.action": "من يمكنه المساعدة؟",
diff --git a/web/i18n/de-DE/plugin.json b/web/i18n/de-DE/plugin.json
index 68cc40aea52..e58db219428 100644
--- a/web/i18n/de-DE/plugin.json
+++ b/web/i18n/de-DE/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "Befugnis",
"auth.authorizationName": "Genehmigungsname",
"auth.authorizations": "Berechtigungen",
+ "auth.authorize": "Autorisieren",
"auth.clientInfo": "Da keine System-Client-Geheimnisse für diesen Tool-Anbieter gefunden wurden, ist eine manuelle Einrichtung erforderlich. Bitte verwenden Sie für redirect_uri",
"auth.connectedWorkspace": "Vernetzter Arbeitsbereich",
"auth.credentialUnavailable": "Anmeldeinformationen derzeit nicht verfügbar. Bitte kontaktieren Sie den Administrator.",
@@ -24,6 +25,7 @@
"auth.enterprise": "Unternehmen",
"auth.oauthClient": "OAuth-Client",
"auth.oauthClientSettings": "OAuth-Client-Einstellungen",
+ "auth.oauthCredentialPermissionDescription": "Wähle, ob die neuen OAuth-Anmeldedaten nur für dich gelten oder mit allen Workspace-Mitgliedern geteilt werden. Diese Einstellung gilt für die Anmeldedaten, nicht für den OAuth-Client, und kann nach der Autorisierung nicht mehr geändert werden.",
"auth.onlyAtCreationHint": "Nach dem Umschalten nicht erneut wählbar",
"auth.onlyAtCreationHintTooltip": "Von anderen Mitgliedern konfiguriert · Kann nach dem Wechsel nicht erneut ausgewählt werden.",
"auth.permissionHint.action": "Wer kann helfen?",
diff --git a/web/i18n/en-US/plugin.json b/web/i18n/en-US/plugin.json
index cc909c2d0a9..ab7f1cc304a 100644
--- a/web/i18n/en-US/plugin.json
+++ b/web/i18n/en-US/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "Authorization",
"auth.authorizationName": "Authorization Name",
"auth.authorizations": "Authorizations",
+ "auth.authorize": "Authorize",
"auth.clientInfo": "As no system client secrets found for this tool provider, setup it manually is required, for redirect_uri, please use",
"auth.connectedWorkspace": "Connected Workspace",
"auth.credentialUnavailable": "Credentials currently unavailable. Please contact admin.",
@@ -24,6 +25,7 @@
"auth.enterprise": "Enterprise",
"auth.oauthClient": "OAuth Client",
"auth.oauthClientSettings": "OAuth Client Settings",
+ "auth.oauthCredentialPermissionDescription": "Choose whether the new OAuth credential is only for you or shared with all workspace members. This setting applies to the credential, not the OAuth client, and can't be changed after authorization.",
"auth.onlyAtCreationHint": "Cannot be selected again after switching",
"auth.onlyAtCreationHintTooltip": "Configured by other members · Cannot be selected again after switching.",
"auth.permissionHint.action": "Who can help?",
diff --git a/web/i18n/es-ES/plugin.json b/web/i18n/es-ES/plugin.json
index ae89e95a446..7fe09f475fb 100644
--- a/web/i18n/es-ES/plugin.json
+++ b/web/i18n/es-ES/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "Autorización",
"auth.authorizationName": "Nombre de autorización",
"auth.authorizations": "Autorizaciones",
+ "auth.authorize": "Autorizar",
"auth.clientInfo": "Como no se encontraron secretos de cliente del sistema para este proveedor de herramientas, se requiere configurarlo manualmente. Para redirect_uri, por favor utiliza",
"auth.connectedWorkspace": "Espacio de trabajo conectado",
"auth.credentialUnavailable": "Credenciales actualmente no disponibles. Por favor, contacte al administrador.",
@@ -24,6 +25,7 @@
"auth.enterprise": "Empresa",
"auth.oauthClient": "Cliente OAuth",
"auth.oauthClientSettings": "Configuración del cliente OAuth",
+ "auth.oauthCredentialPermissionDescription": "Elige si la nueva credencial de OAuth es solo para ti o se comparte con todos los miembros del espacio de trabajo. Esta configuración se aplica a la credencial, no al cliente de OAuth, y no se puede cambiar después de la autorización.",
"auth.onlyAtCreationHint": "No se puede volver a seleccionar después de cambiar",
"auth.onlyAtCreationHintTooltip": "Configurado por otros miembros · No se puede volver a seleccionar después de cambiar.",
"auth.permissionHint.action": "¿Quién puede ayudar?",
diff --git a/web/i18n/fa-IR/plugin.json b/web/i18n/fa-IR/plugin.json
index 1834a6dec2d..bb374e97333 100644
--- a/web/i18n/fa-IR/plugin.json
+++ b/web/i18n/fa-IR/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "مجوز",
"auth.authorizationName": "نام مجوز",
"auth.authorizations": "مجوزها",
+ "auth.authorize": "مجوزدهی",
"auth.clientInfo": "از آنجایی که هیچ راز مشتری سیستم برای این ارائه‌دهنده ابزار پیدا نشد، تنظیم دستی آن ضروری است، لطفاً برای redirect_uri از",
"auth.connectedWorkspace": "فضای کاری متصل",
"auth.credentialUnavailable": "دسترسی به مدارک در حال حاضر امکان‌پذیر نیست. لطفاً با مدیر تماس بگیرید.",
@@ -24,6 +25,7 @@
"auth.enterprise": "تصدی",
"auth.oauthClient": "کلاینت اوتور",
"auth.oauthClientSettings": "تنظیمات کلاینت اوتور",
+ "auth.oauthCredentialPermissionDescription": "انتخاب کنید اعتبارنامه OAuth جدید فقط برای شما باشد یا با همه اعضای فضای کاری به اشتراک گذاشته شود. این تنظیم مربوط به اعتبارنامه است، نه کلاینت OAuth، و پس از مجوزدهی قابل تغییر نیست.",
"auth.onlyAtCreationHint": "بعد از تعویض نمی توان دوباره انتخاب کرد",
"auth.onlyAtCreationHintTooltip": "پیکربندی شده توسط سایر اعضا · پس از تعویض دوباره انتخاب نمی شود.",
"auth.permissionHint.action": "چه کسی می‌تواند کمک کند؟",
diff --git a/web/i18n/fr-FR/plugin.json b/web/i18n/fr-FR/plugin.json
index 4431b9f6e6f..7ce28a6030e 100644
--- a/web/i18n/fr-FR/plugin.json
+++ b/web/i18n/fr-FR/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "Autorisation",
"auth.authorizationName": "Nom d'autorisation",
"auth.authorizations": "Autorisations",
+ "auth.authorize": "Autoriser",
"auth.clientInfo": "Comme aucun secret client du système n'a été trouvé pour ce fournisseur d'outils, une configuration manuelle est requise. Pour redirect_uri, veuillez utiliser",
"auth.connectedWorkspace": "Espace de travail connecté",
"auth.credentialUnavailable": "Les informations d'identification ne sont actuellement pas disponibles. Veuillez contacter l'administrateur.",
@@ -24,6 +25,7 @@
"auth.enterprise": "Entreprise",
"auth.oauthClient": "Client OAuth",
"auth.oauthClientSettings": "Paramètres du client OAuth",
+ "auth.oauthCredentialPermissionDescription": "Choisissez si le nouvel identifiant OAuth est réservé à votre usage ou partagé avec tous les membres de l’espace de travail. Ce paramètre s’applique à l’identifiant, pas au client OAuth, et ne peut plus être modifié après l’autorisation.",
"auth.onlyAtCreationHint": "Ne peut pas être sélectionné après le changement",
"auth.onlyAtCreationHintTooltip": "Configuré par d'autres membres · Ne peut pas être sélectionné après le changement.",
"auth.permissionHint.action": "Qui peut aider ?",
diff --git a/web/i18n/hi-IN/plugin.json b/web/i18n/hi-IN/plugin.json
index 0863af7687c..af6bc3d6229 100644
--- a/web/i18n/hi-IN/plugin.json
+++ b/web/i18n/hi-IN/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "अधिकार",
"auth.authorizationName": "अनु autorización नाम",
"auth.authorizations": "अनुमतियाँ",
+ "auth.authorize": "अधिकृत करें",
"auth.clientInfo": "चूंकि इस टूल प्रदाता के लिए कोई सिस्टम क्लाइंट रहस्य नहीं पाए गए हैं, इसलिए इसे मैन्युअल रूप से सेटअप करना आवश्यक है, कृपया redirect_uri का उपयोग करें",
"auth.connectedWorkspace": "संयुक्त कार्यक्षेत्र",
"auth.credentialUnavailable": "वर्तमान में क्रेडेंशियल्स उपलब्ध नहीं हैं। कृपया प्रशासन से संपर्क करें।",
@@ -24,6 +25,7 @@
"auth.enterprise": "उद्यम",
"auth.oauthClient": "OAuth क्लाइंट",
"auth.oauthClientSettings": "OAuth क्लाइंट सेटिंग्स",
+ "auth.oauthCredentialPermissionDescription": "चुनें कि नया OAuth क्रेडेंशियल केवल आपके लिए हो या कार्यस्थान के सभी सदस्यों के साथ साझा किया जाए। यह सेटिंग क्रेडेंशियल पर लागू होती है, OAuth क्लाइंट पर नहीं, और प्राधिकरण के बाद बदली नहीं जा सकती।",
"auth.onlyAtCreationHint": "स्विच करने के बाद दोबारा चयन नहीं किया जा सकता",
"auth.onlyAtCreationHintTooltip": "अन्य सदस्यों द्वारा कॉन्फ़िगर किया गया · स्विच करने के बाद दोबारा नहीं चुना जा सकता।",
"auth.permissionHint.action": "कौन मदद कर सकता है?",
diff --git a/web/i18n/id-ID/plugin.json b/web/i18n/id-ID/plugin.json
index f8da3d6d936..c924915092c 100644
--- a/web/i18n/id-ID/plugin.json
+++ b/web/i18n/id-ID/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "Otorisasi",
"auth.authorizationName": "Nama Otorisasi",
"auth.authorizations": "Otorisasi",
+ "auth.authorize": "Otorisasi",
"auth.clientInfo": "Karena tidak ada rahasia klien sistem yang ditemukan untuk penyedia alat ini, pengaturannya secara manual diperlukan, untuk redirect_uri, silakan gunakan",
"auth.connectedWorkspace": "Ruang Kerja yang Terhubung",
"auth.credentialUnavailable": "Kredensial saat ini tidak tersedia. Silakan hubungi admin.",
@@ -24,6 +25,7 @@
"auth.enterprise": "Perusahaan",
"auth.oauthClient": "Klien OAuth",
"auth.oauthClientSettings": "Pengaturan Klien OAuth",
+ "auth.oauthCredentialPermissionDescription": "Pilih apakah kredensial OAuth baru hanya untuk Anda atau dibagikan kepada semua anggota ruang kerja. Pengaturan ini berlaku untuk kredensial, bukan klien OAuth, dan tidak dapat diubah setelah otorisasi.",
"auth.onlyAtCreationHint": "Tidak dapat dipilih lagi setelah peralihan",
"auth.onlyAtCreationHintTooltip": "Dikonfigurasi oleh anggota lain · Tidak dapat dipilih lagi setelah beralih.",
"auth.permissionHint.action": "Siapa yang bisa membantu?",
diff --git a/web/i18n/it-IT/plugin.json b/web/i18n/it-IT/plugin.json
index f2ee93f3859..95acde561a4 100644
--- a/web/i18n/it-IT/plugin.json
+++ b/web/i18n/it-IT/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "Autorizzazione",
"auth.authorizationName": "Nome di autorizzazione",
"auth.authorizations": "Autorizzazioni",
+ "auth.authorize": "Autorizza",
"auth.clientInfo": "Poiché non sono stati trovati segreti client di sistema per questo fornitore di strumenti, è necessario configurarlo manualmente. Per redirect_uri, si prega di utilizzare",
"auth.connectedWorkspace": "Area di lavoro connessa",
"auth.credentialUnavailable": "Credenziali attualmente non disponibili. Si prega di contattare l'amministratore.",
@@ -24,6 +25,7 @@
"auth.enterprise": "Impresa",
"auth.oauthClient": "Client OAuth",
"auth.oauthClientSettings": "Impostazioni del client OAuth",
+ "auth.oauthCredentialPermissionDescription": "Scegli se la nuova credenziale OAuth è riservata a te o condivisa con tutti i membri dell'area di lavoro. Questa impostazione si applica alla credenziale, non al client OAuth, e non può essere modificata dopo l'autorizzazione.",
"auth.onlyAtCreationHint": "Non può essere selezionato nuovamente dopo il passaggio",
"auth.onlyAtCreationHintTooltip": "Configurato da altri membri · Non può essere selezionato nuovamente dopo il passaggio.",
"auth.permissionHint.action": "Chi può aiutare?",
diff --git a/web/i18n/ja-JP/plugin.json b/web/i18n/ja-JP/plugin.json
index 29b713c981a..da8d706f5a4 100644
--- a/web/i18n/ja-JP/plugin.json
+++ b/web/i18n/ja-JP/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "認証",
"auth.authorizationName": "認証名",
"auth.authorizations": "認可",
+ "auth.authorize": "承認",
"auth.clientInfo": "このツールプロバイダーにシステムクライアントシークレットが見つからないため、手動で設定する必要があります。redirect_uriには、次を使用してください。",
"auth.connectedWorkspace": "接続されたワークスペース",
"auth.credentialUnavailable": "現在、資格情報は利用できません。管理者にご連絡ください。",
@@ -24,6 +25,7 @@
"auth.enterprise": "エンタープライズ",
"auth.oauthClient": "OAuthクライアント",
"auth.oauthClientSettings": "OAuthクライアント設定",
+ "auth.oauthCredentialPermissionDescription": "新しい OAuth 認証情報を自分だけで使用するか、ワークスペースの全メンバーと共有するかを選択します。この設定は OAuth クライアントではなく認証情報に適用され、認可後は変更できません。",
"auth.onlyAtCreationHint": "切り替え後は再度選択できません",
"auth.onlyAtCreationHintTooltip": "他のメンバーが設定 ・切り替え後は再度選択できません。",
"auth.permissionHint.action": "誰に相談できますか?",
diff --git a/web/i18n/ko-KR/plugin.json b/web/i18n/ko-KR/plugin.json
index 3d80a948c14..c0f9b145f9d 100644
--- a/web/i18n/ko-KR/plugin.json
+++ b/web/i18n/ko-KR/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "권한",
"auth.authorizationName": "권한 이름",
"auth.authorizations": "권한",
+ "auth.authorize": "권한 부여",
"auth.clientInfo": "이 도구 공급자에 대한 시스템 클라이언트 비밀이 발견되지 않았으므로 수동으로 설정해야 하며, redirect_uri는 다음을 사용하십시오.",
"auth.connectedWorkspace": "연결된 작업 공간",
"auth.credentialUnavailable": "현재 자격 증명이 사용 불가능합니다. 관리자에게 문의하십시오.",
@@ -24,6 +25,7 @@
"auth.enterprise": "기업",
"auth.oauthClient": "OAuth 클라이언트",
"auth.oauthClientSettings": "OAuth 클라이언트 설정",
+ "auth.oauthCredentialPermissionDescription": "새 OAuth 자격 증명을 본인만 사용할지, 워크스페이스의 모든 구성원과 공유할지 선택하세요. 이 설정은 OAuth 클라이언트가 아닌 자격 증명에 적용되며, 인증 후에는 변경할 수 없습니다.",
"auth.onlyAtCreationHint": "전환 후에는 다시 선택할 수 없습니다",
"auth.onlyAtCreationHintTooltip": "다른 구성원이 구성 · 전환 후 다시 선택할 수 없습니다.",
"auth.permissionHint.action": "누가 도와줄 수 있나요?",
diff --git a/web/i18n/lo-LA/plugin.json b/web/i18n/lo-LA/plugin.json
index e414a330d68..3d8c671471f 100644
--- a/web/i18n/lo-LA/plugin.json
+++ b/web/i18n/lo-LA/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "ການອະນຸຍາດ",
"auth.authorizationName": "ຊື່ການອະນຸຍາດ",
"auth.authorizations": "ການອະນຸຍາດທັງໝົດ",
+ "auth.authorize": "ອະນຸຍາດ",
"auth.clientInfo": "ເນື່ອງຈາກບໍ່ພົບ client secrets ຂອງລະບົບສຳລັບຜູ້ໃຫ້ບໍລິການເຄື່ອງມືນີ້, ຈຳເປັນຕ້ອງໄດ້ຕັ້ງຄ່າດ້ວຍຕົນເອງ, ສຳລັບ redirect_uri, ກະລຸນານຳໃຊ້",
"auth.connectedWorkspace": "Workspace ທີ່ເຊື່ອມຕໍ່ແລ້ວ",
"auth.credentialUnavailable": "ຂໍ້ມູນການເຂົ້າລະບົບບໍ່ພ້ອມໃຊ້ງານໃນຂະນະນີ້. ກະລຸນາຕິດຕໍ່ຜູ້ດູແລລະບົບ.",
@@ -24,6 +25,7 @@
"auth.enterprise": "ລະດັບອົງກອນ",
"auth.oauthClient": "OAuth Client",
"auth.oauthClientSettings": "ຕັ້ງຄ່າ OAuth Client",
+ "auth.oauthCredentialPermissionDescription": "ເລືອກວ່າຂໍ້ມູນຢືນຢັນ OAuth ໃໝ່ຈະໃຊ້ສະເພາະທ່ານ ຫຼື ແບ່ງປັນໃຫ້ສະມາຊິກທຸກຄົນໃນພື້ນທີ່ເຮັດວຽກ. ການຕັ້ງຄ່ານີ້ນຳໃຊ້ກັບຂໍ້ມູນຢືນຢັນ, ບໍ່ແມ່ນ OAuth client, ແລະບໍ່ສາມາດປ່ຽນໄດ້ຫຼັງຈາກອະນຸຍາດ.",
"auth.onlyAtCreationHint": "ບໍ່ສາມາດເລືອກໃໝ່ໄດ້ຫຼັງຈາກປ່ຽນແປງ",
"auth.onlyAtCreationHintTooltip": "ຖືກຕັ້ງຄ່າໂດຍສະມາຊິກຄົນອື່ນ · ບໍ່ສາມາດເລືອກໃໝ່ໄດ້ຫຼັງຈາກປ່ຽນແປງ.",
"auth.permissionHint.action": "ໃຜສາມາດຊ່ວຍໄດ້?",
diff --git a/web/i18n/nl-NL/plugin.json b/web/i18n/nl-NL/plugin.json
index c9ce156af03..e31111c1f15 100644
--- a/web/i18n/nl-NL/plugin.json
+++ b/web/i18n/nl-NL/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "Authorization",
"auth.authorizationName": "Authorization Name",
"auth.authorizations": "Authorizations",
+ "auth.authorize": "Autoriseren",
"auth.clientInfo": "As no system client secrets found for this tool provider, setup it manually is required, for redirect_uri, please use",
"auth.connectedWorkspace": "Connected Workspace",
"auth.credentialUnavailable": "Credentials currently unavailable. Please contact admin.",
@@ -24,6 +25,7 @@
"auth.enterprise": "Onderneming",
"auth.oauthClient": "OAuth Client",
"auth.oauthClientSettings": "OAuth Client Settings",
+ "auth.oauthCredentialPermissionDescription": "Kies of de nieuwe OAuth-inloggegevens alleen voor jou zijn of worden gedeeld met alle werkruimteleden. Deze instelling geldt voor de inloggegevens, niet voor de OAuth-client, en kan na autorisatie niet meer worden gewijzigd.",
"auth.onlyAtCreationHint": "Na overschakeling niet meer selecteerbaar",
"auth.onlyAtCreationHintTooltip": "Geconfigureerd door andere leden · Kan na het overstappen niet meer geselecteerd worden.",
"auth.permissionHint.action": "Wie kan helpen?",
diff --git a/web/i18n/pl-PL/plugin.json b/web/i18n/pl-PL/plugin.json
index ed4c06fe177..bac26740194 100644
--- a/web/i18n/pl-PL/plugin.json
+++ b/web/i18n/pl-PL/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "Autoryzacja",
"auth.authorizationName": "Nazwa autoryzacji",
"auth.authorizations": "Uprawnienia",
+ "auth.authorize": "Autoryzuj",
"auth.clientInfo": "Ponieważ nie znaleziono tajemnic klientów systemu dla tego dostawcy narzędzi, wymagane jest ręczne skonfigurowanie, dla redirect_uri proszę użyć",
"auth.connectedWorkspace": "Połączona przestrzeń robocza",
"auth.credentialUnavailable": "Kredencje są obecnie niedostępne. Proszę skontaktować się z administratorem.",
@@ -24,6 +25,7 @@
"auth.enterprise": "Przedsiębiorstwo",
"auth.oauthClient": "Klient OAuth",
"auth.oauthClientSettings": "Ustawienia klienta OAuth",
+ "auth.oauthCredentialPermissionDescription": "Wybierz, czy nowe dane uwierzytelniające OAuth mają być dostępne tylko dla Ciebie, czy udostępnione wszystkim członkom obszaru roboczego. To ustawienie dotyczy danych uwierzytelniających, a nie klienta OAuth, i nie można go zmienić po autoryzacji.",
"auth.onlyAtCreationHint": "Po przełączeniu nie można wybrać ponownie",
"auth.onlyAtCreationHintTooltip": "Skonfigurowane przez innych użytkowników · Nie można wybrać ponownie po przełączeniu.",
"auth.permissionHint.action": "Kto może pomóc?",
diff --git a/web/i18n/pt-BR/plugin.json b/web/i18n/pt-BR/plugin.json
index b962b64cf96..5ea2f9b4f44 100644
--- a/web/i18n/pt-BR/plugin.json
+++ b/web/i18n/pt-BR/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "Autorização",
"auth.authorizationName": "Nome da Autorização",
"auth.authorizations": "Autorizações",
+ "auth.authorize": "Autorizar",
"auth.clientInfo": "Como não foram encontrados segredos de cliente do sistema para este provedor de ferramentas, é necessário configurá-lo manualmente. Para redirect_uri, use",
"auth.connectedWorkspace": "Espaço de trabalho conectado",
"auth.credentialUnavailable": "Credenciais atualmente indisponíveis. Por favor, contate o administrador.",
@@ -24,6 +25,7 @@
"auth.enterprise": "Empresa",
"auth.oauthClient": "Cliente OAuth",
"auth.oauthClientSettings": "Configurações do Cliente OAuth",
+ "auth.oauthCredentialPermissionDescription": "Escolha se a nova credencial OAuth será exclusiva para você ou compartilhada com todos os membros do espaço de trabalho. Essa configuração se aplica à credencial, não ao cliente OAuth, e não pode ser alterada após a autorização.",
"auth.onlyAtCreationHint": "Não pode ser selecionado novamente após a troca",
"auth.onlyAtCreationHintTooltip": "Configurado por outros membros · Não pode ser selecionado novamente após a troca.",
"auth.permissionHint.action": "Quem pode ajudar?",
diff --git a/web/i18n/ro-RO/plugin.json b/web/i18n/ro-RO/plugin.json
index 1011cb9f61d..9f0820d4395 100644
--- a/web/i18n/ro-RO/plugin.json
+++ b/web/i18n/ro-RO/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "Autorizație",
"auth.authorizationName": "Numele autorizării",
"auth.authorizations": "Autorizări",
+ "auth.authorize": "Autorizează",
"auth.clientInfo": "Deoarece nu s-au găsit secretele clientului sistemului pentru acest furnizor de instrumente, este necesară configurarea manuală; pentru redirect_uri, vă rugăm să folosiți",
"auth.connectedWorkspace": "Spațiu de lucru conectat",
"auth.credentialUnavailable": "Credențialele nu sunt disponibile în acest moment. Vă rugăm să contactați administratorul.",
@@ -24,6 +25,7 @@
"auth.enterprise": "Întreprindere",
"auth.oauthClient": "Client OAuth",
"auth.oauthClientSettings": "Setările clientului OAuth",
+ "auth.oauthCredentialPermissionDescription": "Alege dacă noua acreditare OAuth este doar pentru tine sau este partajată cu toți membrii spațiului de lucru. Această setare se aplică acreditării, nu clientului OAuth, și nu poate fi modificată după autorizare.",
"auth.onlyAtCreationHint": "Nu poate fi selectat din nou după comutare",
"auth.onlyAtCreationHintTooltip": "Configurat de alți membri · Nu poate fi selectat din nou după comutare.",
"auth.permissionHint.action": "Cine poate ajuta?",
diff --git a/web/i18n/ru-RU/plugin.json b/web/i18n/ru-RU/plugin.json
index 3d83a83e959..cc2b798f782 100644
--- a/web/i18n/ru-RU/plugin.json
+++ b/web/i18n/ru-RU/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "Авторизация",
"auth.authorizationName": "Имя авторизации",
"auth.authorizations": "Авторизации",
+ "auth.authorize": "Авторизовать",
"auth.clientInfo": "Поскольку не найдены секреты клиентской системы для этого поставщика инструментов, необходимо настроить его вручную, для redirect_uri, пожалуйста, используйте",
"auth.connectedWorkspace": "Подключенное рабочее пространство",
"auth.credentialUnavailable": "Учетные данные в настоящее время недоступны. Пожалуйста, свяжитесь с администратором.",
@@ -24,6 +25,7 @@
"auth.enterprise": "Предприятие",
"auth.oauthClient": "OAuth клиент",
"auth.oauthClientSettings": "Настройки клиента OAuth",
+ "auth.oauthCredentialPermissionDescription": "Выберите, будут ли новые учетные данные OAuth доступны только вам или всем участникам рабочего пространства. Эта настройка относится к учетным данным, а не к клиенту OAuth, и ее нельзя изменить после авторизации.",
"auth.onlyAtCreationHint": "Невозможно выбрать снова после переключения",
"auth.onlyAtCreationHintTooltip": "Настроено другими участниками · Невозможно выбрать повторно после переключения.",
"auth.permissionHint.action": "Кто может помочь?",
diff --git a/web/i18n/sl-SI/plugin.json b/web/i18n/sl-SI/plugin.json
index 5698ac76c04..854abf2439d 100644
--- a/web/i18n/sl-SI/plugin.json
+++ b/web/i18n/sl-SI/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "Avtorizacija",
"auth.authorizationName": "Ime pooblastila",
"auth.authorizations": "Avtorizacije",
+ "auth.authorize": "Avtoriziraj",
"auth.clientInfo": "Ker za tega ponudnika orodij niso bili najdeni klientski skrivnosti sistema, je potrebna ročna nastavitev, za redirect_uri prosimo uporabite",
"auth.connectedWorkspace": "Povezani delovni prostor",
"auth.credentialUnavailable": "Trenutno niso na voljo poverilnice. Prosimo, kontaktirajte administratorja.",
@@ -24,6 +25,7 @@
"auth.enterprise": "Podjetje",
"auth.oauthClient": "OAuth odjemalec",
"auth.oauthClientSettings": "Nastavitve odjemalca OAuth",
+ "auth.oauthCredentialPermissionDescription": "Izberite, ali bodo nove poverilnice OAuth namenjene samo vam ali v skupni rabi z vsemi člani delovnega prostora. Ta nastavitev velja za poverilnice, ne za odjemalca OAuth, in je po avtorizaciji ni mogoče spremeniti.",
"auth.onlyAtCreationHint": "Po preklopu ga ni mogoče znova izbrati",
"auth.onlyAtCreationHintTooltip": "Konfigurirali drugi člani · Po zamenjavi ni mogoče znova izbrati.",
"auth.permissionHint.action": "Kdo lahko pomaga?",
diff --git a/web/i18n/th-TH/plugin.json b/web/i18n/th-TH/plugin.json
index 8d4ec24796c..0961caf3e0e 100644
--- a/web/i18n/th-TH/plugin.json
+++ b/web/i18n/th-TH/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "การอนุญาต",
"auth.authorizationName": "ชื่อผู้มีอำนาจ",
"auth.authorizations": "การอนุญาต",
+ "auth.authorize": "อนุญาต",
"auth.clientInfo": "เนื่องจากไม่พบความลับของลูกค้าสำหรับผู้ให้บริการเครื่องมือนี้ จำเป็นต้องตั้งค่าแบบแมนนวล สำหรับ redirect_uri กรุณาใช้",
"auth.connectedWorkspace": "พื้นที่ทํางานที่เชื่อมต่อ",
"auth.credentialUnavailable": "ข้อมูลรับรองไม่สามารถใช้งานได้ในขณะนี้ กรุณาติดต่อผู้ดูแลระบบ.",
@@ -24,6 +25,7 @@
"auth.enterprise": "องค์กร",
"auth.oauthClient": "ไคลเอนต์ OAuth",
"auth.oauthClientSettings": "การตั้งค่าไคลเอนต์ OAuth",
+ "auth.oauthCredentialPermissionDescription": "เลือกว่าข้อมูลประจำตัว OAuth ใหม่จะใช้ได้เฉพาะคุณหรือแชร์กับสมาชิกทุกคนในพื้นที่ทำงาน การตั้งค่านี้ใช้กับข้อมูลประจำตัว ไม่ใช่ไคลเอนต์ OAuth และไม่สามารถเปลี่ยนได้หลังจากอนุญาตแล้ว",
"auth.onlyAtCreationHint": "ไม่สามารถเลือกได้อีกหลังจากเปลี่ยนแล้ว",
"auth.onlyAtCreationHintTooltip": "กำหนดค่าโดยสมาชิกรายอื่น · ไม่สามารถเลือกได้อีกหลังจากเปลี่ยนแล้ว",
"auth.permissionHint.action": "ใครช่วยได้บ้าง?",
diff --git a/web/i18n/tr-TR/plugin.json b/web/i18n/tr-TR/plugin.json
index 58b2758b6db..3054c665e5e 100644
--- a/web/i18n/tr-TR/plugin.json
+++ b/web/i18n/tr-TR/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "Yetkilendirme",
"auth.authorizationName": "Yetkilendirme Adı",
"auth.authorizations": "Yetkilendirmeler",
+ "auth.authorize": "Yetkilendir",
"auth.clientInfo": "Bu araç sağlayıcı için sistem istemci gizlilikleri bulunmadığından, manuel olarak ayar yapılması gerekmektedir. redirect_uri için lütfen şu adresi kullanın",
"auth.connectedWorkspace": "Bağlı Çalışma Alanı",
"auth.credentialUnavailable": "Kimlik bilgileri şu anda mevcut değil. Lütfen yönetici ile iletişime geçin.",
@@ -24,6 +25,7 @@
"auth.enterprise": "Girişim",
"auth.oauthClient": "OAuth İstemcisi",
"auth.oauthClientSettings": "OAuth İstemci Ayarları",
+ "auth.oauthCredentialPermissionDescription": "Yeni OAuth kimlik bilgisinin yalnızca size özel mi olacağını yoksa çalışma alanındaki tüm üyelerle mi paylaşılacağını seçin. Bu ayar OAuth istemcisine değil kimlik bilgisine uygulanır ve yetkilendirmeden sonra değiştirilemez.",
"auth.onlyAtCreationHint": "Geçişten sonra tekrar seçilemez",
"auth.onlyAtCreationHintTooltip": "Diğer üyeler tarafından yapılandırıldı · Geçişten sonra tekrar seçilemez.",
"auth.permissionHint.action": "Kim yardımcı olabilir?",
diff --git a/web/i18n/uk-UA/plugin.json b/web/i18n/uk-UA/plugin.json
index 809e0d4f204..630ece992cf 100644
--- a/web/i18n/uk-UA/plugin.json
+++ b/web/i18n/uk-UA/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "Авторизація",
"auth.authorizationName": "Назва авторизації",
"auth.authorizations": "Авторизації",
+ "auth.authorize": "Авторизувати",
"auth.clientInfo": "Оскільки не знайдено жодних секретів клієнта системи для цього постачальника інструментів, потрібно налаштувати його вручну; для redirect_uri, будь ласка, використовуйте",
"auth.connectedWorkspace": "Підключене робоче середовище",
"auth.credentialUnavailable": "Облікові дані наразі недоступні. Будь ласка, зверніться до адміністратора.",
@@ -24,6 +25,7 @@
"auth.enterprise": "підприємство",
"auth.oauthClient": "Клієнт OAuth",
"auth.oauthClientSettings": "Налаштування клієнта OAuth",
+ "auth.oauthCredentialPermissionDescription": "Виберіть, чи будуть нові облікові дані OAuth доступні лише вам, чи всім учасникам робочого простору. Це налаштування застосовується до облікових даних, а не до клієнта OAuth, і його не можна змінити після авторизації.",
"auth.onlyAtCreationHint": "Не можна вибрати знову після перемикання",
"auth.onlyAtCreationHintTooltip": "Налаштовано іншими учасниками · Неможливо вибрати знову після перемикання.",
"auth.permissionHint.action": "Хто може допомогти?",
diff --git a/web/i18n/vi-VN/plugin.json b/web/i18n/vi-VN/plugin.json
index 01a119995fb..0c53d8f25c2 100644
--- a/web/i18n/vi-VN/plugin.json
+++ b/web/i18n/vi-VN/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "Ủy quyền",
"auth.authorizationName": "Tên ủy quyền",
"auth.authorizations": "Chấp thuận",
+ "auth.authorize": "Ủy quyền",
"auth.clientInfo": "Vì không tìm thấy bí mật khách hàng hệ thống cho nhà cung cấp công cụ này, cần thiết lập thủ công, đối với redirect_uri, vui lòng sử dụng",
"auth.connectedWorkspace": "Không gian làm việc được kết nối",
"auth.credentialUnavailable": "Thông tin đăng nhập hiện không khả dụng. Vui lòng liên hệ với quản trị viên.",
@@ -24,6 +25,7 @@
"auth.enterprise": "Doanh nghiệp",
"auth.oauthClient": "Khách hàng OAuth",
"auth.oauthClientSettings": "Cài đặt khách hàng OAuth",
+ "auth.oauthCredentialPermissionDescription": "Chọn xem thông tin xác thực OAuth mới chỉ dành cho bạn hay được chia sẻ với tất cả thành viên trong không gian làm việc. Cài đặt này áp dụng cho thông tin xác thực, không phải ứng dụng OAuth, và không thể thay đổi sau khi ủy quyền.",
"auth.onlyAtCreationHint": "Không thể chọn lại sau khi chuyển đổi",
"auth.onlyAtCreationHintTooltip": "Được cấu hình bởi các thành viên khác. Không thể chọn lại sau khi chuyển đổi.",
"auth.permissionHint.action": "Ai có thể giúp?",
diff --git a/web/i18n/zh-Hans/plugin.json b/web/i18n/zh-Hans/plugin.json
index 4e72276bf37..184b60d344f 100644
--- a/web/i18n/zh-Hans/plugin.json
+++ b/web/i18n/zh-Hans/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "凭据",
"auth.authorizationName": "凭据名称",
"auth.authorizations": "凭据",
+ "auth.authorize": "授权",
"auth.clientInfo": "由于未找到此工具提供者的系统客户端密钥,因此需要手动设置,对于 redirect_uri,请使用",
"auth.connectedWorkspace": "已连接的工作区",
"auth.credentialUnavailable": "自定义凭据当前不可用,请联系管理员。",
@@ -24,6 +25,7 @@
"auth.enterprise": "企业",
"auth.oauthClient": "OAuth 客户端",
"auth.oauthClientSettings": "OAuth 客户端设置",
+ "auth.oauthCredentialPermissionDescription": "选择新建的 OAuth 凭据是仅供你使用,还是与工作区所有成员共享。此设置作用于凭据而非 OAuth 客户端,授权后无法修改。",
"auth.onlyAtCreationHint": "切换后不可再选回",
"auth.onlyAtCreationHintTooltip": "由其他成员配置 · 切换后不可再选回",
"auth.permissionHint.action": "谁可以帮忙?",
diff --git a/web/i18n/zh-Hant/plugin.json b/web/i18n/zh-Hant/plugin.json
index 87874780e09..61d44151540 100644
--- a/web/i18n/zh-Hant/plugin.json
+++ b/web/i18n/zh-Hant/plugin.json
@@ -13,6 +13,7 @@
"auth.authorization": "授權",
"auth.authorizationName": "授權名稱",
"auth.authorizations": "授權",
+ "auth.authorize": "授權",
"auth.clientInfo": "由於未找到此工具提供者的系統客戶端秘密,因此需要手動設置,對於 redirect_uri,請使用",
"auth.connectedWorkspace": "連線工作區",
"auth.credentialUnavailable": "凭證目前無法使用。請聯繫管理員。",
@@ -24,6 +25,7 @@
"auth.enterprise": "企業",
"auth.oauthClient": "OAuth 客戶端",
"auth.oauthClientSettings": "OAuth 客戶端設置",
+ "auth.oauthCredentialPermissionDescription": "選擇新的 OAuth 憑證僅供你使用,或與工作區的所有成員共用。此設定套用於憑證而非 OAuth 用戶端,且授權後無法變更。",
"auth.onlyAtCreationHint": "切換後無法再次選擇",
"auth.onlyAtCreationHintTooltip": "由其他成員配置 · 切換後無法再次選擇。",
"auth.permissionHint.action": "誰可以幫忙?",
diff --git a/web/models/permission.ts b/web/models/permission.ts
index 71e0295e980..306b4b0c82c 100644
--- a/web/models/permission.ts
+++ b/web/models/permission.ts
@@ -9,3 +9,11 @@ export const PermissionLevel = {
} as const
export type PermissionLevel = (typeof PermissionLevel)[keyof typeof PermissionLevel]
+
+/**
+ * Subset of PermissionLevel accepted for plugin credentials — partial_members
+ * is not supported for OAuth/API-key credentials on the backend.
+ */
+export type CredentialPermission =
+ | typeof PermissionLevel.onlyMe
+ | typeof PermissionLevel.allTeamMembers
diff --git a/web/service/use-plugins-auth.ts b/web/service/use-plugins-auth.ts
index 70c46e5457f..a991a37775f 100644
--- a/web/service/use-plugins-auth.ts
+++ b/web/service/use-plugins-auth.ts
@@ -1,5 +1,6 @@
import type { FormSchema } from '@/app/components/base/form/types'
import type { Credential, CredentialTypeEnum } from '@/app/components/plugins/plugin-auth/types'
+import type { CredentialPermission } from '@/models/permission'
import { useMutation, useQuery } from '@tanstack/react-query'
import { del, get, post } from './base'
import { useInvalid } from './use-base'
@@ -80,12 +81,13 @@ export const useGetPluginCredentialSchema = (url: string) => {
export const useGetPluginOAuthUrl = (url: string) => {
return useMutation({
mutationKey: [NAME_SPACE, 'oauth-url', url],
- mutationFn: () => {
+ mutationFn: (params?: { visibility?: CredentialPermission }) => {
+ const visibility = params?.visibility
return get<{
authorization_url: string
state: string
context_id: string
- }>(url)
+ }>(url, { params: { visibility } })
},
})
}