Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions .github/workflows/plugin-tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
name: Plugin Tests

on:
push:
branches: [master, feature/sdk-plugin-index]
pull_request:
branches: [master]
workflow_dispatch:

permissions:
contents: read

concurrency:
group: plugin-tests-${{ github.event_name }}-${{ github.ref }}
cancel-in-progress: true

env:
PYTHONUTF8: '1'
ENV_PLUGIN_MARKET_URL: ''

jobs:
python:
name: Python ${{ matrix.python }} (Linux)
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
python: ['3.10', '3.12']
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
- name: Build bundled epack plugin
run: python -m plugins.epack.build_epack
- name: Install dependencies
run: python -m pip install . pytest setuptools wheel uvicorn
- name: Run Python regression tests
run: python -m pytest tests plugins/tests -q

windows-sdk:
name: SDK index (Windows)
runs-on: windows-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install dependencies
run: python -m pip install . pytest setuptools wheel uvicorn
- name: Run SDK index and HTTP market regression tests
run: >-
python -m pytest -q
plugins/tests/test_sdk_index.py
plugins/tests/test_sdk_index_webui.py
plugins/tests/test_market.py
plugins/tests/test_env_cli.py
plugins/tests/test_epack_workflow.py

webui:
name: WebUI
runs-on: ubuntu-latest
timeout-minutes: 20
defaults:
run:
working-directory: plugins/webui/frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
cache-dependency-path: plugins/webui/frontend/package-lock.json
- name: Install Python dependencies
run: python -m pip install ../../.. uvicorn
- name: Install frontend dependencies
run: npm ci
- name: Type-check frontend
run: npm run typecheck
- name: Run frontend unit tests
run: npm test
- name: Build frontend assets
run: npm run build
- name: Verify committed frontend assets
run: git diff --exit-code -- ../static
- name: Install Chromium
run: npx playwright install --with-deps chromium
- name: Test SDK catalog and plugin workflows in Chromium
run: npm run test:e2e -- sdk-market.spec.ts webui.spec.ts
- name: Retain browser test artifacts
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v4
with:
name: plugin-browser-results
path: plugins/webui/frontend/test-results/
retention-days: 7
3 changes: 2 additions & 1 deletion cmds/cmd_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@ def _print_result(value, as_json):
return
if isinstance(value, dict) and set(value) >= set(['enabled', 'url', 'source']):
if value.get('enabled'):
source = 'environment variable' if value.get('source') == 'env' else 'configuration file'
source = {'env': 'environment variable', 'file': 'configuration file', 'sdk': 'SDK repository index'}.get(
value.get('source'), value.get('source'))
print('Plugin market: %s (%s)' % (value['url'], source))
else:
print('Plugin market is not configured.')
Expand Down
25 changes: 20 additions & 5 deletions plugins/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ upgrades, enables, disables, diagnoses and uninstalls them. CLI and browser
operations share the same state and `PluginService` facade.

The local lifecycle still installs from `.epack` files. An optional plugin
market URL can be configured; when it is present, the WebUI shows an online
catalog and downloads a matching artifact through the local Host API. Env
market URL can be configured; otherwise the SDK repository plugin index is
used when present. The WebUI shows an online catalog and downloads a matching
artifact through the local Host API. Env
never installs from a raw plugin id or URL.

## Layout
Expand All @@ -19,7 +20,7 @@ never installs from a raw plugin id or URL.
- `installer.py`, `store.py`, `launchers.py`: transactional lifecycle state and command launchers.
- `dispatcher.py`, `sdk/`: mandatory command dispatch and plugin runtime context.
- `epack/`: plugin project initialization, validation, build and package inspection.
- `market.py`: optional plugin market URL and Host API client.
- `market.py`, `sdk_index.py`: HTTP market and serverless SDK index clients.
- `webui/`: local Host API, Vue source and prebuilt host assets.
- `bundled/epack/`: source project for the optional official `epack` developer tool.
- `examples/`: CLI-only, WebUI-only and combined example plugin projects.
Expand Down Expand Up @@ -99,7 +100,21 @@ rt-env plugin market clear
```

`ENV_PLUGIN_MARKET_URL` overrides `${ENV_ROOT}/var/plugins/market.json`.
Without a configured URL, the WebUI hides the online plugin page.
Without an explicit market URL, Env uses
`${ENV_ROOT}/packages/sdk/env-plugins/index.json` when present. Its sdk-index-style
root (`{"version": 1, "index": ["<plugin-directory>"]}`) references child
`index.json` files containing plugin metadata and `versions[].artifacts[]`.
Each artifact declares an HTTPS `url`, `.epack` filename, lowercase `sha256`,
compatibility fields matching its manifest, and optional `size_bytes`. GitHub
Release URLs are supported with restricted HTTPS asset redirects. See the SDK
repository's `env-plugins/README.md` for the complete format and publishing steps.
Refreshing the catalog rereads local files; update the SDK Git repository first
to receive new entries. The highest compatible non-yanked version is selected.
Downloads use Env network settings and checksum validation, then the existing
package checks and unsigned-package consent. `epack push` still targets HTTP
markets; SDK publication means uploading a release and updating the Git index.
The online page is hidden only when neither source exists. Clearing a saved
HTTP URL restores the SDK default (unless overridden by the environment).

Add `--purge-data` to uninstall a plugin and remove its private configuration,
data and cache. Workspace files are never removed by the uninstall workflow.
Expand Down Expand Up @@ -468,4 +483,4 @@ individual images to 16 MiB.
- Service backends require `uvicorn` and its runtime dependencies to be included as dependency wheels.
- Frontend resources must be prebuilt and must not contain source maps, symbolic links or path-traversal members.
- V1 packages are currently unsigned local artifacts. Do not make `--yes` the default policy for packages from untrusted sources.
- The WebUI shows the online catalog only when a market URL is configured. Installation still uses a one-time local upload id after the Host API downloads and inspects the artifact.
- The WebUI shows the online catalog when an HTTP market is configured or the SDK plugin index exists. Installation still uses a one-time local upload id after the Host API downloads and inspects the artifact.
8 changes: 6 additions & 2 deletions plugins/README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ RT-Thread Env 是一套面向 RT-Thread 开发的命令行工具集。`plugins/`
- `installer.py`、`store.py`、`launchers.py`:管理安装状态、事务回滚和插件命令启动器。
- `dispatcher.py`、`sdk/`:统一分发插件命令,并创建插件运行上下文。
- `epack/`:插件工程初始化、校验、构建和包检查工具。
- `market.py`:可选的在线插件市场地址和 Host API 客户端。
- `market.py`、`sdk_index.py`:HTTP 在线市场和 SDK 仓库插件索引客户端。
- `webui/`:Env 本机 Host API、前端源码和发行版静态资源。
- `bundled/epack/`:官方可选 `epack` 开发工具的插件工程。
- `examples/`:CLI、WebUI 以及两者组合的示例工程。
Expand Down Expand Up @@ -81,7 +81,11 @@ rt-env plugin market set http://127.0.0.1:8800
rt-env plugin market clear
```

`ENV_PLUGIN_MARKET_URL` 优先于 `${ENV_ROOT}/var/plugins/market.json`。未配置地址时,WebUI 不显示在线插件页面。
`ENV_PLUGIN_MARKET_URL` 优先于 `${ENV_ROOT}/var/plugins/market.json`。没有显式市场地址时,默认读取 `${ENV_ROOT}/packages/sdk/env-plugins/index.json`;只有两类来源都不存在时,WebUI 才不显示在线插件页面。清除文件中的 HTTP 配置可恢复 SDK 来源。

SDK 插件索引的根文件使用 `{"version": 1, "index": ["<插件目录>"]}`,每个直接子目录的 `index.json` 包含插件 `id`、`name` 和 `versions[].artifacts[]`。制品必须包含 HTTPS `url`、`.epack` 文件名、小写 `sha256` 及与包一致的 `compatibility`,可选 `size_bytes`;可直接使用 GitHub Release 地址。详细格式见 SDK 仓库 `env-plugins/README.md`。

索引随 SDK Git 仓库更新分发,刷新在线目录只重读本地索引,不隐式拉取 Git。安装选择最高兼容且未撤回的版本,校验摘要后复用已有包检查和未签名确认;沿用网络设置中的代理、超时。`epack push` 仍用于 HTTP 市场,SDK 来源应上传 Release 后维护索引。

卸载时加上 `--purge-data` 会同时删除插件自己的配置、数据和缓存;工作区文件不会由卸载流程删除。

Expand Down
6 changes: 5 additions & 1 deletion plugins/epack/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,11 @@ def run(argv, context=None):
elif args.command == 'inspect':
result = EpackArchive(_path(args.package, context)).inspect().summary()
elif args.command in ('push', 'publish'):
market = args.market or load_market_config(PluginPaths())['url']
config = load_market_config(PluginPaths())
if not args.market and config['source'] == 'sdk':
raise UsageError('SDK plugin index is read-only; upload the .epack to a release and update its index, '
'or use --market to publish to an HTTP market')
market = args.market or config['url']
if not market:
raise UsageError('plugin market is not configured; use --market or env plugin market set')
token = _read_token(args.token_file, context) if args.token_file else None
Expand Down
88 changes: 52 additions & 36 deletions plugins/market.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
current_env_version,
normalize_architecture,
normalize_platform,
python_abi,
version_satisfies,
)
from .errors import PluginError, UsageError
Expand Down Expand Up @@ -75,6 +76,9 @@ def load_market_config(paths, environ=None):
return {'enabled': False, 'url': '', 'source': None}
raw = _read_file_url(paths)
if not raw:
index = os.path.join(paths.env_root, 'packages', 'sdk', 'env-plugins', 'index.json')
if os.path.isfile(index):
return {'enabled': True, 'url': index, 'source': 'sdk'}
return {'enabled': False, 'url': '', 'source': None}
try:
return {'enabled': True, 'url': normalize_market_url(raw), 'source': 'file'}
Expand Down Expand Up @@ -117,7 +121,7 @@ def runtime_profile():
'env': env_version,
'python': '%d.%d.%d' % sys.version_info[:3],
'implementation': platform.python_implementation().lower(),
'abi': 'py3',
'abi': python_abi(),
'platform': normalize_platform(),
'architecture': normalize_architecture(),
}
Expand Down Expand Up @@ -422,41 +426,7 @@ def download(self, sha256, destination, filename=None):
raise UsageError('artifact checksum is invalid')
path = '/api/v1/artifacts/%s/download' % digest
response = self._open(path, timeout=DOWNLOAD_TIMEOUT)
try:
header = (response.headers.get('X-Checksum-SHA256') or '').strip().lower()
length = response.headers.get('Content-Length')
if length is not None:
try:
declared = int(length)
except ValueError:
raise MarketError('plugin market returned an invalid download size', code='market_invalid_response')
if declared < 0 or declared > DOWNLOAD_LIMIT:
raise MarketError('plugin package exceeds size limit', code='payload_too_large', status=413)
hasher = hashlib.sha256()
total = 0
with open(destination, 'wb') as output:
while True:
chunk = response.read(64 * 1024)
if not chunk:
break
total += len(chunk)
if total > DOWNLOAD_LIMIT:
raise MarketError('plugin package exceeds size limit', code='payload_too_large', status=413)
hasher.update(chunk)
output.write(chunk)
actual = hasher.hexdigest()
if header and header != actual:
raise MarketError('downloaded package checksum does not match', code='checksum_mismatch')
if actual != digest:
raise MarketError('downloaded package checksum does not match', code='checksum_mismatch')
return {
'path': destination,
'sha256': actual,
'size_bytes': total,
'filename': filename or os.path.basename(destination),
}
finally:
response.close()
return save_download(response, digest, destination, filename)

def _get_json(self, path, query=None):
response = self._open(path, query=query, timeout=JSON_TIMEOUT)
Expand Down Expand Up @@ -503,6 +473,52 @@ def _open(self, path, query=None, timeout=JSON_TIMEOUT):
raise MarketError('plugin market is unreachable', code='market_unreachable', status=502)


def save_download(response, digest, destination, filename=None, expected_size=None):
"""Verify a streamed artifact for either market backend."""
try:
header = (response.headers.get('X-Checksum-SHA256') or '').strip().lower()
length = response.headers.get('Content-Length')
declared = None
if length is not None:
try:
declared = int(length)
except ValueError:
raise MarketError('plugin market returned an invalid download size', code='market_invalid_response')
if declared < 0 or declared > DOWNLOAD_LIMIT:
raise MarketError('plugin package exceeds size limit', code='payload_too_large', status=413)
hasher = hashlib.sha256()
total = 0
with open(destination, 'wb') as output:
while True:
chunk = response.read(64 * 1024)
if not chunk:
break
total += len(chunk)
if total > DOWNLOAD_LIMIT:
raise MarketError('plugin package exceeds size limit', code='payload_too_large', status=413)
hasher.update(chunk)
output.write(chunk)
actual = hasher.hexdigest()
if (header and header != actual) or actual != digest:
raise MarketError('downloaded package checksum does not match', code='checksum_mismatch')
if (declared is not None and total != declared) or (expected_size is not None and total != expected_size):
raise MarketError('downloaded package size does not match', code='size_mismatch')
return {
'path': destination,
'sha256': actual,
'size_bytes': total,
'filename': filename or os.path.basename(destination),
}
except Exception:
try:
os.unlink(destination)
except OSError:
pass
raise
finally:
response.close()


def public_artifact(artifact):
if artifact is None:
return None
Expand Down
Loading
Loading