Skip to content

Commit ab8be79

Browse files
authored
feat(webui): support marketplace plugin install links (#11375)
* feat(webui): support marketplace plugin install links * test(webui): remove install-link frontend test additions * docs: describe WebUI marketplace installation links * fix(webui): clarify source access in install confirmation * fix: use Cloud as the backend-defined default plugin registry * fix(webui): confirm dangerous link installs and reuse source type
1 parent 30fdbe8 commit ab8be79

23 files changed

Lines changed: 469 additions & 53 deletions

File tree

‎astrbot/cli/utils/plugin.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
import httpx
1111
import yaml
1212

13+
from astrbot.core.config.default import PLUGIN_DEFAULT_REGISTRY_URL
14+
1315
from .version_comparator import VersionComparator
1416

1517

@@ -160,10 +162,12 @@ def build_plug_list(plugins_dir: Path) -> list:
160162
online_plugins_dict = {}
161163
try:
162164
with httpx.Client() as client:
163-
resp = client.get("https://api.soulter.top/astrbot/plugins")
165+
resp = client.get(PLUGIN_DEFAULT_REGISTRY_URL)
164166
resp.raise_for_status()
165167
data = resp.json()
166168
for plugin_id, plugin_info in data.items():
169+
if plugin_id == "$meta":
170+
continue
167171
online_plugins_dict[str(plugin_id)] = {
168172
"name": str(plugin_id),
169173
"desc": str(plugin_info.get("desc", "")),

‎astrbot/core/config/default.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010

1111
from .agent import get_runtime_config_default
1212

13+
PLUGIN_DEFAULT_REGISTRY_URL = "https://cloud.astrbot.app/api/v1/market/plugins.json"
14+
1315

1416
def get_local_permission_defaults(system: str | None = None) -> dict:
1517
"""Return fresh Local permission defaults shared by all operating systems.

‎astrbot/dashboard/api/plugins.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
PluginPageServiceError,
4646
)
4747
from astrbot.dashboard.services.plugin_service import (
48+
PLUGIN_DEFAULT_REGISTRY_URL,
4849
PLUGIN_OPERATION_FAILED_MESSAGE,
4950
PluginService,
5051
PluginServiceError,
@@ -631,7 +632,12 @@ async def list_plugin_sources(
631632
_auth: AuthContext = Depends(require_plugin_scope),
632633
service: PluginService = Depends(get_service),
633634
):
634-
return ok({"sources": await service.get_custom_sources()})
635+
return ok(
636+
{
637+
"sources": await service.get_custom_sources(),
638+
"default_registry_url": PLUGIN_DEFAULT_REGISTRY_URL,
639+
}
640+
)
635641

636642

637643
@router.post("/plugin-sources")

‎astrbot/dashboard/services/plugin_service.py‎

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from astrbot.core.astr_agent_runtime.computer.computer_client import (
2121
sync_skills_to_active_sandboxes,
2222
)
23+
from astrbot.core.config.default import PLUGIN_DEFAULT_REGISTRY_URL
2324
from astrbot.core.repository import (
2425
GitUnavailableError,
2526
normalize_repository_url,
@@ -110,6 +111,7 @@ def __init__(
110111
EventType.OnPluginErrorEvent: "插件报错时",
111112
}
112113
self._logo_cache: dict[str, str] = {}
114+
self._create_source_lock = asyncio.Lock()
113115

114116
@staticmethod
115117
def _payload(data: object) -> dict[str, Any]:
@@ -1091,9 +1093,9 @@ def build_registry_source(custom_url: str | None) -> RegistrySource:
10911093
urls = [custom_url]
10921094
else:
10931095
cache_file = os.path.join(data_dir, "plugins.json")
1094-
md5_url = "https://api.soulter.top/astrbot/plugins-md5"
1096+
md5_url = PLUGIN_DEFAULT_REGISTRY_URL.removesuffix(".json") + "-md5.json"
10951097
urls = [
1096-
"https://api.soulter.top/astrbot/plugins",
1098+
PLUGIN_DEFAULT_REGISTRY_URL,
10971099
"https://github.com/AstrBotDevs/AstrBot_Plugins_Collection/raw/refs/heads/main/plugin_cache_original.json",
10981100
]
10991101
return RegistrySource(urls=urls, cache_file=cache_file, md5_url=md5_url)
@@ -2095,13 +2097,30 @@ def _custom_sources_from_payload(payload: dict[str, Any]) -> list:
20952097
raise PluginServiceError("sources fields must be a list")
20962098
return sources
20972099

2098-
@staticmethod
2099-
async def create_custom_source(data: object) -> list:
2100+
async def create_custom_source(self, data: object) -> list:
2101+
"""Append a plugin source once, including when the request is retried.
2102+
2103+
Args:
2104+
data: Source fields from the add-source request.
2105+
2106+
Returns:
2107+
The saved list of custom sources.
2108+
"""
21002109
source = data if isinstance(data, dict) else {}
2101-
sources = await PluginService.get_custom_sources()
2102-
sources.append(source)
2103-
await sp.global_put("custom_plugin_sources", sources)
2104-
return sources
2110+
url = self.normalize_registry_url(source.get("url"))
2111+
async with self._create_source_lock:
2112+
sources = await self.get_custom_sources()
2113+
if url and any(
2114+
self.normalize_registry_url(
2115+
item.get("url") if isinstance(item, dict) else item
2116+
)
2117+
== url
2118+
for item in sources
2119+
):
2120+
return sources
2121+
sources.append(source)
2122+
await sp.global_put("custom_plugin_sources", sources)
2123+
return sources
21052124

21062125
@staticmethod
21072126
async def replace_custom_sources(data: object) -> list:

‎dashboard/src/api/v1.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import {
4646
type PluginVersionSupportRequest,
4747
type PluginValidateRepoRequest,
4848
type PluginConfigFileDeleteRequest,
49+
type PluginSourceRequest,
4950
type ProviderConfigRequest,
5051
type PypiIndexTestRequest,
5152
type RuntimeInfo,
@@ -1398,6 +1399,9 @@ export const pluginApi = {
13981399
sources() {
13991400
return typed<any>(openApiV1.listPluginSources());
14001401
},
1402+
createSource(body: PluginSourceRequest) {
1403+
return typed<OpenConfig>(openApiV1.createPluginSource({ body }));
1404+
},
14011405
replaceSources(sources: OpenConfig[]) {
14021406
return typed<OpenConfig>(
14031407
openApiV1.replacePluginSources({ body: { sources: sources as any } }),

‎dashboard/src/i18n/locales/en-US/features/extension.json‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,16 @@
219219
"dataHint": "Deletes data in data/plugin_data and data/plugins_data, as well as KV preference data in the database"
220220
},
221221
"install": {
222+
"sourceRequired": "Add this plugin source to continue to the installation confirmation. AstrBot will access this URL when you continue. Only add sources you trust.",
223+
"addSourceAndContinue": "Add and continue",
224+
"validatingSource": "Checking the plugin source…",
225+
"savingSource": "Adding the plugin source…",
226+
"loadingPlugin": "Looking up the plugin…",
227+
"retryPreview": "Retry",
228+
"marketPluginNotFound": "The selected plugin source has no installable entry for this plugin.",
229+
"invalidMarketPluginId": "Invalid marketplace plugin ID. Use author/name.",
230+
"invalidRegistryUrl": "Enter a valid HTTPS URL for the plugin source.",
231+
"linkConflict": "The installation link specifies more than one source.",
222232
"title": "Install Extension",
223233
"fromFile": "Install from File",
224234
"fromUrl": "Install from URL",

‎dashboard/src/i18n/locales/ja-JP/features/extension.json‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,16 @@
219219
"dataHint": "data/plugin_data、plugins_data ディレクトリ内のデータと、データベース内のプラグインの KV データを削除します"
220220
},
221221
"install": {
222+
"sourceRequired": "このプラグインソースを追加してから、インストールを確認してください。続行すると AstrBot がこの URL にアクセスします。信頼できるソースのみ追加してください。",
223+
"addSourceAndContinue": "追加して続行",
224+
"validatingSource": "プラグインソースを確認中…",
225+
"savingSource": "プラグインソースを追加中…",
226+
"loadingPlugin": "プラグインを検索中…",
227+
"retryPreview": "再試行",
228+
"marketPluginNotFound": "指定されたプラグインソースにインストール可能なプラグインが見つかりませんでした。",
229+
"invalidMarketPluginId": "プラグイン ID が無効です。author/name の形式を使用してください。",
230+
"invalidRegistryUrl": "プラグインソースには有効な HTTPS URL を指定してください。",
231+
"linkConflict": "インストールリンクに複数のソースが指定されています。",
222232
"title": "プラグインをインストール",
223233
"fromFile": "ファイルからインストール",
224234
"fromUrl": "URL からインストール",

‎dashboard/src/i18n/locales/ru-RU/features/extension.json‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,16 @@
219219
"dataHint": "Данные находятся в data/plugin_data и data/plugins_data, а также KV-данные в базе данных"
220220
},
221221
"install": {
222+
"sourceRequired": "Добавьте этот источник плагинов, чтобы перейти к подтверждению установки. При продолжении AstrBot обратится к этому URL. Добавляйте только доверенные источники.",
223+
"addSourceAndContinue": "Добавить и продолжить",
224+
"validatingSource": "Проверка источника плагинов…",
225+
"savingSource": "Добавление источника плагинов…",
226+
"loadingPlugin": "Поиск плагина…",
227+
"retryPreview": "Повторить",
228+
"marketPluginNotFound": "В указанном источнике нет этого плагина, доступного для установки.",
229+
"invalidMarketPluginId": "Недопустимый идентификатор плагина. Используйте формат author/name.",
230+
"invalidRegistryUrl": "Укажите корректный HTTPS-адрес источника плагинов.",
231+
"linkConflict": "В ссылке установки указано несколько источников.",
222232
"title": "Установка плагина",
223233
"fromFile": "Из файла",
224234
"fromUrl": "По ссылке",

‎dashboard/src/i18n/locales/zh-CN/features/extension.json‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,16 @@
219219
"dataHint": "删除 data/plugin_data、plugins_data 目录下的数据,以及数据库中插件的 KV 数据"
220220
},
221221
"install": {
222+
"sourceRequired": "请先添加这个插件源,再确认安装插件。继续后,AstrBot 将访问该地址,请仅添加可信的插件源。",
223+
"addSourceAndContinue": "添加并继续",
224+
"validatingSource": "正在验证插件源…",
225+
"savingSource": "正在添加插件源…",
226+
"loadingPlugin": "正在查找插件…",
227+
"retryPreview": "重试",
228+
"marketPluginNotFound": "指定的插件源中没有找到可安装的插件。",
229+
"invalidMarketPluginId": "无效的市场插件 ID,应为作者/插件名。",
230+
"invalidRegistryUrl": "插件源地址必须是有效的 HTTPS URL。",
231+
"linkConflict": "安装链接包含多个安装来源。",
222232
"title": "安装插件",
223233
"fromFile": "从文件安装",
224234
"fromUrl": "从链接安装",

‎dashboard/src/router/index.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import AuthRoutes from './AuthRoutes';
44
import ChatBoxRoutes from './ChatBoxRoutes';
55
import { useAuthStore } from '@/stores/auth';
66
import { useRouterLoadingStore } from '@/stores/routerLoading';
7+
import { getPluginInstallReturnUrl, hasPluginInstallLink } from '@/utils/pluginInstallLink.mjs';
78

89
export const router = createRouter({
910
history: createWebHashHistory(import.meta.env.BASE_URL),
@@ -39,12 +40,15 @@ router.beforeEach(async (to, from, next) => {
3940

4041
// 如果用户已登录且试图访问登录页面,则重定向到首页
4142
if (to.path === '/auth/login' && auth.has_token()) {
42-
return next('/welcome');
43+
return next(getPluginInstallReturnUrl(router, to.query.redirect) || '/welcome');
4344
}
4445

4546
if (to.matched.some((record) => record.meta.requiresAuth)) {
4647
if (authRequired && !auth.has_token()) {
4748
auth.returnUrl = to.fullPath;
49+
if (hasPluginInstallLink(to)) {
50+
return next({ path: '/auth/login', query: { redirect: to.fullPath } });
51+
}
4852
return next('/auth/login');
4953
}
5054
return next();

0 commit comments

Comments
 (0)