Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(plugin): add plugin framework workflow

t8y2b5072f1a3e15
diff --git a/.gitattributes b/.gitattributes
index 3555aba67f..9992a8f3dc 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -11,6 +11,9 @@ apps/desktop/tsconfig.json text eol=lf
apps/desktop/*.ts text eol=lf
src-tauri/windows/nsis/**/*.nsi text eol=lf
+# Keep plugin dev-host formatting checks consistent on Windows checkouts.
+plugins/sdk/dev-host/** text=auto eol=lf
+
# Keep tests available for review and CI without counting them as shipped code
# in GitHub's repository language breakdown.
packages/app-tests/** linguist-vendored
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index bb14fa4c7d..e5eb6367d3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -100,6 +100,9 @@ jobs:
- name: Install frontend dependencies
run: pnpm install --frozen-lockfile
+ - name: Install plugin development host dependencies
+ run: npm ci --prefix plugins/sdk/dev-host
+
- name: Setup Rust
uses: dtolnay/[email protected]
diff --git a/.github/workflows/plugin-cli-release.yml b/.github/workflows/plugin-cli-release.yml
new file mode 100644
index 0000000000..b928ce8283
--- /dev/null
+++ b/.github/workflows/plugin-cli-release.yml
@@ -0,0 +1,371 @@
+name: Plugin CLI Release
+
+on:
+ push:
+ tags:
+ - "plugin-cli-v*"
+ workflow_dispatch:
+ inputs:
+ version:
+ description: "Plugin CLI version to publish, for example 0.1.1"
+ required: true
+ default: "0.1.1"
+ npm-tag:
+ description: "npm distribution tag"
+ required: true
+ default: "latest"
+ type: choice
+ options:
+ - latest
+ - next
+
+permissions:
+ attestations: write
+ contents: write
+ id-token: write
+
+concurrency:
+ group: plugin-cli-release
+ cancel-in-progress: false
+
+jobs:
+ prepare:
+ name: Validate plugin CLI release
+ runs-on: ubuntu-24.04
+ outputs:
+ tag: ${{ steps.release.outputs.tag }}
+ version: ${{ steps.release.outputs.version }}
+ npm-tag: ${{ steps.release.outputs.npm-tag }}
+ steps:
+ - uses: actions/checkout@v5
+ with:
+ fetch-depth: 0
+
+ - uses: actions/setup-node@v6
+ with:
+ node-version: 22.13.0
+ registry-url: https://registry.npmjs.org
+
+ - uses: dtolnay/rust-toolchain@stable
+
+ - uses: actions/setup-go@v6
+ with:
+ go-version: "1.22.x"
+ cache: false
+
+ - name: Validate release branch and versions
+ id: release
+ env:
+ INPUT_VERSION: ${{ inputs.version }}
+ INPUT_NPM_TAG: ${{ inputs.npm-tag }}
+ run: |
+ node <<'NODE'
+ const fs = require("fs");
+
+ let version;
+ let tag;
+ let npmTag;
+ if (process.env.GITHUB_EVENT_NAME === "push") {
+ tag = process.env.GITHUB_REF_NAME;
+ const match = /^plugin-cli-v(.+)$/.exec(tag);
+ if (!match) throw new Error(`Unexpected plugin CLI tag: ${tag}`);
+ version = match[1];
+ npmTag = version.includes("-") ? "next" : "latest";
+ } else {
+ if (process.env.GITHUB_REF !== "refs/heads/main") {
+ throw new Error(`Manual plugin CLI releases must run from main, received ${process.env.GITHUB_REF}.`);
+ }
+ version = process.env.INPUT_VERSION.trim();
+ tag = `plugin-cli-v${version}`;
+ npmTag = process.env.INPUT_NPM_TAG;
+ }
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) {
+ throw new Error(`Invalid semantic version: ${version}`);
+ }
+ if (version.includes("-") && npmTag === "latest") {
+ throw new Error(`Prerelease ${version} cannot use the npm latest tag.`);
+ }
+
+ const packagePaths = [
+ "packages/plugin-cli/package.json",
+ "packages/plugin-cli-darwin-arm64/package.json",
+ "packages/plugin-cli-darwin-x64/package.json",
+ "packages/plugin-cli-linux-arm64-gnu/package.json",
+ "packages/plugin-cli-linux-x64-gnu/package.json",
+ "packages/plugin-cli-win32-arm64/package.json",
+ "packages/plugin-cli-win32-x64/package.json",
+ ];
+ for (const path of packagePaths) {
+ const pkg = JSON.parse(fs.readFileSync(path, "utf8"));
+ if (pkg.version !== version) {
+ throw new Error(`${path} has version ${pkg.version}; expected ${version}.`);
+ }
+ }
+
+ const cliCargo = fs.readFileSync("plugins/sdk/cli/Cargo.toml", "utf8");
+ const cliVersion = cliCargo.match(/^version\s*=\s*"([^"]+)"/m)?.[1];
+ if (cliVersion !== version) {
+ throw new Error(`plugins/sdk/cli/Cargo.toml has version ${cliVersion}; expected ${version}.`);
+ }
+
+ const launcher = JSON.parse(fs.readFileSync(packagePaths[0], "utf8"));
+ for (const [dependency, dependencyVersion] of Object.entries(launcher.optionalDependencies ?? {})) {
+ if (dependencyVersion !== version) {
+ throw new Error(`${dependency} is pinned to ${dependencyVersion}; expected ${version}.`);
+ }
+ }
+
+ fs.appendFileSync(process.env.GITHUB_OUTPUT, `version=${version}\n`);
+ fs.appendFileSync(process.env.GITHUB_OUTPUT, `tag=${tag}\n`);
+ fs.appendFileSync(process.env.GITHUB_OUTPUT, `npm-tag=${npmTag}\n`);
+ NODE
+
+ - name: Check npm token
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+ run: |
+ if [ -z "${NODE_AUTH_TOKEN}" ]; then
+ echo "::error::NPM_TOKEN secret is required to publish @dbx-app/plugin-cli."
+ exit 1
+ fi
+
+ - name: Test Rust CLI
+ run: cargo test --locked --manifest-path plugins/sdk/cli/Cargo.toml
+
+ - name: Prepare and test plugin development runtime
+ run: |
+ npm ci --prefix plugins/sdk/dev-host
+ npm test --prefix plugins/sdk/dev-host
+
+ - name: Test npm launcher
+ run: npm --prefix packages/plugin-cli test
+
+ - name: Verify packed npm installation
+ env:
+ DBX_PLUGIN_CLI_VERIFY_NATIVE: "1"
+ run: node scripts/verify-plugin-cli-package.mjs
+
+ - name: Create immutable source tag
+ if: github.event_name == 'workflow_dispatch'
+ env:
+ TAG: ${{ steps.release.outputs.tag }}
+ run: |
+ git fetch origin --tags --force
+ if git rev-parse "refs/tags/${TAG}" >/dev/null 2>&1; then
+ TAG_SHA="$(git rev-list -n 1 "refs/tags/${TAG}")"
+ HEAD_SHA="$(git rev-parse HEAD)"
+ if [ "${TAG_SHA}" != "${HEAD_SHA}" ]; then
+ echo "::error::${TAG} already points to ${TAG_SHA}, not ${HEAD_SHA}."
+ exit 1
+ fi
+ echo "${TAG} already points to this commit."
+ else
+ git tag "${TAG}" HEAD
+ git push origin "refs/tags/${TAG}:refs/tags/${TAG}"
+ fi
+
+ publish-platforms:
+ name: Publish ${{ matrix.package-name }}
+ needs: prepare
+ runs-on: ${{ matrix.runner }}
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - runner: macos-15
+ target: aarch64-apple-darwin
+ package-dir: plugin-cli-darwin-arm64
+ package-name: "@dbx-app/plugin-cli-darwin-arm64"
+ binary: dbx-plugin
+ - runner: macos-15-intel
+ target: x86_64-apple-darwin
+ package-dir: plugin-cli-darwin-x64
+ package-name: "@dbx-app/plugin-cli-darwin-x64"
+ binary: dbx-plugin
+ - runner: ubuntu-24.04-arm
+ target: aarch64-unknown-linux-gnu
+ package-dir: plugin-cli-linux-arm64-gnu
+ package-name: "@dbx-app/plugin-cli-linux-arm64-gnu"
+ binary: dbx-plugin
+ - runner: ubuntu-24.04
+ target: x86_64-unknown-linux-gnu
+ package-dir: plugin-cli-linux-x64-gnu
+ package-name: "@dbx-app/plugin-cli-linux-x64-gnu"
+ binary: dbx-plugin
+ - runner: windows-11-arm
+ target: aarch64-pc-windows-msvc
+ package-dir: plugin-cli-win32-arm64
+ package-name: "@dbx-app/plugin-cli-win32-arm64"
+ binary: dbx-plugin.exe
+ - runner: windows-2025
+ target: x86_64-pc-windows-msvc
+ package-dir: plugin-cli-win32-x64
+ package-name: "@dbx-app/plugin-cli-win32-x64"
+ binary: dbx-plugin.exe
+ steps:
+ - uses: actions/checkout@v5
+ with:
+ ref: ${{ needs.prepare.outputs.tag }}
+
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ targets: ${{ matrix.target }}
+
+ - uses: actions/setup-python@v6
+ if: runner.os == 'Linux'
+ with:
+ python-version: "3.x"
+
+ - name: Install Linux compatibility builder
+ if: runner.os == 'Linux'
+ run: pip install ziglang==0.14.0 cargo-zigbuild==0.23.0
+
+ - name: Build precompiled CLI
+ shell: bash
+ env:
+ CARGO_TARGET_DIR: ${{ github.workspace }}/target/plugin-cli
+ run: |
+ if [[ "${{ runner.os }}" == "Linux" ]]; then
+ cargo zigbuild --locked --release --manifest-path plugins/sdk/cli/Cargo.toml --target "${{ matrix.target }}.2.31"
+ else
+ cargo build --locked --release --manifest-path plugins/sdk/cli/Cargo.toml --target "${{ matrix.target }}"
+ fi
+
+ - name: Stage platform package
+ shell: bash
+ run: |
+ mkdir -p "packages/${{ matrix.package-dir }}/bin"
+ cp "target/plugin-cli/${{ matrix.target }}/release/${{ matrix.binary }}" "packages/${{ matrix.package-dir }}/bin/${{ matrix.binary }}"
+ if [[ "${{ runner.os }}" != "Windows" ]]; then
+ chmod +x "packages/${{ matrix.package-dir }}/bin/${{ matrix.binary }}"
+ fi
+
+ - uses: actions/setup-node@v6
+ with:
+ node-version: 22.13.0
+ registry-url: https://registry.npmjs.org
+
+ - name: Publish platform package
+ shell: bash
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+ VERSION: ${{ needs.prepare.outputs.version }}
+ NPM_TAG: ${{ needs.prepare.outputs.npm-tag }}
+ run: |
+ if npm view "${{ matrix.package-name }}@${VERSION}" version >/dev/null 2>&1; then
+ echo "${{ matrix.package-name }}@${VERSION} already exists; refreshing ${NPM_TAG}."
+ npm dist-tag add "${{ matrix.package-name }}@${VERSION}" "${NPM_TAG}"
+ else
+ npm publish "./packages/${{ matrix.package-dir }}" --access public --provenance --tag "${NPM_TAG}"
+ fi
+
+ publish-launcher:
+ name: Publish @dbx-app/plugin-cli
+ needs: [prepare, publish-platforms]
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v5
+ with:
+ ref: ${{ needs.prepare.outputs.tag }}
+
+ - uses: actions/setup-node@v6
+ with:
+ node-version: 22.13.0
+ registry-url: https://registry.npmjs.org
+
+ - name: Prepare development runtime build dependencies
+ run: npm ci --prefix plugins/sdk/dev-host
+
+ - name: Wait for platform packages
+ env:
+ VERSION: ${{ needs.prepare.outputs.version }}
+ run: |
+ wait_for_package() {
+ package="$1"
+ for attempt in $(seq 1 60); do
+ if npm view "${package}@${VERSION}" version >/dev/null 2>&1; then
+ return 0
+ fi
+ echo "Waiting for ${package}@${VERSION} (${attempt}/60)."
+ sleep 10
+ done
+ return 1
+ }
+
+ for package in \
+ @dbx-app/plugin-cli-darwin-arm64 \
+ @dbx-app/plugin-cli-darwin-x64 \
+ @dbx-app/plugin-cli-linux-arm64-gnu \
+ @dbx-app/plugin-cli-linux-x64-gnu \
+ @dbx-app/plugin-cli-win32-arm64 \
+ @dbx-app/plugin-cli-win32-x64; do
+ wait_for_package "${package}" || {
+ echo "::error::${package}@${VERSION} is unavailable; refusing to publish the launcher."
+ exit 1
+ }
+ done
+
+ - name: Publish launcher and bundled SDK
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+ VERSION: ${{ needs.prepare.outputs.version }}
+ NPM_TAG: ${{ needs.prepare.outputs.npm-tag }}
+ run: |
+ if npm view "@dbx-app/plugin-cli@${VERSION}" version >/dev/null 2>&1; then
+ echo "@dbx-app/plugin-cli@${VERSION} already exists; refreshing ${NPM_TAG}."
+ npm dist-tag add "@dbx-app/plugin-cli@${VERSION}" "${NPM_TAG}"
+ else
+ npm publish ./packages/plugin-cli --access public --provenance --tag "${NPM_TAG}"
+ fi
+
+ verify-published-package:
+ name: Verify clean npm installation
+ needs: [prepare, publish-launcher]
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/setup-node@v6
+ with:
+ node-version: 22.13.0
+ registry-url: https://registry.npmjs.org
+
+ - uses: dtolnay/rust-toolchain@stable
+
+ - uses: actions/setup-go@v6
+ with:
+ go-version: "1.22.x"
+ cache: false
+
+ - name: Install from npm and package every template
+ env:
+ VERSION: ${{ needs.prepare.outputs.version }}
+ run: |
+ set -euo pipefail
+ work="$(mktemp -d)"
+ cd "${work}"
+ npm init -y >/dev/null
+
+ for attempt in $(seq 1 60); do
+ if npm view "@dbx-app/plugin-cli@${VERSION}" version >/dev/null 2>&1; then
+ break
+ fi
+ if [ "${attempt}" -eq 60 ]; then
+ echo "::error::@dbx-app/plugin-cli@${VERSION} did not become visible on npm."
+ exit 1
+ fi
+ sleep 10
+ done
+
+ npm install --ignore-scripts --no-audit --no-fund "@dbx-app/plugin-cli@${VERSION}"
+ ./node_modules/.bin/dbx-plugin --version
+
+ for template in frontend rust go; do
+ ./node_modules/.bin/dbx-plugin create "${template}-plugin" \
+ --template "${template}" \
+ --yes \
+ --id "com.example.npm-${template}" \
+ --name "npm ${template} smoke" \
+ --publisher example \
+ --description "Published npm package smoke"
+ ./node_modules/.bin/dbx-plugin package "${template}-plugin"
+ test "$(find "${template}-plugin/dist" -maxdepth 1 -name '*.dbxp' | wc -l)" -eq 1
+ done
diff --git a/.github/workflows/plugin-dev-host.yml b/.github/workflows/plugin-dev-host.yml
new file mode 100644
index 0000000000..4aab18ea15
--- /dev/null
+++ b/.github/workflows/plugin-dev-host.yml
@@ -0,0 +1,39 @@
+name: Plugin development host
+on:
+ pull_request:
+ paths:
+ - '.gitattributes'
+ - 'plugins/sdk/cli/**'
+ - 'plugins/sdk/dev-host/**'
+ - 'packages/plugin-cli/**'
+ - 'scripts/verify-plugin-cli-package.mjs'
+ - '.github/workflows/plugin-dev-host.yml'
+ workflow_dispatch:
+permissions:
+ contents: read
+jobs:
+ test:
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-24.04, macos-15, windows-2022]
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '22'
+ - uses: dtolnay/rust-toolchain@stable
+ - uses: actions/setup-go@v5
+ with:
+ go-version: '1.22'
+ cache: false
+ - run: npm ci --prefix plugins/sdk/dev-host
+ - run: npm run lint --prefix plugins/sdk/dev-host
+ - run: npm run fmt:check --prefix plugins/sdk/dev-host
+ - run: npm test --prefix plugins/sdk/dev-host
+ - run: cargo test --locked --manifest-path plugins/sdk/cli/Cargo.toml
+ - run: npm test --prefix packages/plugin-cli
+ - run: node scripts/verify-plugin-cli-package.mjs
+ env:
+ DBX_PLUGIN_CLI_VERIFY_NATIVE: '1'
diff --git a/.github/workflows/plugin-release-reusable.yml b/.github/workflows/plugin-release-reusable.yml
new file mode 100644
index 0000000000..547c8398fb
--- /dev/null
+++ b/.github/workflows/plugin-release-reusable.yml
@@ -0,0 +1,218 @@
+name: Reusable DBX plugin release
+
+on:
+ workflow_call:
+ inputs:
+ release-tag:
+ description: Existing GitHub Release tag that receives the plugin assets
+ required: true
+ type: string
+ package-command:
+ description: Command that builds one unsigned candidate .dbxp and one .artifact.json for DBX_PLUGIN_TARGET
+ required: true
+ type: string
+ working-directory:
+ description: Plugin repository directory containing the package command
+ default: .
+ required: false
+ type: string
+ package-path:
+ description: Glob relative to working-directory for built .dbxp files
+ default: dist/*.dbxp
+ required: false
+ type: string
+ metadata-path:
+ description: Glob relative to working-directory for built .artifact.json files
+ default: dist/*.artifact.json
+ required: false
+ type: string
+ node-version:
+ default: "22"
+ required: false
+ type: string
+ go-version:
+ default: "1.22.x"
+ required: false
+ type: string
+ rust-toolchain:
+ default: stable
+ required: false
+ type: string
+ sdk-ref:
+ description: DBX tag or commit used only when installing the plugin CLI from source
+ default: plugin-sdk-v1
+ required: false
+ type: string
+ plugin-cli-version:
+ description: Published @dbx-app/plugin-cli version used to package the plugin
+ default: "0.1.1"
+ required: false
+ type: string
+ install-plugin-cli:
+ description: Install the dbx-plugin CLI before packaging
+ default: true
+ required: false
+ type: boolean
+ install-plugin-cli-from-source:
+ description: Build the CLI from sdk-ref instead of installing its precompiled npm package
+ default: false
+ required: false
+ type: boolean
+ build-matrix:
+ description: JSON matrix with runner and DBX target pairs; use one universal entry for platform-independent plugins
+ default: >-
+ {"include":[{"runner":"ubuntu-24.04","target":"linux-x64"},{"runner":"ubuntu-24.04-arm","target":"linux-arm64"},{"runner":"windows-2022","target":"windows-x64"},{"runner":"macos-15-intel","target":"darwin-x64"},{"runner":"macos-15","target":"darwin-arm64"}]}
+ required: false
+ type: string
+permissions:
+ contents: read
+
+jobs:
+ build:
+ name: Build ${{ matrix.target }}
+ strategy:
+ fail-fast: false
+ matrix: ${{ fromJSON(inputs.build-matrix) }}
+ runs-on: ${{ matrix.runner }}
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: ${{ inputs.node-version }}
+
+ - uses: actions/setup-go@v5
+ with:
+ go-version: ${{ inputs.go-version }}
+
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ toolchain: ${{ inputs.rust-toolchain }}
+
+ - name: Checkout DBX plugin SDK
+ if: inputs.install-plugin-cli && inputs.install-plugin-cli-from-source
+ uses: actions/checkout@v4
+ with:
+ repository: t8y2/dbx
+ ref: ${{ inputs.sdk-ref }}
+ path: .dbx-plugin-sdk
+
+ - name: Install precompiled DBX plugin CLI
+ if: inputs.install-plugin-cli && !inputs.install-plugin-cli-from-source
+ shell: bash
+ run: npm install --global "@dbx-app/plugin-cli@${{ inputs.plugin-cli-version }}"
+
+ - name: Install DBX plugin CLI from source
+ if: inputs.install-plugin-cli && inputs.install-plugin-cli-from-source
+ shell: bash
+ run: cargo install --locked --path .dbx-plugin-sdk/plugins/sdk/cli
+
+ - name: Build unsigned plugin candidate
+ shell: bash
+ working-directory: ${{ inputs.working-directory }}
+ env:
+ DBX_PLUGIN_TARGET: ${{ matrix.target }}
+ DBX_PLUGIN_SDK_ROOT: ${{ inputs.install-plugin-cli-from-source && format('{0}/.dbx-plugin-sdk', github.workspace) || '' }}
+ run: ${{ inputs.package-command }}
+
+ - name: Upload target artifacts
+ uses: actions/upload-artifact@v4
+ with:
+ name: dbx-plugin-${{ matrix.target }}
+ if-no-files-found: error
+ retention-days: 1
+ path: |
+ ${{ inputs.working-directory }}/${{ inputs.package-path }}
+ ${{ inputs.working-directory }}/${{ inputs.metadata-path }}
+
+ publish:
+ name: Publish plugin release assets
+ needs: build
+ runs-on: ubuntu-24.04
+ permissions:
+ contents: write
+ steps:
+ - name: Download target artifacts
+ uses: actions/download-artifact@v4
+ with:
+ pattern: dbx-plugin-*
+ path: release-assets
+ merge-multiple: true
+
+ - name: Validate and merge candidate metadata
+ shell: bash
+ run: |
+ node <<'NODE'
+ const childProcess = require("node:child_process");
+ const crypto = require("node:crypto");
+ const fs = require("node:fs");
+ const path = require("node:path");
+
+ function filesUnder(root) {
+ return fs.readdirSync(root, { withFileTypes: true }).flatMap((entry) => {
+ const current = path.join(root, entry.name);
+ return entry.isDirectory() ? filesUnder(current) : [current];
+ });
+ }
+
+ const files = filesUnder("release-assets");
+ const metadataFiles = files.filter((file) => file.endsWith(".artifact.json"));
+ const packages = new Map();
+ for (const file of files.filter((file) => file.endsWith(".dbxp"))) {
+ const name = path.basename(file);
+ if (packages.has(name)) throw new Error(`Duplicate package filename ${name}`);
+ packages.set(name, file);
+ }
+ if (metadataFiles.length === 0 || packages.size === 0) throw new Error("Release produced no DBX plugin artifacts");
+
+ const targets = new Set();
+ let pluginIdentity;
+ const artifacts = metadataFiles.map((file) => {
+ const artifact = JSON.parse(fs.readFileSync(file, "utf8"));
+ if (!/^[a-z0-9-]{1,64}$/.test(artifact.target || "")) throw new Error(`Invalid artifact target in ${file}`);
+ if (!/^[a-fA-F0-9]{64}$/.test(artifact.sha256 || "")) throw new Error(`Invalid artifact SHA-256 in ${file}`);
+ if (artifact.signingKeyId !== undefined) throw new Error(`Candidate metadata ${file} must not declare signingKeyId`);
+ if (!Number.isSafeInteger(artifact.size) || artifact.size < 0) throw new Error(`Invalid artifact size in ${file}`);
+ const packageName = path.basename(new URL(artifact.url, "https://plugins.invalid/releases/").pathname);
+ const packageFile = packages.get(packageName);
+ if (!packageFile) throw new Error(`Artifact metadata ${file} references missing package ${packageName}`);
+ const packageBytes = fs.readFileSync(packageFile);
+ const packageSha256 = crypto.createHash("sha256").update(packageBytes).digest("hex");
+ if (artifact.size !== packageBytes.length) throw new Error(`Artifact metadata ${file} has the wrong package size`);
+ if (artifact.sha256.toLowerCase() !== packageSha256) throw new Error(`Artifact metadata ${file} has the wrong package SHA-256`);
+ const entries = childProcess.execFileSync("unzip", ["-Z1", packageFile], { encoding: "utf8" }).split(/\r?\n/);
+ if (entries.includes("signature.json")) throw new Error(`Candidate package ${packageName} must be unsigned`);
+ const manifest = JSON.parse(childProcess.execFileSync("unzip", ["-p", packageFile, "manifest.json"], { encoding: "utf8" }));
+ const identity = {
+ id: manifest.id,
+ name: manifest.name,
+ description: manifest.description || "",
+ publisher: manifest.publisher,
+ version: manifest.version,
+ permissions: [...(manifest.permissions || [])].sort(),
+ };
+ if (!identity.id || !identity.name || !identity.publisher || !identity.version) throw new Error(`Package ${packageName} has incomplete manifest identity`);
+ if (pluginIdentity && JSON.stringify(pluginIdentity) !== JSON.stringify(identity)) throw new Error(`Package ${packageName} manifest identity differs from other targets`);
+ pluginIdentity ||= identity;
+ if (targets.has(artifact.target)) throw new Error(`Duplicate artifact target ${artifact.target}`);
+ targets.add(artifact.target);
+ return artifact;
+ }).sort((left, right) => left.target.localeCompare(right.target));
+
+ fs.writeFileSync("release-assets/release-candidates.json", `${JSON.stringify({ plugin: pluginIdentity, artifacts }, null, 2)}\n`);
+ NODE
+
+ - name: Upload assets to GitHub Release
+ shell: bash
+ env:
+ GH_TOKEN: ${{ github.token }}
+ RELEASE_TAG: ${{ inputs.release-tag }}
+ run: |
+ mapfile -d '' packages < <(find release-assets -type f -name '*.dbxp' -print0)
+ if [ "${#packages[@]}" -eq 0 ]; then
+ echo "No .dbxp packages were downloaded" >&2
+ exit 1
+ fi
+ gh release upload "$RELEASE_TAG" "${packages[@]}" release-assets/release-candidates.json \
+ --repo "$GITHUB_REPOSITORY" \
+ --clobber
diff --git a/.gitignore b/.gitignore
index ba7f012d58..9c8303be20 100644
--- a/.gitignore
+++ b/.gitignore
@@ -32,6 +32,7 @@ plugins/jdbc/build/
plugins/jdbc/bin/main/
plugins/jdbc/bin/test/
plugins/jdbc/dist/
+packages/plugin-cli/sdk-root/
docs/.next/
docs/out/
docs/.source/
@@ -65,6 +66,7 @@ Thumbs.db
.env
.env.*
!.env.example
+.dbx-plugin-signing-key.env
# Temp
tmp/
@@ -81,6 +83,7 @@ review_classified.json
# Logs
*.log
+/.dbx-dev/
# Generated changelog data
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d6bf524497..9340b42ce3 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -65,6 +65,7 @@ For a real local Java agent test, build the target `shadowJar`, back up and repl
| `crates/dbx-web/` | Docker / Web HTTP backend |
| `packages/cli/` | `@dbx-app/cli` |
| `packages/mcp-server/` | `@dbx-app/mcp-server` |
+| `packages/plugin-cli/` | Precompiled `@dbx-app/plugin-cli` launcher and bundled plugin SDKs |
| `packages/mongo-shell/` | Private MongoDB editor parsing helpers |
| `docs/` | Official documentation site |
| `examples/` | Sample configs and automation scripts |
diff --git a/Cargo.lock b/Cargo.lock
index fea02f8576..2ae52b7acc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1916,6 +1916,7 @@ dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"curve25519-dalek-derive",
+ "digest 0.10.7",
"fiat-crypto 0.2.9",
"rustc_version",
"subtle",
@@ -2092,9 +2093,11 @@ dependencies = [
"csv",
"dbx-sqlite-worker",
"deadpool-postgres",
+ "ed25519-dalek 2.2.0",
"encoding_rs",
"flate2",
"font-kit",
+ "fs2",
"futures",
"httpdate",
"iana-time-zone",
@@ -2126,6 +2129,7 @@ dependencies = [
"rust_decimal",
"rustls 0.23.43",
"rustls-pemfile 2.2.0",
+ "semver",
"serde",
"serde_json",
"serde_yaml",
@@ -2587,19 +2591,43 @@ dependencies = [
"digest 0.11.3",
"elliptic-curve",
"rfc6979",
- "signature",
+ "signature 3.0.0",
"spki 0.8.0-rc.4",
"zeroize",
]
+[[package]]
+name = "ed25519"
+version = "2.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
+dependencies = [
+ "pkcs8 0.10.2",
+ "signature 2.2.0",
+]
+
[[package]]
name = "ed25519"
version = "3.0.0-rc.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6e914c7c52decb085cea910552e24c63ac019e3ab8bf001ff736da9a9d9d890"
dependencies = [
- "pkcs8",
- "signature",
+ "pkcs8 0.11.0-rc.11",
+ "signature 3.0.0",
+]
+
+[[package]]
+name = "ed25519-dalek"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
+dependencies = [
+ "curve25519-dalek 4.1.3",
+ "ed25519 2.2.3",
+ "serde",
+ "sha2 0.10.9",
+ "subtle",
+ "zeroize",
]
[[package]]
@@ -2609,11 +2637,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053618a4c3d3bc24f188aa660ae75a46eeab74ef07fb415c61431e5e7cd4749b"
dependencies = [
"curve25519-dalek 5.0.0-pre.6",
- "ed25519",
+ "ed25519 3.0.0-rc.4",
"rand_core 0.10.1",
"serde",
"sha2 0.11.0",
- "signature",
+ "signature 3.0.0",
"subtle",
"zeroize",
]
@@ -2638,7 +2666,7 @@ dependencies = [
"hybrid-array",
"once_cell",
"pem-rfc7468 1.0.0",
- "pkcs8",
+ "pkcs8 0.11.0-rc.11",
"rand_core 0.10.1",
"rustcrypto-ff",
"rustcrypto-group",
@@ -3035,6 +3063,16 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "fs2"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"
+dependencies = [
+ "libc",
+ "winapi",
+]
+
[[package]]
name = "fs_extra"
version = "1.3.0"
@@ -4210,7 +4248,7 @@ dependencies = [
"bcrypt-pbkdf",
"crypto-bigint",
"ecdsa",
- "ed25519-dalek",
+ "ed25519-dalek 3.0.0-pre.6",
"hex",
"hmac 0.13.0",
"num-bigint-dig",
@@ -4222,7 +4260,7 @@ dependencies = [
"sec1",
"sha1 0.11.0",
"sha2 0.11.0",
- "signature",
+ "signature 3.0.0",
"ssh-cipher",
"ssh-encoding",
"subtle",
@@ -6097,6 +6135,16 @@ dependencies = [
"spki 0.8.0-rc.4",
]
+[[package]]
+name = "pkcs8"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
+dependencies = [
+ "der 0.7.10",
+ "spki 0.7.3",
+]
+
[[package]]
name = "pkcs8"
version = "0.11.0-rc.11"
@@ -7053,10 +7101,10 @@ dependencies = [
"crypto-primes",
"digest 0.11.3",
"pkcs1",
- "pkcs8",
+ "pkcs8 0.11.0-rc.11",
"rand_core 0.10.1",
"sha2 0.11.0",
- "signature",
+ "signature 3.0.0",
"spki 0.8.0-rc.4",
"zeroize",
]
@@ -7121,7 +7169,7 @@ dependencies = [
"der 0.8.1",
"digest 0.10.7",
"ecdsa",
- "ed25519-dalek",
+ "ed25519-dalek 3.0.0-pre.6",
"elliptic-curve",
"enum_dispatch",
"flate2",
@@ -7150,7 +7198,7 @@ dependencies = [
"pbkdf2 0.13.0",
"pkcs1",
"pkcs5",
- "pkcs8",
+ "pkcs8 0.11.0-rc.11",
"polyval 0.7.3",
"rand 0.10.2",
"rand_core 0.10.1",
@@ -7165,7 +7213,7 @@ dependencies = [
"sha2 0.10.9",
"sha2 0.11.0",
"sha3",
- "signature",
+ "signature 3.0.0",
"spki 0.8.0-rc.4",
"ssh-encoding",
"subtle",
@@ -8034,6 +8082,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "signature"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
+dependencies = [
+ "rand_core 0.6.4",
+]
+
[[package]]
name = "signature"
version = "3.0.0"
diff --git a/README.md b/README.md
index cd6f290dad..93b42359a4 100644
--- a/README.md
+++ b/README.md
@@ -458,6 +458,8 @@ make docs
The official DBX documentation site lives in `docs/`. If you want to improve the website content or documentation pages, edit the files under `docs/` and run `make docs` to preview the site locally.
+Plugin authors should start with [Develop and Submit DBX Plugins](https://dbxio.com/en/docs/plugin-development). Plugin source normally stays in its own repository; Marketplace listing pull requests go to [`t8y2/dbx-store`](https://github.com/t8y2/dbx-store), while plugin host, SDK, and CLI changes go to this repository.
+
For clean, reproducible local database instances, use the versioned Docker Compose recipes under [`deploy/database/`](deploy/database/README.md):
```bash
@@ -495,6 +497,7 @@ The installer will be in `src-tauri/target/release/bundle/`.
## Documentation
- [Official docs](https://dbxio.com/en/docs/what-is-dbx) — feature guides and tutorials
+- [Plugin development](https://dbxio.com/en/docs/plugin-development) — create plugins and submit Marketplace listings to the correct repository
- [Database Test Lab](https://dbxio.com/en/docs/database-lab) — local database recipes for development and verification
- [Contributing](CONTRIBUTING.md) — how to pick up issues and open PRs
- [Web API reference](docs/content/docs/web-api.mdx) — HTTP API for Docker/Web deployments
diff --git a/SECURITY.md b/SECURITY.md
index 31abe6da34..aba4865b51 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -26,5 +26,8 @@ Security-sensitive areas include:
- AI provider keys and OpenAI-compatible endpoint configuration.
- MCP and CLI access to local DBX connections.
- Docker web service authentication and data directory handling.
+- Plugin package verification, native sidecar execution, sandboxed plugin UI, host bridge permissions, and plugin connection secrets.
+
+Plugin connection secrets are stored outside ordinary connection JSON. Unencrypted sync snapshots are always redacted. If encrypted secret sync is enabled with a user-provided passphrase, plugin secrets are included only in the encrypted payload and are restored through the normal secret-store path.
Please avoid testing against systems you do not own or have explicit permission to assess.
diff --git a/agents/drivers/duckdb/Cargo.lock b/agents/drivers/duckdb/Cargo.lock
index 6265365ab5..54376b084e 100644
--- a/agents/drivers/duckdb/Cargo.lock
+++ b/agents/drivers/duckdb/Cargo.lock
@@ -1154,6 +1154,7 @@ dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"curve25519-dalek-derive",
+ "digest 0.10.7",
"fiat-crypto 0.2.9",
"rustc_version",
"subtle",
@@ -1245,8 +1246,10 @@ dependencies = [
"csv",
"dbx-sqlite-worker",
"deadpool-postgres",
+ "ed25519-dalek 2.2.0",
"encoding_rs",
"flate2",
+ "fs2",
"futures",
"httpdate",
"iana-time-zone",
@@ -1275,6 +1278,7 @@ dependencies = [
"rust_decimal",
"rustls 0.23.42",
"rustls-pemfile 2.2.0",
+ "semver",
"serde",
"serde_json",
"serde_yaml",
@@ -1551,19 +1555,43 @@ dependencies = [
"digest 0.11.3",
"elliptic-curve",
"rfc6979",
- "signature",
+ "signature 3.0.0",
"spki 0.8.0-rc.4",
"zeroize",
]
+[[package]]
+name = "ed25519"
+version = "2.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
+dependencies = [
+ "pkcs8 0.10.2",
+ "signature 2.2.0",
+]
+
[[package]]
name = "ed25519"
version = "3.0.0-rc.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6e914c7c52decb085cea910552e24c63ac019e3ab8bf001ff736da9a9d9d890"
dependencies = [
- "pkcs8",
- "signature",
+ "pkcs8 0.11.0-rc.11",
+ "signature 3.0.0",
+]
+
+[[package]]
+name = "ed25519-dalek"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
+dependencies = [
+ "curve25519-dalek 4.1.3",
+ "ed25519 2.2.3",
+ "serde",
+ "sha2 0.10.9",
+ "subtle",
+ "zeroize",
]
[[package]]
@@ -1573,11 +1601,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053618a4c3d3bc24f188aa660ae75a46eeab74ef07fb415c61431e5e7cd4749b"
dependencies = [
"curve25519-dalek 5.0.0-pre.6",
- "ed25519",
+ "ed25519 3.0.0-rc.4",
"rand_core 0.10.1",
"serde",
"sha2 0.11.0",
- "signature",
+ "signature 3.0.0",
"subtle",
"zeroize",
]
@@ -1602,7 +1630,7 @@ dependencies = [
"hybrid-array",
"once_cell",
"pem-rfc7468 1.0.0",
- "pkcs8",
+ "pkcs8 0.11.0-rc.11",
"rand_core 0.10.1",
"rustcrypto-ff",
"rustcrypto-group",
@@ -1799,6 +1827,16 @@ dependencies = [
"percent-encoding",
]
+[[package]]
+name = "fs2"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"
+dependencies = [
+ "libc",
+ "winapi",
+]
+
[[package]]
name = "fs_extra"
version = "1.3.0"
@@ -2321,7 +2359,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
- "windows-core 0.57.0",
+ "windows-core 0.62.2",
]
[[package]]
@@ -2526,7 +2564,7 @@ dependencies = [
"bcrypt-pbkdf",
"crypto-bigint",
"ecdsa",
- "ed25519-dalek",
+ "ed25519-dalek 3.0.0-pre.6",
"hex",
"hmac 0.13.0",
"num-bigint-dig",
@@ -2538,7 +2576,7 @@ dependencies = [
"sec1",
"sha1 0.11.0",
"sha2 0.11.0",
- "signature",
+ "signature 3.0.0",
"ssh-cipher",
"ssh-encoding",
"subtle",
@@ -3729,6 +3767,16 @@ dependencies = [
"spki 0.8.0-rc.4",
]
+[[package]]
+name = "pkcs8"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
+dependencies = [
+ "der 0.7.10",
+ "spki 0.7.3",
+]
+
[[package]]
name = "pkcs8"
version = "0.11.0-rc.11"
@@ -4399,10 +4447,10 @@ dependencies = [
"crypto-primes",
"digest 0.11.3",
"pkcs1",
- "pkcs8",
+ "pkcs8 0.11.0-rc.11",
"rand_core 0.10.1",
"sha2 0.11.0",
- "signature",
+ "signature 3.0.0",
"spki 0.8.0-rc.4",
"zeroize",
]
@@ -4448,7 +4496,7 @@ dependencies = [
"der 0.8.1",
"digest 0.10.7",
"ecdsa",
- "ed25519-dalek",
+ "ed25519-dalek 3.0.0-pre.6",
"elliptic-curve",
"enum_dispatch",
"flate2",
@@ -4477,7 +4525,7 @@ dependencies = [
"pbkdf2 0.13.0",
"pkcs1",
"pkcs5",
- "pkcs8",
+ "pkcs8 0.11.0-rc.11",
"polyval 0.7.3",
"rand 0.10.2",
"rand_core 0.10.1",
@@ -4492,7 +4540,7 @@ dependencies = [
"sha2 0.10.9",
"sha2 0.11.0",
"sha3",
- "signature",
+ "signature 3.0.0",
"spki 0.8.0-rc.4",
"ssh-encoding",
"subtle",
@@ -5063,6 +5111,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "signature"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
+dependencies = [
+ "rand_core 0.6.4",
+]
+
[[package]]
name = "signature"
version = "3.0.0"
@@ -5415,7 +5472,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
- "getrandom 0.3.4",
+ "getrandom 0.4.3",
"once_cell",
"rustix 1.1.4",
"windows-sys 0.61.2",
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index 38d52ba736..933b3cf200 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -70,6 +70,7 @@ import { openQueryResultArchiveFile } from "@/lib/query/queryResultArchiveFile";
import { rememberExternalSqlFileTarget, resolveExternalSqlFileTarget, unassociatedExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";
import { externalSqlFileOpenErrorMessage, externalSqlEditorMaxBytes, isSqlFilePath, readBrowserSqlFile, sqlFileTitleFromPath } from "@/lib/sql/sqlFileOpen";
import type { ConnectionConfig, DatabaseType, ObjectBrowserFilter, ObjectSourceKind, QueryTab, TabOutputView, TreeNode } from "@/types/database";
+import type { PluginCenterFocus } from "@/lib/plugins/pluginCenterNavigation";
import { parseConnectionDeepLink, type ConnectionDeepLinkDraft } from "@/lib/connection/connectionDeepLink";
import { parseAiConfigDeepLink, type AiConfigDeepLinkDraft } from "@/lib/ai/aiConfigDeepLink";
import { activeDesktopAiRuns, blockingDesktopAiRunsForQuit } from "@/lib/ai/desktopAiRunRegistry";
@@ -155,6 +156,7 @@ const QueryHistory = defineAsyncComponent(() => import("@/components/editor/Quer
const SqlLibraryPanel = defineAsyncComponent(() => import("@/components/layout/SqlLibraryPanel.vue"));
const SqlFilePanel = defineAsyncComponent(() => import("@/components/layout/SqlFilePanel.vue"));
const DriverStorePage = defineAsyncComponent(() => import("@/components/config/DriverStoreDialog.vue"));
+const PluginCenterPage = defineAsyncComponent(() => import("@/components/plugins/PluginContributionsPanel.vue"));
const EditorSettingsPage = defineAsyncComponent(() => import("@/components/editor/EditorSettingsDialog.vue"));
const UpdateDialog = defineAsyncComponent(() => import("@/components/layout/UpdateDialog.vue"));
const CloseActionPromptDialog = defineAsyncComponent(() => import("@/components/layout/CloseActionPromptDialog.vue"));
@@ -323,8 +325,13 @@ const showQueryEditorObjectSourceDialog = ref(false);
const driverStoreTabOpen = ref(false);
const driverStoreActive = ref(false);
const driverStoreActiveTab = ref<"agent" | "jdbc" | "storage" | "runtime">("agent");
-const settingsReturnSurface = ref<"query" | "driverStore" | "welcome">("welcome");
+const pluginCenterTabOpen = ref(false);
+const pluginCenterActive = ref(false);
+const pluginCenterFocus = ref<PluginCenterFocus | null>(null);
+const connectionPluginProvider = ref<PluginCenterFocus | null>(null);
+const settingsReturnSurface = ref<"query" | "driverStore" | "pluginCenter" | "welcome">("welcome");
const showDriverStore = computed(() => driverStoreTabOpen.value && driverStoreActive.value);
+const showPluginCenter = computed(() => pluginCenterTabOpen.value && pluginCenterActive.value);
const showSettingsPage = computed(() => Boolean(settingsPageTabOpen.value && settingsStore.settingsPageActive));
const showQuickOpen = ref(false);
const showTabSwitcher = ref(false);
@@ -863,7 +870,7 @@ const specialPageTabs = computed(() => ({
driverStoreActive: driverStoreActive.value,
driverUpdateCount: toolbarAgentDriverUpdateCount.value,
}));
-provide(GROUP_TAB_BAR_PORTAL, createGroupTabBarPortal(computed(() => !isDetachedWindowContext && (driverStoreActive.value || settingsStore.settingsPageActive))));
+provide(GROUP_TAB_BAR_PORTAL, createGroupTabBarPortal(computed(() => !isDetachedWindowContext && (driverStoreActive.value || pluginCenterActive.value || settingsStore.settingsPageActive))));
provide(EDITOR_TOOLBAR_ACTIONS, {
explainMode,
blockDangerousRedisCommands,
@@ -976,6 +983,7 @@ const { setupTauriListeners, cleanupTauriListeners } = useTauriEvents({
openDbFilePath,
openConnectionDeepLink,
openAiConfigDeepLink,
+ closeActiveSurface,
});
const { showCloseActionPrompt, chooseQuit, chooseMinimize, cancelCloseActionPrompt, performCloseAction, setupCloseActionPromptListener, cleanupCloseActionPromptListener } = useCloseActionPrompt({ requestClose: requestAppClose });
useVisibilityChange();
@@ -1005,16 +1013,17 @@ function openSettings(initialTab = "appearance", initialSection?: string) {
settingsInitialSection.value = initialSection;
settingsNavigationRequestId.value += 1;
if (!settingsStore.settingsPageActive) {
- settingsReturnSurface.value = showDriverStore.value ? "driverStore" : activeTab.value ? "query" : "welcome";
+ settingsReturnSurface.value = showDriverStore.value ? "driverStore" : showPluginCenter.value ? "pluginCenter" : activeTab.value ? "query" : "welcome";
}
activateSettingsPage();
}
-type MainContentSurface = "query" | "settings" | "driverStore";
+type MainContentSurface = "query" | "settings" | "driverStore" | "pluginCenter";
function activateMainContentSurface(surface: MainContentSurface) {
settingsStore.settingsPageActive = surface === "settings";
driverStoreActive.value = surface === "driverStore";
+ pluginCenterActive.value = surface === "pluginCenter";
}
watch(
@@ -1051,6 +1060,10 @@ function closeSettingsPage() {
activateMainContentSurface("driverStore");
return;
}
+ if (settingsReturnSurface.value === "pluginCenter" && pluginCenterTabOpen.value) {
+ activateMainContentSurface("pluginCenter");
+ return;
+ }
activateMainContentSurface("query");
}
@@ -1076,6 +1089,23 @@ function closeDriverStorePage() {
driverStoreActiveTab.value = "agent";
driverStoreFocus.value = null;
}
+
+function openPluginCenterPage(focus?: PluginCenterFocus | null) {
+ pluginCenterFocus.value = focus ?? null;
+ pluginCenterTabOpen.value = true;
+ activateMainContentSurface("pluginCenter");
+}
+
+function closePluginCenterPage() {
+ pluginCenterTabOpen.value = false;
+ pluginCenterFocus.value = null;
+ activateMainContentSurface("query");
+}
+
+function openPluginConnectionDialog(pluginId: string, providerId: string) {
+ connectionPluginProvider.value = { pluginId, providerId };
+ showConnectionDialog.value = true;
+}
const toolbarAgentDriverUpdateCount = computed(() => (updateNotificationsEnabled.value ? agentDriverUpdateCount.value : 0));
const toolbarHasUpdateAvailable = computed(() => updateNotificationsEnabled.value && hasUpdateAvailable.value);
const toolbarMcpUpdateAvailable = computed(() => updateNotificationsEnabled.value && mcpUpdateAvailable.value);
@@ -2299,6 +2329,7 @@ function setConnectionDialogOpen(value: boolean) {
showConnectionDialog.value = value;
if (!value) {
connectionDialogPrefill.value = null;
+ connectionPluginProvider.value = null;
connectionDialogInitialTab.value = undefined;
}
}
@@ -2407,6 +2438,19 @@ async function openConnectionQuery(connectionId: string) {
}
return;
}
+ if (initialTarget.kind === "plugin-workbench") {
+ try {
+ await queryStore.openPluginConnection(connectionId);
+ } catch (e: any) {
+ toast(
+ t("connection.connectFailed", {
+ message: translateBackendError(t, e),
+ }),
+ 5000,
+ );
+ }
+ return;
+ }
if (initialTarget.kind === "etcd" || initialTarget.kind === "zookeeper" || initialTarget.kind === "consul") {
try {
await connectionStore.ensureConnected(connectionId);
@@ -3072,6 +3116,18 @@ function handleNativeSelectAll(e: KeyboardEvent) {
if (shouldBlockAppNativeSelectAll(e)) e.preventDefault();
}
+async function closeActiveSurface() {
+ if (showSettingsPage.value) {
+ closeSettingsPage();
+ } else if (showPluginCenter.value) {
+ closePluginCenterPage();
+ } else if (showDriverStore.value) {
+ closeDriverStorePage();
+ } else if (queryStore.activeTabId) {
+ if (await queryStore.clearQueryResults(queryStore.activeTabId)) return;
+ queryStore.closeTab(queryStore.activeTabId);
+ }
+}
async function handleKeydown(e: KeyboardEvent) {
if (e.defaultPrevented) return;
@@ -3187,14 +3243,7 @@ async function handleKeydown(e: KeyboardEvent) {
}
if (isCloseTabShortcut(e, shortcuts)) {
e.preventDefault();
- if (showSettingsPage.value) {
- closeSettingsPage();
- } else if (showDriverStore.value) {
- closeDriverStorePage();
- } else if (queryStore.activeTabId) {
- if (await queryStore.clearQueryResults(queryStore.activeTabId)) return;
- queryStore.closeTab(queryStore.activeTabId);
- }
+ await closeActiveSurface();
return;
}
if (isSaveShortcut(e, shortcuts) && e.target instanceof Element && isObjectSourceSaveShortcutTarget(e.target)) {
@@ -3522,6 +3571,7 @@ onUnmounted(() => {
:sql-library-save-feedback-id="sqlLibrarySaveFeedbackId"
:show-sql-file-panel="showSqlFilePanel"
:show-driver-store="showDriverStore"
+ :show-plugin-center="showPluginCenter"
:show-settings-page="showSettingsPage"
:checking-updates="checkingUpdates"
:has-update-available="toolbarHasUpdateAvailable"
@@ -3545,6 +3595,7 @@ onUnmounted(() => {
@open-github="openGitHub"
@open-settings="openSettings(toolbarMcpUpdateAvailable ? 'mcp' : 'appearance')"
@open-driver-store="openDriverStorePage"
+ @open-plugin-center="openPluginCenterPage()"
@check-updates="checkUpdates()"
@open-transfer="dialogs.showTransferDialog.value = true"
@open-sql-file="dialogs.showSqlFileDialog.value = true"
@@ -3574,6 +3625,8 @@ onUnmounted(() => {
ref="appTabBarRef"
:driver-store-open="driverStoreTabOpen"
:driver-store-active="driverStoreActive"
+ :plugin-center-open="pluginCenterTabOpen"
+ :plugin-center-active="pluginCenterActive"
:settings-page-open="settingsPageTabOpen"
:settings-page-active="settingsStore.settingsPageActive"
:agent-driver-update-count="toolbarAgentDriverUpdateCount"
@@ -3582,9 +3635,11 @@ onUnmounted(() => {
:tab-bar-width="tabBarWidth"
:tab-bar-collapsed="tabBarCollapsed"
@activate-driver-store="openDriverStorePage"
+ @activate-plugin-center="openPluginCenterPage(pluginCenterFocus)"
@activate-settings-page="activateSettingsPage"
@activate-tab="activateQueryTab"
@close-driver-store="closeDriverStorePage"
+ @close-plugin-center="closePluginCenterPage"
@close-settings-page="closeSettingsPage"
@save-tab="handleSaveTab"
@discard-tab-close="handleDiscardPendingTabClose"
@@ -3594,6 +3649,7 @@ onUnmounted(() => {
@detach-tab="detachTab"
>
<DriverStorePage v-if="driverStoreTabOpen" v-show="driverStoreActive" v-model:active-tab="driverStoreActiveTab" class="flex-1 min-h-0" :update-notifications-enabled="updateNotificationsEnabled" :focus-target="driverStoreFocus" @update-count-change="updateAgentDriverUpdateCount" />
+ <PluginCenterPage v-if="pluginCenterTabOpen" v-show="pluginCenterActive" class="flex-1 min-h-0" :focus-target="pluginCenterFocus" @new-connection="openPluginConnectionDialog" />
<EditorSettingsPage
v-if="settingsPageTabOpen"
v-show="settingsStore.settingsPageActive"
@@ -3635,7 +3691,7 @@ onUnmounted(() => {
</DialogFooter>
</DialogContent>
</Dialog>
- <div v-show="!driverStoreActive && !settingsStore.settingsPageActive" class="flex min-h-0 min-w-0 flex-1 flex-col">
+ <div v-show="!driverStoreActive && !pluginCenterActive && !settingsStore.settingsPageActive" class="flex min-h-0 min-w-0 flex-1 flex-col">
<div class="flex flex-col flex-1 min-h-0">
<SqlEditorWorkspace
ref="contentAreaRef"
@@ -3845,6 +3901,7 @@ onUnmounted(() => {
<AppDialogs
:show-connection-dialog="showConnectionDialog"
:connection-prefill="connectionDialogPrefill"
+ :connection-plugin-provider="connectionPluginProvider"
:connection-initial-tab="connectionDialogInitialTab"
:show-danger-dialog="showDangerDialog"
:danger-sql="dangerSql"
diff --git a/apps/desktop/src/components/config/DriverStoreDialog.vue b/apps/desktop/src/components/config/DriverStoreDialog.vue
index a997fa7b33..8919ca0e85 100644
--- a/apps/desktop/src/components/config/DriverStoreDialog.vue
+++ b/apps/desktop/src/components/config/DriverStoreDialog.vue
@@ -34,7 +34,7 @@ import {
type DriverInstallProgress,
} from "@/lib/connection/driverInstallProgressUi";
import { installRegisteredManagedJdbcDriver, isManagedJdbcDriver, managedJdbcDriverRows, uninstallRegisteredManagedJdbcDriver } from "@/lib/database/managedJdbcDrivers";
-import type { DriverStoreFocus } from "@/lib/connection/agentDriverInstallHint";
+import type { DriverStoreFocus, DriverStoreTab } from "@/lib/connection/agentDriverInstallHint";
import { isOfflineDriverPackage, webDriverImportAccept } from "@/lib/driverStore/driverImportSelection";
import { translateBackendError } from "@/i18n/backend-errors";
import { runAgentOfflineExportAction } from "@/lib/driverStore/agentOfflineExportFlow";
@@ -55,7 +55,7 @@ function backendError(e: unknown): string {
const props = withDefaults(
defineProps<{
updateNotificationsEnabled?: boolean;
- activeTab?: "agent" | "jdbc" | "storage" | "runtime";
+ activeTab?: DriverStoreTab;
focusTarget?: DriverStoreFocus | null;
}>(),
{
@@ -67,12 +67,12 @@ const props = withDefaults(
const emit = defineEmits<{
"update-count-change": [count: number];
- "update:activeTab": [tab: "agent" | "jdbc" | "storage" | "runtime"];
+ "update:activeTab": [tab: DriverStoreTab];
}>();
const driverStoreTab = computed({
get: () => props.activeTab,
- set: (tab: "agent" | "jdbc" | "storage" | "runtime") => emit("update:activeTab", tab),
+ set: (tab: DriverStoreTab) => emit("update:activeTab", tab),
});
// ──────────── Driver store path ────────────
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index e9a20f7525..59ce4b2fca 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -14,7 +14,25 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { HelpTooltip, Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Switch } from "@/components/ui/switch";
-import type { ConnectionConfig, ConnectionTestResult, DatabaseConnectionInfo, DatabaseType, HttpTunnelConfig, IdentifierCase, JdbcDriverInfo, JdbcLocalBundleInfo, JdbcMavenBundleInfo, ProxyTunnelConfig, SshConfigHostEntry, SshTunnelConfig, TransportLayerConfig } from "@/types/database";
+import type {
+ ConnectionConfig,
+ ConnectionTestResult,
+ DatabaseConnectionInfo,
+ DatabaseType,
+ HttpTunnelConfig,
+ IdentifierCase,
+ InstalledPlugin,
+ JdbcDriverInfo,
+ JdbcLocalBundleInfo,
+ JdbcMavenBundleInfo,
+ PluginConnectionAction,
+ PluginFormField,
+ PluginFormFieldValue,
+ ProxyTunnelConfig,
+ SshConfigHostEntry,
+ SshTunnelConfig,
+ TransportLayerConfig,
+} from "@/types/database";
import { CONNECTION_PICKER_OPTIONS, CONNECTION_PROFILES, CONNECTION_PROFILE_ICONS, type ConnectionPickerOption, type ConnectionProfileCategory, type ConnectionProfileDefinition } from "@/types/generated/connectionProfiles";
import type { InfluxDbExternalConfig, InfluxDbVersion } from "@/types/influxdb";
import type { VictoriaMetricsExternalConfig } from "@/types/victoriametrics";
@@ -33,7 +51,11 @@ import { normalizeRedisKeyTemplates, redisKeyTemplatesToTextarea } from "@/lib/r
import { normalizeGlobalConnectTimeoutSecs, normalizeGlobalQueryTimeoutSecs, useSettingsStore } from "@/stores/settingsStore";
import { useToast } from "@/composables/useToast";
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
+import PluginConnectionFields from "@/components/plugins/PluginConnectionFields.vue";
+import PluginIcon from "@/components/plugins/PluginIcon.vue";
import * as api from "@/lib/backend/api";
+import { buildPluginConnectionConfig, createFrontendPluginRegistry, parsePluginConnectionProviderOptionValue, pluginConnectionActionsForDialog, pluginConnectionFormValues, pluginConnectionProviderIcon, pluginConnectionProviderOptionValue } from "@/lib/plugins/frontendPlugin";
+import type { PluginCenterFocus } from "@/lib/plugins/pluginCenterNavigation";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { applyMeilisearchBasePathToExternalConfig, applyParsedConnectionUrl, normalizeMongoConnectionString, parseConnectionUrl } from "@/lib/connection/connectionUrl";
import { DEFAULT_QUERY_TIMEOUT_SECS, MAX_CONNECT_TIMEOUT_SECS, MAX_QUERY_TIMEOUT_SECS } from "@/lib/connection/timeoutLimits";
@@ -167,8 +189,8 @@ import {
jdbcProductProfileIdsForCategory,
} from "@/lib/database/jdbcProductProfiles";
-type DbOption = ConnectionPickerOption;
-type DbCategoryKey = ConnectionProfileCategory;
+type DbOption = Omit<ConnectionPickerOption, "category"> & { category?: DbCategoryKey; plugin?: boolean; pluginId?: string; pluginIcon?: string };
+type DbCategoryKey = ConnectionProfileCategory | "plugins";
type DbCategory = { key: DbCategoryKey; title: string; options: DbOption[] };
type DialogStep = "select" | "config";
export type ConfigTab = "connection" | "advanced" | "tls" | "transport";
@@ -234,7 +256,7 @@ type LegacyConnectionConfig = ConnectionConfig & LegacyTransportFields;
type ConnectionForm = Omit<ConnectionConfig, "id">;
type ConnectionTestState = ConnectionTestResult & { ok: boolean; scope?: "connection" | "ssh" };
-const { t } = useI18n();
+const { t, locale: appLocale } = useI18n();
const { toast } = useToast();
const settingsStore = useSettingsStore();
const connectionNoteVisibilityDraft = reactive(createConnectionNoteVisibilityDraft(settingsStore.editorSettings.sidebarShowConnectionNotes));
@@ -250,6 +272,7 @@ const isDesktop = isTauriRuntime();
const props = defineProps<{
editConfig?: ConnectionConfig;
prefillConfig?: ConnectionDeepLinkDraft | null;
+ pluginProvider?: PluginCenterFocus | null;
initialTab?: ConfigTab;
}>();
@@ -305,6 +328,12 @@ const connectionErrorDetail = ref("");
const testResultCopied = ref(false);
const connectionErrorCopied = ref(false);
const editingId = ref<string | null>(null);
+const installedPlugins = ref<InstalledPlugin[]>([]);
+const pluginFormValues = ref<Record<string, PluginFormFieldValue>>({});
+const pluginLoadError = ref("");
+const runningPluginActionId = ref<string | null>(null);
+type PluginActionStatus = { ok: boolean; message: string };
+const pluginActionStatus = ref<PluginActionStatus | null>(null);
const draftTestConnectionId = ref(uuid());
const showVisibleDatabasesDialog = ref(false);
const isLoadingVisibleDatabases = ref(false);
@@ -1125,6 +1154,9 @@ const driverProfiles: Record<string, ConnectionProfileDefinition> = {
};
function profileForConfig(config: ConnectionConfig) {
+ if (config.db_type === "plugin" && config.plugin_id && config.plugin_connection_provider) {
+ return pluginConnectionProviderOptionValue(config.plugin_id, config.plugin_connection_provider);
+ }
if (config.db_type === "oracle") return "oracle";
if (config.driver_profile && driverProfiles[config.driver_profile]) {
if (config.driver_profile === "oceanbase-oracle") return "oceanbase";
@@ -1143,10 +1175,93 @@ function profileForConfig(config: ConnectionConfig) {
}
function selectedProfile() {
+ if (form.value.db_type === "plugin") {
+ const entry = selectedPluginProvider.value;
+ const providerId = parsePluginConnectionProviderOptionValue(selectedType.value)?.providerId;
+ return {
+ type: "plugin" as DatabaseType,
+ port: form.value.port || 0,
+ user: form.value.username || "",
+ label: entry?.contribution.label || form.value.driver_label || providerId || "Plugin",
+ icon: "plugin",
+ };
+ }
const profile = selectedType.value === "gbase" && (form.value.driver_profile === "gbase8a" || form.value.driver_profile === "gbase8s") ? form.value.driver_profile : selectedType.value;
return driverProfiles[profile] ?? driverProfiles.mysql;
}
+const isPluginConnection = computed(() => form.value.db_type === "plugin");
+const pluginConnectionProviders = computed(() => createFrontendPluginRegistry(installedPlugins.value, appLocale.value).listConnectionProviders());
+const selectedPluginProvider = computed(() => pluginProviderEntryForOption(selectedType.value));
+const selectedPluginIcon = computed(() => (selectedPluginProvider.value ? pluginConnectionProviderIcon(selectedPluginProvider.value) : undefined));
+const pluginFooterActions = computed<PluginConnectionAction[]>(() => (selectedPluginProvider.value ? pluginConnectionActionsForDialog(selectedPluginProvider.value.contribution, !!editingId.value) : []));
+const pluginFooterBusy = computed(() => isTesting.value || isSaving.value || !!runningPluginActionId.value);
+
+function pluginProviderEntry(pluginId: string, providerId: string) {
+ return pluginConnectionProviders.value.find((entry) => entry.plugin.manifest.id === pluginId && entry.contribution.id === providerId) || null;
+}
+
+function pluginProviderEntryForOption(value: string) {
+ const target = parsePluginConnectionProviderOptionValue(value);
+ return target ? pluginProviderEntry(target.pluginId, target.providerId) : null;
+}
+
+function applyPluginProvider(value: string, preserveConnectionFields = false, existing?: ConnectionConfig): boolean {
+ const target = parsePluginConnectionProviderOptionValue(value);
+ if (!target) return false;
+ const entry = pluginProviderEntry(target.pluginId, target.providerId);
+ if (!entry) return false;
+
+ selectedType.value = value;
+ if (!preserveConnectionFields) {
+ form.value = {
+ ...defaultForm(),
+ name: entry.contribution.label,
+ db_type: "plugin",
+ driver_profile: "plugin",
+ driver_label: entry.contribution.label,
+ host: "",
+ port: 0,
+ username: "",
+ password: "",
+ query_timeout_secs: 60,
+ };
+ } else {
+ form.value.db_type = "plugin";
+ form.value.driver_profile = "plugin";
+ form.value.driver_label = entry.contribution.label;
+ }
+ pluginFormValues.value = pluginConnectionFormValues(entry.contribution, existing);
+ if (!preserveConnectionFields) {
+ const nameField = entry.contribution.fields.find((field) => field.binding === "name");
+ const defaultName = nameField ? pluginFormValues.value[nameField.key] : undefined;
+ if (typeof defaultName === "string" && defaultName.trim()) form.value.name = defaultName.trim();
+ }
+ connectionUrlInput.value = "";
+ appliedConnectionUrlInput.value = "";
+ return true;
+}
+
+async function loadInstalledPlugins() {
+ pluginLoadError.value = "";
+ try {
+ installedPlugins.value = await api.listPlugins();
+ } catch (cause) {
+ installedPlugins.value = [];
+ pluginLoadError.value = cause instanceof Error ? cause.message : String(cause);
+ }
+}
+
+function applyRequestedPluginProvider(target: PluginCenterFocus | null | undefined) {
+ if (!target?.pluginId || !target.providerId) return false;
+ const value = pluginConnectionProviderOptionValue(target.pluginId, target.providerId);
+ if (!applyPluginProvider(value)) return false;
+ selectedDbCategory.value = "plugins";
+ dialogStep.value = "config";
+ configTab.value = "connection";
+ return true;
+}
+
function mqExtraRecord(config?: Partial<MqAdminConfig>): Record<string, unknown> {
const extra = config?.extra;
return extra && typeof extra === "object" && !Array.isArray(extra) ? (extra as Record<string, unknown>) : {};
@@ -2622,6 +2737,13 @@ watch(
customColorInput.value = config.color || "";
selectedTransportLayerId.value = form.value.transport_layers?.[0]?.id || null;
selectedType.value = profile;
+ if (config.db_type === "plugin") {
+ selectedDbCategory.value = "plugins";
+ const entry = config.plugin_id && config.plugin_connection_provider ? pluginProviderEntry(config.plugin_id, config.plugin_connection_provider) : null;
+ pluginFormValues.value = entry ? pluginConnectionFormValues(entry.contribution, config) : {};
+ } else {
+ pluginFormValues.value = {};
+ }
if (profile === "oceanbase") {
oceanbaseSubMode.value = oceanbaseMode;
}
@@ -2785,12 +2907,27 @@ function onDbTypeChange(val: string) {
}
const category = dbCategoryForOption(val);
if (category) selectedDbCategory.value = category;
+ // Keep in sync with PLUGIN_CONNECTION_PROVIDER_OPTION_PREFIX in lib/plugins/frontendPlugin.
+ if (val.startsWith("plugin-provider:")) {
+ onPluginProviderOptionChange(val);
+ return;
+ }
customDriverName.value = "";
applyProfile(val, !!editingId.value);
resetTestState();
resetVisibleSchemasState();
}
+function onPluginProviderOptionChange(val: string) {
+ const pluginTarget = parsePluginConnectionProviderOptionValue(val);
+ if (pluginTarget) {
+ const existing = props.editConfig?.db_type === "plugin" && props.editConfig.plugin_id === pluginTarget.pluginId && props.editConfig.plugin_connection_provider === pluginTarget.providerId ? props.editConfig : undefined;
+ applyPluginProvider(val, !!editingId.value, existing);
+ }
+ resetTestState();
+ resetVisibleSchemasState();
+}
+
function selectIgniteConnectionProfile(profile: IgniteConnectionProfile) {
if (form.value.db_type === profile) return;
const category = dbCategoryForOption(profile);
@@ -2904,11 +3041,22 @@ assertCompleteDatabaseCategories(
const hiddenPickerOptionTypes = new Set(Object.keys(MERGED_PICKER_OPTION_FOR_TYPE));
const dbCategories = computed<DbCategory[]>(() => {
- return dbCategoryDefinitions.map((category) => ({
+ const categories: DbCategory[] = dbCategoryDefinitions.map((category) => ({
key: category.key,
title: t(category.titleKey),
options: dbOptions.filter((option) => category.optionValues.includes(option.value) && !hiddenPickerOptionTypes.has(option.value)),
}));
+ const pluginOptions: DbOption[] = pluginConnectionProviders.value.map((entry) => ({
+ value: pluginConnectionProviderOptionValue(entry.plugin.manifest.id, entry.contribution.id),
+ label: entry.contribution.label,
+ plugin: true,
+ pluginId: entry.plugin.manifest.id,
+ pluginIcon: pluginConnectionProviderIcon(entry),
+ }));
+ if (pluginOptions.length) {
+ categories.push({ key: "plugins", title: t("connection.databaseCategoryPlugins"), options: pluginOptions });
+ }
+ return categories;
});
function matchesDbOption(option: DbOption, keyword: string, categoryTitle = "") {
@@ -2963,7 +3111,7 @@ function dbCategoryForOption(value: string): DbCategoryKey | undefined {
return dbCategories.value.find((category) => category.options.some((option) => option.value === pickerValue))?.key;
}
-const selectedDbIcon = computed(() => iconTypeMap[selectedType.value] || selectedProfile().icon || selectedType.value);
+const selectedDbIcon = computed(() => (isPluginConnection.value ? "plugin" : iconTypeMap[selectedType.value] || selectedProfile().icon || selectedType.value));
function supportsNativeAgentJdbcDriverConfigType(dbType: DatabaseType): boolean {
return dbType === "prestosql" || dbType === "bigquery" || dbType === "dameng";
}
@@ -3424,6 +3572,70 @@ const testResultMessage = computed(() => {
if (!testResult.value.ok) return translateBackendError(t, testResult.value.message);
return testResult.value.scope === "ssh" ? t("connection.sshTunnelTestSuccess") : t("connection.testSuccess");
});
+const pluginActionStatusMessage = computed(() => {
+ if (!pluginActionStatus.value) return "";
+ return pluginActionStatus.value.ok ? pluginActionStatus.value.message : translateBackendError(t, pluginActionStatus.value.message);
+});
+
+function pluginFieldValue(field: PluginFormField): PluginFormFieldValue {
+ if (field.binding === "name") return form.value.name;
+ return pluginFormValues.value[field.key] ?? field.default;
+}
+
+function pluginFieldHasValue(field: PluginFormField): boolean {
+ const value = pluginFieldValue(field);
+ return typeof value === "string" ? value.trim().length > 0 : value !== undefined;
+}
+
+function pluginActionLabel(action: PluginConnectionAction): string {
+ if (action.label) return action.label;
+ if (action.kind === "test") return t("connection.test");
+ if (action.kind === "save") return t("connection.save");
+ if (action.kind === "save-and-connect") return t("connection.saveAndConnect");
+ return action.id;
+}
+
+function pluginActionVariant(action: PluginConnectionAction): PluginConnectionAction["variant"] {
+ return action.variant || (action.kind === "save" || action.kind === "save-and-connect" ? "default" : "outline");
+}
+
+function pluginActionIsBusy(action: PluginConnectionAction): boolean {
+ if (action.kind === "test") return isTesting.value;
+ if (action.kind === "save" || action.kind === "save-and-connect") return isSaving.value;
+ return runningPluginActionId.value === action.id;
+}
+
+function pluginActionNeedsValidForm(action: PluginConnectionAction): boolean {
+ return action.kind !== "custom" || action.requires_valid_form !== false;
+}
+
+function pluginActionDisabled(action: PluginConnectionAction): boolean {
+ if (pluginFooterBusy.value) return true;
+ return pluginActionNeedsValidForm(action) && !hasRequiredConnectionTarget.value;
+}
+
+function updatePluginFormValues(values: Record<string, PluginFormFieldValue>) {
+ pluginFormValues.value = values;
+ resetTestState();
+}
+
+function applyPluginActionFieldValues(values: Record<string, PluginFormFieldValue | null> | undefined) {
+ if (!values) return;
+ const provider = selectedPluginProvider.value?.contribution;
+ if (!provider) return;
+ const nextValues = { ...pluginFormValues.value };
+ for (const [key, returnedValue] of Object.entries(values)) {
+ const field = provider.fields.find((candidate) => candidate.key === key);
+ if (!field) continue;
+ const value = returnedValue === null ? undefined : returnedValue;
+ if (field.binding === "name") {
+ form.value.name = typeof value === "string" ? value : "";
+ }
+ if (value === undefined) delete nextValues[key];
+ else nextValues[key] = value;
+ }
+ pluginFormValues.value = nextValues;
+}
const agentInstallPercent = computed(() => driverInstallProgressPercent(agentInstallProgress.value));
const agentInstallProgressLabel = computed(() => {
const progress = agentInstallProgress.value;
@@ -3449,6 +3661,10 @@ const connectionLabelSmallClass = `${connectionLabelClass} text-xs`;
const connectionLabelTopClass = `${connectionLabelClass} mt-2`;
const connectionLabelSmallPaddedClass = `${connectionLabelClass} pt-2 text-xs`;
const hasRequiredConnectionTarget = computed(() => {
+ if (isPluginConnection.value) {
+ const provider = selectedPluginProvider.value?.contribution;
+ return !!provider && provider.fields.every((field) => !field.required || pluginFieldHasValue(field));
+ }
if (form.value.db_type === "mq") {
if (mqSystemKind.value === "kafka") return mqKafkaConnectionSource.value === "zookeeper" ? !!mqKafkaZooKeeperServers.value.trim() : !!mqKafkaBootstrapServers.value.trim();
if (mqSystemKind.value === "rocketmq") return !!mqRocketmqNamesrvAddr.value.trim();
@@ -3587,6 +3803,43 @@ async function testConnection() {
}
}
+async function runPluginConnectionAction(action: PluginConnectionAction) {
+ if (!isPluginConnection.value || pluginFooterBusy.value) return;
+ pluginActionStatus.value = null;
+ if (action.kind === "test") {
+ await testConnection();
+ if (testResult.value?.ok && action.close_on_success === true) open.value = false;
+ return;
+ }
+ if (action.kind === "save" || action.kind === "save-and-connect") {
+ await save({
+ connectAfterSave: action.kind === "save-and-connect",
+ closeOnSuccess: action.close_on_success ?? true,
+ });
+ return;
+ }
+ if (!ensureConnectionHostResolvedFromUrl()) return;
+ runningPluginActionId.value = action.id;
+ resetTestState();
+ try {
+ const config = connectionConfigForSubmit(editingId.value || draftTestConnectionId.value, "", pluginActionNeedsValidForm(action));
+ const result = await api.invokePluginConnectionAction(config, action.id);
+ applyPluginActionFieldValues(result.fieldValues);
+ const message = result.message?.trim();
+ if (message) pluginActionStatus.value = { ok: true, message };
+ if (action.close_on_success === true) {
+ if (message) toast(message, 3000);
+ open.value = false;
+ }
+ } catch (error) {
+ const message = mongodbAuthFailureHint(errorMessage(error));
+ pluginActionStatus.value = { ok: false, message };
+ showConnectionError(message);
+ } finally {
+ runningPluginActionId.value = null;
+ }
+}
+
async function testSshTunnel() {
if (isTesting.value || isTestingSshTunnel.value) return;
@@ -3810,7 +4063,22 @@ function connectionConfigForSshTunnelTest(id: string): ConnectionConfig {
return config;
}
-function connectionConfigForSubmit(id: string, generatedName = ""): ConnectionConfig {
+function connectionConfigForSubmit(id: string, generatedName = "", validatePluginRequired = true): ConnectionConfig {
+ if (isPluginConnection.value) {
+ const entry = selectedPluginProvider.value;
+ if (!entry) throw new Error(pluginLoadError.value || t("connection.pluginProviderUnavailable"));
+ if (validatePluginRequired) {
+ const missingField = entry.contribution.fields.find((field) => field.required && !pluginFieldHasValue(field));
+ if (missingField) throw new Error(t("connection.pluginRequiredField", { field: missingField.label }));
+ }
+ const values = { ...pluginFormValues.value };
+ for (const field of entry.contribution.fields) {
+ if (field.binding === "name") values[field.key] = form.value.name;
+ }
+ const existing = props.editConfig?.db_type === "plugin" && props.editConfig.plugin_id === entry.plugin.manifest.id && props.editConfig.plugin_connection_provider === entry.contribution.id ? props.editConfig : undefined;
+ const config = buildPluginConnectionConfig(entry.plugin.manifest.id, entry.contribution, values, existing);
+ return { ...formValueForSubmit(), ...config, id, name: form.value.name.trim() || generatedName.trim() || config.name, note: form.value.note?.trim() || undefined };
+ }
const config = { ...formValueForSubmit(), id } as LegacyConnectionConfig;
config.database_info = undefined;
config.database = normalizeStoredConnectionDatabase(config.db_type, config.database);
@@ -4020,7 +4288,7 @@ function connectionConfigForSubmit(id: string, generatedName = ""): ConnectionCo
setGaussdbIdentifierQuoteStyle(config, style);
setGaussdbTargetServerType(config, targetServerType);
setGaussdbCountQueryDop(config, countQueryDop);
- } else if (!isDoltDriverProfile(config.driver_profile)) {
+ } else if (config.db_type !== "plugin" && !isDoltDriverProfile(config.driver_profile)) {
config.external_config = undefined;
}
if (config.db_type === "mongodb" && !mongoUseUrl.value) {
@@ -5142,6 +5410,19 @@ watch(
void loadAgentDrivers();
void loadSshConfigHosts();
}
+ void loadInstalledPlugins().then(() => {
+ if (!open.value) return;
+ if (props.editConfig?.db_type === "plugin" && props.editConfig.plugin_id && props.editConfig.plugin_connection_provider) {
+ const entry = pluginProviderEntry(props.editConfig.plugin_id, props.editConfig.plugin_connection_provider);
+ if (entry) {
+ selectedType.value = pluginConnectionProviderOptionValue(props.editConfig.plugin_id, props.editConfig.plugin_connection_provider);
+ selectedDbCategory.value = "plugins";
+ pluginFormValues.value = pluginConnectionFormValues(entry.contribution, props.editConfig);
+ }
+ } else if (!props.prefillConfig) {
+ applyRequestedPluginProvider(props.pluginProvider);
+ }
+ });
// Preload database names so the summary count is accurate right away.
void nextTick(() => {
if (canChooseVisibleDatabases.value && hasVisibleDatabaseFilter.value) {
@@ -5163,6 +5444,17 @@ watch(
},
);
+watch(
+ () => props.pluginProvider,
+ (target) => {
+ if (!open.value || props.editConfig || props.prefillConfig || !target) return;
+ if (!applyRequestedPluginProvider(target)) {
+ void loadInstalledPlugins().then(() => applyRequestedPluginProvider(target));
+ }
+ },
+ { deep: true },
+);
+
watch([() => form.value.db_type, () => form.value.username], () => {
if (isOracleSysUser(form.value)) form.value.sysdba = true;
});
@@ -5401,7 +5693,7 @@ async function persistConnectionNoteVisibilityDraft() {
await persistConnectionNoteVisibilityDraftState(connectionNoteVisibilityDraft, settingsStore.editorSettings.sidebarShowConnectionNotes, (value) => settingsStore.updateEditorSettingsAndPersist({ sidebarShowConnectionNotes: value }));
}
-async function save() {
+async function save(options: { connectAfterSave?: boolean; closeOnSuccess?: boolean } = {}) {
if (!ensureConnectionHostResolvedFromUrl()) return;
if (isSaving.value) return;
if (!hasNacosNamespaceScopeForSave()) {
@@ -5409,6 +5701,8 @@ async function save() {
await openVisibleNacosNamespacesPicker();
return;
}
+ const connectAfterSave = options.connectAfterSave ?? (!editingId.value && form.value.db_type !== "jdbc");
+ const closeOnSuccess = options.closeOnSuccess ?? true;
const databaseInfoForSave = visibleTestDatabaseInfo.value ?? visibleSavedDatabaseInfo.value;
isSaving.value = true;
let connectionSaved = false;
@@ -5422,6 +5716,24 @@ async function save() {
connectionSaved = true;
await persistConnectionNoteVisibilityDraft();
store.stopEditing();
+ if (connectAfterSave) {
+ if (closeOnSuccess) {
+ open.value = false;
+ await nextTick();
+ }
+ emit("connectStarted", updated.name);
+ void store
+ .connect(updated)
+ .then(() => {
+ emit("connectSucceeded", updated.name);
+ })
+ .catch((e: any) => {
+ const message = String(e?.message || e);
+ if (message.includes(CONNECTION_ATTEMPT_CANCELLED_MESSAGE)) return;
+ emit("connectFailed", appendConnectionErrorHints(updated, mongodbAuthFailureHint(message), t));
+ });
+ return;
+ }
} else {
const config = withSavedDatabaseInfo(connectionConfigForSubmit(draftTestConnectionId.value), databaseInfoForSave);
await ensureRequiredAgentDriverInstalled(config);
@@ -5431,11 +5743,11 @@ async function save() {
connectionSaved = true;
await persistConnectionNoteVisibilityDraft();
draftTestConnectionId.value = uuid();
- if (config.db_type === "jdbc") {
- open.value = false;
+ if (!connectAfterSave) {
+ if (closeOnSuccess) open.value = false;
return;
}
- open.value = false;
+ if (closeOnSuccess) open.value = false;
await nextTick();
emit("connectStarted", config.name);
void store
@@ -5452,7 +5764,7 @@ async function save() {
});
return;
}
- open.value = false;
+ if (closeOnSuccess) open.value = false;
} catch (e: any) {
const cause = mongodbAuthFailureHint(String(e?.message || e));
const message = connectionSaved ? t("connection.savedSettingsFailed", { message: cause }) : cause;
@@ -5939,7 +6251,8 @@ function openExternalUrl(url: string) {
@dblclick="goToConnectionStep(opt.value)"
>
<span class="flex h-10 w-10 items-center justify-center rounded-xl bg-muted/60 transition group-hover:bg-background">
- <DatabaseIcon :db-type="iconTypeMap[opt.value] || opt.value" class="h-6 w-6" />
+ <PluginIcon v-if="opt.plugin" :plugin-id="opt.pluginId || ''" :icon="opt.pluginIcon" class="h-6 w-6" />
+ <DatabaseIcon v-else :db-type="iconTypeMap[opt.value] || opt.value" class="h-6 w-6" />
</span>
<span class="flex min-h-8 max-w-full items-center justify-center">
<span class="line-clamp-2 text-sm leading-4 font-medium">{{ opt.label }}</span>
@@ -5958,7 +6271,8 @@ function openExternalUrl(url: string) {
@click="onDbTypeChange(opt.value)"
@dblclick="goToConnectionStep(opt.value)"
>
- <DatabaseIcon :db-type="iconTypeMap[opt.value] || opt.value" class="h-5 w-5 shrink-0" />
+ <PluginIcon v-if="opt.plugin" :plugin-id="opt.pluginId || ''" :icon="opt.pluginIcon" class="h-5 w-5 shrink-0" />
+ <DatabaseIcon v-else :db-type="iconTypeMap[opt.value] || opt.value" class="h-5 w-5 shrink-0" />
<span class="min-w-0 flex-1 truncate text-sm font-medium">{{ opt.label }}</span>
<span v-if="isDbSearchActive" class="text-xs text-muted-foreground">{{ category.title }}</span>
</button>
@@ -5974,7 +6288,8 @@ function openExternalUrl(url: string) {
<DialogFooter class="flex shrink-0 items-center gap-2">
<div class="mr-auto flex min-w-0 items-center gap-2 text-sm text-muted-foreground">
- <DatabaseIcon :db-type="selectedDbIcon" class="h-4 w-4 shrink-0" />
+ <PluginIcon v-if="isPluginConnection" :plugin-id="selectedPluginProvider?.plugin.manifest.id || ''" :icon="selectedPluginIcon" class="h-4 w-4" />
+ <DatabaseIcon v-else :db-type="selectedDbIcon" class="h-4 w-4 shrink-0" />
<span class="truncate">{{ t("connection.selectedDatabase") }}: {{ selectedProfile().label }}</span>
</div>
<Button :disabled="!hasDbPickerResults || !selectedDbOptionIsVisible" @click="goToConnectionStep()">
@@ -5998,7 +6313,7 @@ function openExternalUrl(url: string) {
<TabsContent value="connection" class="m-0 flex min-h-0 flex-1 flex-col overflow-hidden">
<div class="connection-form-body grid min-h-0 flex-1 scroll-pb-6 gap-4 overflow-y-auto pt-4 pr-2 pb-6" :class="{ 'connection-form-body--nacos': form.db_type === 'nacos' }">
- <div v-if="!isJdbcConnection && form.db_type !== 'nacos' && form.db_type !== 'consul' && form.db_type !== 'mq'" class="grid grid-cols-4 items-center gap-4">
+ <div v-if="!isPluginConnection && !isJdbcConnection && form.db_type !== 'nacos' && form.db_type !== 'consul' && form.db_type !== 'mq'" class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.connectionUrlOptional") }}</Label>
<div class="col-span-3 flex items-center gap-1">
<Input v-model="connectionUrlInput" class="flex-1" :placeholder="connectionUrlPlaceholder" @keydown.enter.prevent="applyConnectionUrl" />
@@ -6025,7 +6340,8 @@ function openExternalUrl(url: string) {
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.type") }}</Label>
<button type="button" class="col-span-3 flex items-center gap-2 rounded-md border bg-muted/20 px-3 py-2 hover:bg-muted/40 cursor-pointer transition" @click="backToDatabasePicker()">
- <DatabaseIcon :db-type="selectedDbIcon" class="h-4 w-4 shrink-0" />
+ <PluginIcon v-if="isPluginConnection && selectedPluginProvider" :plugin-id="selectedPluginProvider.plugin.manifest.id" :icon="selectedPluginIcon" class="h-4 w-4 shrink-0" />
+ <DatabaseIcon v-else :db-type="selectedDbIcon" class="h-4 w-4 shrink-0" />
<span class="min-w-0 flex-1 truncate text-sm text-left">{{ selectedProfile().label }}</span>
<Pencil class="h-3 w-3 text-muted-foreground" />
</button>
@@ -6105,1810 +6421,1819 @@ function openExternalUrl(url: string) {
</div>
</div>
- <div v-if="form.db_type === 'h2'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.mode") }}</Label>
- <div class="col-span-3 flex gap-2">
- <Button size="sm" :variant="h2ConnectionMode === 'file' ? 'default' : 'outline'" @click="switchH2ConnectionMode('file')">
- {{ t("connection.h2FileMode") }}
- </Button>
- <Button size="sm" :variant="h2ConnectionMode === 'tcp' ? 'default' : 'outline'" @click="switchH2ConnectionMode('tcp')">
- {{ t("connection.h2TcpMode") }}
- </Button>
- </div>
- </div>
-
- <div v-if="form.db_type === 'h2'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">Driver</Label>
- <div class="col-span-3 flex flex-wrap gap-2">
- <Button size="sm" :variant="!form.driver_profile || form.driver_profile === 'h2' || form.driver_profile === 'h2-auto' ? 'default' : 'outline'" @click="switchH2DriverProfile('h2')">Auto</Button>
- <Button size="sm" :variant="form.driver_profile === 'h2-v1' ? 'default' : 'outline'" @click="switchH2DriverProfile('h2-v1')">H2 1.x</Button>
- <Button size="sm" :variant="form.driver_profile === 'h2-v2' || form.driver_profile === 'h2-legacy' ? 'default' : 'outline'" @click="switchH2DriverProfile('h2-v2')">H2 2.0–2.1</Button>
- <Button size="sm" :variant="form.driver_profile === 'h2-v3' ? 'default' : 'outline'" @click="switchH2DriverProfile('h2-v3')">H2 2.2+</Button>
- <Button size="sm" :variant="form.driver_profile === 'h2-custom' ? 'default' : 'outline'" @click="switchH2DriverProfile('h2-custom')">Custom JAR</Button>
- </div>
- </div>
-
- <template v-if="isH2CustomDriver">
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.jdbcDriverPaths") }}</Label>
- <div class="col-span-3 space-y-2">
- <Select v-if="jdbcDriverSelectItems.length > 0" :model-value="selectedJdbcDriverPath" @update:model-value="onJdbcDriverSelect">
- <SelectTrigger>
- <SelectValue :placeholder="t('connection.jdbcDriverSelectPlaceholder')" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem v-for="driver in jdbcDriverSelectItems" :key="driver.id" :value="driver.id">
- {{ driver.label }}
- </SelectItem>
- </SelectContent>
- </Select>
- <div class="flex items-start gap-1">
- <textarea
- v-model="jdbcDriverPathsInput"
- class="flex min-h-12 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- :placeholder="t('connection.jdbcDriverPathsPlaceholder')"
- />
- <Tooltip v-if="isDesktop">
- <TooltipTrigger as-child>
- <Button type="button" variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseJdbcDriverPaths">
- <FolderOpen class="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{{ t("connection.jdbcDriverBrowse") }}</TooltipContent>
- </Tooltip>
- </div>
- </div>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.jdbcDriverClass") }}</Label>
- <Input v-model="form.jdbc_driver_class" class="col-span-3" placeholder="org.h2.Driver" />
+ <template v-if="isPluginConnection">
+ <PluginConnectionFields v-if="selectedPluginProvider" :model-value="pluginFormValues" :contribution="selectedPluginProvider.contribution" :hidden-bindings="['name']" layout="connection-dialog" @update:model-value="updatePluginFormValues" />
+ <div v-else class="col-span-full rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm text-destructive">
+ {{ pluginLoadError || t("connection.pluginProviderUnavailable") }}
</div>
</template>
- <div v-if="h2DriverMissing" class="grid grid-cols-4 items-center gap-4">
- <span />
- <p class="col-span-3 text-xs text-muted-foreground">
- {{ t("connection.driverInstallHintPrefix") }}<a class="underline cursor-pointer text-primary hover:text-primary/80" @click="emit('openDriverStore', agentDriverFocus)">{{ t("toolbar.driverManager") }}</a
- >{{ t("connection.driverInstallHintSuffix") }}
- </p>
- </div>
-
- <!-- JDBC: optional external plugin -->
- <template v-if="isJdbcConnection">
- <div v-if="form.driver_profile === 'dremio'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mode") }}</Label>
+ <template v-else>
+ <div v-if="form.db_type === 'h2'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.mode") }}</Label>
<div class="col-span-3 flex gap-2">
- <Button size="sm" :variant="dremioConnectionMode === 'arrow-flight-sql' ? 'default' : 'outline'" @click="applyDremioConnectionMode('arrow-flight-sql')">
- {{ t("connection.dremioArrowFlightSqlMode") }}
- </Button>
- <Button size="sm" :variant="dremioConnectionMode === 'legacy' ? 'default' : 'outline'" @click="applyDremioConnectionMode('legacy')">
- {{ t("connection.dremioLegacyJdbcMode") }}
+ <Button size="sm" :variant="h2ConnectionMode === 'file' ? 'default' : 'outline'" @click="switchH2ConnectionMode('file')">
+ {{ t("connection.h2FileMode") }}
</Button>
- </div>
- </div>
- <div v-if="activeJdbcProductProfile && activeJdbcProductProfile.modes.length > 1" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mode") }}</Label>
- <div class="col-span-3 flex gap-2">
- <Button v-for="mode in activeJdbcProductProfile.modes" :key="mode.id" type="button" size="sm" :variant="jdbcProductConnectionMode === mode.id ? 'default' : 'outline'" @click="applyJdbcProductConnectionMode(mode.id)">
- {{ t(mode.labelKey) }}
+ <Button size="sm" :variant="h2ConnectionMode === 'tcp' ? 'default' : 'outline'" @click="switchH2ConnectionMode('tcp')">
+ {{ t("connection.h2TcpMode") }}
</Button>
</div>
</div>
- <div v-if="activeJdbcProductProfile && activeJdbcProductMode" class="grid grid-cols-4 items-start gap-4">
- <span />
- <div class="col-span-3 space-y-1 text-xs text-muted-foreground">
- <p>{{ t(activeJdbcProductMode.hintKey) }}</p>
- <p>
- {{ t(activeJdbcProductProfile.driverManagerHintPrefixKey) }}<a class="underline cursor-pointer text-primary hover:text-primary/80" @click="emit('openDriverStore', agentDriverFocus)">{{ t("toolbar.driverManager") }}</a
- >{{ t(activeJdbcProductProfile.driverManagerHintSuffixKey) }}
- </p>
+
+ <div v-if="form.db_type === 'h2'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">Driver</Label>
+ <div class="col-span-3 flex flex-wrap gap-2">
+ <Button size="sm" :variant="!form.driver_profile || form.driver_profile === 'h2' || form.driver_profile === 'h2-auto' ? 'default' : 'outline'" @click="switchH2DriverProfile('h2')">Auto</Button>
+ <Button size="sm" :variant="form.driver_profile === 'h2-v1' ? 'default' : 'outline'" @click="switchH2DriverProfile('h2-v1')">H2 1.x</Button>
+ <Button size="sm" :variant="form.driver_profile === 'h2-v2' || form.driver_profile === 'h2-legacy' ? 'default' : 'outline'" @click="switchH2DriverProfile('h2-v2')">H2 2.0–2.1</Button>
+ <Button size="sm" :variant="form.driver_profile === 'h2-v3' ? 'default' : 'outline'" @click="switchH2DriverProfile('h2-v3')">H2 2.2+</Button>
+ <Button size="sm" :variant="form.driver_profile === 'h2-custom' ? 'default' : 'outline'" @click="switchH2DriverProfile('h2-custom')">Custom JAR</Button>
</div>
</div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.jdbcUrl") }}</Label>
- <Input v-model="form.connection_string" class="col-span-3" :placeholder="t('connection.jdbcUrlPlaceholder')" @blur="syncJdbcProfileModeFromUrl" />
- </div>
- <div v-if="isJdbcxConnection" class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.jdbcxExtensions") }}</Label>
- <div class="col-span-3 flex items-start justify-between gap-4 rounded-md border px-3 py-2" :class="jdbcxHighPrivilegeExtensionsAllowed ? 'border-amber-500/60 bg-amber-500/10' : 'bg-muted/20'">
- <div class="space-y-1">
- <div class="text-sm font-medium">{{ t("connection.jdbcxHighPrivilegeExtensions") }}</div>
- <p class="text-xs text-muted-foreground">{{ t("connection.jdbcxHighPrivilegeExtensionsWarning") }}</p>
+
+ <template v-if="isH2CustomDriver">
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.jdbcDriverPaths") }}</Label>
+ <div class="col-span-3 space-y-2">
+ <Select v-if="jdbcDriverSelectItems.length > 0" :model-value="selectedJdbcDriverPath" @update:model-value="onJdbcDriverSelect">
+ <SelectTrigger>
+ <SelectValue :placeholder="t('connection.jdbcDriverSelectPlaceholder')" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="driver in jdbcDriverSelectItems" :key="driver.id" :value="driver.id">
+ {{ driver.label }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <div class="flex items-start gap-1">
+ <textarea
+ v-model="jdbcDriverPathsInput"
+ class="flex min-h-12 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ :placeholder="t('connection.jdbcDriverPathsPlaceholder')"
+ />
+ <Tooltip v-if="isDesktop">
+ <TooltipTrigger as-child>
+ <Button type="button" variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseJdbcDriverPaths">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.jdbcDriverBrowse") }}</TooltipContent>
+ </Tooltip>
+ </div>
</div>
- <Switch v-model="jdbcxHighPrivilegeExtensionsAllowed" class="mt-0.5 shrink-0" />
</div>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
- <Input v-model="form.username" class="col-span-3" :placeholder="jdbcUsernamePlaceholder" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>
- <PasswordInput v-model="form.password" class="col-span-3" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <span />
- <div class="col-span-3 flex items-center gap-1.5 text-sm">
- <label class="flex items-center gap-2">
- <input v-model="form.save_password" type="checkbox" class="h-4 w-4 rounded border-border accent-primary" :aria-label="t('connection.savePassword')" />
- <span class="whitespace-nowrap">{{ t("connection.savePassword") }}</span>
- </label>
- <HelpTooltip :label="t('connection.savePassword')">
- {{ form.save_password ? t("connection.savePasswordHint") : t("connection.savePasswordSessionHint") }}
- </HelpTooltip>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.jdbcDriverClass") }}</Label>
+ <Input v-model="form.jdbc_driver_class" class="col-span-3" placeholder="org.h2.Driver" />
</div>
+ </template>
+
+ <div v-if="h2DriverMissing" class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <p class="col-span-3 text-xs text-muted-foreground">
+ {{ t("connection.driverInstallHintPrefix") }}<a class="underline cursor-pointer text-primary hover:text-primary/80" @click="emit('openDriverStore', agentDriverFocus)">{{ t("toolbar.driverManager") }}</a
+ >{{ t("connection.driverInstallHintSuffix") }}
+ </p>
</div>
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.jdbcDriverPaths") }}</Label>
- <div class="col-span-3 space-y-2">
- <Select v-if="jdbcDriverSelectItems.length > 0" :model-value="selectedJdbcDriverPath" @update:model-value="onJdbcDriverSelect">
- <SelectTrigger>
- <SelectValue :placeholder="t('connection.jdbcDriverSelectPlaceholder')" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem v-for="driver in jdbcDriverSelectItems" :key="driver.id" :value="driver.id">
- {{ driver.label }}
- </SelectItem>
- </SelectContent>
- </Select>
- <div class="flex items-center justify-between gap-3 rounded-md border bg-muted/20 px-3 py-2">
- <div class="flex min-w-0 items-center gap-2">
- <div class="truncate text-xs font-medium">{{ t("connection.jdbcManualClasspath") }}</div>
- <Badge variant="outline" class="h-5 shrink-0 rounded-full px-2 text-[10px] font-medium">
- {{ t("connection.jdbcManualClasspathCount", { count: jdbcManualClasspathCount }) }}
- </Badge>
- </div>
- <Switch v-model="jdbcManualClasspathOpen" />
- </div>
- <div v-if="jdbcManualClasspathOpen" class="flex items-start gap-1">
- <textarea
- v-model="jdbcDriverPathsInput"
- class="flex min-h-12 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- :placeholder="t('connection.jdbcDriverPathsPlaceholder')"
- />
- <Tooltip v-if="isDesktop">
- <TooltipTrigger as-child>
- <Button type="button" variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseJdbcDriverPaths">
- <FolderOpen class="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{{ t("connection.jdbcDriverBrowse") }}</TooltipContent>
- </Tooltip>
+
+ <!-- JDBC: optional external plugin -->
+ <template v-if="isJdbcConnection">
+ <div v-if="form.driver_profile === 'dremio'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mode") }}</Label>
+ <div class="col-span-3 flex gap-2">
+ <Button size="sm" :variant="dremioConnectionMode === 'arrow-flight-sql' ? 'default' : 'outline'" @click="applyDremioConnectionMode('arrow-flight-sql')">
+ {{ t("connection.dremioArrowFlightSqlMode") }}
+ </Button>
+ <Button size="sm" :variant="dremioConnectionMode === 'legacy' ? 'default' : 'outline'" @click="applyDremioConnectionMode('legacy')">
+ {{ t("connection.dremioLegacyJdbcMode") }}
+ </Button>
</div>
</div>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.jdbcDriverClass") }}</Label>
- <Input v-model="form.jdbc_driver_class" class="col-span-3" :placeholder="t('connection.jdbcDriverClassPlaceholder')" />
- </div>
- <div class="grid grid-cols-4 items-start gap-4">
- <span />
- <div class="col-span-3 space-y-2">
- <p v-if="!isJdbcProductConnection" class="text-xs text-muted-foreground">
- {{ t("connection.jdbcPluginHint") }}
- </p>
- <div class="flex flex-wrap gap-2">
- <Button type="button" variant="outline" size="sm" @click="openJdbcDriverManager">
- <FolderOpen class="h-3.5 w-3.5" />
- {{ t("toolbar.driverManager") }}
- </Button>
- <Button type="button" variant="outline" size="sm" @click="openExternalUrl(activeJdbcProductProfile?.docsUrl || 'https://dbxio.com')">
- <ExternalLink class="h-3.5 w-3.5" />
- {{ activeJdbcProductProfile ? t(activeJdbcProductProfile.docsLabelKey) : t("connection.jdbcDocs") }}
+ <div v-if="activeJdbcProductProfile && activeJdbcProductProfile.modes.length > 1" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mode") }}</Label>
+ <div class="col-span-3 flex gap-2">
+ <Button v-for="mode in activeJdbcProductProfile.modes" :key="mode.id" type="button" size="sm" :variant="jdbcProductConnectionMode === mode.id ? 'default' : 'outline'" @click="applyJdbcProductConnectionMode(mode.id)">
+ {{ t(mode.labelKey) }}
</Button>
</div>
</div>
- </div>
- </template>
-
- <!-- Local database files: file path only -->
- <template v-else-if="usesLocalFilePathInput">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.filePath") }}</Label>
- <div class="col-span-3 space-y-1">
- <div class="flex items-center gap-1">
- <Input v-model="form.host" class="flex-1" :placeholder="sqliteUsesSsh ? t('connection.sqliteRemotePathPlaceholder') : filePathPlaceholder" />
- <Tooltip v-if="isDesktop">
- <TooltipTrigger as-child>
- <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="sqliteUsesSsh" @click="browseDbFilePath">
- <FolderOpen class="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{{ t("connection.sshKeyPathBrowse") }}</TooltipContent>
- </Tooltip>
- <Tooltip v-if="isDesktop && form.db_type === 'duckdb'">
- <TooltipTrigger as-child>
- <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="createDuckDbFilePath">
- <FilePlus2 class="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{{ t("connection.createDuckDbFile") }}</TooltipContent>
- </Tooltip>
- <Tooltip v-if="isDesktop && form.db_type === 'sqlite'">
- <TooltipTrigger as-child>
- <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="sqliteUsesSsh" @click="createSqliteFilePath">
- <FilePlus2 class="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{{ t("connection.createSqliteFile") }}</TooltipContent>
- </Tooltip>
+ <div v-if="activeJdbcProductProfile && activeJdbcProductMode" class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <div class="col-span-3 space-y-1 text-xs text-muted-foreground">
+ <p>{{ t(activeJdbcProductMode.hintKey) }}</p>
+ <p>
+ {{ t(activeJdbcProductProfile.driverManagerHintPrefixKey) }}<a class="underline cursor-pointer text-primary hover:text-primary/80" @click="emit('openDriverStore', agentDriverFocus)">{{ t("toolbar.driverManager") }}</a
+ >{{ t(activeJdbcProductProfile.driverManagerHintSuffixKey) }}
+ </p>
</div>
- <p v-if="sqliteUsesSsh" class="text-xs text-muted-foreground">
- {{ t("connection.sqliteRemotePathHint") }}
- </p>
- <p v-if="sqliteUsesSsh" class="rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs leading-5 text-amber-700 dark:text-amber-400">
- {{ t("connection.sqliteSshCipherUnsupportedHint") }}
- </p>
- <p v-else-if="supportsMemoryDatabasePath" class="text-xs text-muted-foreground">
- {{ t("connection.memoryDatabasePathHint") }}
- </p>
</div>
- </div>
- <div v-if="form.db_type === 'sqlite' && sqliteUsesSsh" class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.sqliteWorkerPlacement") }}</Label>
- <div class="col-span-3 space-y-2">
- <div class="flex min-h-9 flex-wrap items-center gap-x-5 gap-y-2">
- <Tooltip v-for="option in sqliteWorkerPlacementOptions" :key="option.value" :delay-duration="0">
- <TooltipTrigger as-child>
- <label class="flex cursor-pointer items-center gap-1.5 text-sm">
- <input type="radio" name="sqlite-worker-placement" class="h-3.5 w-3.5 accent-primary" :value="option.value" v-model="sqliteWorkerPlacement" />
- <span>{{ t(option.labelKey) }}</span>
- <Badge v-if="option.recommended" class="h-4 rounded-full px-1.5 text-[10px] leading-none">{{ t("connection.sqliteWorkerPlacementDefault") }}</Badge>
- </label>
- </TooltipTrigger>
- <TooltipContent side="bottom" class="max-w-[18rem] flex-col items-start gap-1 py-2 text-left">
- <div class="flex items-center gap-1.5 font-medium">
- <span>{{ t(option.labelKey) }}</span>
- <Badge v-if="option.recommended" class="h-4 rounded-full px-1.5 text-[10px] leading-none">{{ t("connection.sqliteWorkerPlacementDefault") }}</Badge>
- </div>
- <p class="text-[11px] leading-relaxed text-background/80">{{ t(option.hintKey) }}</p>
- </TooltipContent>
- </Tooltip>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.jdbcUrl") }}</Label>
+ <Input v-model="form.connection_string" class="col-span-3" :placeholder="t('connection.jdbcUrlPlaceholder')" @blur="syncJdbcProfileModeFromUrl" />
+ </div>
+ <div v-if="isJdbcxConnection" class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.jdbcxExtensions") }}</Label>
+ <div class="col-span-3 flex items-start justify-between gap-4 rounded-md border px-3 py-2" :class="jdbcxHighPrivilegeExtensionsAllowed ? 'border-amber-500/60 bg-amber-500/10' : 'bg-muted/20'">
+ <div class="space-y-1">
+ <div class="text-sm font-medium">{{ t("connection.jdbcxHighPrivilegeExtensions") }}</div>
+ <p class="text-xs text-muted-foreground">{{ t("connection.jdbcxHighPrivilegeExtensionsWarning") }}</p>
+ </div>
+ <Switch v-model="jdbcxHighPrivilegeExtensionsAllowed" class="mt-0.5 shrink-0" />
</div>
- <Input v-if="sqliteWorkerPlacement !== 'session'" v-model="sqliteWorkerPath" :placeholder="sqliteWorkerPlacement === 'persist' ? t('connection.sqliteWorkerPersistPathPlaceholder') : t('connection.sqliteWorkerPreplacedPathPlaceholder')" />
- <p v-if="shouldShowSqliteSshWorkerInstallHint" class="text-xs text-muted-foreground">
- {{ t("connection.driverInstallHintPrefix") }}<a class="underline cursor-pointer text-primary hover:text-primary/80" @click="emit('openDriverStore', agentDriverFocus)">{{ t("toolbar.driverManager") }}</a
- >{{ t("connection.driverInstallHintSuffix") }}
- </p>
</div>
- </div>
- <div v-if="form.db_type === 'sqlite' && !sqliteUsesSsh" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.sqliteCipherKey") }}</Label>
- <PasswordInput v-model="form.password" class="col-span-3" :placeholder="t('connection.sqliteCipherKeyPlaceholder')" />
- </div>
- <div v-if="form.db_type === 'sqlite' && !sqliteUsesSsh" class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.sqliteExtensions") }}</Label>
- <div class="col-span-3 space-y-1">
- <div class="flex items-start gap-1">
- <textarea
- v-model="sqliteExtensionPaths"
- class="flex min-h-[76px] flex-1 rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- :placeholder="t('connection.sqliteExtensionsPlaceholder')"
- spellcheck="false"
- />
- <Tooltip v-if="isDesktop">
- <TooltipTrigger as-child>
- <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseSqliteExtensionPath">
- <FolderOpen class="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{{ t("connection.sqliteExtensionBrowse") }}</TooltipContent>
- </Tooltip>
- </div>
- <p class="text-xs text-muted-foreground">
- {{ t("connection.sqliteExtensionsHint") }}
- </p>
- </div>
- </div>
- <div v-if="form.db_type === 'duckdb'" class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.initScript") }}</Label>
- <div class="col-span-3 space-y-1">
- <textarea
- v-model="form.init_script"
- class="flex min-h-[76px] w-full rounded-md border border-input bg-transparent px-3 py-2 font-mono text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- :placeholder="t('connection.initScriptPlaceholder')"
- spellcheck="false"
- />
- <p class="text-xs text-muted-foreground">
- {{ t("connection.initScriptHint") }}
- </p>
- </div>
- </div>
- <template v-if="form.db_type === 'h2' || form.db_type === 'access'">
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.user") }}{{ form.db_type === "access" ? t("connection.optionalSuffix") : "" }}</Label>
- <Input v-model="form.username" class="col-span-3" :placeholder="form.db_type === 'access' ? '' : 'sa'" />
+ <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
+ <Input v-model="form.username" class="col-span-3" :placeholder="jdbcUsernamePlaceholder" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.password") }}{{ form.db_type === "access" ? t("connection.optionalSuffix") : "" }}</Label>
+ <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>
<PasswordInput v-model="form.password" class="col-span-3" />
</div>
- </template>
- </template>
-
- <!-- Message Queue: admin URL and auth -->
- <template v-else-if="form.db_type === 'mq'">
- <template v-if="mqSystemKind === 'kafka'">
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqKafkaConnectionSource") }}</Label>
- <Select v-model="mqKafkaConnectionSource">
- <SelectTrigger class="col-span-3 h-9">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem v-for="option in mqKafkaConnectionSourceOptions" :key="option.value" :value="option.value">
- {{ option.label }}
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
- <div v-if="mqKafkaConnectionSource === 'bootstrap'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqBootstrapServers") }}</Label>
- <Input v-model="mqKafkaBootstrapServers" class="col-span-3" :placeholder="t('connection.mqBootstrapServersPlaceholder')" />
- </div>
- <div v-else class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqKafkaZooKeeperServers") }}</Label>
- <Input v-model="mqKafkaZooKeeperServers" class="col-span-3" :placeholder="t('connection.mqKafkaZooKeeperServersPlaceholder')" />
+ <span />
+ <div class="col-span-3 flex items-center gap-1.5 text-sm">
+ <label class="flex items-center gap-2">
+ <input v-model="form.save_password" type="checkbox" class="h-4 w-4 rounded border-border accent-primary" :aria-label="t('connection.savePassword')" />
+ <span class="whitespace-nowrap">{{ t("connection.savePassword") }}</span>
+ </label>
+ <HelpTooltip :label="t('connection.savePassword')">
+ {{ form.save_password ? t("connection.savePasswordHint") : t("connection.savePasswordSessionHint") }}
+ </HelpTooltip>
+ </div>
</div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqSecurity") }}</Label>
- <Select v-model="mqKafkaSecurityProtocol">
- <SelectTrigger class="col-span-3 h-9">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem v-for="option in mqKafkaSecurityProtocolOptions" :key="option.value" :value="option.value">
- {{ option.label }}
- </SelectItem>
- </SelectContent>
- </Select>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.jdbcDriverPaths") }}</Label>
+ <div class="col-span-3 space-y-2">
+ <Select v-if="jdbcDriverSelectItems.length > 0" :model-value="selectedJdbcDriverPath" @update:model-value="onJdbcDriverSelect">
+ <SelectTrigger>
+ <SelectValue :placeholder="t('connection.jdbcDriverSelectPlaceholder')" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="driver in jdbcDriverSelectItems" :key="driver.id" :value="driver.id">
+ {{ driver.label }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <div class="flex items-center justify-between gap-3 rounded-md border bg-muted/20 px-3 py-2">
+ <div class="flex min-w-0 items-center gap-2">
+ <div class="truncate text-xs font-medium">{{ t("connection.jdbcManualClasspath") }}</div>
+ <Badge variant="outline" class="h-5 shrink-0 rounded-full px-2 text-[10px] font-medium">
+ {{ t("connection.jdbcManualClasspathCount", { count: jdbcManualClasspathCount }) }}
+ </Badge>
+ </div>
+ <Switch v-model="jdbcManualClasspathOpen" />
+ </div>
+ <div v-if="jdbcManualClasspathOpen" class="flex items-start gap-1">
+ <textarea
+ v-model="jdbcDriverPathsInput"
+ class="flex min-h-12 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ :placeholder="t('connection.jdbcDriverPathsPlaceholder')"
+ />
+ <Tooltip v-if="isDesktop">
+ <TooltipTrigger as-child>
+ <Button type="button" variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseJdbcDriverPaths">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.jdbcDriverBrowse") }}</TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
</div>
- </template>
- <template v-else-if="mqSystemKind === 'rocketmq'">
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.rocketmqNamesrvAddr") }}</Label>
- <Input v-model="mqRocketmqNamesrvAddr" class="col-span-3" :placeholder="t('connection.rocketmqNamesrvAddrPlaceholder')" />
+ <Label :class="connectionLabelClass">{{ t("connection.jdbcDriverClass") }}</Label>
+ <Input v-model="form.jdbc_driver_class" class="col-span-3" :placeholder="t('connection.jdbcDriverClassPlaceholder')" />
</div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.rocketmqClusterName") }}</Label>
- <Input v-model="mqRocketmqClusterName" class="col-span-3" :placeholder="t('connection.rocketmqClusterNamePlaceholder')" />
+ <div class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <div class="col-span-3 space-y-2">
+ <p v-if="!isJdbcProductConnection" class="text-xs text-muted-foreground">
+ {{ t("connection.jdbcPluginHint") }}
+ </p>
+ <div class="flex flex-wrap gap-2">
+ <Button type="button" variant="outline" size="sm" @click="openJdbcDriverManager">
+ <FolderOpen class="h-3.5 w-3.5" />
+ {{ t("toolbar.driverManager") }}
+ </Button>
+ <Button type="button" variant="outline" size="sm" @click="openExternalUrl(activeJdbcProductProfile?.docsUrl || 'https://dbxio.com')">
+ <ExternalLink class="h-3.5 w-3.5" />
+ {{ activeJdbcProductProfile ? t(activeJdbcProductProfile.docsLabelKey) : t("connection.jdbcDocs") }}
+ </Button>
+ </div>
+ </div>
</div>
</template>
- <template v-else-if="mqSystemKind === 'rabbitmq'">
+
+ <!-- Local database files: file path only -->
+ <template v-else-if="usesLocalFilePathInput">
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqRabbitmqAddresses") }}</Label>
- <Input v-model="mqRabbitmqAddresses" class="col-span-3" :placeholder="t('connection.mqRabbitmqAddressesPlaceholder')" />
+ <Label :class="connectionLabelClass">{{ t("connection.filePath") }}</Label>
+ <div class="col-span-3 space-y-1">
+ <div class="flex items-center gap-1">
+ <Input v-model="form.host" class="flex-1" :placeholder="sqliteUsesSsh ? t('connection.sqliteRemotePathPlaceholder') : filePathPlaceholder" />
+ <Tooltip v-if="isDesktop">
+ <TooltipTrigger as-child>
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="sqliteUsesSsh" @click="browseDbFilePath">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.sshKeyPathBrowse") }}</TooltipContent>
+ </Tooltip>
+ <Tooltip v-if="isDesktop && form.db_type === 'duckdb'">
+ <TooltipTrigger as-child>
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="createDuckDbFilePath">
+ <FilePlus2 class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.createDuckDbFile") }}</TooltipContent>
+ </Tooltip>
+ <Tooltip v-if="isDesktop && form.db_type === 'sqlite'">
+ <TooltipTrigger as-child>
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="sqliteUsesSsh" @click="createSqliteFilePath">
+ <FilePlus2 class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.createSqliteFile") }}</TooltipContent>
+ </Tooltip>
+ </div>
+ <p v-if="sqliteUsesSsh" class="text-xs text-muted-foreground">
+ {{ t("connection.sqliteRemotePathHint") }}
+ </p>
+ <p v-if="sqliteUsesSsh" class="rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs leading-5 text-amber-700 dark:text-amber-400">
+ {{ t("connection.sqliteSshCipherUnsupportedHint") }}
+ </p>
+ <p v-else-if="supportsMemoryDatabasePath" class="text-xs text-muted-foreground">
+ {{ t("connection.memoryDatabasePathHint") }}
+ </p>
+ </div>
</div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqVirtualHost") }}</Label>
- <Input v-model="mqRabbitmqVirtualHost" class="col-span-3" :placeholder="t('connection.mqVirtualHostPlaceholder')" />
+ <div v-if="form.db_type === 'sqlite' && sqliteUsesSsh" class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.sqliteWorkerPlacement") }}</Label>
+ <div class="col-span-3 space-y-2">
+ <div class="flex min-h-9 flex-wrap items-center gap-x-5 gap-y-2">
+ <Tooltip v-for="option in sqliteWorkerPlacementOptions" :key="option.value" :delay-duration="0">
+ <TooltipTrigger as-child>
+ <label class="flex cursor-pointer items-center gap-1.5 text-sm">
+ <input type="radio" name="sqlite-worker-placement" class="h-3.5 w-3.5 accent-primary" :value="option.value" v-model="sqliteWorkerPlacement" />
+ <span>{{ t(option.labelKey) }}</span>
+ <Badge v-if="option.recommended" class="h-4 rounded-full px-1.5 text-[10px] leading-none">{{ t("connection.sqliteWorkerPlacementDefault") }}</Badge>
+ </label>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" class="max-w-[18rem] flex-col items-start gap-1 py-2 text-left">
+ <div class="flex items-center gap-1.5 font-medium">
+ <span>{{ t(option.labelKey) }}</span>
+ <Badge v-if="option.recommended" class="h-4 rounded-full px-1.5 text-[10px] leading-none">{{ t("connection.sqliteWorkerPlacementDefault") }}</Badge>
+ </div>
+ <p class="text-[11px] leading-relaxed text-background/80">{{ t(option.hintKey) }}</p>
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ <Input v-if="sqliteWorkerPlacement !== 'session'" v-model="sqliteWorkerPath" :placeholder="sqliteWorkerPlacement === 'persist' ? t('connection.sqliteWorkerPersistPathPlaceholder') : t('connection.sqliteWorkerPreplacedPathPlaceholder')" />
+ <p v-if="shouldShowSqliteSshWorkerInstallHint" class="text-xs text-muted-foreground">
+ {{ t("connection.driverInstallHintPrefix") }}<a class="underline cursor-pointer text-primary hover:text-primary/80" @click="emit('openDriverStore', agentDriverFocus)">{{ t("toolbar.driverManager") }}</a
+ >{{ t("connection.driverInstallHintSuffix") }}
+ </p>
+ </div>
</div>
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqRabbitmqAdminUrl") }}</Label>
+ <div v-if="form.db_type === 'sqlite' && !sqliteUsesSsh" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.sqliteCipherKey") }}</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" :placeholder="t('connection.sqliteCipherKeyPlaceholder')" />
+ </div>
+ <div v-if="form.db_type === 'sqlite' && !sqliteUsesSsh" class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.sqliteExtensions") }}</Label>
<div class="col-span-3 space-y-1">
- <Input v-model="mqAdminUrl" :placeholder="t('connection.mqRabbitmqAdminUrlPlaceholder')" />
+ <div class="flex items-start gap-1">
+ <textarea
+ v-model="sqliteExtensionPaths"
+ class="flex min-h-[76px] flex-1 rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ :placeholder="t('connection.sqliteExtensionsPlaceholder')"
+ spellcheck="false"
+ />
+ <Tooltip v-if="isDesktop">
+ <TooltipTrigger as-child>
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseSqliteExtensionPath">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.sqliteExtensionBrowse") }}</TooltipContent>
+ </Tooltip>
+ </div>
<p class="text-xs text-muted-foreground">
- {{ t("connection.mqRabbitmqAdminUrlHint") }}
+ {{ t("connection.sqliteExtensionsHint") }}
</p>
</div>
</div>
- </template>
- <template v-else>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqAdminUrl") }}</Label>
- <Input v-model="mqAdminUrl" class="col-span-3" placeholder="http://127.0.0.1:8080" />
- </div>
- </template>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqAuth") }}</Label>
- <div class="col-span-3 flex flex-wrap gap-2">
- <Button size="sm" :variant="mqAuthKind === 'none' ? 'default' : 'outline'" @click="mqAuthKind = 'none'">{{ t("connection.mqAuthNone") }}</Button>
- <Button v-if="mqSystemKind === 'pulsar'" size="sm" :variant="mqAuthKind === 'token' ? 'default' : 'outline'" @click="mqAuthKind = 'token'">{{ t("connection.mqAuthToken") }}</Button>
- <Button size="sm" :variant="mqAuthKind === 'basic' ? 'default' : 'outline'" @click="mqAuthKind = 'basic'">{{ mqSystemKind === "rocketmq" ? t("connection.rocketmqAclAuth") : t("connection.mqAuthBasic") }}</Button>
- <Button v-if="mqSystemKind === 'kafka'" size="sm" :variant="mqAuthKind === 'kerberos' ? 'default' : 'outline'" @click="mqAuthKind = 'kerberos'">{{ t("connection.mqAuthKerberos") }}</Button>
- <Button v-if="mqSystemKind === 'pulsar'" size="sm" :variant="mqAuthKind === 'apiKey' ? 'default' : 'outline'" @click="mqAuthKind = 'apiKey'">{{ t("connection.mqAuthApiKey") }}</Button>
- <Button v-if="mqSystemKind === 'pulsar'" size="sm" :variant="mqAuthKind === 'oauth2' ? 'default' : 'outline'" @click="mqAuthKind = 'oauth2'">{{ t("connection.mqAuthOauth2") }}</Button>
- </div>
- </div>
- <template v-if="mqAuthKind === 'token'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqToken") }}</Label>
- <PasswordInput v-model="mqToken" class="col-span-3" />
+ <div v-if="form.db_type === 'duckdb'" class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.initScript") }}</Label>
+ <div class="col-span-3 space-y-1">
+ <textarea
+ v-model="form.init_script"
+ class="flex min-h-[76px] w-full rounded-md border border-input bg-transparent px-3 py-2 font-mono text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ :placeholder="t('connection.initScriptPlaceholder')"
+ spellcheck="false"
+ />
+ <p class="text-xs text-muted-foreground">
+ {{ t("connection.initScriptHint") }}
+ </p>
+ </div>
</div>
+ <template v-if="form.db_type === 'h2' || form.db_type === 'access'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.user") }}{{ form.db_type === "access" ? t("connection.optionalSuffix") : "" }}</Label>
+ <Input v-model="form.username" class="col-span-3" :placeholder="form.db_type === 'access' ? '' : 'sa'" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.password") }}{{ form.db_type === "access" ? t("connection.optionalSuffix") : "" }}</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" />
+ </div>
+ </template>
</template>
- <template v-else-if="mqAuthKind === 'basic'">
+
+ <!-- Message Queue: admin URL and auth -->
+ <template v-else-if="form.db_type === 'mq'">
+ <template v-if="mqSystemKind === 'kafka'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqKafkaConnectionSource") }}</Label>
+ <Select v-model="mqKafkaConnectionSource">
+ <SelectTrigger class="col-span-3 h-9">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="option in mqKafkaConnectionSourceOptions" :key="option.value" :value="option.value">
+ {{ option.label }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <div v-if="mqKafkaConnectionSource === 'bootstrap'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqBootstrapServers") }}</Label>
+ <Input v-model="mqKafkaBootstrapServers" class="col-span-3" :placeholder="t('connection.mqBootstrapServersPlaceholder')" />
+ </div>
+ <div v-else class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqKafkaZooKeeperServers") }}</Label>
+ <Input v-model="mqKafkaZooKeeperServers" class="col-span-3" :placeholder="t('connection.mqKafkaZooKeeperServersPlaceholder')" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqSecurity") }}</Label>
+ <Select v-model="mqKafkaSecurityProtocol">
+ <SelectTrigger class="col-span-3 h-9">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="option in mqKafkaSecurityProtocolOptions" :key="option.value" :value="option.value">
+ {{ option.label }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </template>
+ <template v-else-if="mqSystemKind === 'rocketmq'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.rocketmqNamesrvAddr") }}</Label>
+ <Input v-model="mqRocketmqNamesrvAddr" class="col-span-3" :placeholder="t('connection.rocketmqNamesrvAddrPlaceholder')" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.rocketmqClusterName") }}</Label>
+ <Input v-model="mqRocketmqClusterName" class="col-span-3" :placeholder="t('connection.rocketmqClusterNamePlaceholder')" />
+ </div>
+ </template>
+ <template v-else-if="mqSystemKind === 'rabbitmq'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqRabbitmqAddresses") }}</Label>
+ <Input v-model="mqRabbitmqAddresses" class="col-span-3" :placeholder="t('connection.mqRabbitmqAddressesPlaceholder')" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqVirtualHost") }}</Label>
+ <Input v-model="mqRabbitmqVirtualHost" class="col-span-3" :placeholder="t('connection.mqVirtualHostPlaceholder')" />
+ </div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqRabbitmqAdminUrl") }}</Label>
+ <div class="col-span-3 space-y-1">
+ <Input v-model="mqAdminUrl" :placeholder="t('connection.mqRabbitmqAdminUrlPlaceholder')" />
+ <p class="text-xs text-muted-foreground">
+ {{ t("connection.mqRabbitmqAdminUrlHint") }}
+ </p>
+ </div>
+ </div>
+ </template>
+ <template v-else>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqAdminUrl") }}</Label>
+ <Input v-model="mqAdminUrl" class="col-span-3" placeholder="http://127.0.0.1:8080" />
+ </div>
+ </template>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ mqSystemKind === "rocketmq" ? t("connection.rocketmqAccessKey") : t("connection.user") }}</Label>
- <Input v-model="mqBasicUsername" class="col-span-3" :placeholder="mqSystemKind === 'rabbitmq' ? t('connection.mqRabbitmqUsernamePlaceholder') : ''" />
+ <Label :class="connectionLabelClass">{{ t("connection.mqAuth") }}</Label>
+ <div class="col-span-3 flex flex-wrap gap-2">
+ <Button size="sm" :variant="mqAuthKind === 'none' ? 'default' : 'outline'" @click="mqAuthKind = 'none'">{{ t("connection.mqAuthNone") }}</Button>
+ <Button v-if="mqSystemKind === 'pulsar'" size="sm" :variant="mqAuthKind === 'token' ? 'default' : 'outline'" @click="mqAuthKind = 'token'">{{ t("connection.mqAuthToken") }}</Button>
+ <Button size="sm" :variant="mqAuthKind === 'basic' ? 'default' : 'outline'" @click="mqAuthKind = 'basic'">{{ mqSystemKind === "rocketmq" ? t("connection.rocketmqAclAuth") : t("connection.mqAuthBasic") }}</Button>
+ <Button v-if="mqSystemKind === 'kafka'" size="sm" :variant="mqAuthKind === 'kerberos' ? 'default' : 'outline'" @click="mqAuthKind = 'kerberos'">{{ t("connection.mqAuthKerberos") }}</Button>
+ <Button v-if="mqSystemKind === 'pulsar'" size="sm" :variant="mqAuthKind === 'apiKey' ? 'default' : 'outline'" @click="mqAuthKind = 'apiKey'">{{ t("connection.mqAuthApiKey") }}</Button>
+ <Button v-if="mqSystemKind === 'pulsar'" size="sm" :variant="mqAuthKind === 'oauth2' ? 'default' : 'outline'" @click="mqAuthKind = 'oauth2'">{{ t("connection.mqAuthOauth2") }}</Button>
+ </div>
</div>
+ <template v-if="mqAuthKind === 'token'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqToken") }}</Label>
+ <PasswordInput v-model="mqToken" class="col-span-3" />
+ </div>
+ </template>
+ <template v-else-if="mqAuthKind === 'basic'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ mqSystemKind === "rocketmq" ? t("connection.rocketmqAccessKey") : t("connection.user") }}</Label>
+ <Input v-model="mqBasicUsername" class="col-span-3" :placeholder="mqSystemKind === 'rabbitmq' ? t('connection.mqRabbitmqUsernamePlaceholder') : ''" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ mqSystemKind === "rocketmq" ? t("connection.rocketmqSecretKey") : t("connection.password") }}</Label>
+ <PasswordInput v-model="mqBasicPassword" class="col-span-3" :placeholder="mqSystemKind === 'rabbitmq' ? t('connection.mqRabbitmqPasswordPlaceholder') : ''" />
+ </div>
+ <div v-if="mqSystemKind === 'kafka'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqSaslMechanism") }}</Label>
+ <Select v-model="mqKafkaSaslMechanism">
+ <SelectTrigger class="col-span-3 h-9">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="option in mqKafkaSaslMechanismOptions" :key="option.value" :value="option.value">
+ {{ option.label }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </template>
+ <template v-else-if="mqSystemKind === 'kafka' && mqAuthKind === 'kerberos'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.kafkaKerberosPrincipal") }}</Label>
+ <Input v-model="mqKafkaKerberosPrincipal" class="col-span-3" placeholder="[email protected]" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.kafkaKerberosKeytab") }}</Label>
+ <div class="col-span-3 flex items-center gap-1">
+ <Input v-model="mqKafkaKerberosKeytabPath" class="flex-1" :placeholder="t('connection.kafkaKerberosKeytabPlaceholder')" />
+ <Tooltip v-if="isDesktop">
+ <TooltipTrigger as-child>
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseKafkaKerberosFile('keytab')">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.kafkaKerberosKeytabBrowse") }}</TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.kafkaKerberosServiceName") }}</Label>
+ <Input v-model="mqKafkaKerberosServiceName" class="col-span-3" placeholder="kafka" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.kafkaKerberosKrb5Conf") }}</Label>
+ <div class="col-span-3 flex items-center gap-1">
+ <Input v-model="mqKafkaKrb5ConfPath" class="flex-1" :placeholder="t('connection.kafkaKerberosKrb5ConfPlaceholder')" />
+ <Tooltip v-if="isDesktop">
+ <TooltipTrigger as-child>
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseKafkaKerberosFile('krb5')">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.kafkaKerberosKrb5ConfBrowse") }}</TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <div></div>
+ <div class="col-span-3 space-y-1 text-xs leading-5 text-muted-foreground">
+ <p>{{ t("connection.kafkaKerberosPathHint") }}</p>
+ <p>{{ t("connection.kafkaKerberosAuthHint") }}</p>
+ </div>
+ </div>
+ </template>
+ <template v-else-if="mqAuthKind === 'apiKey'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqApiKeyHeader") }}</Label>
+ <Input v-model="mqApiKeyHeader" class="col-span-3" placeholder="Authorization" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqApiKeyValue") }}</Label>
+ <PasswordInput v-model="mqApiKeyValue" class="col-span-3" />
+ </div>
+ </template>
+ <template v-else-if="mqAuthKind === 'oauth2'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqOauthIssuerUrl") }}</Label>
+ <Input v-model="mqOauthIssuerUrl" class="col-span-3" placeholder="https://issuer.example.com/oauth/token" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqOauthClientId") }}</Label>
+ <Input v-model="mqOauthClientId" class="col-span-3" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqOauthClientSecret") }}</Label>
+ <PasswordInput v-model="mqOauthClientSecret" class="col-span-3" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqOauthAudience") }}</Label>
+ <Input v-model="mqOauthAudience" class="col-span-3" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqOauthScope") }}</Label>
+ <Input v-model="mqOauthScope" class="col-span-3" />
+ </div>
+ </template>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ mqSystemKind === "rocketmq" ? t("connection.rocketmqSecretKey") : t("connection.password") }}</Label>
- <PasswordInput v-model="mqBasicPassword" class="col-span-3" :placeholder="mqSystemKind === 'rabbitmq' ? t('connection.mqRabbitmqPasswordPlaceholder') : ''" />
+ <Label :class="connectionLabelSmallClass">{{ t("connection.mqTls") }}</Label>
+ <label class="col-span-3 inline-flex items-center gap-2">
+ <input type="checkbox" v-model="mqTlsSkipVerify" class="mr-0" />
+ <span class="text-xs text-muted-foreground">{{ t("connection.mqTlsSkipVerify") }}</span>
+ </label>
</div>
- <div v-if="mqSystemKind === 'kafka'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqSaslMechanism") }}</Label>
- <Select v-model="mqKafkaSaslMechanism">
+ <div v-if="mqSystemKind === 'pulsar'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqPinnedVersion") }}</Label>
+ <Select v-model="mqPinnedVersion">
<SelectTrigger class="col-span-3 h-9">
<SelectValue />
</SelectTrigger>
<SelectContent>
- <SelectItem v-for="option in mqKafkaSaslMechanismOptions" :key="option.value" :value="option.value">
- {{ option.label }}
+ <SelectItem v-for="option in MQ_PINNED_VERSION_OPTIONS" :key="option.value" :value="option.value">
+ <div class="grid gap-0.5 text-left">
+ <span>{{ option.label }}</span>
+ <span class="text-xs text-muted-foreground">{{ option.description }}</span>
+ </div>
</SelectItem>
</SelectContent>
</Select>
</div>
- </template>
- <template v-else-if="mqSystemKind === 'kafka' && mqAuthKind === 'kerberos'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.kafkaKerberosPrincipal") }}</Label>
- <Input v-model="mqKafkaKerberosPrincipal" class="col-span-3" placeholder="[email protected]" />
+ <div v-if="mqSystemKind === 'pulsar'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqTokenSigning") }}</Label>
+ <Select v-model="mqTokenSigningMode">
+ <SelectTrigger class="col-span-3 h-9">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">{{ t("connection.mqTokenSigningNone") }}</SelectItem>
+ <SelectItem value="hs256">HS256 SECRET</SelectItem>
+ <SelectItem value="rs256">RS256 PRIVATE</SelectItem>
+ </SelectContent>
+ </Select>
</div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.kafkaKerberosKeytab") }}</Label>
- <div class="col-span-3 flex items-center gap-1">
- <Input v-model="mqKafkaKerberosKeytabPath" class="flex-1" :placeholder="t('connection.kafkaKerberosKeytabPlaceholder')" />
- <Tooltip v-if="isDesktop">
- <TooltipTrigger as-child>
- <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseKafkaKerberosFile('keytab')">
- <FolderOpen class="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{{ t("connection.kafkaKerberosKeytabBrowse") }}</TooltipContent>
- </Tooltip>
- </div>
+ <div v-if="mqSystemKind !== 'kafka' && mqTokenSigningMode !== 'none'" class="grid grid-cols-4 items-start gap-4">
+ <Label class="pt-2 text-right">{{ t("connection.mqTokenSigningKey") }}</Label>
+ <textarea
+ v-model="mqTokenSigningKey"
+ class="col-span-3 min-h-24 rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ :placeholder="mqTokenSigningMode === 'hs256' ? t('connection.mqTokenSigningKeyPlaceholderHs256') : t('connection.mqTokenSigningKeyPlaceholderRs256')"
+ />
</div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.kafkaKerberosServiceName") }}</Label>
- <Input v-model="mqKafkaKerberosServiceName" class="col-span-3" placeholder="kafka" />
+ <div v-if="mqSystemKind !== 'kafka' && mqTokenSigningMode !== 'none'" class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <p class="col-span-3 m-0 text-xs leading-5 text-muted-foreground">{{ t("connection.mqTokenSigningHint") }}</p>
</div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.kafkaKerberosKrb5Conf") }}</Label>
- <div class="col-span-3 flex items-center gap-1">
- <Input v-model="mqKafkaKrb5ConfPath" class="flex-1" :placeholder="t('connection.kafkaKerberosKrb5ConfPlaceholder')" />
- <Tooltip v-if="isDesktop">
- <TooltipTrigger as-child>
- <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseKafkaKerberosFile('krb5')">
- <FolderOpen class="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{{ t("connection.kafkaKerberosKrb5ConfBrowse") }}</TooltipContent>
- </Tooltip>
+ </template>
+
+ <!-- Nacos: profile-aware endpoint, namespace and auth -->
+ <template v-else-if="form.db_type === 'nacos'">
+ <section data-nacos-profile-selector class="overflow-hidden rounded-lg border bg-muted/10">
+ <div class="border-b px-4 py-3">
+ <div class="text-sm font-medium">{{ t("nacos.nacosConnectionPlan") }}</div>
+ <p class="mt-0.5 text-xs leading-5 text-muted-foreground">{{ t("nacos.nacosConnectionPlanDescription") }}</p>
</div>
- </div>
- <div class="grid grid-cols-4 items-start gap-4">
- <div></div>
- <div class="col-span-3 space-y-1 text-xs leading-5 text-muted-foreground">
- <p>{{ t("connection.kafkaKerberosPathHint") }}</p>
- <p>{{ t("connection.kafkaKerberosAuthHint") }}</p>
+ <div class="grid grid-cols-3 gap-2 p-3">
+ <button
+ v-for="profile in NACOS_CONNECTION_PROFILES"
+ :key="profile.value"
+ type="button"
+ class="min-w-0 rounded-md border px-3 py-2.5 text-left transition-colors hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ :class="nacosConnectionProfile === profile.value ? 'border-primary bg-primary/5 shadow-sm' : 'border-border bg-background'"
+ :aria-pressed="nacosConnectionProfile === profile.value"
+ @click="selectNacosConnectionProfile(profile.value)"
+ >
+ <span class="block truncate text-sm font-medium">{{ profile.title }}</span>
+ </button>
</div>
- </div>
- </template>
- <template v-else-if="mqAuthKind === 'apiKey'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqApiKeyHeader") }}</Label>
- <Input v-model="mqApiKeyHeader" class="col-span-3" placeholder="Authorization" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqApiKeyValue") }}</Label>
- <PasswordInput v-model="mqApiKeyValue" class="col-span-3" />
- </div>
- </template>
- <template v-else-if="mqAuthKind === 'oauth2'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqOauthIssuerUrl") }}</Label>
- <Input v-model="mqOauthIssuerUrl" class="col-span-3" placeholder="https://issuer.example.com/oauth/token" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqOauthClientId") }}</Label>
- <Input v-model="mqOauthClientId" class="col-span-3" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqOauthClientSecret") }}</Label>
- <PasswordInput v-model="mqOauthClientSecret" class="col-span-3" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqOauthAudience") }}</Label>
- <Input v-model="mqOauthAudience" class="col-span-3" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqOauthScope") }}</Label>
- <Input v-model="mqOauthScope" class="col-span-3" />
- </div>
- </template>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.mqTls") }}</Label>
- <label class="col-span-3 inline-flex items-center gap-2">
- <input type="checkbox" v-model="mqTlsSkipVerify" class="mr-0" />
- <span class="text-xs text-muted-foreground">{{ t("connection.mqTlsSkipVerify") }}</span>
- </label>
- </div>
- <div v-if="mqSystemKind === 'pulsar'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqPinnedVersion") }}</Label>
- <Select v-model="mqPinnedVersion">
- <SelectTrigger class="col-span-3 h-9">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem v-for="option in MQ_PINNED_VERSION_OPTIONS" :key="option.value" :value="option.value">
- <div class="grid gap-0.5 text-left">
- <span>{{ option.label }}</span>
- <span class="text-xs text-muted-foreground">{{ option.description }}</span>
+ </section>
+
+ <section data-nacos-endpoint-section class="rounded-lg border p-4">
+ <div class="grid gap-4">
+ <div v-if="nacosImplementation === 'nacos' && nacosVersionMode === 'v3'" class="grid gap-1.5">
+ <Label>{{ t("nacos.nacosApiPlane") }}</Label>
+ <div class="grid grid-cols-2 gap-1 rounded-md border bg-muted/20 p-1">
+ <button
+ v-for="plane in ['admin', 'console'] as NacosApiPlane[]"
+ :key="plane"
+ type="button"
+ class="min-w-0 rounded px-3 py-2 text-left transition-colors"
+ :class="nacosApiPlane === plane ? 'bg-background shadow-sm' : 'text-muted-foreground hover:text-foreground'"
+ :aria-pressed="nacosApiPlane === plane"
+ @click="nacosApiPlane = plane"
+ >
+ <span class="block text-sm font-medium">{{ t(`nacos.nacosApiPlane${plane === "admin" ? "Admin" : "Console"}`) }}</span>
+ <span class="mt-0.5 block text-xs leading-4">{{ t(`nacos.nacosApiPlane${plane === "admin" ? "Admin" : "Console"}Hint`) }}</span>
+ </button>
</div>
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
- <div v-if="mqSystemKind === 'pulsar'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqTokenSigning") }}</Label>
- <Select v-model="mqTokenSigningMode">
- <SelectTrigger class="col-span-3 h-9">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="none">{{ t("connection.mqTokenSigningNone") }}</SelectItem>
- <SelectItem value="hs256">HS256 SECRET</SelectItem>
- <SelectItem value="rs256">RS256 PRIVATE</SelectItem>
- </SelectContent>
- </Select>
- </div>
- <div v-if="mqSystemKind !== 'kafka' && mqTokenSigningMode !== 'none'" class="grid grid-cols-4 items-start gap-4">
- <Label class="pt-2 text-right">{{ t("connection.mqTokenSigningKey") }}</Label>
- <textarea
- v-model="mqTokenSigningKey"
- class="col-span-3 min-h-24 rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm outline-none focus-visible:ring-1 focus-visible:ring-ring"
- :placeholder="mqTokenSigningMode === 'hs256' ? t('connection.mqTokenSigningKeyPlaceholderHs256') : t('connection.mqTokenSigningKeyPlaceholderRs256')"
- />
- </div>
- <div v-if="mqSystemKind !== 'kafka' && mqTokenSigningMode !== 'none'" class="grid grid-cols-4 items-start gap-4">
- <span />
- <p class="col-span-3 m-0 text-xs leading-5 text-muted-foreground">{{ t("connection.mqTokenSigningHint") }}</p>
- </div>
- </template>
-
- <!-- Nacos: profile-aware endpoint, namespace and auth -->
- <template v-else-if="form.db_type === 'nacos'">
- <section data-nacos-profile-selector class="overflow-hidden rounded-lg border bg-muted/10">
- <div class="border-b px-4 py-3">
- <div class="text-sm font-medium">{{ t("nacos.nacosConnectionPlan") }}</div>
- <p class="mt-0.5 text-xs leading-5 text-muted-foreground">{{ t("nacos.nacosConnectionPlanDescription") }}</p>
- </div>
- <div class="grid grid-cols-3 gap-2 p-3">
- <button
- v-for="profile in NACOS_CONNECTION_PROFILES"
- :key="profile.value"
- type="button"
- class="min-w-0 rounded-md border px-3 py-2.5 text-left transition-colors hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- :class="nacosConnectionProfile === profile.value ? 'border-primary bg-primary/5 shadow-sm' : 'border-border bg-background'"
- :aria-pressed="nacosConnectionProfile === profile.value"
- @click="selectNacosConnectionProfile(profile.value)"
- >
- <span class="block truncate text-sm font-medium">{{ profile.title }}</span>
- </button>
- </div>
- </section>
-
- <section data-nacos-endpoint-section class="rounded-lg border p-4">
- <div class="grid gap-4">
- <div v-if="nacosImplementation === 'nacos' && nacosVersionMode === 'v3'" class="grid gap-1.5">
- <Label>{{ t("nacos.nacosApiPlane") }}</Label>
- <div class="grid grid-cols-2 gap-1 rounded-md border bg-muted/20 p-1">
- <button
- v-for="plane in ['admin', 'console'] as NacosApiPlane[]"
- :key="plane"
- type="button"
- class="min-w-0 rounded px-3 py-2 text-left transition-colors"
- :class="nacosApiPlane === plane ? 'bg-background shadow-sm' : 'text-muted-foreground hover:text-foreground'"
- :aria-pressed="nacosApiPlane === plane"
- @click="nacosApiPlane = plane"
- >
- <span class="block text-sm font-medium">{{ t(`nacos.nacosApiPlane${plane === "admin" ? "Admin" : "Console"}`) }}</span>
- <span class="mt-0.5 block text-xs leading-4">{{ t(`nacos.nacosApiPlane${plane === "admin" ? "Admin" : "Console"}Hint`) }}</span>
- </button>
</div>
- </div>
- <div class="grid gap-1.5">
- <Label>{{ t("nacos.nacosServiceAddress") }}</Label>
- <Input v-model="nacosServerAddr" :placeholder="nacosPrimaryAddressPlaceholder" />
- <p class="text-xs leading-5 text-muted-foreground">
- <template>{{ nacosServiceAddressHint }}</template>
+ <div class="grid gap-1.5">
+ <Label>{{ t("nacos.nacosServiceAddress") }}</Label>
+ <Input v-model="nacosServerAddr" :placeholder="nacosPrimaryAddressPlaceholder" />
+ <p class="text-xs leading-5 text-muted-foreground">
+ <template>{{ nacosServiceAddressHint }}</template>
+ </p>
+ </div>
+ <p v-if="nacosV3AdminEndpointWarning" class="rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs leading-5 text-amber-700 dark:text-amber-400">
+ {{ nacosV3AdminEndpointWarning }}
</p>
</div>
- <p v-if="nacosV3AdminEndpointWarning" class="rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs leading-5 text-amber-700 dark:text-amber-400">
- {{ nacosV3AdminEndpointWarning }}
- </p>
- </div>
- </section>
+ </section>
- <section data-nacos-access-section class="rounded-lg border p-4">
- <div class="mb-4">
- <div class="text-sm font-medium">{{ t("nacos.nacosAuth") }}</div>
- <p class="mt-0.5 text-xs text-muted-foreground">{{ t("nacos.nacosAuthHint") }}</p>
- </div>
- <div class="grid max-w-md gap-1.5">
- <div class="grid gap-1.5">
- <div class="flex h-9 items-center gap-1 rounded-md border bg-muted/20 p-0.5">
- <Button type="button" size="sm" class="h-8 flex-1" :variant="nacosAuthKind === 'none' ? 'default' : 'ghost'" @click="nacosAuthKind = 'none'">{{ t("connection.nacosAuthNone") }}</Button>
- <Button type="button" size="sm" class="h-8 flex-1" :variant="nacosAuthKind === 'usernamePassword' ? 'default' : 'ghost'" @click="nacosAuthKind = 'usernamePassword'">{{ t("nacos.nacosUsernamePassword") }}</Button>
- </div>
+ <section data-nacos-access-section class="rounded-lg border p-4">
+ <div class="mb-4">
+ <div class="text-sm font-medium">{{ t("nacos.nacosAuth") }}</div>
+ <p class="mt-0.5 text-xs text-muted-foreground">{{ t("nacos.nacosAuthHint") }}</p>
</div>
- </div>
- <div v-if="nacosAuthKind === 'usernamePassword'" class="mt-4 grid gap-4 sm:grid-cols-2">
- <div class="grid gap-1.5">
- <Label>{{ t("connection.user") }}</Label>
- <Input v-model="nacosUsername" placeholder="nacos" />
+ <div class="grid max-w-md gap-1.5">
+ <div class="grid gap-1.5">
+ <div class="flex h-9 items-center gap-1 rounded-md border bg-muted/20 p-0.5">
+ <Button type="button" size="sm" class="h-8 flex-1" :variant="nacosAuthKind === 'none' ? 'default' : 'ghost'" @click="nacosAuthKind = 'none'">{{ t("connection.nacosAuthNone") }}</Button>
+ <Button type="button" size="sm" class="h-8 flex-1" :variant="nacosAuthKind === 'usernamePassword' ? 'default' : 'ghost'" @click="nacosAuthKind = 'usernamePassword'">{{ t("nacos.nacosUsernamePassword") }}</Button>
+ </div>
+ </div>
</div>
- <div class="grid gap-1.5">
- <Label>{{ t("connection.password") }}</Label>
- <PasswordInput v-model="nacosPassword" />
+ <div v-if="nacosAuthKind === 'usernamePassword'" class="mt-4 grid gap-4 sm:grid-cols-2">
+ <div class="grid gap-1.5">
+ <Label>{{ t("connection.user") }}</Label>
+ <Input v-model="nacosUsername" placeholder="nacos" />
+ </div>
+ <div class="grid gap-1.5">
+ <Label>{{ t("connection.password") }}</Label>
+ <PasswordInput v-model="nacosPassword" />
+ </div>
</div>
- </div>
- <p v-if="isNacosV3AdminPlane && nacosAuthKind === 'usernamePassword'" class="mt-4 border-t pt-4 text-xs leading-5 text-muted-foreground">
- {{ t("nacos.nacosV3AdminNamespaceScopeHint") }}
- </p>
- <p v-else-if="nacosImplementation === 'rnacos' && nacosAuthKind === 'usernamePassword'" class="mt-4 border-t pt-4 text-xs leading-5 text-muted-foreground">
- {{ t("nacos.rnacosNamespaceAccessScopeHint") }}
- </p>
- </section>
+ <p v-if="isNacosV3AdminPlane && nacosAuthKind === 'usernamePassword'" class="mt-4 border-t pt-4 text-xs leading-5 text-muted-foreground">
+ {{ t("nacos.nacosV3AdminNamespaceScopeHint") }}
+ </p>
+ <p v-else-if="nacosImplementation === 'rnacos' && nacosAuthKind === 'usernamePassword'" class="mt-4 border-t pt-4 text-xs leading-5 text-muted-foreground">
+ {{ t("nacos.rnacosNamespaceAccessScopeHint") }}
+ </p>
+ </section>
- <section data-nacos-advanced-hint class="flex items-start gap-3 rounded-lg border border-dashed bg-muted/20 px-4 py-3">
- <CircleHelp class="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
- <div class="min-w-0 flex-1">
- <div class="text-sm font-medium">{{ t("nacos.nacosAdvancedHint") }}</div>
- <p class="mt-0.5 text-xs leading-5 text-muted-foreground">{{ t("nacos.nacosAdvancedHintDescription") }}</p>
- </div>
- <Button type="button" variant="outline" size="sm" class="shrink-0" @click="configTab = 'advanced'">{{ t("nacos.nacosGoAdvanced") }}</Button>
- </section>
- </template>
+ <section data-nacos-advanced-hint class="flex items-start gap-3 rounded-lg border border-dashed bg-muted/20 px-4 py-3">
+ <CircleHelp class="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ <div class="min-w-0 flex-1">
+ <div class="text-sm font-medium">{{ t("nacos.nacosAdvancedHint") }}</div>
+ <p class="mt-0.5 text-xs leading-5 text-muted-foreground">{{ t("nacos.nacosAdvancedHintDescription") }}</p>
+ </div>
+ <Button type="button" variant="outline" size="sm" class="shrink-0" @click="configTab = 'advanced'">{{ t("nacos.nacosGoAdvanced") }}</Button>
+ </section>
+ </template>
- <!-- Redis: host, port, user, password, ssl -->
- <template v-else-if="form.db_type === 'redis'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.mode") }}</Label>
- <div class="col-span-3 flex gap-2">
- <Button size="sm" :variant="form.redis_connection_mode === 'standalone' ? 'default' : 'outline'" @click="form.redis_connection_mode = 'standalone'">
- {{ t("connection.redisStandaloneMode") }}
- </Button>
- <Button size="sm" :variant="form.redis_connection_mode === 'sentinel' ? 'default' : 'outline'" @click="form.redis_connection_mode = 'sentinel'">
- {{ t("connection.redisSentinelMode") }}
- </Button>
- <Button size="sm" :variant="form.redis_connection_mode === 'cluster' ? 'default' : 'outline'" @click="form.redis_connection_mode = 'cluster'">
- {{ t("connection.redisClusterMode") }}
- </Button>
- </div>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ form.redis_connection_mode === "sentinel" ? t("connection.redisFirstSentinel") : form.redis_connection_mode === "cluster" ? t("connection.redisFirstClusterNode") : t("connection.host") }}</Label>
- <Input v-model="form.host" class="col-span-2" />
- <Input v-model.number="form.port" type="number" class="col-span-1" />
- </div>
- <template v-if="form.redis_connection_mode === 'sentinel'">
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.redisSentinelNodes") }}</Label>
- <textarea
- v-model="form.redis_sentinel_nodes"
- class="col-span-3 flex min-h-[76px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- placeholder="sentinel-1:26379&#10;sentinel-2:26379"
- spellcheck="false"
- />
+ <!-- Redis: host, port, user, password, ssl -->
+ <template v-else-if="form.db_type === 'redis'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.mode") }}</Label>
+ <div class="col-span-3 flex gap-2">
+ <Button size="sm" :variant="form.redis_connection_mode === 'standalone' ? 'default' : 'outline'" @click="form.redis_connection_mode = 'standalone'">
+ {{ t("connection.redisStandaloneMode") }}
+ </Button>
+ <Button size="sm" :variant="form.redis_connection_mode === 'sentinel' ? 'default' : 'outline'" @click="form.redis_connection_mode = 'sentinel'">
+ {{ t("connection.redisSentinelMode") }}
+ </Button>
+ <Button size="sm" :variant="form.redis_connection_mode === 'cluster' ? 'default' : 'outline'" @click="form.redis_connection_mode = 'cluster'">
+ {{ t("connection.redisClusterMode") }}
+ </Button>
+ </div>
</div>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.redisSentinelMaster") }}</Label>
- <Input v-model="form.redis_sentinel_master" class="col-span-3" placeholder="mymaster" />
+ <Label :class="connectionLabelClass">{{ form.redis_connection_mode === "sentinel" ? t("connection.redisFirstSentinel") : form.redis_connection_mode === "cluster" ? t("connection.redisFirstClusterNode") : t("connection.host") }}</Label>
+ <Input v-model="form.host" class="col-span-2" />
+ <Input v-model.number="form.port" type="number" class="col-span-1" />
</div>
+ <template v-if="form.redis_connection_mode === 'sentinel'">
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.redisSentinelNodes") }}</Label>
+ <textarea
+ v-model="form.redis_sentinel_nodes"
+ class="col-span-3 flex min-h-[76px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ placeholder="sentinel-1:26379&#10;sentinel-2:26379"
+ spellcheck="false"
+ />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.redisSentinelMaster") }}</Label>
+ <Input v-model="form.redis_sentinel_master" class="col-span-3" placeholder="mymaster" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.redisSentinelUser") }}</Label>
+ <Input v-model="form.redis_sentinel_username" class="col-span-3" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.redisSentinelPassword") }}</Label>
+ <PasswordInput v-model="form.redis_sentinel_password" class="col-span-3" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.redisSentinelTls") }}</Label>
+ <label class="col-span-3 inline-flex items-center gap-2">
+ <input type="checkbox" v-model="form.redis_sentinel_tls" class="mr-0" />
+ <span class="text-xs text-muted-foreground">{{ t("connection.redisSentinelTlsHint") }}</span>
+ </label>
+ </div>
+ </template>
+ <template v-else-if="form.redis_connection_mode === 'cluster'">
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.redisClusterNodes") }}</Label>
+ <textarea
+ v-model="form.redis_cluster_nodes"
+ class="col-span-3 flex min-h-[76px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ placeholder="redis-1:6379&#10;redis-2:6379"
+ spellcheck="false"
+ />
+ </div>
+ </template>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.redisSentinelUser") }}</Label>
- <Input v-model="form.redis_sentinel_username" class="col-span-3" />
+ <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
+ <Input v-model="form.username" class="col-span-3" placeholder="default" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.redisSentinelPassword") }}</Label>
- <PasswordInput v-model="form.redis_sentinel_password" class="col-span-3" />
+ <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" :placeholder="t('connection.databasePlaceholder')" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.redisSentinelTls") }}</Label>
- <label class="col-span-3 inline-flex items-center gap-2">
- <input type="checkbox" v-model="form.redis_sentinel_tls" class="mr-0" />
- <span class="text-xs text-muted-foreground">{{ t("connection.redisSentinelTlsHint") }}</span>
- </label>
+ <Label :class="connectionLabelSmallClass">{{ t("connection.redisKeySeparator") }}</Label>
+ <Input v-model="form.redis_key_separator" class="col-span-3 h-8 text-xs" placeholder=":" />
</div>
- </template>
- <template v-else-if="form.redis_connection_mode === 'cluster'">
<div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.redisClusterNodes") }}</Label>
- <textarea
- v-model="form.redis_cluster_nodes"
- class="col-span-3 flex min-h-[76px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- placeholder="redis-1:6379&#10;redis-2:6379"
- spellcheck="false"
- />
+ <Label :class="connectionLabelTopClass">{{ t("connection.redisKeyTemplates") }}</Label>
+ <div class="col-span-3 space-y-1">
+ <textarea
+ v-model="redisKeyTemplatesText"
+ class="flex min-h-[76px] w-full rounded-md border border-input bg-transparent px-3 py-2 font-mono text-xs shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ :placeholder="t('connection.redisKeyTemplatesPlaceholder')"
+ spellcheck="false"
+ />
+ <p class="text-xs text-muted-foreground">{{ t("connection.redisKeyTemplatesHint") }}</p>
+ </div>
</div>
</template>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
- <Input v-model="form.username" class="col-span-3" placeholder="default" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>
- <PasswordInput v-model="form.password" class="col-span-3" :placeholder="t('connection.databasePlaceholder')" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.redisKeySeparator") }}</Label>
- <Input v-model="form.redis_key_separator" class="col-span-3 h-8 text-xs" placeholder=":" />
- </div>
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.redisKeyTemplates") }}</Label>
- <div class="col-span-3 space-y-1">
- <textarea
- v-model="redisKeyTemplatesText"
- class="flex min-h-[76px] w-full rounded-md border border-input bg-transparent px-3 py-2 font-mono text-xs shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- :placeholder="t('connection.redisKeyTemplatesPlaceholder')"
- spellcheck="false"
- />
- <p class="text-xs text-muted-foreground">{{ t("connection.redisKeyTemplatesHint") }}</p>
- </div>
- </div>
- </template>
- <!-- Consul KV: HTTP endpoint, ACL token and scope -->
- <template v-else-if="form.db_type === 'consul'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.consulAddress") }}</Label>
- <Input v-model="consulServerAddr" class="col-span-3" placeholder="http://127.0.0.1:8500" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.consulToken") }}</Label>
- <PasswordInput v-model="form.password" class="col-span-3" :placeholder="t('connection.consulTokenPlaceholder')" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.consulDatacenter") }}</Label>
- <Input v-model="consulDatacenter" class="col-span-3" placeholder="dc1" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.consulNamespace") }}</Label>
- <Input v-model="consulNamespace" class="col-span-3" placeholder="default" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.consulPartition") }}</Label>
- <Input v-model="consulPartition" class="col-span-3" placeholder="default" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.consulAgentTargetNode") }}</Label>
- <Input v-model="consulAgentTargetNode" class="col-span-3" placeholder="consul-client-1" />
- </div>
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.consulAgentTargetAddress") }}</Label>
- <div class="col-span-3 space-y-1">
- <Input v-model="consulAgentTargetAddress" placeholder="127.0.0.1" />
- <p class="text-xs text-muted-foreground">{{ t("connection.consulAgentTargetHint") }}</p>
+ <!-- Consul KV: HTTP endpoint, ACL token and scope -->
+ <template v-else-if="form.db_type === 'consul'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.consulAddress") }}</Label>
+ <Input v-model="consulServerAddr" class="col-span-3" placeholder="http://127.0.0.1:8500" />
</div>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.consulConsistency") }}</Label>
- <Select v-model="consulConsistency">
- <SelectTrigger class="col-span-3 h-9"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectItem value="default">{{ t("connection.consulConsistencyDefault") }}</SelectItem>
- <SelectItem value="stale">{{ t("connection.consulConsistencyStale") }}</SelectItem>
- <SelectItem value="consistent">{{ t("connection.consulConsistencyConsistent") }}</SelectItem>
- </SelectContent>
- </Select>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.consulTlsSkipVerify") }}</Label>
- <div class="col-span-3 flex items-center gap-2">
- <Switch v-model="consulTlsSkipVerify" />
- <span class="text-xs text-muted-foreground">{{ t("connection.consulTlsSkipVerifyHint") }}</span>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.consulToken") }}</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" :placeholder="t('connection.consulTokenPlaceholder')" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.consulDatacenter") }}</Label>
+ <Input v-model="consulDatacenter" class="col-span-3" placeholder="dc1" />
</div>
- </div>
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.consulMeshFeatures") }}</Label>
- <div class="col-span-3 flex items-start justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
- <div class="space-y-1">
- <div class="text-sm font-medium">{{ t("connection.consulMeshVisible") }}</div>
- <p class="text-xs text-muted-foreground">{{ t("connection.consulMeshVisibleHint") }}</p>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.consulNamespace") }}</Label>
+ <Input v-model="consulNamespace" class="col-span-3" placeholder="default" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.consulPartition") }}</Label>
+ <Input v-model="consulPartition" class="col-span-3" placeholder="default" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.consulAgentTargetNode") }}</Label>
+ <Input v-model="consulAgentTargetNode" class="col-span-3" placeholder="consul-client-1" />
+ </div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.consulAgentTargetAddress") }}</Label>
+ <div class="col-span-3 space-y-1">
+ <Input v-model="consulAgentTargetAddress" placeholder="127.0.0.1" />
+ <p class="text-xs text-muted-foreground">{{ t("connection.consulAgentTargetHint") }}</p>
</div>
- <Switch v-model="consulMeshVisible" class="mt-0.5 shrink-0" />
</div>
- </div>
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.consulOperatorWrites") }}</Label>
- <div class="col-span-3 grid gap-2 rounded-md border bg-muted/20 px-3 py-2 text-xs">
- <label class="flex items-center gap-2"><input v-model="consulOperatorVisible" type="checkbox" />{{ t("connection.consulOperatorVisible") }}</label>
- <label class="flex items-center gap-2"><input v-model="consulOperatorSnapshotRestoreEnabled" type="checkbox" />{{ t("connection.consulOperatorSnapshotRestore") }}</label>
- <label class="flex items-center gap-2"><input v-model="consulOperatorAutopilotWriteEnabled" type="checkbox" />{{ t("connection.consulOperatorAutopilot") }}</label>
- <label class="flex items-center gap-2"><input v-model="consulOperatorRaftWriteEnabled" type="checkbox" />{{ t("connection.consulOperatorRaft") }}</label>
- <label class="flex items-center gap-2"><input v-model="consulOperatorKeyringWriteEnabled" type="checkbox" />{{ t("connection.consulOperatorKeyring") }}</label>
- <label class="flex items-center gap-2"><input v-model="consulOperatorLicenseWriteEnabled" type="checkbox" />{{ t("connection.consulOperatorLicense") }}</label>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.consulConsistency") }}</Label>
+ <Select v-model="consulConsistency">
+ <SelectTrigger class="col-span-3 h-9"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="default">{{ t("connection.consulConsistencyDefault") }}</SelectItem>
+ <SelectItem value="stale">{{ t("connection.consulConsistencyStale") }}</SelectItem>
+ <SelectItem value="consistent">{{ t("connection.consulConsistencyConsistent") }}</SelectItem>
+ </SelectContent>
+ </Select>
</div>
- </div>
- </template>
-
- <!-- etcd: endpoints, user, password, TLS -->
- <template v-else-if="form.db_type === 'etcd'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">API</Label>
- <div class="col-span-3 space-y-1.5">
- <div class="flex flex-wrap gap-2">
- <Button size="sm" :variant="!form.driver_profile || form.driver_profile === 'etcd' ? 'default' : 'outline'" @click="switchEtcdApiVersion('etcd')">v3 (etcd 3.x)</Button>
- <Button size="sm" :variant="form.driver_profile === 'etcd-v2' ? 'default' : 'outline'" @click="switchEtcdApiVersion('etcd-v2')">v2 (etcd 2.x)</Button>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.consulTlsSkipVerify") }}</Label>
+ <div class="col-span-3 flex items-center gap-2">
+ <Switch v-model="consulTlsSkipVerify" />
+ <span class="text-xs text-muted-foreground">{{ t("connection.consulTlsSkipVerifyHint") }}</span>
</div>
- <p v-if="form.driver_profile === 'etcd-v2'" class="text-xs text-muted-foreground">
- {{ t("connection.etcdV2ApiHint") }}
- </p>
</div>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.host") }}</Label>
- <Input v-model="form.host" class="col-span-2" />
- <Input v-model.number="form.port" type="number" class="col-span-1" />
- </div>
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.etcdEndpoints") }}</Label>
- <div class="col-span-3 space-y-1">
- <textarea
- v-model="etcdEndpointsLines"
- class="flex min-h-[76px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- placeholder="http://127.0.0.1:2379&#10;https://etcd-2:2379"
- spellcheck="false"
- />
- <p class="text-xs text-muted-foreground">
- {{ t("connection.etcdEndpointsHint") }}
- </p>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.consulMeshFeatures") }}</Label>
+ <div class="col-span-3 flex items-start justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
+ <div class="space-y-1">
+ <div class="text-sm font-medium">{{ t("connection.consulMeshVisible") }}</div>
+ <p class="text-xs text-muted-foreground">{{ t("connection.consulMeshVisibleHint") }}</p>
+ </div>
+ <Switch v-model="consulMeshVisible" class="mt-0.5 shrink-0" />
+ </div>
</div>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
- <Input v-model="form.username" class="col-span-3" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>
- <PasswordInput v-model="form.password" class="col-span-3" />
- </div>
- </template>
-
- <!-- ZooKeeper: host, connect string, user, password -->
- <template v-else-if="form.db_type === 'zookeeper'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.host") }}</Label>
- <Input v-model="form.host" class="col-span-2" placeholder="127.0.0.1" />
- <Input v-model.number="form.port" type="number" class="col-span-1" />
- </div>
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.zookeeperConnectString") }}</Label>
- <div class="col-span-3 space-y-1">
- <textarea
- v-model="zookeeperConnectString"
- class="flex min-h-[76px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- placeholder="127.0.0.1:2181&#10;zk-2:2181"
- spellcheck="false"
- />
- <p class="text-xs text-muted-foreground">
- {{ t("connection.zookeeperConnectStringHint") }}
- </p>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.consulOperatorWrites") }}</Label>
+ <div class="col-span-3 grid gap-2 rounded-md border bg-muted/20 px-3 py-2 text-xs">
+ <label class="flex items-center gap-2"><input v-model="consulOperatorVisible" type="checkbox" />{{ t("connection.consulOperatorVisible") }}</label>
+ <label class="flex items-center gap-2"><input v-model="consulOperatorSnapshotRestoreEnabled" type="checkbox" />{{ t("connection.consulOperatorSnapshotRestore") }}</label>
+ <label class="flex items-center gap-2"><input v-model="consulOperatorAutopilotWriteEnabled" type="checkbox" />{{ t("connection.consulOperatorAutopilot") }}</label>
+ <label class="flex items-center gap-2"><input v-model="consulOperatorRaftWriteEnabled" type="checkbox" />{{ t("connection.consulOperatorRaft") }}</label>
+ <label class="flex items-center gap-2"><input v-model="consulOperatorKeyringWriteEnabled" type="checkbox" />{{ t("connection.consulOperatorKeyring") }}</label>
+ <label class="flex items-center gap-2"><input v-model="consulOperatorLicenseWriteEnabled" type="checkbox" />{{ t("connection.consulOperatorLicense") }}</label>
+ </div>
</div>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.zookeeperAuthMethod") }}</Label>
- <Select v-model="zookeeperAuthScheme">
- <SelectTrigger class="col-span-3 h-9">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="digest">{{ t("connection.zookeeperAuthDigest") }}</SelectItem>
- <SelectItem value="sasl_digest">{{ t("connection.zookeeperAuthSaslDigest") }}</SelectItem>
- </SelectContent>
- </Select>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
- <Input v-model="form.username" class="col-span-3" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>
- <PasswordInput v-model="form.password" class="col-span-3" />
- </div>
- </template>
-
- <!-- DynamoDB: endpoint, region, AWS credentials -->
- <template v-else-if="form.db_type === 'dynamodb'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.dynamodbEndpoint") }}</Label>
- <Input v-model="form.host" class="col-span-2" placeholder="dynamodb.us-east-1.amazonaws.com" />
- <Input v-model.number="form.port" type="number" class="col-span-1" min="1" max="65535" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <span />
- <label class="col-span-3 flex items-center gap-2 text-sm">
- <input v-model="form.ssl" type="checkbox" />
- <span>{{ t("connection.sslEnable") }}</span>
- </label>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.dynamodbRegion") }}</Label>
- <Input v-model="form.database" class="col-span-3" placeholder="us-east-1" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.dynamodbAccessKeyId") }}</Label>
- <Input v-model="form.username" class="col-span-3" autocomplete="username" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.dynamodbSecretAccessKey") }}</Label>
- <PasswordInput v-model="form.password" class="col-span-3" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.dynamodbSessionToken") }}</Label>
- <PasswordInput v-model="form.connection_string" class="col-span-3" :placeholder="t('connection.dynamodbSessionTokenPlaceholder')" />
- </div>
- </template>
+ </template>
- <!-- MongoDB: URL or form -->
- <template v-else-if="form.db_type === 'mongodb'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.driverMode") }}</Label>
- <div class="col-span-3 flex items-center gap-2">
- <Button size="sm" :variant="mongoDriverMode === 'legacy' ? 'outline' : 'default'" @click="mongoDriverMode = 'auto'">{{ t("connection.mongoDriverAuto") }}</Button>
- <Button size="sm" :variant="mongoDriverMode === 'legacy' ? 'default' : 'outline'" :disabled="mongoUsesOidc" @click="mongoDriverMode = 'legacy'">{{ t("connection.mongoDriverLegacy") }}</Button>
- <Tooltip>
- <TooltipTrigger as-child>
- <CircleHelp class="h-3.5 w-3.5 cursor-help text-muted-foreground hover:text-foreground" />
- </TooltipTrigger>
- <TooltipContent side="top" align="center" class="max-w-[320px] text-xs leading-relaxed">
- {{ t("connection.mongoLegacyHint") }}
- </TooltipContent>
- </Tooltip>
+ <!-- etcd: endpoints, user, password, TLS -->
+ <template v-else-if="form.db_type === 'etcd'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">API</Label>
+ <div class="col-span-3 space-y-1.5">
+ <div class="flex flex-wrap gap-2">
+ <Button size="sm" :variant="!form.driver_profile || form.driver_profile === 'etcd' ? 'default' : 'outline'" @click="switchEtcdApiVersion('etcd')">v3 (etcd 3.x)</Button>
+ <Button size="sm" :variant="form.driver_profile === 'etcd-v2' ? 'default' : 'outline'" @click="switchEtcdApiVersion('etcd-v2')">v2 (etcd 2.x)</Button>
+ </div>
+ <p v-if="form.driver_profile === 'etcd-v2'" class="text-xs text-muted-foreground">
+ {{ t("connection.etcdV2ApiHint") }}
+ </p>
+ </div>
</div>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.mode") }}</Label>
- <div class="col-span-3 flex gap-2">
- <Button size="sm" :variant="mongoUseUrl ? 'outline' : 'default'" @click="mongoUseUrl = false">{{ t("connection.modeForm") }}</Button>
- <Button size="sm" :variant="mongoUseUrl ? 'default' : 'outline'" @click="mongoUseUrl = true">URL</Button>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.host") }}</Label>
+ <Input v-model="form.host" class="col-span-2" />
+ <Input v-model.number="form.port" type="number" class="col-span-1" />
</div>
- </div>
- <template v-if="mongoUseUrl">
<div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">URL</Label>
- <textarea
- v-model="form.connection_string"
- class="col-span-3 flex min-h-[80px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- placeholder="mongodb+srv://user:[email protected]/mydb"
- />
- <p v-if="mongoUsesOidc" class="col-start-2 col-span-3 text-xs text-muted-foreground">
- {{ t("connection.oidcBrowserAuthHint") }}
- </p>
+ <Label :class="connectionLabelTopClass">{{ t("connection.etcdEndpoints") }}</Label>
+ <div class="col-span-3 space-y-1">
+ <textarea
+ v-model="etcdEndpointsLines"
+ class="flex min-h-[76px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ placeholder="http://127.0.0.1:2379&#10;https://etcd-2:2379"
+ spellcheck="false"
+ />
+ <p class="text-xs text-muted-foreground">
+ {{ t("connection.etcdEndpointsHint") }}
+ </p>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
+ <Input v-model="form.username" class="col-span-3" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" />
</div>
</template>
- <template v-else>
+
+ <!-- ZooKeeper: host, connect string, user, password -->
+ <template v-else-if="form.db_type === 'zookeeper'">
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.host") }}</Label>
- <Input v-model="form.host" class="col-span-2" />
+ <Input v-model="form.host" class="col-span-2" placeholder="127.0.0.1" />
<Input v-model.number="form.port" type="number" class="col-span-1" />
</div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.zookeeperConnectString") }}</Label>
+ <div class="col-span-3 space-y-1">
+ <textarea
+ v-model="zookeeperConnectString"
+ class="flex min-h-[76px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ placeholder="127.0.0.1:2181&#10;zk-2:2181"
+ spellcheck="false"
+ />
+ <p class="text-xs text-muted-foreground">
+ {{ t("connection.zookeeperConnectStringHint") }}
+ </p>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.zookeeperAuthMethod") }}</Label>
+ <Select v-model="zookeeperAuthScheme">
+ <SelectTrigger class="col-span-3 h-9">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="digest">{{ t("connection.zookeeperAuthDigest") }}</SelectItem>
+ <SelectItem value="sasl_digest">{{ t("connection.zookeeperAuthSaslDigest") }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
+ <Input v-model="form.username" class="col-span-3" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" />
+ </div>
+ </template>
+
+ <!-- DynamoDB: endpoint, region, AWS credentials -->
+ <template v-else-if="form.db_type === 'dynamodb'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.dynamodbEndpoint") }}</Label>
+ <Input v-model="form.host" class="col-span-2" placeholder="dynamodb.us-east-1.amazonaws.com" />
+ <Input v-model.number="form.port" type="number" class="col-span-1" min="1" max="65535" />
+ </div>
<div class="grid grid-cols-4 items-center gap-4">
<span />
<label class="col-span-3 flex items-center gap-2 text-sm">
- <input type="checkbox" v-model="form.ssl" class="mr-0" />
+ <input v-model="form.ssl" type="checkbox" />
<span>{{ t("connection.sslEnable") }}</span>
</label>
</div>
- <template v-if="form.ssl">
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mongoTlsAllowInvalidCertificates") }}</Label>
- <label class="col-span-3 flex items-start gap-2 cursor-pointer">
- <input v-model="mongoTlsAllowInvalidCertificates" type="checkbox" class="mr-0 mt-0.5" />
- <span class="text-xs leading-5 text-muted-foreground">
- {{ t("connection.mongoTlsAllowInvalidCertificatesHint") }}
- </span>
- </label>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.dynamodbRegion") }}</Label>
+ <Input v-model="form.database" class="col-span-3" placeholder="us-east-1" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.dynamodbAccessKeyId") }}</Label>
+ <Input v-model="form.username" class="col-span-3" autocomplete="username" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.dynamodbSecretAccessKey") }}</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.dynamodbSessionToken") }}</Label>
+ <PasswordInput v-model="form.connection_string" class="col-span-3" :placeholder="t('connection.dynamodbSessionTokenPlaceholder')" />
+ </div>
+ </template>
+
+ <!-- MongoDB: URL or form -->
+ <template v-else-if="form.db_type === 'mongodb'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.driverMode") }}</Label>
+ <div class="col-span-3 flex items-center gap-2">
+ <Button size="sm" :variant="mongoDriverMode === 'legacy' ? 'outline' : 'default'" @click="mongoDriverMode = 'auto'">{{ t("connection.mongoDriverAuto") }}</Button>
+ <Button size="sm" :variant="mongoDriverMode === 'legacy' ? 'default' : 'outline'" :disabled="mongoUsesOidc" @click="mongoDriverMode = 'legacy'">{{ t("connection.mongoDriverLegacy") }}</Button>
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <CircleHelp class="h-3.5 w-3.5 cursor-help text-muted-foreground hover:text-foreground" />
+ </TooltipTrigger>
+ <TooltipContent side="top" align="center" class="max-w-[320px] text-xs leading-relaxed">
+ {{ t("connection.mongoLegacyHint") }}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.mode") }}</Label>
+ <div class="col-span-3 flex gap-2">
+ <Button size="sm" :variant="mongoUseUrl ? 'outline' : 'default'" @click="mongoUseUrl = false">{{ t("connection.modeForm") }}</Button>
+ <Button size="sm" :variant="mongoUseUrl ? 'default' : 'outline'" @click="mongoUseUrl = true">URL</Button>
</div>
+ </div>
+ <template v-if="mongoUseUrl">
<div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mongoRetryWrites") }}</Label>
- <label class="col-span-3 flex items-start gap-2 cursor-pointer">
- <input v-model="mongoRetryWrites" type="checkbox" class="mr-0 mt-0.5" />
- <span class="text-xs leading-5 text-muted-foreground">
- {{ t("connection.mongoRetryWritesHint") }}
- </span>
- </label>
+ <Label :class="connectionLabelTopClass">URL</Label>
+ <textarea
+ v-model="form.connection_string"
+ class="col-span-3 flex min-h-[80px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ placeholder="mongodb+srv://user:[email protected]/mydb"
+ />
+ <p v-if="mongoUsesOidc" class="col-start-2 col-span-3 text-xs text-muted-foreground">
+ {{ t("connection.oidcBrowserAuthHint") }}
+ </p>
</div>
+ </template>
+ <template v-else>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.caCertPath") }}</Label>
- <div class="col-span-3 flex items-center gap-1">
- <Input v-model="form.ca_cert_path" class="flex-1" :placeholder="t('connection.caCertPathPlaceholder')" />
- <Tooltip v-if="isDesktop">
- <TooltipTrigger as-child>
- <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseCaCertPath">
- <FolderOpen class="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{{ t("connection.caCertPathBrowse") }}</TooltipContent>
- </Tooltip>
+ <Label :class="connectionLabelClass">{{ t("connection.host") }}</Label>
+ <Input v-model="form.host" class="col-span-2" />
+ <Input v-model.number="form.port" type="number" class="col-span-1" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <label class="col-span-3 flex items-center gap-2 text-sm">
+ <input type="checkbox" v-model="form.ssl" class="mr-0" />
+ <span>{{ t("connection.sslEnable") }}</span>
+ </label>
+ </div>
+ <template v-if="form.ssl">
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mongoTlsAllowInvalidCertificates") }}</Label>
+ <label class="col-span-3 flex items-start gap-2 cursor-pointer">
+ <input v-model="mongoTlsAllowInvalidCertificates" type="checkbox" class="mr-0 mt-0.5" />
+ <span class="text-xs leading-5 text-muted-foreground">
+ {{ t("connection.mongoTlsAllowInvalidCertificatesHint") }}
+ </span>
+ </label>
+ </div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mongoRetryWrites") }}</Label>
+ <label class="col-span-3 flex items-start gap-2 cursor-pointer">
+ <input v-model="mongoRetryWrites" type="checkbox" class="mr-0 mt-0.5" />
+ <span class="text-xs leading-5 text-muted-foreground">
+ {{ t("connection.mongoRetryWritesHint") }}
+ </span>
+ </label>
</div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.caCertPath") }}</Label>
+ <div class="col-span-3 flex items-center gap-1">
+ <Input v-model="form.ca_cert_path" class="flex-1" :placeholder="t('connection.caCertPathPlaceholder')" />
+ <Tooltip v-if="isDesktop">
+ <TooltipTrigger as-child>
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseCaCertPath">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.caCertPathBrowse") }}</TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ </template>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
+ <Input v-model="form.username" class="col-span-3" />
+ </div>
+ <div v-if="mongoAuthMechanism !== 'MONGODB-OIDC'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.defaultDatabase") }}</Label>
+ <Input v-model="form.database" class="col-span-3" :placeholder="t('connection.databasePlaceholder')" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.authDatabase") }}</Label>
+ <Input v-model="mongoAuthDatabase" class="col-span-3" :disabled="mongoAuthMechanism === 'MONGODB-OIDC'" :placeholder="mongoAuthMechanism === 'MONGODB-OIDC' ? '$external' : t('connection.authDatabasePlaceholder')" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.authMechanism") }}</Label>
+ <Select v-model="mongoAuthMechanism">
+ <SelectTrigger class="col-span-3">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="default">{{ t("connection.authMechanismDefault") }}</SelectItem>
+ <SelectItem value="SCRAM-SHA-1">SCRAM-SHA-1</SelectItem>
+ <SelectItem value="SCRAM-SHA-256">SCRAM-SHA-256</SelectItem>
+ <SelectItem value="MONGODB-OIDC">MONGODB-OIDC</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <div v-if="mongoAuthMechanism === 'MONGODB-OIDC'" class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <p class="col-span-3 text-xs text-muted-foreground">
+ {{ t("connection.oidcBrowserAuthHint") }}
+ </p>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.urlParams") }}</Label>
+ <Input v-model="form.url_params" class="col-span-3" placeholder="replicaSet=rs0&authSource=admin" />
</div>
</template>
+ </template>
+
+ <!-- MQTT: broker address, client ID, protocol version, auth, TLS -->
+ <template v-else-if="form.db_type === 'mqtt'">
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
- <Input v-model="form.username" class="col-span-3" />
- </div>
- <div v-if="mongoAuthMechanism !== 'MONGODB-OIDC'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>
- <PasswordInput v-model="form.password" class="col-span-3" />
+ <Label :class="connectionLabelClass">{{ t("connection.mqttBrokerAddress") }}</Label>
+ <Input v-model="mqttHost" class="col-span-3" :placeholder="t('connection.mqttBrokerAddressPlaceholder')" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.defaultDatabase") }}</Label>
- <Input v-model="form.database" class="col-span-3" :placeholder="t('connection.databasePlaceholder')" />
+ <Label :class="connectionLabelClass">{{ t("connection.mqttBrokerPort") }}</Label>
+ <Input v-model.number="mqttPort" type="number" class="col-span-3 w-24" min="1" max="65535" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.authDatabase") }}</Label>
- <Input v-model="mongoAuthDatabase" class="col-span-3" :disabled="mongoAuthMechanism === 'MONGODB-OIDC'" :placeholder="mongoAuthMechanism === 'MONGODB-OIDC' ? '$external' : t('connection.authDatabasePlaceholder')" />
+ <Label :class="connectionLabelClass">{{ t("connection.mqttClientId") }}</Label>
+ <Input v-model="mqttClientId" class="col-span-3" :placeholder="t('connection.mqttClientIdPlaceholder')" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.authMechanism") }}</Label>
- <Select v-model="mongoAuthMechanism">
- <SelectTrigger class="col-span-3">
+ <Label :class="connectionLabelClass">{{ t("connection.mqttProtocolVersion") }}</Label>
+ <Select v-model="mqttProtocolVersion">
+ <SelectTrigger class="col-span-3 h-9">
<SelectValue />
</SelectTrigger>
<SelectContent>
- <SelectItem value="default">{{ t("connection.authMechanismDefault") }}</SelectItem>
- <SelectItem value="SCRAM-SHA-1">SCRAM-SHA-1</SelectItem>
- <SelectItem value="SCRAM-SHA-256">SCRAM-SHA-256</SelectItem>
- <SelectItem value="MONGODB-OIDC">MONGODB-OIDC</SelectItem>
+ <SelectItem value="v5">MQTT 5.0</SelectItem>
+ <SelectItem value="v4">MQTT 3.1.1</SelectItem>
+ <SelectItem value="v3">MQTT 3.1</SelectItem>
</SelectContent>
</Select>
</div>
- <div v-if="mongoAuthMechanism === 'MONGODB-OIDC'" class="grid grid-cols-4 items-start gap-4">
- <span />
- <p class="col-span-3 text-xs text-muted-foreground">
- {{ t("connection.oidcBrowserAuthHint") }}
- </p>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqttTransport") }}</Label>
+ <div class="col-span-3 flex gap-2">
+ <Button size="sm" :variant="mqttTransportMode === 'tcp' ? 'default' : 'outline'" @click="mqttTransportMode = 'tcp'">{{ t("connection.mqttTransportTcp") }}</Button>
+ <Button size="sm" :variant="mqttTransportMode === 'websocket' ? 'default' : 'outline'" @click="mqttTransportMode = 'websocket'">{{ t("connection.mqttTransportWebSocket") }}</Button>
+ </div>
+ </div>
+ <div v-if="mqttTransportMode === 'websocket'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqttWsPath") }}</Label>
+ <Input v-model="mqttWsPath" class="col-span-3" :placeholder="t('connection.mqttWsPathPlaceholder')" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.urlParams") }}</Label>
- <Input v-model="form.url_params" class="col-span-3" placeholder="replicaSet=rs0&authSource=admin" />
+ <Label :class="connectionLabelClass">{{ t("connection.mqAuth") }}</Label>
+ <div class="col-span-3 flex gap-2">
+ <Button size="sm" :variant="mqttAuthKind === 'none' ? 'default' : 'outline'" @click="mqttAuthKind = 'none'">{{ t("connection.mqAuthNone") }}</Button>
+ <Button size="sm" :variant="mqttAuthKind === 'password' ? 'default' : 'outline'" @click="mqttAuthKind = 'password'">{{ t("connection.mqAuthBasic") }}</Button>
+ <Button size="sm" :variant="mqttAuthKind === 'certificate' ? 'default' : 'outline'" @click="mqttAuthKind = 'certificate'">{{ t("connection.mqttAuthCertificate") }}</Button>
+ </div>
</div>
- </template>
- </template>
-
- <!-- MQTT: broker address, client ID, protocol version, auth, TLS -->
- <template v-else-if="form.db_type === 'mqtt'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqttBrokerAddress") }}</Label>
- <Input v-model="mqttHost" class="col-span-3" :placeholder="t('connection.mqttBrokerAddressPlaceholder')" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqttBrokerPort") }}</Label>
- <Input v-model.number="mqttPort" type="number" class="col-span-3 w-24" min="1" max="65535" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqttClientId") }}</Label>
- <Input v-model="mqttClientId" class="col-span-3" :placeholder="t('connection.mqttClientIdPlaceholder')" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqttProtocolVersion") }}</Label>
- <Select v-model="mqttProtocolVersion">
- <SelectTrigger class="col-span-3 h-9">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="v5">MQTT 5.0</SelectItem>
- <SelectItem value="v4">MQTT 3.1.1</SelectItem>
- <SelectItem value="v3">MQTT 3.1</SelectItem>
- </SelectContent>
- </Select>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqttTransport") }}</Label>
- <div class="col-span-3 flex gap-2">
- <Button size="sm" :variant="mqttTransportMode === 'tcp' ? 'default' : 'outline'" @click="mqttTransportMode = 'tcp'">{{ t("connection.mqttTransportTcp") }}</Button>
- <Button size="sm" :variant="mqttTransportMode === 'websocket' ? 'default' : 'outline'" @click="mqttTransportMode = 'websocket'">{{ t("connection.mqttTransportWebSocket") }}</Button>
+ <template v-if="mqttAuthKind === 'password'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqttUsername") }}</Label>
+ <Input v-model="mqttUsername" class="col-span-3" :placeholder="t('connection.mqttUsernamePlaceholder')" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqttPassword") }}</Label>
+ <Input v-model="mqttPassword" type="password" class="col-span-3" :placeholder="t('connection.mqttPasswordPlaceholder')" />
+ </div>
+ </template>
+ <template v-else-if="mqttAuthKind === 'certificate'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqttCaCertPath") }}</Label>
+ <Input v-model="mqttCaCertPath" class="col-span-3" placeholder="/path/to/ca.pem" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqttClientCertPath") }}</Label>
+ <Input v-model="mqttClientCertPath" class="col-span-3" placeholder="/path/to/client.crt" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqttClientKeyPath") }}</Label>
+ <Input v-model="mqttClientKeyPath" class="col-span-3" placeholder="/path/to/client.key" />
+ </div>
+ </template>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqttTls") }}</Label>
+ <div class="col-span-3 flex items-center gap-2">
+ <Switch v-model="mqttTls" />
+ <Label class="text-sm" :class="mqttTls ? '' : 'text-muted-foreground'">TLS</Label>
+ <template v-if="mqttTls">
+ <Switch v-model="mqttTlsSkipVerify" class="ml-4" />
+ <Label class="text-sm" :class="mqttTlsSkipVerify ? '' : 'text-muted-foreground'">{{ t("connection.mqttTlsSkipVerify") }}</Label>
+ </template>
+ </div>
</div>
- </div>
- <div v-if="mqttTransportMode === 'websocket'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqttWsPath") }}</Label>
- <Input v-model="mqttWsPath" class="col-span-3" :placeholder="t('connection.mqttWsPathPlaceholder')" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqAuth") }}</Label>
- <div class="col-span-3 flex gap-2">
- <Button size="sm" :variant="mqttAuthKind === 'none' ? 'default' : 'outline'" @click="mqttAuthKind = 'none'">{{ t("connection.mqAuthNone") }}</Button>
- <Button size="sm" :variant="mqttAuthKind === 'password' ? 'default' : 'outline'" @click="mqttAuthKind = 'password'">{{ t("connection.mqAuthBasic") }}</Button>
- <Button size="sm" :variant="mqttAuthKind === 'certificate' ? 'default' : 'outline'" @click="mqttAuthKind = 'certificate'">{{ t("connection.mqttAuthCertificate") }}</Button>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.mqttKeepAlive") }}</Label>
+ <Input v-model.number="mqttKeepAliveSecs" type="number" class="col-span-3 w-32" min="1" max="65535" />
</div>
- </div>
- <template v-if="mqttAuthKind === 'password'">
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqttUsername") }}</Label>
- <Input v-model="mqttUsername" class="col-span-3" :placeholder="t('connection.mqttUsernamePlaceholder')" />
+ <Label :class="connectionLabelClass">{{ t("connection.mqttConnectTimeout") }}</Label>
+ <Input v-model.number="mqttConnectTimeoutSecs" type="number" class="col-span-3 w-32" min="1" max="300" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqttPassword") }}</Label>
- <Input v-model="mqttPassword" type="password" class="col-span-3" :placeholder="t('connection.mqttPasswordPlaceholder')" />
+ <Label :class="connectionLabelClass">最大报文(字节)</Label>
+ <Input v-model.number="mqttMaxPacketSizeBytes" type="number" class="col-span-3 w-40" min="1024" max="268435455" />
</div>
</template>
- <template v-else-if="mqttAuthKind === 'certificate'">
+
+ <template v-else-if="form.db_type === 'victoriametrics'">
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqttCaCertPath") }}</Label>
- <Input v-model="mqttCaCertPath" class="col-span-3" placeholder="/path/to/ca.pem" />
+ <Label :class="connectionLabelClass">{{ t("connection.host") }}</Label>
+ <Input v-model="form.host" class="col-span-2" />
+ <Input v-model.number="form.port" type="number" class="col-span-1" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqttClientCertPath") }}</Label>
- <Input v-model="mqttClientCertPath" class="col-span-3" placeholder="/path/to/client.crt" />
+ <span />
+ <label class="col-span-3 flex items-center gap-2 text-sm">
+ <input type="checkbox" v-model="form.ssl" />
+ <span>{{ t("connection.sslEnable") }}</span>
+ </label>
</div>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqttClientKeyPath") }}</Label>
- <Input v-model="mqttClientKeyPath" class="col-span-3" placeholder="/path/to/client.key" />
+ <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
+ <Input v-model="form.username" class="col-span-3" autocomplete="username" />
</div>
- </template>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqttTls") }}</Label>
- <div class="col-span-3 flex items-center gap-2">
- <Switch v-model="mqttTls" />
- <Label class="text-sm" :class="mqttTls ? '' : 'text-muted-foreground'">TLS</Label>
- <template v-if="mqttTls">
- <Switch v-model="mqttTlsSkipVerify" class="ml-4" />
- <Label class="text-sm" :class="mqttTlsSkipVerify ? '' : 'text-muted-foreground'">{{ t("connection.mqttTlsSkipVerify") }}</Label>
- </template>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" />
</div>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqttKeepAlive") }}</Label>
- <Input v-model.number="mqttKeepAliveSecs" type="number" class="col-span-3 w-32" min="1" max="65535" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.mqttConnectTimeout") }}</Label>
- <Input v-model.number="mqttConnectTimeoutSecs" type="number" class="col-span-3 w-32" min="1" max="300" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">最大报文(字节)</Label>
- <Input v-model.number="mqttMaxPacketSizeBytes" type="number" class="col-span-3 w-40" min="1024" max="268435455" />
- </div>
- </template>
-
- <template v-else-if="form.db_type === 'victoriametrics'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.host") }}</Label>
- <Input v-model="form.host" class="col-span-2" />
- <Input v-model.number="form.port" type="number" class="col-span-1" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <span />
- <label class="col-span-3 flex items-center gap-2 text-sm">
- <input type="checkbox" v-model="form.ssl" />
- <span>{{ t("connection.sslEnable") }}</span>
- </label>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
- <Input v-model="form.username" class="col-span-3" autocomplete="username" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>
- <PasswordInput v-model="form.password" class="col-span-3" />
- </div>
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.victoriametricsApiPath") }}</Label>
- <div class="col-span-3 space-y-1.5">
- <Input v-model="victoriaMetricsApiPath" placeholder="/prometheus" />
- <p class="text-xs leading-5 text-muted-foreground">{{ t("connection.victoriametricsApiPathHint") }}</p>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.victoriametricsApiPath") }}</Label>
+ <div class="col-span-3 space-y-1.5">
+ <Input v-model="victoriaMetricsApiPath" placeholder="/prometheus" />
+ <p class="text-xs leading-5 text-muted-foreground">{{ t("connection.victoriametricsApiPathHint") }}</p>
+ </div>
</div>
- </div>
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.victoriametricsLookback") }}</Label>
- <div class="col-span-3 space-y-1.5">
- <Input v-model="victoriaMetricsLookback" class="w-28" placeholder="1h" />
- <p class="text-xs leading-5 text-muted-foreground">{{ t("connection.victoriametricsLookbackHint") }}</p>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.victoriametricsLookback") }}</Label>
+ <div class="col-span-3 space-y-1.5">
+ <Input v-model="victoriaMetricsLookback" class="w-28" placeholder="1h" />
+ <p class="text-xs leading-5 text-muted-foreground">{{ t("connection.victoriametricsLookbackHint") }}</p>
+ </div>
</div>
- </div>
- </template>
+ </template>
- <!-- InfluxDB: v1 username/password or v2 token/org/bucket -->
- <template v-else-if="form.db_type === 'influxdb'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.version") }}</Label>
- <Select v-model="influxDbVersion">
- <SelectTrigger class="col-span-3">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="1">InfluxDB 1.x</SelectItem>
- <SelectItem value="2">InfluxDB 2.x</SelectItem>
- <SelectItem value="3">InfluxDB 3.x</SelectItem>
- </SelectContent>
- </Select>
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.host") }}</Label>
- <Input v-model="form.host" class="col-span-2" />
- <Input v-model.number="form.port" type="number" class="col-span-1" />
- </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <span />
- <label class="col-span-3 flex items-center gap-2 text-sm">
- <input type="checkbox" v-model="form.ssl" class="mr-0" />
- <span>{{ t("connection.sslEnable") }}</span>
- </label>
- </div>
- <template v-if="influxDbVersion === '2'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">Organization</Label>
- <Input v-model="influxDbOrg" class="col-span-3" placeholder="my-org" />
- </div>
+ <!-- InfluxDB: v1 username/password or v2 token/org/bucket -->
+ <template v-else-if="form.db_type === 'influxdb'">
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">Bucket</Label>
- <Input v-model="form.database" class="col-span-3" placeholder="my-bucket" />
+ <Label :class="connectionLabelSmallClass">{{ t("connection.version") }}</Label>
+ <Select v-model="influxDbVersion">
+ <SelectTrigger class="col-span-3">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="1">InfluxDB 1.x</SelectItem>
+ <SelectItem value="2">InfluxDB 2.x</SelectItem>
+ <SelectItem value="3">InfluxDB 3.x</SelectItem>
+ </SelectContent>
+ </Select>
</div>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">Token</Label>
- <PasswordInput v-model="form.password" class="col-span-3" />
+ <Label :class="connectionLabelClass">{{ t("connection.host") }}</Label>
+ <Input v-model="form.host" class="col-span-2" />
+ <Input v-model.number="form.port" type="number" class="col-span-1" />
</div>
- </template>
- <template v-else-if="influxDbVersion === '3'">
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.database") }}</Label>
- <Input v-model="form.database" class="col-span-3" placeholder="my-database" />
+ <span />
+ <label class="col-span-3 flex items-center gap-2 text-sm">
+ <input type="checkbox" v-model="form.ssl" class="mr-0" />
+ <span>{{ t("connection.sslEnable") }}</span>
+ </label>
</div>
+ <template v-if="influxDbVersion === '2'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">Organization</Label>
+ <Input v-model="influxDbOrg" class="col-span-3" placeholder="my-org" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">Bucket</Label>
+ <Input v-model="form.database" class="col-span-3" placeholder="my-bucket" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">Token</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" />
+ </div>
+ </template>
+ <template v-else-if="influxDbVersion === '3'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.database") }}</Label>
+ <Input v-model="form.database" class="col-span-3" placeholder="my-database" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">Token</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" />
+ </div>
+ </template>
+ <template v-else>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
+ <Input v-model="form.username" class="col-span-3" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.database") }}</Label>
+ <Input v-model="form.database" class="col-span-3" :placeholder="t('connection.databasePlaceholder')" />
+ </div>
+ </template>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">Token</Label>
- <PasswordInput v-model="form.password" class="col-span-3" />
+ <Label :class="connectionLabelClass">{{ t("connection.urlParams") }}</Label>
+ <Input v-model="form.url_params" class="col-span-3" :placeholder="influxDbVersion === '2' ? 'precision=ns' : influxDbVersion === '3' ? '' : 'epoch=ms'" />
</div>
</template>
- <template v-else>
+
+ <!-- Turso: simplified form (URL + Token) -->
+ <template v-else-if="form.db_type === 'turso'">
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
- <Input v-model="form.username" class="col-span-3" />
+ <Label :class="connectionLabelClass">{{ t("connection.host") }}</Label>
+ <Input v-model="form.host" class="col-span-3" :placeholder="t('connection.tursoHostPlaceholder')" />
+ </div>
+
+ <div class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <p class="col-span-3 text-xs text-muted-foreground">{{ t("connection.tursoHostHint") }}</p>
</div>
+
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>
- <PasswordInput v-model="form.password" class="col-span-3" />
+ <Label :class="connectionLabelClass">Auth Token</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" placeholder="eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9..." />
+ </div>
+
+ <div class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <p class="col-span-3 text-xs text-muted-foreground">{{ t("connection.tursoTokenHint") }} <code class="px-1 py-0.5 rounded bg-muted text-xs">turso db tokens create &lt;database-name&gt;</code></p>
</div>
+
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.database") }}</Label>
- <Input v-model="form.database" class="col-span-3" :placeholder="t('connection.databasePlaceholder')" />
+ <Label :class="connectionLabelClass">{{ t("connection.urlParams") }}</Label>
+ <Input v-model="form.url_params" class="col-span-3" :placeholder="t('connection.tursoUrlParamsPlaceholder')" />
</div>
</template>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.urlParams") }}</Label>
- <Input v-model="form.url_params" class="col-span-3" :placeholder="influxDbVersion === '2' ? 'precision=ns' : influxDbVersion === '3' ? '' : 'epoch=ms'" />
- </div>
- </template>
-
- <!-- Turso: simplified form (URL + Token) -->
- <template v-else-if="form.db_type === 'turso'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.host") }}</Label>
- <Input v-model="form.host" class="col-span-3" :placeholder="t('connection.tursoHostPlaceholder')" />
- </div>
- <div class="grid grid-cols-4 items-start gap-4">
- <span />
- <p class="col-span-3 text-xs text-muted-foreground">{{ t("connection.tursoHostHint") }}</p>
- </div>
+ <template v-else-if="form.db_type === 'cloudflare-d1'">
+ <CloudflareD1ConnectionFields v-model:account-id="form.host" v-model:database-id="form.database" v-model:api-token="form.password" />
+ </template>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">Auth Token</Label>
- <PasswordInput v-model="form.password" class="col-span-3" placeholder="eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9..." />
- </div>
+ <!-- MySQL / PostgreSQL: host, port, user, password, database -->
+ <template v-else>
+ <div v-if="form.db_type === 'ignite' || form.db_type === 'ignite3'" class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.igniteVersion") }}</Label>
+ <div class="col-span-3 grid grid-cols-2 gap-2">
+ <button
+ v-for="profile in IGNITE_CONNECTION_PROFILES"
+ :key="profile.value"
+ type="button"
+ class="min-w-0 rounded-md border px-3 py-2.5 text-left transition-colors hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ :class="form.db_type === profile.value ? 'border-primary bg-primary/5 shadow-sm' : 'border-border bg-background'"
+ :aria-pressed="form.db_type === profile.value"
+ @click="selectIgniteConnectionProfile(profile.value)"
+ >
+ <span class="block truncate text-sm font-medium">{{ profile.title }}</span>
+ </button>
+ </div>
+ </div>
- <div class="grid grid-cols-4 items-start gap-4">
- <span />
- <p class="col-span-3 text-xs text-muted-foreground">{{ t("connection.tursoTokenHint") }} <code class="px-1 py-0.5 rounded bg-muted text-xs">turso db tokens create &lt;database-name&gt;</code></p>
- </div>
+ <div v-if="form.db_type === 'elasticsearch'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.mode") }}</Label>
+ <div class="col-span-3 grid h-8 grid-cols-2 overflow-hidden rounded-md border border-input bg-muted/30 p-0.5">
+ <button
+ type="button"
+ class="h-7 rounded-sm px-3 text-sm transition-colors"
+ :class="elasticsearchConnectionMode === 'direct' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
+ :aria-pressed="elasticsearchConnectionMode === 'direct'"
+ @click="switchElasticsearchConnectionMode('direct')"
+ >
+ {{ t("connection.elasticsearchDirectMode") }}
+ </button>
+ <button
+ type="button"
+ class="h-7 rounded-sm px-3 text-sm transition-colors"
+ :class="elasticsearchConnectionMode === 'kibana' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
+ :aria-pressed="elasticsearchConnectionMode === 'kibana'"
+ @click="switchElasticsearchConnectionMode('kibana')"
+ >
+ {{ t("connection.elasticsearchKibanaProxyMode") }}
+ </button>
+ </div>
+ </div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.urlParams") }}</Label>
- <Input v-model="form.url_params" class="col-span-3" :placeholder="t('connection.tursoUrlParamsPlaceholder')" />
- </div>
- </template>
+ <div v-if="form.db_type === 'sqlserver'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.driverMode") }}</Label>
+ <div class="col-span-3 flex items-center gap-2">
+ <Button size="sm" :variant="sqlServerDriverMode === 'legacy' ? 'outline' : 'default'" :disabled="agentInstallRunning" @click="setSqlServerDriverMode('auto')">{{ t("connection.mongoDriverAuto") }}</Button>
+ <Button size="sm" :variant="sqlServerDriverMode === 'legacy' ? 'default' : 'outline'" :disabled="agentInstallRunning" @click="setSqlServerDriverMode('legacy')">{{ t("connection.mongoDriverLegacy") }}</Button>
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <CircleHelp class="h-3.5 w-3.5 cursor-help text-muted-foreground hover:text-foreground" />
+ </TooltipTrigger>
+ <TooltipContent side="top" align="center" class="max-w-[320px] whitespace-pre-line text-xs leading-relaxed">
+ {{ t("connection.sqlServerLegacyCompatibilityModeHint") }}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
- <template v-else-if="form.db_type === 'cloudflare-d1'">
- <CloudflareD1ConnectionFields v-model:account-id="form.host" v-model:database-id="form.database" v-model:api-token="form.password" />
- </template>
+ <div v-if="form.db_type === 'dameng'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.driverMode") }}</Label>
+ <div class="col-span-3 flex items-center gap-2">
+ <Button size="sm" :variant="damengDriverMode === 'builtin' ? 'default' : 'outline'" @click="setDamengDriverMode('builtin')">
+ {{ t("connection.damengBuiltinDriver") }}
+ </Button>
+ <Button size="sm" :variant="damengDriverMode === 'custom' ? 'default' : 'outline'" @click="setDamengDriverMode('custom')">
+ {{ t("connection.damengCustomDriver") }}
+ </Button>
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <CircleHelp class="h-3.5 w-3.5 cursor-help text-muted-foreground hover:text-foreground" />
+ </TooltipTrigger>
+ <TooltipContent side="top" align="center" class="max-w-[320px] text-xs leading-relaxed">
+ {{ t("connection.damengDriverModeHint") }}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
- <!-- MySQL / PostgreSQL: host, port, user, password, database -->
- <template v-else>
- <div v-if="form.db_type === 'ignite' || form.db_type === 'ignite3'" class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.igniteVersion") }}</Label>
- <div class="col-span-3 grid grid-cols-2 gap-2">
- <button
- v-for="profile in IGNITE_CONNECTION_PROFILES"
- :key="profile.value"
- type="button"
- class="min-w-0 rounded-md border px-3 py-2.5 text-left transition-colors hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- :class="form.db_type === profile.value ? 'border-primary bg-primary/5 shadow-sm' : 'border-border bg-background'"
- :aria-pressed="form.db_type === profile.value"
- @click="selectIgniteConnectionProfile(profile.value)"
- >
- <span class="block truncate text-sm font-medium">{{ profile.title }}</span>
- </button>
+ <!-- GaussDB: multi-host dynamic list -->
+ <template v-if="form.db_type === 'gaussdb'">
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.host") }}</Label>
+ <div class="col-span-3 space-y-2">
+ <div v-for="(entry, idx) in gaussdbHostEntries" :key="idx" class="flex items-start gap-2">
+ <Input v-model="entry.host" class="flex-1 min-w-0 break-all" placeholder="127.0.0.1" />
+ <Input v-model.number="entry.port" type="number" class="w-24 shrink-0" />
+ <Button type="button" variant="outline" size="icon" class="h-8 w-8 shrink-0" :disabled="gaussdbHostEntries.length <= 1" @click="removeGaussdbHostEntry(idx)">
+ <Trash2 class="h-4 w-4" />
+ </Button>
+ </div>
+ <Button type="button" variant="outline" size="sm" class="mt-1" @click="addGaussdbHostEntry">
+ <Plus class="mr-1 h-3.5 w-3.5" />
+ {{ t("connection.addHost") }}
+ </Button>
+ </div>
+ </div>
+ </template>
+ <div v-else-if="form.db_type === 'meilisearch'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.host") }}</Label>
+ <Input v-model="meilisearchHostInput" class="col-span-3" :placeholder="connectionUrlPlaceholder" @input="resetTestState" />
+ </div>
+ <div v-else-if="form.db_type !== 'oracle' || form.oracle_connection_type !== 'tns'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ form.db_type === "elasticsearch" && elasticsearchConnectionMode === "kibana" ? t("connection.elasticsearchKibanaHost") : t("connection.host") }}</Label>
+ <Input v-model="form.host" class="col-span-2" />
+ <Input v-model.number="form.port" type="number" class="col-span-1" @input="markSqlServerPortExplicit" />
</div>
- </div>
- <div v-if="form.db_type === 'elasticsearch'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.mode") }}</Label>
- <div class="col-span-3 grid h-8 grid-cols-2 overflow-hidden rounded-md border border-input bg-muted/30 p-0.5">
- <button
- type="button"
- class="h-7 rounded-sm px-3 text-sm transition-colors"
- :class="elasticsearchConnectionMode === 'direct' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
- :aria-pressed="elasticsearchConnectionMode === 'direct'"
- @click="switchElasticsearchConnectionMode('direct')"
- >
- {{ t("connection.elasticsearchDirectMode") }}
- </button>
- <button
- type="button"
- class="h-7 rounded-sm px-3 text-sm transition-colors"
- :class="elasticsearchConnectionMode === 'kibana' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
- :aria-pressed="elasticsearchConnectionMode === 'kibana'"
- @click="switchElasticsearchConnectionMode('kibana')"
- >
- {{ t("connection.elasticsearchKibanaProxyMode") }}
- </button>
+ <div v-if="isDamengCustomDriver" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.jdbcUrl") }}</Label>
+ <Input v-model="form.connection_string" class="col-span-3" :placeholder="defaultDamengJdbcUrl(form)" />
</div>
- </div>
- <div v-if="form.db_type === 'sqlserver'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.driverMode") }}</Label>
- <div class="col-span-3 flex items-center gap-2">
- <Button size="sm" :variant="sqlServerDriverMode === 'legacy' ? 'outline' : 'default'" :disabled="agentInstallRunning" @click="setSqlServerDriverMode('auto')">{{ t("connection.mongoDriverAuto") }}</Button>
- <Button size="sm" :variant="sqlServerDriverMode === 'legacy' ? 'default' : 'outline'" :disabled="agentInstallRunning" @click="setSqlServerDriverMode('legacy')">{{ t("connection.mongoDriverLegacy") }}</Button>
- <Tooltip>
- <TooltipTrigger as-child>
- <CircleHelp class="h-3.5 w-3.5 cursor-help text-muted-foreground hover:text-foreground" />
- </TooltipTrigger>
- <TooltipContent side="top" align="center" class="max-w-[320px] whitespace-pre-line text-xs leading-relaxed">
- {{ t("connection.sqlServerLegacyCompatibilityModeHint") }}
- </TooltipContent>
- </Tooltip>
+ <div v-if="form.db_type === 'elasticsearch' && elasticsearchConnectionMode === 'kibana'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.elasticsearchKibanaBasePath") }}</Label>
+ <Input v-model="elasticsearchKibanaBasePath" class="col-span-3" placeholder="/kibana/s/default" @input="resetTestState" />
</div>
- </div>
- <div v-if="form.db_type === 'dameng'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.driverMode") }}</Label>
- <div class="col-span-3 flex items-center gap-2">
- <Button size="sm" :variant="damengDriverMode === 'builtin' ? 'default' : 'outline'" @click="setDamengDriverMode('builtin')">
- {{ t("connection.damengBuiltinDriver") }}
- </Button>
- <Button size="sm" :variant="damengDriverMode === 'custom' ? 'default' : 'outline'" @click="setDamengDriverMode('custom')">
- {{ t("connection.damengCustomDriver") }}
- </Button>
- <Tooltip>
- <TooltipTrigger as-child>
- <CircleHelp class="h-3.5 w-3.5 cursor-help text-muted-foreground hover:text-foreground" />
- </TooltipTrigger>
- <TooltipContent side="top" align="center" class="max-w-[320px] text-xs leading-relaxed">
- {{ t("connection.damengDriverModeHint") }}
- </TooltipContent>
- </Tooltip>
+ <div v-if="form.db_type === 'elasticsearch'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.elasticsearchConnectivityCheckPath") }}</Label>
+ <Input v-model="elasticsearchConnectivityCheckPath" class="col-span-3" :placeholder="t('connection.elasticsearchConnectivityCheckPathPlaceholder')" @input="resetTestState" />
</div>
- </div>
- <!-- GaussDB: multi-host dynamic list -->
- <template v-if="form.db_type === 'gaussdb'">
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.host") }}</Label>
- <div class="col-span-3 space-y-2">
- <div v-for="(entry, idx) in gaussdbHostEntries" :key="idx" class="flex items-start gap-2">
- <Input v-model="entry.host" class="flex-1 min-w-0 break-all" placeholder="127.0.0.1" />
- <Input v-model.number="entry.port" type="number" class="w-24 shrink-0" />
- <Button type="button" variant="outline" size="icon" class="h-8 w-8 shrink-0" :disabled="gaussdbHostEntries.length <= 1" @click="removeGaussdbHostEntry(idx)">
- <Trash2 class="h-4 w-4" />
- </Button>
- </div>
- <Button type="button" variant="outline" size="sm" class="mt-1" @click="addGaussdbHostEntry">
- <Plus class="mr-1 h-3.5 w-3.5" />
- {{ t("connection.addHost") }}
- </Button>
+ <div v-if="form.db_type === 'elasticsearch'" class="grid grid-cols-4 items-center gap-4">
+ <div class="flex items-center gap-1">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.elasticsearchIndexGroupingPattern") }}</Label>
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <CircleHelp class="h-3.5 w-3.5 cursor-help text-muted-foreground hover:text-foreground" />
+ </TooltipTrigger>
+ <TooltipContent side="top" align="center" class="max-w-[280px] text-xs leading-relaxed">
+ {{ t("connection.elasticsearchIndexGroupingPatternHint") }}
+ </TooltipContent>
+ </Tooltip>
</div>
+ <Input v-model="elasticsearchIndexGroupingPattern" class="col-span-3" :placeholder="t('connection.elasticsearchIndexGroupingPatternPlaceholder')" @input="resetTestState" />
</div>
- </template>
- <div v-else-if="form.db_type === 'meilisearch'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.host") }}</Label>
- <Input v-model="meilisearchHostInput" class="col-span-3" :placeholder="connectionUrlPlaceholder" @input="resetTestState" />
- </div>
- <div v-else-if="form.db_type !== 'oracle' || form.oracle_connection_type !== 'tns'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ form.db_type === "elasticsearch" && elasticsearchConnectionMode === "kibana" ? t("connection.elasticsearchKibanaHost") : t("connection.host") }}</Label>
- <Input v-model="form.host" class="col-span-2" />
- <Input v-model.number="form.port" type="number" class="col-span-1" @input="markSqlServerPortExplicit" />
- </div>
-
- <div v-if="isDamengCustomDriver" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.jdbcUrl") }}</Label>
- <Input v-model="form.connection_string" class="col-span-3" :placeholder="defaultDamengJdbcUrl(form)" />
- </div>
- <div v-if="form.db_type === 'elasticsearch' && elasticsearchConnectionMode === 'kibana'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.elasticsearchKibanaBasePath") }}</Label>
- <Input v-model="elasticsearchKibanaBasePath" class="col-span-3" placeholder="/kibana/s/default" @input="resetTestState" />
- </div>
+ <div v-if="form.driver_profile === 'gbase8s'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.gbaseServer") }}</Label>
+ <div class="col-span-3 space-y-1">
+ <Input v-model="form.gbase_server" placeholder="gbase01" />
+ <p class="text-xs text-muted-foreground">{{ t("connection.gbaseServerHint") }}</p>
+ </div>
+ </div>
- <div v-if="form.db_type === 'elasticsearch'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.elasticsearchConnectivityCheckPath") }}</Label>
- <Input v-model="elasticsearchConnectivityCheckPath" class="col-span-3" :placeholder="t('connection.elasticsearchConnectivityCheckPathPlaceholder')" @input="resetTestState" />
- </div>
+ <div v-if="form.db_type === 'informix'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.informixServer") }}</Label>
+ <Input v-model="form.informix_server" class="col-span-3" placeholder="ol_informix1170" />
+ </div>
- <div v-if="form.db_type === 'elasticsearch'" class="grid grid-cols-4 items-center gap-4">
- <div class="flex items-center gap-1">
- <Label :class="connectionLabelSmallClass">{{ t("connection.elasticsearchIndexGroupingPattern") }}</Label>
- <Tooltip>
- <TooltipTrigger as-child>
- <CircleHelp class="h-3.5 w-3.5 cursor-help text-muted-foreground hover:text-foreground" />
- </TooltipTrigger>
- <TooltipContent side="top" align="center" class="max-w-[280px] text-xs leading-relaxed">
- {{ t("connection.elasticsearchIndexGroupingPatternHint") }}
- </TooltipContent>
- </Tooltip>
+ <div v-if="form.db_type !== 'meilisearch' && form.db_type !== 'spanner'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
+ <Input v-model="form.username" class="col-span-3" />
</div>
- <Input v-model="elasticsearchIndexGroupingPattern" class="col-span-3" :placeholder="t('connection.elasticsearchIndexGroupingPatternPlaceholder')" @input="resetTestState" />
- </div>
- <div v-if="form.driver_profile === 'gbase8s'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.gbaseServer") }}</Label>
- <div class="col-span-3 space-y-1">
- <Input v-model="form.gbase_server" placeholder="gbase01" />
- <p class="text-xs text-muted-foreground">{{ t("connection.gbaseServerHint") }}</p>
+ <div v-if="form.db_type !== 'spanner'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ form.db_type === "meilisearch" ? t("connection.mqAuthApiKey") : t("connection.password") }}</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" />
</div>
- </div>
- <div v-if="form.db_type === 'informix'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.informixServer") }}</Label>
- <Input v-model="form.informix_server" class="col-span-3" placeholder="ol_informix1170" />
- </div>
+ <div v-if="form.db_type !== 'spanner'" class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <div class="col-span-3 flex items-center gap-1.5 text-sm">
+ <label class="flex items-center gap-2">
+ <input v-model="form.save_password" type="checkbox" class="h-4 w-4 rounded border-border accent-primary" :aria-label="t('connection.savePassword')" />
+ <span class="whitespace-nowrap">{{ t("connection.savePassword") }}</span>
+ </label>
+ <HelpTooltip :label="t('connection.savePassword')">
+ {{ form.save_password ? t("connection.savePasswordHint") : t("connection.savePasswordSessionHint") }}
+ </HelpTooltip>
+ </div>
+ </div>
- <div v-if="form.db_type !== 'meilisearch' && form.db_type !== 'spanner'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
- <Input v-model="form.username" class="col-span-3" />
- </div>
+ <div v-if="form.db_type !== 'hbase' && form.db_type !== 'meilisearch' && form.db_type !== 'spanner'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ databaseLabel }}</Label>
+ <Input v-model="form.database" class="col-span-3" :placeholder="databasePlaceholder" />
+ </div>
- <div v-if="form.db_type !== 'spanner'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ form.db_type === "meilisearch" ? t("connection.mqAuthApiKey") : t("connection.password") }}</Label>
- <PasswordInput v-model="form.password" class="col-span-3" />
- </div>
+ <!-- Cloud Spanner: project/instance/database resource path instead of user/password/database -->
+ <template v-if="form.db_type === 'spanner'">
+ <div class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <p class="col-span-3 text-xs leading-5 text-muted-foreground">{{ t("connection.spannerHostHint") }}</p>
+ </div>
+ <SpannerConnectionFields v-model:database="form.database" @change="resetTestState" />
+ </template>
- <div v-if="form.db_type !== 'spanner'" class="grid grid-cols-4 items-center gap-4">
- <span />
- <div class="col-span-3 flex items-center gap-1.5 text-sm">
- <label class="flex items-center gap-2">
- <input v-model="form.save_password" type="checkbox" class="h-4 w-4 rounded border-border accent-primary" :aria-label="t('connection.savePassword')" />
- <span class="whitespace-nowrap">{{ t("connection.savePassword") }}</span>
- </label>
- <HelpTooltip :label="t('connection.savePassword')">
- {{ form.save_password ? t("connection.savePasswordHint") : t("connection.savePasswordSessionHint") }}
- </HelpTooltip>
+ <div v-if="form.db_type === 'oracle' && form.oracle_connection_type === 'tns'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">TNS_ADMIN</Label>
+ <div class="col-span-3 flex items-center gap-1">
+ <Input v-model="oracleTnsAdminPath" class="flex-1" :placeholder="t('connection.oracleTnsAdminPlaceholder')" />
+ <Tooltip v-if="isDesktop">
+ <TooltipTrigger as-child>
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseOracleTnsNamesFile">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.oracleTnsAdminBrowse") }}</TooltipContent>
+ </Tooltip>
+ </div>
</div>
- </div>
-
- <div v-if="form.db_type !== 'hbase' && form.db_type !== 'meilisearch' && form.db_type !== 'spanner'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ databaseLabel }}</Label>
- <Input v-model="form.database" class="col-span-3" :placeholder="databasePlaceholder" />
- </div>
- <!-- Cloud Spanner: project/instance/database resource path instead of user/password/database -->
- <template v-if="form.db_type === 'spanner'">
- <div class="grid grid-cols-4 items-start gap-4">
+ <div v-if="form.db_type === 'oracle' && form.oracle_connection_type === 'tns'" class="grid grid-cols-4 items-start gap-4">
<span />
- <p class="col-span-3 text-xs leading-5 text-muted-foreground">{{ t("connection.spannerHostHint") }}</p>
+ <p class="col-span-3 text-xs text-muted-foreground">{{ t("connection.oracleTnsPathHint") }}</p>
</div>
- <SpannerConnectionFields v-model:database="form.database" @change="resetTestState" />
- </template>
- <div v-if="form.db_type === 'oracle' && form.oracle_connection_type === 'tns'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">TNS_ADMIN</Label>
- <div class="col-span-3 flex items-center gap-1">
- <Input v-model="oracleTnsAdminPath" class="flex-1" :placeholder="t('connection.oracleTnsAdminPlaceholder')" />
- <Tooltip v-if="isDesktop">
- <TooltipTrigger as-child>
- <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseOracleTnsNamesFile">
- <FolderOpen class="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{{ t("connection.oracleTnsAdminBrowse") }}</TooltipContent>
- </Tooltip>
- </div>
- </div>
+ <template v-if="form.db_type === 'hive' || form.db_type === 'kyuubi' || form.db_type === 'impala'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.hiveAuthMode") }}</Label>
+ <div class="col-span-3 grid h-8 grid-cols-2 overflow-hidden rounded-md border border-input bg-muted/30 p-0.5">
+ <button type="button" class="h-7 rounded-sm px-3 text-sm transition-colors" :class="hiveAuthMode === 'none' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'" :aria-pressed="hiveAuthMode === 'none'" @click="hiveAuthMode = 'none'">
+ {{ t("connection.hiveAuthNone") }}
+ </button>
+ <button
+ type="button"
+ class="h-7 rounded-sm px-3 text-sm transition-colors"
+ :class="hiveAuthMode === 'kerberos' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
+ :aria-pressed="hiveAuthMode === 'kerberos'"
+ @click="hiveAuthMode = 'kerberos'"
+ >
+ Kerberos
+ </button>
+ </div>
+ </div>
- <div v-if="form.db_type === 'oracle' && form.oracle_connection_type === 'tns'" class="grid grid-cols-4 items-start gap-4">
- <span />
- <p class="col-span-3 text-xs text-muted-foreground">{{ t("connection.oracleTnsPathHint") }}</p>
- </div>
+ <template v-if="hiveAuthMode === 'kerberos'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.hivePrincipal") }}</Label>
+ <Input v-model="hivePrincipal" class="col-span-3" :placeholder="form.db_type === 'impala' ? 'impala/[email protected]' : 'hive/[email protected]'" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">krb5.conf</Label>
+ <div class="col-span-3 flex items-center gap-1">
+ <Input v-model="hiveKrb5ConfPath" class="flex-1" placeholder="/etc/krb5.conf" />
+ <Tooltip v-if="isDesktop">
+ <TooltipTrigger as-child>
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseHiveKerberosFile('krb5')">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.hiveKrb5ConfBrowse") }}</TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">JAAS</Label>
+ <div class="col-span-3 flex items-center gap-1">
+ <Input v-model="hiveJaasConfigPath" class="flex-1" placeholder="/etc/hive-jaas.conf" />
+ <Tooltip v-if="isDesktop">
+ <TooltipTrigger as-child>
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseHiveKerberosFile('jaas')">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.hiveJaasConfigBrowse") }}</TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.hiveTicketCache") }}</Label>
+ <label class="col-span-3 flex items-center gap-2 cursor-pointer">
+ <input type="checkbox" v-model="hiveUseSubjectCredsOnlyFalse" class="mr-0" />
+ <span class="text-xs text-muted-foreground">{{ t("connection.hiveTicketCacheFallback") }}</span>
+ </label>
+ </div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.hiveJvmOptions") }}</Label>
+ <textarea
+ v-model="hiveExtraJavaOptions"
+ class="col-span-3 min-h-16 rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ :placeholder="t('connection.hiveJvmOptionsPlaceholder')"
+ />
+ </div>
+ </template>
+ </template>
- <template v-if="form.db_type === 'hive' || form.db_type === 'kyuubi' || form.db_type === 'impala'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.hiveAuthMode") }}</Label>
- <div class="col-span-3 grid h-8 grid-cols-2 overflow-hidden rounded-md border border-input bg-muted/30 p-0.5">
- <button type="button" class="h-7 rounded-sm px-3 text-sm transition-colors" :class="hiveAuthMode === 'none' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'" :aria-pressed="hiveAuthMode === 'none'" @click="hiveAuthMode = 'none'">
- {{ t("connection.hiveAuthNone") }}
+ <div v-if="form.db_type === 'oracle'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.mode") }}</Label>
+ <div class="col-span-3 grid h-8 grid-cols-3 overflow-hidden rounded-md border border-input bg-muted/30 p-0.5">
+ <button
+ type="button"
+ class="h-7 rounded-sm px-3 text-sm transition-colors"
+ :class="form.oracle_connection_type === 'service_name' || !form.oracle_connection_type ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
+ :aria-pressed="form.oracle_connection_type === 'service_name' || !form.oracle_connection_type"
+ @click="form.oracle_connection_type = 'service_name'"
+ >
+ {{ t("connection.serviceNameOnly") }}
+ </button>
+ <button
+ type="button"
+ class="h-7 rounded-sm px-3 text-sm transition-colors"
+ :class="form.oracle_connection_type === 'sid' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
+ :aria-pressed="form.oracle_connection_type === 'sid'"
+ @click="form.oracle_connection_type = 'sid'"
+ >
+ SID
</button>
<button
type="button"
class="h-7 rounded-sm px-3 text-sm transition-colors"
- :class="hiveAuthMode === 'kerberos' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
- :aria-pressed="hiveAuthMode === 'kerberos'"
- @click="hiveAuthMode = 'kerberos'"
+ :class="form.oracle_connection_type === 'tns' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
+ :aria-pressed="form.oracle_connection_type === 'tns'"
+ @click="form.oracle_connection_type = 'tns'"
>
- Kerberos
+ TNS
</button>
</div>
</div>
- <template v-if="hiveAuthMode === 'kerberos'">
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.hivePrincipal") }}</Label>
- <Input v-model="hivePrincipal" class="col-span-3" :placeholder="form.db_type === 'impala' ? 'impala/[email protected]' : 'hive/[email protected]'" />
+ <div v-if="shouldShowAgentDriverInstallHint" class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <p class="col-span-3 text-xs text-muted-foreground">
+ {{ t("connection.driverInstallHintPrefix") }}<a class="underline cursor-pointer text-primary hover:text-primary/80" @click="emit('openDriverStore', agentDriverFocus)">{{ t("toolbar.driverManager") }}</a
+ >{{ t("connection.driverInstallHintSuffix") }}
+ </p>
+ </div>
+
+ <div v-if="form.db_type === 'oracle'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">SYSDBA</Label>
+ <label class="col-span-3 flex items-center gap-2 cursor-pointer">
+ <input type="checkbox" v-model="form.sysdba" class="mr-0" :disabled="isOracleSysUser(form)" />
+ <span class="text-xs text-muted-foreground">as SYSDBA</span>
+ </label>
+ </div>
+
+ <div v-if="supportsGenericUrlParams" class="connection-url-params-row grid grid-cols-4 items-start gap-4" :class="{ 'connection-url-params-row--compact': !showGenericUrlParamsHint, 'connection-url-params-row--with-hint': showGenericUrlParamsHint }">
+ <Label :class="[connectionLabelClass, 'connection-url-params-label']">{{ t("connection.urlParams") }}</Label>
+ <div class="col-span-3 space-y-1.5">
+ <Input
+ v-model="form.url_params"
+ :placeholder="
+ form.db_type === 'mysql'
+ ? 'charset=utf8mb4'
+ : form.db_type === 'doris' || form.db_type === 'starrocks'
+ ? 'sessionVariables=query_timeout=60'
+ : form.db_type === 'saphana'
+ ? 'databaseName=TENANT_DB'
+ : form.db_type === 'clickhouse'
+ ? 'secure=true'
+ : form.db_type === 'bigquery'
+ ? 'OAuthType=0;[email protected];OAuthPvtKeyPath=/path/key.json'
+ : form.db_type === 'spanner'
+ ? 'credentials=/path/key.json;autocommit=true'
+ : form.db_type === 'informix'
+ ? 'CLIENT_LOCALE=en_US.utf8;DB_LOCALE=en_US.utf8'
+ : form.db_type === 'spark'
+ ? 'catalog=paimon_catalog'
+ : form.db_type === 'cassandra'
+ ? 'localdatacenter=dc1'
+ : 'sslmode=prefer'
+ "
+ />
+ <p v-if="showGenericUrlParamsHint" class="text-xs leading-5 text-muted-foreground">
+ {{ t("connection.localInfilePathHint") }}
+ </p>
</div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">krb5.conf</Label>
- <div class="col-span-3 flex items-center gap-1">
- <Input v-model="hiveKrb5ConfPath" class="flex-1" placeholder="/etc/krb5.conf" />
- <Tooltip v-if="isDesktop">
- <TooltipTrigger as-child>
- <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseHiveKerberosFile('krb5')">
- <FolderOpen class="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{{ t("connection.hiveKrb5ConfBrowse") }}</TooltipContent>
- </Tooltip>
- </div>
+ </div>
+
+ <div v-if="form.db_type === 'dameng'" class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.damengJvmOptions") }}</Label>
+ <div class="col-span-3 space-y-1.5">
+ <textarea
+ v-model="damengJvmOptions"
+ class="min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ :placeholder="t('connection.damengJvmOptionsPlaceholder')"
+ />
+ <p class="text-xs leading-5 text-muted-foreground">
+ {{ t("connection.damengJvmOptionsHint") }}
+ </p>
</div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">JAAS</Label>
- <div class="col-span-3 flex items-center gap-1">
- <Input v-model="hiveJaasConfigPath" class="flex-1" placeholder="/etc/hive-jaas.conf" />
- <Tooltip v-if="isDesktop">
- <TooltipTrigger as-child>
- <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseHiveKerberosFile('jaas')">
- <FolderOpen class="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{{ t("connection.hiveJaasConfigBrowse") }}</TooltipContent>
- </Tooltip>
+ </div>
+
+ <template v-if="supportsNativeAgentJdbcDriverConfig">
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.jdbcDriverPaths") }}</Label>
+ <div class="col-span-3 space-y-2">
+ <Select v-if="jdbcDriverSelectItems.length > 0" :model-value="selectedJdbcDriverPath" @update:model-value="onJdbcDriverSelect">
+ <SelectTrigger>
+ <SelectValue :placeholder="t('connection.jdbcDriverSelectPlaceholder')" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="driver in jdbcDriverSelectItems" :key="driver.id" :value="driver.id">
+ {{ driver.label }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <div class="flex items-center justify-between gap-3 rounded-md border bg-muted/20 px-3 py-2">
+ <div class="flex min-w-0 items-center gap-2">
+ <div class="truncate text-xs font-medium">{{ t("connection.jdbcManualClasspath") }}</div>
+ <Badge variant="outline" class="h-5 shrink-0 rounded-full px-2 text-[10px] font-medium">
+ {{ t("connection.jdbcManualClasspathCount", { count: jdbcManualClasspathCount }) }}
+ </Badge>
+ </div>
+ <Switch v-model="jdbcManualClasspathOpen" />
+ </div>
+ <div v-if="jdbcManualClasspathOpen" class="flex items-start gap-1">
+ <textarea
+ v-model="jdbcDriverPathsInput"
+ class="flex min-h-12 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ :placeholder="t('connection.jdbcDriverPathsPlaceholder')"
+ />
+ <Tooltip v-if="isDesktop">
+ <TooltipTrigger as-child>
+ <Button type="button" variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseJdbcDriverPaths">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.jdbcDriverBrowse") }}</TooltipContent>
+ </Tooltip>
+ </div>
</div>
</div>
<div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.hiveTicketCache") }}</Label>
- <label class="col-span-3 flex items-center gap-2 cursor-pointer">
- <input type="checkbox" v-model="hiveUseSubjectCredsOnlyFalse" class="mr-0" />
- <span class="text-xs text-muted-foreground">{{ t("connection.hiveTicketCacheFallback") }}</span>
- </label>
+ <Label :class="connectionLabelClass">{{ t("connection.jdbcDriverClass") }}</Label>
+ <Input v-model="form.jdbc_driver_class" class="col-span-3" :placeholder="t('connection.jdbcDriverClassPlaceholder')" />
</div>
<div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.hiveJvmOptions") }}</Label>
- <textarea
- v-model="hiveExtraJavaOptions"
- class="col-span-3 min-h-16 rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- :placeholder="t('connection.hiveJvmOptionsPlaceholder')"
- />
+ <span />
+ <div class="col-span-3 space-y-2">
+ <p class="text-xs text-muted-foreground">
+ {{ form.db_type === "dameng" ? t("connection.damengCustomDriverHint") : t("connection.jdbcPluginHint") }}
+ </p>
+ <div class="flex flex-wrap gap-2">
+ <Button type="button" variant="outline" size="sm" @click="emit('openDriverStore', { target: 'tab', tab: 'jdbc' })">
+ <FolderOpen class="h-3.5 w-3.5" />
+ {{ t("toolbar.driverManager") }}
+ </Button>
+ <Button v-if="form.db_type !== 'dameng'" type="button" variant="outline" size="sm" @click="openExternalUrl('https://dbxio.com')">
+ <ExternalLink class="h-3.5 w-3.5" />
+ {{ t("connection.jdbcDocs") }}
+ </Button>
+ </div>
+ </div>
</div>
</template>
</template>
- <div v-if="form.db_type === 'oracle'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">{{ t("connection.mode") }}</Label>
- <div class="col-span-3 grid h-8 grid-cols-3 overflow-hidden rounded-md border border-input bg-muted/30 p-0.5">
- <button
- type="button"
- class="h-7 rounded-sm px-3 text-sm transition-colors"
- :class="form.oracle_connection_type === 'service_name' || !form.oracle_connection_type ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
- :aria-pressed="form.oracle_connection_type === 'service_name' || !form.oracle_connection_type"
- @click="form.oracle_connection_type = 'service_name'"
- >
- {{ t("connection.serviceNameOnly") }}
- </button>
- <button
- type="button"
- class="h-7 rounded-sm px-3 text-sm transition-colors"
- :class="form.oracle_connection_type === 'sid' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
- :aria-pressed="form.oracle_connection_type === 'sid'"
- @click="form.oracle_connection_type = 'sid'"
- >
- SID
- </button>
- <button
- type="button"
- class="h-7 rounded-sm px-3 text-sm transition-colors"
- :class="form.oracle_connection_type === 'tns' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
- :aria-pressed="form.oracle_connection_type === 'tns'"
- @click="form.oracle_connection_type = 'tns'"
- >
- TNS
- </button>
- </div>
- </div>
-
- <div v-if="shouldShowAgentDriverInstallHint" class="grid grid-cols-4 items-center gap-4">
- <span />
- <p class="col-span-3 text-xs text-muted-foreground">
- {{ t("connection.driverInstallHintPrefix") }}<a class="underline cursor-pointer text-primary hover:text-primary/80" @click="emit('openDriverStore', agentDriverFocus)">{{ t("toolbar.driverManager") }}</a
- >{{ t("connection.driverInstallHintSuffix") }}
- </p>
- </div>
-
- <div v-if="form.db_type === 'oracle'" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelSmallClass">SYSDBA</Label>
- <label class="col-span-3 flex items-center gap-2 cursor-pointer">
- <input type="checkbox" v-model="form.sysdba" class="mr-0" :disabled="isOracleSysUser(form)" />
- <span class="text-xs text-muted-foreground">as SYSDBA</span>
- </label>
- </div>
-
- <div v-if="supportsGenericUrlParams" class="connection-url-params-row grid grid-cols-4 items-start gap-4" :class="{ 'connection-url-params-row--compact': !showGenericUrlParamsHint, 'connection-url-params-row--with-hint': showGenericUrlParamsHint }">
- <Label :class="[connectionLabelClass, 'connection-url-params-label']">{{ t("connection.urlParams") }}</Label>
- <div class="col-span-3 space-y-1.5">
- <Input
- v-model="form.url_params"
- :placeholder="
- form.db_type === 'mysql'
- ? 'charset=utf8mb4'
- : form.db_type === 'doris' || form.db_type === 'starrocks'
- ? 'sessionVariables=query_timeout=60'
- : form.db_type === 'saphana'
- ? 'databaseName=TENANT_DB'
- : form.db_type === 'clickhouse'
- ? 'secure=true'
- : form.db_type === 'bigquery'
- ? 'OAuthType=0;[email protected];OAuthPvtKeyPath=/path/key.json'
- : form.db_type === 'spanner'
- ? 'credentials=/path/key.json;autocommit=true'
- : form.db_type === 'informix'
- ? 'CLIENT_LOCALE=en_US.utf8;DB_LOCALE=en_US.utf8'
- : form.db_type === 'spark'
- ? 'catalog=paimon_catalog'
- : form.db_type === 'cassandra'
- ? 'localdatacenter=dc1'
- : 'sslmode=prefer'
- "
- />
- <p v-if="showGenericUrlParamsHint" class="text-xs leading-5 text-muted-foreground">
- {{ t("connection.localInfilePathHint") }}
- </p>
- </div>
+ <div v-if="visibleDatabaseInfo" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.databaseInfo.title") }}</Label>
+ <Popover>
+ <PopoverTrigger as-child>
+ <button
+ type="button"
+ class="col-span-3 flex h-9 min-w-0 items-center gap-2 rounded-md border bg-muted/20 px-2.5 text-left text-xs transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ :title="databaseInfoCompactLabel"
+ :aria-label="t('connection.databaseInfo.open', { database: databaseInfoCompactLabel })"
+ >
+ <DatabaseLucide class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <span class="rounded-full bg-background px-1.5 py-0.5 text-[11px] text-muted-foreground">{{ databaseInfoStatusLabel }}</span>
+ <span class="min-w-0 flex-1 truncate text-muted-foreground">{{ databaseInfoCompactLabel }}</span>
+ </button>
+ </PopoverTrigger>
+ <PopoverContent side="top" align="start" class="w-[360px] max-w-[calc(100vw-24px)] gap-3 p-3" @click.stop @keydown.stop>
+ <div class="flex min-w-0 items-start justify-between gap-3">
+ <div class="min-w-0">
+ <div class="flex min-w-0 items-center gap-2">
+ <DatabaseLucide class="h-4 w-4 shrink-0 text-muted-foreground" />
+ <div class="min-w-0 text-sm font-medium">{{ t("connection.databaseInfo.title") }}</div>
+ </div>
+ <p class="mt-1 text-xs text-muted-foreground">{{ databaseInfoDescription }}</p>
+ </div>
+ <Button variant="ghost" size="icon-xs" class="h-7 w-7 shrink-0" :title="t('connection.databaseInfo.copy')" :aria-label="t('connection.databaseInfo.copy')" @click="copyDatabaseInfo">
+ <Copy class="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ <dl class="mt-3 grid min-w-0 grid-cols-[minmax(7.5rem,auto)_minmax(0,1fr)] gap-x-4 gap-y-2 text-xs">
+ <template v-for="row in databaseInfoDisplayRows" :key="row.key">
+ <dt class="text-muted-foreground">{{ row.label }}</dt>
+ <dd class="min-w-0 break-words text-right font-medium">{{ row.displayValue }}</dd>
+ </template>
+ </dl>
+ </PopoverContent>
+ </Popover>
</div>
- <div v-if="form.db_type === 'dameng'" class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.damengJvmOptions") }}</Label>
- <div class="col-span-3 space-y-1.5">
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.note") }}</Label>
+ <div class="col-span-3 flex min-w-0 items-start gap-3">
<textarea
- v-model="damengJvmOptions"
- class="min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- :placeholder="t('connection.damengJvmOptionsPlaceholder')"
+ ref="noteTextareaRef"
+ v-model="form.note"
+ rows="1"
+ class="min-h-8 min-w-0 flex-1 resize-none overflow-y-hidden rounded-md border border-input bg-transparent px-2.5 py-1 text-base leading-5 transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30 md:text-sm"
+ :placeholder="t('connection.notePlaceholder')"
+ @input="resizeNoteTextarea"
/>
- <p class="text-xs leading-5 text-muted-foreground">
- {{ t("connection.damengJvmOptionsHint") }}
- </p>
- </div>
- </div>
-
- <template v-if="supportsNativeAgentJdbcDriverConfig">
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.jdbcDriverPaths") }}</Label>
- <div class="col-span-3 space-y-2">
- <Select v-if="jdbcDriverSelectItems.length > 0" :model-value="selectedJdbcDriverPath" @update:model-value="onJdbcDriverSelect">
- <SelectTrigger>
- <SelectValue :placeholder="t('connection.jdbcDriverSelectPlaceholder')" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem v-for="driver in jdbcDriverSelectItems" :key="driver.id" :value="driver.id">
- {{ driver.label }}
- </SelectItem>
- </SelectContent>
- </Select>
- <div class="flex items-center justify-between gap-3 rounded-md border bg-muted/20 px-3 py-2">
- <div class="flex min-w-0 items-center gap-2">
- <div class="truncate text-xs font-medium">{{ t("connection.jdbcManualClasspath") }}</div>
- <Badge variant="outline" class="h-5 shrink-0 rounded-full px-2 text-[10px] font-medium">
- {{ t("connection.jdbcManualClasspathCount", { count: jdbcManualClasspathCount }) }}
- </Badge>
- </div>
- <Switch v-model="jdbcManualClasspathOpen" />
- </div>
- <div v-if="jdbcManualClasspathOpen" class="flex items-start gap-1">
- <textarea
- v-model="jdbcDriverPathsInput"
- class="flex min-h-12 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- :placeholder="t('connection.jdbcDriverPathsPlaceholder')"
- />
- <Tooltip v-if="isDesktop">
+ <div class="mt-1.5 flex shrink-0 items-center gap-2">
+ <div class="flex items-center gap-1">
+ <Label for="connection-note-sidebar-visibility" class="text-xs font-normal text-muted-foreground">
+ {{ t("connection.noteShow") }}
+ </Label>
+ <Tooltip>
<TooltipTrigger as-child>
- <Button type="button" variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseJdbcDriverPaths">
- <FolderOpen class="h-4 w-4" />
- </Button>
+ <CircleHelp class="h-3.5 w-3.5 cursor-help text-muted-foreground hover:text-foreground" />
</TooltipTrigger>
- <TooltipContent>{{ t("connection.jdbcDriverBrowse") }}</TooltipContent>
+ <TooltipContent side="top" align="center" class="max-w-[280px] text-xs leading-relaxed">
+ {{ t("connection.noteShowInSidebar") }}
+ </TooltipContent>
</Tooltip>
</div>
+ <Switch id="connection-note-sidebar-visibility" v-model="showConnectionNotesInSidebar" :aria-label="t('connection.noteShowInSidebar')" />
</div>
</div>
- <div class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.jdbcDriverClass") }}</Label>
- <Input v-model="form.jdbc_driver_class" class="col-span-3" :placeholder="t('connection.jdbcDriverClassPlaceholder')" />
- </div>
- <div class="grid grid-cols-4 items-start gap-4">
- <span />
- <div class="col-span-3 space-y-2">
- <p class="text-xs text-muted-foreground">
- {{ form.db_type === "dameng" ? t("connection.damengCustomDriverHint") : t("connection.jdbcPluginHint") }}
- </p>
- <div class="flex flex-wrap gap-2">
- <Button type="button" variant="outline" size="sm" @click="emit('openDriverStore', { target: 'tab', tab: 'jdbc' })">
- <FolderOpen class="h-3.5 w-3.5" />
- {{ t("toolbar.driverManager") }}
- </Button>
- <Button v-if="form.db_type !== 'dameng'" type="button" variant="outline" size="sm" @click="openExternalUrl('https://dbxio.com')">
- <ExternalLink class="h-3.5 w-3.5" />
- {{ t("connection.jdbcDocs") }}
- </Button>
- </div>
- </div>
- </div>
- </template>
- </template>
-
- <div v-if="visibleDatabaseInfo" class="grid grid-cols-4 items-center gap-4">
- <Label :class="connectionLabelClass">{{ t("connection.databaseInfo.title") }}</Label>
- <Popover>
- <PopoverTrigger as-child>
- <button
- type="button"
- class="col-span-3 flex h-9 min-w-0 items-center gap-2 rounded-md border bg-muted/20 px-2.5 text-left text-xs transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- :title="databaseInfoCompactLabel"
- :aria-label="t('connection.databaseInfo.open', { database: databaseInfoCompactLabel })"
- >
- <DatabaseLucide class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- <span class="rounded-full bg-background px-1.5 py-0.5 text-[11px] text-muted-foreground">{{ databaseInfoStatusLabel }}</span>
- <span class="min-w-0 flex-1 truncate text-muted-foreground">{{ databaseInfoCompactLabel }}</span>
- </button>
- </PopoverTrigger>
- <PopoverContent side="top" align="start" class="w-[360px] max-w-[calc(100vw-24px)] gap-3 p-3" @click.stop @keydown.stop>
- <div class="flex min-w-0 items-start justify-between gap-3">
- <div class="min-w-0">
- <div class="flex min-w-0 items-center gap-2">
- <DatabaseLucide class="h-4 w-4 shrink-0 text-muted-foreground" />
- <div class="min-w-0 text-sm font-medium">{{ t("connection.databaseInfo.title") }}</div>
- </div>
- <p class="mt-1 text-xs text-muted-foreground">{{ databaseInfoDescription }}</p>
- </div>
- <Button variant="ghost" size="icon-xs" class="h-7 w-7 shrink-0" :title="t('connection.databaseInfo.copy')" :aria-label="t('connection.databaseInfo.copy')" @click="copyDatabaseInfo">
- <Copy class="h-3.5 w-3.5" />
- </Button>
- </div>
- <dl class="mt-3 grid min-w-0 grid-cols-[minmax(7.5rem,auto)_minmax(0,1fr)] gap-x-4 gap-y-2 text-xs">
- <template v-for="row in databaseInfoDisplayRows" :key="row.key">
- <dt class="text-muted-foreground">{{ row.label }}</dt>
- <dd class="min-w-0 break-words text-right font-medium">{{ row.displayValue }}</dd>
- </template>
- </dl>
- </PopoverContent>
- </Popover>
- </div>
-
- <div class="grid grid-cols-4 items-start gap-4">
- <Label :class="connectionLabelTopClass">{{ t("connection.note") }}</Label>
- <div class="col-span-3 flex min-w-0 items-start gap-3">
- <textarea
- ref="noteTextareaRef"
- v-model="form.note"
- rows="1"
- class="min-h-8 min-w-0 flex-1 resize-none overflow-y-hidden rounded-md border border-input bg-transparent px-2.5 py-1 text-base leading-5 transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30 md:text-sm"
- :placeholder="t('connection.notePlaceholder')"
- @input="resizeNoteTextarea"
- />
- <div class="mt-1.5 flex shrink-0 items-center gap-2">
- <div class="flex items-center gap-1">
- <Label for="connection-note-sidebar-visibility" class="text-xs font-normal text-muted-foreground">
- {{ t("connection.noteShow") }}
- </Label>
- <Tooltip>
- <TooltipTrigger as-child>
- <CircleHelp class="h-3.5 w-3.5 cursor-help text-muted-foreground hover:text-foreground" />
- </TooltipTrigger>
- <TooltipContent side="top" align="center" class="max-w-[280px] text-xs leading-relaxed">
- {{ t("connection.noteShowInSidebar") }}
- </TooltipContent>
- </Tooltip>
- </div>
- <Switch id="connection-note-sidebar-visibility" v-model="showConnectionNotesInSidebar" :aria-label="t('connection.noteShowInSidebar')" />
- </div>
</div>
- </div>
+ </template>
</div>
</TabsContent>
@@ -8928,7 +9253,12 @@ function openExternalUrl(url: string) {
<ArrowLeft class="h-4 w-4" />
{{ t("connection.back") }}
</Button>
- <template v-if="testResult">
+ <template v-if="pluginActionStatus">
+ <span class="block min-w-0 flex-1 basis-0 truncate text-xs" :class="pluginActionStatus.ok ? 'text-green-600' : 'text-red-600'" :title="pluginActionStatusMessage" role="status" aria-live="polite">
+ {{ pluginActionStatusMessage }}
+ </span>
+ </template>
+ <template v-else-if="testResult">
<span class="block min-w-0 flex-1 basis-0 truncate text-xs" :class="testResult.ok ? 'text-green-600' : 'text-red-600'" :title="testResultMessage" role="status" aria-live="polite">
{{ testResultMessage }}
</span>
@@ -8938,27 +9268,35 @@ function openExternalUrl(url: string) {
</Button>
</template>
</div>
- <Button v-if="canChooseVisibleNacosNamespaces" variant="outline" class="shrink-0" :disabled="isTesting || isTestingSshTunnel || isSaving || isLoadingVisibleNacosNamespaces || !hasRequiredConnectionTarget" @click="openVisibleNacosNamespacesPicker">
- <Loader2 v-if="isLoadingVisibleNacosNamespaces" class="mr-1.5 h-4 w-4 animate-spin" />
- <ListFilter v-else class="mr-1.5 h-4 w-4" />
- {{ t(nacosNamespacePickerTitleKey) }}
- </Button>
- <Button v-else-if="canChooseVisibleDatabases" variant="outline" class="shrink-0" :disabled="isTesting || isTestingSshTunnel || isSaving || isLoadingVisibleDatabases || !hasRequiredConnectionTarget" @click="openVisibleDatabasesPicker">
- <Loader2 v-if="isLoadingVisibleDatabases" class="mr-1.5 h-4 w-4 animate-spin" />
- <ListFilter v-else class="mr-1.5 h-4 w-4" />
- {{ hasVisibleObjectFilter ? visibleObjectSummary : visibleFilterUsesSchemas ? t("contextMenu.configureVisibleObjects") : t("contextMenu.selectVisibleDatabases") }}
- </Button>
- <Button v-if="canChooseVisibleSchemas && !visibleFilterUsesSchemas && hasVisibleSchemaFilter" variant="outline" class="shrink-0" :disabled="isTesting || isTestingSshTunnel || isSaving || isLoadingVisibleSchemas || !hasRequiredConnectionTarget" @click="openVisibleSchemasPicker">
- <Loader2 v-if="isLoadingVisibleSchemas" class="mr-1.5 h-4 w-4 animate-spin" />
- <ListFilter v-else class="mr-1.5 h-4 w-4" />
- {{ visibleSchemaSummary }}
- </Button>
- <Button variant="outline" class="shrink-0" :disabled="isTesting || isTestingSshTunnel || isSaving" @click="testConnection">
- {{ isTesting ? t("connection.testing") : t("connection.test") }}
- </Button>
- <Button class="shrink-0" @click="save" :disabled="isSaving || isTestingSshTunnel || !hasRequiredConnectionTarget">
- {{ isSaving ? t("common.loading") : editingId || isJdbcConnection ? t("connection.save") : t("connection.saveAndConnect") }}
- </Button>
+ <template v-if="isPluginConnection">
+ <Button v-for="action in pluginFooterActions" :key="action.id" type="button" class="shrink-0" :variant="pluginActionVariant(action)" :disabled="pluginActionDisabled(action)" :title="action.description" @click="runPluginConnectionAction(action)">
+ <Loader2 v-if="pluginActionIsBusy(action)" class="mr-1.5 h-4 w-4 animate-spin" />
+ {{ pluginActionLabel(action) }}
+ </Button>
+ </template>
+ <template v-else>
+ <Button v-if="canChooseVisibleNacosNamespaces" variant="outline" class="shrink-0" :disabled="isTesting || isTestingSshTunnel || isSaving || isLoadingVisibleNacosNamespaces || !hasRequiredConnectionTarget" @click="openVisibleNacosNamespacesPicker">
+ <Loader2 v-if="isLoadingVisibleNacosNamespaces" class="mr-1.5 h-4 w-4 animate-spin" />
+ <ListFilter v-else class="mr-1.5 h-4 w-4" />
+ {{ t(nacosNamespacePickerTitleKey) }}
+ </Button>
+ <Button v-else-if="canChooseVisibleDatabases" variant="outline" class="shrink-0" :disabled="isTesting || isTestingSshTunnel || isSaving || isLoadingVisibleDatabases || !hasRequiredConnectionTarget" @click="openVisibleDatabasesPicker">
+ <Loader2 v-if="isLoadingVisibleDatabases" class="mr-1.5 h-4 w-4 animate-spin" />
+ <ListFilter v-else class="mr-1.5 h-4 w-4" />
+ {{ hasVisibleObjectFilter ? visibleObjectSummary : visibleFilterUsesSchemas ? t("contextMenu.configureVisibleObjects") : t("contextMenu.selectVisibleDatabases") }}
+ </Button>
+ <Button v-if="canChooseVisibleSchemas && !visibleFilterUsesSchemas && hasVisibleSchemaFilter" variant="outline" class="shrink-0" :disabled="isTesting || isTestingSshTunnel || isSaving || isLoadingVisibleSchemas || !hasRequiredConnectionTarget" @click="openVisibleSchemasPicker">
+ <Loader2 v-if="isLoadingVisibleSchemas" class="mr-1.5 h-4 w-4 animate-spin" />
+ <ListFilter v-else class="mr-1.5 h-4 w-4" />
+ {{ visibleSchemaSummary }}
+ </Button>
+ <Button variant="outline" class="shrink-0" :disabled="isTesting || isTestingSshTunnel || isSaving" @click="testConnection">
+ {{ isTesting ? t("connection.testing") : t("connection.test") }}
+ </Button>
+ <Button class="shrink-0" @click="save" :disabled="isSaving || isTestingSshTunnel || !hasRequiredConnectionTarget">
+ {{ isSaving ? t("common.loading") : editingId || isJdbcConnection ? t("connection.save") : t("connection.saveAndConnect") }}
+ </Button>
+ </template>
</DialogFooter>
</template>
</DialogContent>
diff --git a/apps/desktop/src/components/layout/AppDialogs.vue b/apps/desktop/src/components/layout/AppDialogs.vue
index 599fcd0cca..594adc0dd4 100644
--- a/apps/desktop/src/components/layout/AppDialogs.vue
+++ b/apps/desktop/src/components/layout/AppDialogs.vue
@@ -32,10 +32,12 @@ import type { DriverStoreFocus } from "@/lib/connection/agentDriverInstallHint";
import type { SqlParameterDescriptor, SqlParameterSyntax } from "@/lib/sql/sqlParameters";
import type { ConfigTab } from "@/components/connection/ConnectionDialog.vue";
import type { DatabaseType } from "@/types/database";
+import type { PluginCenterFocus } from "@/lib/plugins/pluginCenterNavigation";
const props = defineProps<{
showConnectionDialog: boolean;
connectionPrefill?: ConnectionDeepLinkDraft | null;
+ connectionPluginProvider?: PluginCenterFocus | null;
connectionInitialTab?: ConfigTab;
showDangerDialog: boolean;
dangerSql: string;
@@ -140,7 +142,8 @@ const editConfig = computed(() => {
const shouldShowConnectionDialog = computed(() => props.showConnectionDialog || !!editConfig.value);
watch(editConfig, (v) => {
- if (v) emit("update:showConnectionDialog", true);
+ if (!v) return;
+ emit("update:showConnectionDialog", true);
});
watch(
@@ -167,6 +170,7 @@ watch(
:open="shouldShowConnectionDialog"
:edit-config="editConfig"
:prefill-config="connectionPrefill"
+ :plugin-provider="connectionPluginProvider"
:initial-tab="connectionInitialTab"
@update:open="emit('update:showConnectionDialog', $event)"
@connect-started="emit('connectStarted', $event)"
diff --git a/apps/desktop/src/components/layout/AppTabBar.vue b/apps/desktop/src/components/layout/AppTabBar.vue
index e516f16a66..08be62ae3b 100644
--- a/apps/desktop/src/components/layout/AppTabBar.vue
+++ b/apps/desktop/src/components/layout/AppTabBar.vue
@@ -14,6 +14,8 @@ import "./appTabBar.css";
const props = defineProps<{
driverStoreOpen?: boolean;
driverStoreActive?: boolean;
+ pluginCenterOpen?: boolean;
+ pluginCenterActive?: boolean;
settingsPageOpen?: boolean;
settingsPageActive?: boolean;
agentDriverUpdateCount?: number;
@@ -26,6 +28,8 @@ const props = defineProps<{
const emit = defineEmits<{
"activate-driver-store": [];
"close-driver-store": [];
+ "activate-plugin-center": [];
+ "close-plugin-center": [];
"activate-settings-page": [];
"close-settings-page": [];
"activate-tab": [tabId: string];
@@ -121,7 +125,7 @@ watch(
},
);
-type SpecialRegularSurface = "driverStore" | "settings";
+type SpecialRegularSurface = "driverStore" | "pluginCenter" | "settings";
function closeSpecialRegularSurfaces(keep?: SpecialRegularSurface) {
if (keep !== "driverStore" && props.driverStoreOpen) {
@@ -130,6 +134,9 @@ function closeSpecialRegularSurfaces(keep?: SpecialRegularSurface) {
if (keep !== "settings" && props.settingsPageOpen) {
emit("close-settings-page");
}
+ if (keep !== "pluginCenter" && props.pluginCenterOpen) {
+ emit("close-plugin-center");
+ }
}
// Regular tabs live in editor groups now, so "close other tabs" at App level
@@ -143,6 +150,10 @@ function closeOtherActiveTabs() {
closeSpecialRegularSurfaces("driverStore");
return;
}
+ if (props.pluginCenterActive) {
+ closeSpecialRegularSurfaces("pluginCenter");
+ return;
+ }
const activeTabId = queryStore.activeTabId;
if (!activeTabId) {
@@ -188,9 +199,12 @@ function handleCancelClose() {
<template>
<!-- Targets remain mounted while inactive so the original group bars can
move here without losing their local presentation state. -->
- <div v-show="driverStoreActive || settingsPageActive" data-special-page-workspace class="flex min-h-0 min-w-0 flex-1 overflow-hidden" :class="layoutClass">
+ <div v-show="driverStoreActive || pluginCenterActive || settingsPageActive" data-special-page-workspace class="flex min-h-0 min-w-0 flex-1 overflow-hidden" :class="layoutClass">
<div data-special-page-navigation class="flex min-h-0 min-w-0 shrink-0 flex-col overflow-auto" :style="navigationStyle">
<div v-for="group in queryStore.groups" :key="group.id" :ref="(element) => setTabBarTarget(group.id, element)" :data-special-page-tab-target="group.id" class="flex min-h-0 min-w-0" :class="isVerticalLayout ? 'flex-1' : 'shrink-0'" />
+ <button v-if="pluginCenterOpen" type="button" data-plugin-center-tab class="shrink-0 rounded-md px-2 py-1 text-left text-sm" :class="pluginCenterActive ? 'bg-accent text-accent-foreground' : 'text-muted-foreground'" @click="emit('activate-plugin-center')">
+ {{ t("toolbar.pluginCenter") }}
+ </button>
</div>
<div data-special-page-content class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
<slot />
diff --git a/apps/desktop/src/components/layout/AppToolbar.vue b/apps/desktop/src/components/layout/AppToolbar.vue
index 37fa34ef55..8e63e65243 100644
--- a/apps/desktop/src/components/layout/AppToolbar.vue
+++ b/apps/desktop/src/components/layout/AppToolbar.vue
@@ -2,7 +2,7 @@
import { computed, ref, onMounted, onBeforeUnmount, h, nextTick, watch } from "vue";
import { useI18n } from "vue-i18n";
import { invoke } from "@tauri-apps/api/core";
-import { ChevronsRight, DatabaseZap, FilePlus2, Moon, Sun, SunMoon, History, Bot, ArrowLeftRight, FileCode, BookMarked, GitCompareArrows, TableProperties, Settings, CloudDownload, Package, FileDown, FolderTree } from "@lucide/vue";
+import { ChevronsRight, DatabaseZap, FilePlus2, Moon, Sun, SunMoon, History, Bot, ArrowLeftRight, FileCode, BookMarked, GitCompareArrows, TableProperties, Settings, CloudDownload, Package, PlugZap, FileDown, FolderTree } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import LightDropdown from "@/components/ui/LightDropdown.vue";
@@ -38,6 +38,7 @@ const props = defineProps<{
sqlLibrarySaveFeedbackId: number;
showSqlFilePanel: boolean;
showDriverStore: boolean;
+ showPluginCenter: boolean;
showSettingsPage: boolean;
checkingUpdates: boolean;
updateVersion?: string;
@@ -64,6 +65,7 @@ const emit = defineEmits<{
"open-github": [];
"open-settings": [];
"open-driver-store": [];
+ "open-plugin-center": [];
"check-updates": [];
"open-transfer": [];
"open-sql-file": [];
@@ -438,6 +440,9 @@ const moreItems = computed(() => {
disabled: false,
});
}
+ if (!toolbarItems.value.pluginCenter) {
+ items.push({ value: "plugin-center", label: t("toolbar.pluginCenter"), icon: PlugZap, action: () => emit("open-plugin-center"), disabled: false });
+ }
// "More" menu items (individually toggleable)
if (toolbarItems.value.sqlFile) {
@@ -504,6 +509,9 @@ const collapsedItems = computed(() => {
disabled: false,
});
}
+ if (toolbarItems.value.pluginCenter) {
+ items.push({ value: "plugin-center", label: t("toolbar.pluginCenter"), icon: PlugZap, action: () => emit("open-plugin-center"), disabled: false });
+ }
// Always include moreItems (may contain hidden left-side items + overflowed right items)
if (moreItems.value.length > 0) {
items.push(...moreItems.value);
@@ -571,6 +579,10 @@ const toolbarStyle = computed(() => {
<!-- 小圆点仅提示"有可更新驱动",具体数量交给对话框内标签页红点展示,避免工具栏长期挂红数字。 -->
<span v-if="agentDriverUpdateCount > 0" class="ml-0.5 inline-block h-2 w-2 rounded-full bg-red-500" :aria-label="t('toolbar.updatableDriverCount')" :title="t('toolbar.updatableDriverCount')" />
</Button>
+ <Button v-if="toolbarItems.pluginCenter" variant="ghost" size="sm" :class="[toolbarTextButtonClass, { 'bg-accent': showPluginCenter }]" @click="emit('open-plugin-center')">
+ <PlugZap class="h-3.5 w-3.5" />
+ <span :class="toolbarTextLabelClass">{{ t("toolbar.pluginCenter") }}</span>
+ </Button>
<LightDropdown
v-if="showMoreDropdown"
diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vue
index a2397b346f..c180fe73d0 100644
--- a/apps/desktop/src/components/layout/ContentArea.vue
+++ b/apps/desktop/src/components/layout/ContentArea.vue
@@ -123,6 +123,8 @@ const XuguServerDashboard = defineAsyncComponent(() => import("@/components/admi
const DamengJobAdmin = defineAsyncComponent(() => import("@/components/admin/DamengJobAdmin.vue"));
const DamengUserAdmin = defineAsyncComponent(() => import("@/components/admin/DamengUserAdmin.vue"));
const DamengRoleAdmin = defineAsyncComponent(() => import("@/components/admin/DamengRoleAdmin.vue"));
+const PluginWorkbenchTab = defineAsyncComponent(() => import("@/components/plugins/PluginWorkbenchTab.vue"));
+const PluginFilesystemTab = defineAsyncComponent(() => import("@/components/plugins/PluginFilesystemTab.vue"));
const ExplainPlanViewer = defineAsyncComponent(() => import("@/components/explain/ExplainPlanViewer.vue"));
const QueryChart = defineAsyncComponent(() => import("@/components/chart/QueryChart.vue"));
import { useQueryStore } from "@/stores/queryStore";
@@ -981,6 +983,25 @@ function onRefreshActiveKvBrowser(event: Event) {
void nextTick(() => refreshData());
}
+function openPluginResultView(pluginId: string, contributionId: string, label: string) {
+ const result = props.activeTab.result;
+ if (!result) return;
+ // Plugin workbenches receive a bounded snapshot; plugins re-query through
+ // their backend when they need the full or streamed result set.
+ const cappedRows = result.rows.slice(0, 500);
+ queryStore.openPluginWorkbench(pluginId, contributionId, {
+ title: label,
+ connectionId: props.activeTab.connectionId || "",
+ database: props.activeTab.database || "",
+ context: {
+ connectionId: props.activeTab.connectionId || "",
+ database: props.activeTab.database || "",
+ sql: props.activeTab.sql,
+ result: { columns: result.columns, rows: cappedRows, truncated: result.rows.length > cappedRows.length },
+ },
+ });
+}
+
async function exportResultArchive() {
if (resultArchiveExporting.value) return;
resultArchiveExporting.value = true;
@@ -1712,9 +1733,11 @@ defineExpose({
:can-export-archive="canExportResultArchive"
:archive-exporting="resultArchiveExporting"
:compact="standaloneResultToolbarCompact"
+ :has-result="!!activeTab.result"
@select-explain="emit('update:activeOutputView', activeTab.id, 'explain')"
@select-profile="emit('update:activeOutputView', activeTab.id, 'profile')"
@export-archive="exportResultArchive"
+ @open-result-view="openPluginResultView"
/>
</div>
@@ -1953,9 +1976,11 @@ defineExpose({
:can-export-archive="canExportResultArchive"
:archive-exporting="resultArchiveExporting"
:compact="compact"
+ :has-result="!!activeTab.result"
@select-explain="emit('update:activeOutputView', activeTab.id, 'explain')"
@select-profile="emit('update:activeOutputView', activeTab.id, 'profile')"
@export-archive="exportResultArchive"
+ @open-result-view="openPluginResultView"
/>
</template>
<template v-if="activeTab.result && isQueryExecutionErrorResult(activeTab.result)" #error-actions="{ errorMessage }">
@@ -2501,6 +2526,23 @@ defineExpose({
</div>
</template>
+ <template v-else-if="activeTab.mode === 'plugin-workbench' && activeTab.pluginWorkbench">
+ <div class="flex-1 min-h-0">
+ <PluginWorkbenchTab :key="activeTab.id" :plugin-id="activeTab.pluginWorkbench.pluginId" :contribution-id="activeTab.pluginWorkbench.contributionId" :context="activeTab.pluginWorkbench.context" />
+ </div>
+ </template>
+ <template v-else-if="activeTab.mode === 'plugin-filesystem' && activeTab.pluginFilesystem">
+ <div class="flex h-full min-h-0 flex-col">
+ <PluginFilesystemTab
+ :key="activeTab.id"
+ :plugin-id="activeTab.pluginFilesystem.pluginId"
+ :provider-id="activeTab.pluginFilesystem.providerId"
+ :connection-id="activeTab.connectionId || undefined"
+ :root-uri="activeTab.pluginFilesystem.rootUri"
+ :initial-uri="activeTab.pluginFilesystem.currentUri"
+ />
+ </div>
+ </template>
<template v-else-if="activeTab.mode === 'databases' && activeConnection">
<div class="min-w-0 flex-1 min-h-0">
<DatabaseBrowser ref="databaseBrowserRef" :key="activeTab.id" :connection="activeConnection" />
diff --git a/apps/desktop/src/components/layout/QueryResultToolbarActions.vue b/apps/desktop/src/components/layout/QueryResultToolbarActions.vue
index be3261de03..2e3a15a1e5 100644
--- a/apps/desktop/src/components/layout/QueryResultToolbarActions.vue
+++ b/apps/desktop/src/components/layout/QueryResultToolbarActions.vue
@@ -1,12 +1,16 @@
<script setup lang="ts">
-import { GitBranch, Gauge, Loader2, Upload } from "@lucide/vue";
+import { computed, ref } from "vue";
+import { GitBranch, Gauge, Loader2, PlugZap, Upload } from "@lucide/vue";
import { useI18n } from "vue-i18n";
import { Button } from "@/components/ui/button";
import LightTooltip from "@/components/ui/LightTooltip.vue";
+import * as api from "@/lib/backend/api";
+import { createFrontendPluginRegistry, type PluginContributionEntry } from "@/lib/plugins/frontendPlugin";
+import type { InstalledPlugin, PluginResultViewContribution } from "@/types/database";
type OutputView = "result" | "summary" | "explain" | "chart" | "messages" | "profile";
-withDefaults(
+const props = withDefaults(
defineProps<{
activeView: OutputView;
canShowExplain: boolean;
@@ -14,17 +18,30 @@ withDefaults(
canExportArchive: boolean;
archiveExporting: boolean;
compact?: boolean;
+ hasResult?: boolean;
}>(),
- { compact: false },
+ { compact: false, hasResult: false },
);
const emit = defineEmits<{
selectExplain: [];
selectProfile: [];
exportArchive: [];
+ openResultView: [pluginId: string, contributionId: string, label: string];
}>();
-const { t } = useI18n();
+const { t, locale: appLocale } = useI18n();
+
+const installedPlugins = ref<InstalledPlugin[]>([]);
+const resultViews = computed<PluginContributionEntry<PluginResultViewContribution>[]>(() => createFrontendPluginRegistry(installedPlugins.value, appLocale.value).listResultViews());
+const visibleResultViews = computed(() => (props.hasResult ? resultViews.value.slice(0, 4) : []));
+
+void api.listPlugins().then(
+ (plugins) => {
+ installedPlugins.value = plugins.filter((plugin) => plugin.compatibility.compatible);
+ },
+ () => {},
+);
</script>
<template>
@@ -79,5 +96,19 @@ const { t } = useI18n();
<span v-if="!compact" class="inline-flex h-4 items-center leading-none">{{ t("tabs.exportResultArchive") }}</span>
</Button>
</LightTooltip>
+ <LightTooltip v-for="view in visibleResultViews" :key="view.plugin.manifest.id + ':' + view.contribution.id" :text="t('pluginPlatform.openResultView', { label: view.contribution.label })" :disabled="!compact" side="bottom" :delay="0" :close-delay="0" nowrap>
+ <Button
+ variant="ghost"
+ size="sm"
+ class="h-5 shrink-0 text-xs leading-none text-muted-foreground hover:text-foreground"
+ :class="compact ? 'w-6 gap-0 px-0' : 'gap-1 px-2'"
+ :title="t('pluginPlatform.openResultView', { label: view.contribution.label })"
+ :aria-label="t('pluginPlatform.openResultView', { label: view.contribution.label })"
+ @click="emit('openResultView', view.plugin.manifest.id, view.contribution.id, view.contribution.label)"
+ >
+ <PlugZap class="block h-3.5 w-3.5 self-center" />
+ <span v-if="!compact" class="inline-flex h-4 items-center leading-none">{{ view.contribution.label }}</span>
+ </Button>
+ </LightTooltip>
</div>
</template>
diff --git a/apps/desktop/src/components/layout/__tests__/AppTabBar.spec.ts b/apps/desktop/src/components/layout/__tests__/AppTabBar.spec.ts
index 9546a1cfef..c3908d039a 100644
--- a/apps/desktop/src/components/layout/__tests__/AppTabBar.spec.ts
+++ b/apps/desktop/src/components/layout/__tests__/AppTabBar.spec.ts
@@ -19,7 +19,7 @@ describe("AppTabBar shared group navigation", () => {
});
it("retains targets while hiding inactive special content and follows all placements", () => {
- expect(tabBarSource).toContain('v-show="driverStoreActive || settingsPageActive"');
+ expect(tabBarSource).toContain('v-show="driverStoreActive || pluginCenterActive || settingsPageActive"');
expect(tabBarSource).toContain("data-special-page-navigation");
expect(tabBarSource).toContain("data-special-page-content");
expect(tabBarSource).toContain("<slot />");
diff --git a/apps/desktop/src/components/layout/__tests__/appContentSurfaces.contract.spec.ts b/apps/desktop/src/components/layout/__tests__/appContentSurfaces.contract.spec.ts
index cfab0ed9b6..bd1c5a5d29 100644
--- a/apps/desktop/src/components/layout/__tests__/appContentSurfaces.contract.spec.ts
+++ b/apps/desktop/src/components/layout/__tests__/appContentSurfaces.contract.spec.ts
@@ -10,7 +10,7 @@ const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "ut
// assertions pin the sibling order so a future merge cannot re-introduce it.
describe("App main content surface structure", () => {
it("hides only the editor workspace via the surface guard, never the special pages", () => {
- const guard = 'v-show="!driverStoreActive && !settingsStore.settingsPageActive"';
+ const guard = 'v-show="!driverStoreActive && !pluginCenterActive && !settingsStore.settingsPageActive"';
// The empty-state slot shares the query surface's visibility guard.
expect(appSource.split(guard).length - 1).toBe(1);
diff --git a/apps/desktop/src/components/plugins/PluginConnectionFields.spec.ts b/apps/desktop/src/components/plugins/PluginConnectionFields.spec.ts
new file mode 100644
index 0000000000..b8bb52c5c5
--- /dev/null
+++ b/apps/desktop/src/components/plugins/PluginConnectionFields.spec.ts
@@ -0,0 +1,113 @@
+// @vitest-environment happy-dom
+
+import { createApp, defineComponent, h, nextTick, reactive, type App } from "vue";
+import { afterEach, describe, expect, it } from "vitest";
+import i18n from "@/i18n";
+import PluginConnectionFields from "./PluginConnectionFields.vue";
+import type { PluginConnectionProviderContribution, PluginFormFieldBinding, PluginFormFieldValue } from "@/types/database";
+
+const mountedApps: App[] = [];
+
+const contribution: PluginConnectionProviderContribution = {
+ type: "connection-provider",
+ id: "example.connection",
+ label: "Example connection",
+ database_type: "example",
+ fields: [
+ { key: "host", label: "Host", type: "text", required: true, placeholder: "localhost" },
+ { key: "password", label: "Password", type: "password" },
+ {
+ key: "protocol",
+ label: "Protocol",
+ type: "radio",
+ default: "https",
+ options: [
+ { label: "HTTPS", value: "https" },
+ { label: "HTTP", value: "http" },
+ ],
+ },
+ ],
+};
+
+async function mountFields(initialValues: Record<string, PluginFormFieldValue> = {}, hiddenBindings: PluginFormFieldBinding[] = [], layout: "stacked" | "connection-dialog" = "stacked") {
+ const state = reactive({ values: initialValues });
+ const container = document.createElement("div");
+ document.body.append(container);
+ const app = createApp(
+ defineComponent({
+ setup() {
+ return () =>
+ h(PluginConnectionFields, {
+ contribution,
+ modelValue: state.values,
+ hiddenBindings,
+ layout,
+ "onUpdate:modelValue": (value: Record<string, PluginFormFieldValue>) => {
+ state.values = value;
+ },
+ });
+ },
+ }),
+ );
+ mountedApps.push(app);
+ app.use(i18n);
+ app.mount(container);
+ await nextTick();
+ return state;
+}
+
+afterEach(() => {
+ for (const app of mountedApps.splice(0)) app.unmount();
+ document.body.innerHTML = "";
+});
+
+describe("PluginConnectionFields", () => {
+ it("renders declared fields and emits immutable model updates", async () => {
+ const state = await mountFields({ password: "secret" });
+ const hostInput = document.querySelector<HTMLInputElement>("#example-connection-host");
+ const passwordInput = document.querySelector<HTMLInputElement>("#example-connection-password");
+
+ expect(hostInput?.placeholder).toBe("localhost");
+ expect(passwordInput?.value).toBe("secret");
+
+ if (!hostInput) throw new Error("host input not mounted");
+ hostInput.value = "db.internal";
+ hostInput.dispatchEvent(new Event("input", { bubbles: true }));
+ await nextTick();
+
+ expect(state.values).toEqual({ password: "secret", host: "db.internal" });
+ });
+
+ it("can hide host-owned common bindings", async () => {
+ contribution.fields[0].binding = "host";
+ await mountFields({}, ["host"]);
+ expect(document.querySelector("#example-connection-host")).toBeNull();
+ expect(document.querySelector("#example-connection-password")).not.toBeNull();
+ contribution.fields[0].binding = undefined;
+ });
+
+ it("uses the native four-column connection layout without a nested card", async () => {
+ await mountFields({}, [], "connection-dialog");
+
+ const root = document.querySelector(".contents");
+ const hostInput = document.querySelector("#example-connection-host");
+ const fieldRow = hostInput?.closest(".grid");
+
+ expect(root).not.toBeNull();
+ expect(root?.textContent).not.toContain("Example connection");
+ expect(fieldRow?.classList.contains("grid-cols-4")).toBe(true);
+ expect(document.querySelector(".rounded-lg.border")).toBeNull();
+ });
+
+ it("renders radio fields and emits the selected option", async () => {
+ const state = await mountFields();
+ const radios = Array.from(document.querySelectorAll<HTMLInputElement>("input[type='radio']"));
+
+ expect(radios).toHaveLength(2);
+ expect(radios[0]?.checked).toBe(true);
+ radios[1]?.click();
+ await nextTick();
+
+ expect(state.values.protocol).toBe("http");
+ });
+});
diff --git a/apps/desktop/src/components/plugins/PluginConnectionFields.vue b/apps/desktop/src/components/plugins/PluginConnectionFields.vue
new file mode 100644
index 0000000000..b3631b3a5a
--- /dev/null
+++ b/apps/desktop/src/components/plugins/PluginConnectionFields.vue
@@ -0,0 +1,114 @@
+<script setup lang="ts">
+import { computed } from "vue";
+import { Input } from "@/components/ui/input";
+import PasswordInput from "@/components/ui/PasswordInput.vue";
+import { Label } from "@/components/ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import type { PluginConnectionProviderContribution, PluginFormField, PluginFormFieldBinding, PluginFormFieldValue } from "@/types/database";
+
+const props = defineProps<{
+ contribution: PluginConnectionProviderContribution;
+ modelValue: Record<string, PluginFormFieldValue>;
+ hiddenBindings?: PluginFormFieldBinding[];
+ layout?: "stacked" | "connection-dialog";
+}>();
+
+const emit = defineEmits<{
+ "update:modelValue": [value: Record<string, PluginFormFieldValue>];
+}>();
+
+const formValues = computed(() => props.modelValue);
+const visibleFields = computed(() => props.contribution.fields.filter((field) => !field.binding || !props.hiddenBindings?.includes(field.binding)));
+const isConnectionDialogLayout = computed(() => props.layout === "connection-dialog");
+
+function fieldValue(field: PluginFormField): PluginFormFieldValue {
+ return formValues.value[field.key] ?? field.default ?? defaultValueFor(field);
+}
+
+function updateField(field: PluginFormField, value: PluginFormFieldValue) {
+ emit("update:modelValue", { ...formValues.value, [field.key]: value });
+}
+
+function updateTextField(field: PluginFormField, value: string | number) {
+ if (field.type === "number") {
+ updateField(field, value === "" ? undefined : Number(value));
+ return;
+ }
+ updateField(field, String(value));
+}
+
+function updateBooleanField(field: PluginFormField, value: boolean) {
+ updateField(field, value);
+}
+
+function updateSelectField(field: PluginFormField, value: unknown) {
+ if (value === null || value === undefined) {
+ updateField(field, undefined);
+ return;
+ }
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") updateField(field, value);
+}
+
+function fieldId(field: PluginFormField): string {
+ return `${props.contribution.id}-${field.key}`.replace(/[^a-zA-Z0-9_-]/g, "-");
+}
+
+function defaultValueFor(field: PluginFormField): PluginFormFieldValue {
+ if (field.type === "boolean") return false;
+ if (field.type === "number") return undefined;
+ return "";
+}
+</script>
+
+<template>
+ <div :class="isConnectionDialogLayout ? 'contents' : 'space-y-4'">
+ <div v-if="!isConnectionDialogLayout && (contribution.label || contribution.description)" class="space-y-1">
+ <div v-if="contribution.label" class="text-sm font-medium">{{ contribution.label }}</div>
+ <div v-if="contribution.description" class="text-xs text-muted-foreground">{{ contribution.description }}</div>
+ </div>
+ <div v-else-if="isConnectionDialogLayout && contribution.description" class="col-span-full grid grid-cols-4 items-start gap-4">
+ <span />
+ <p class="col-span-3 m-0 text-xs leading-5 text-muted-foreground">{{ contribution.description }}</p>
+ </div>
+
+ <div v-for="field in visibleFields" :key="field.key" :class="isConnectionDialogLayout ? 'col-span-full grid grid-cols-4 items-start gap-4' : 'space-y-1.5'">
+ <Label :for="fieldId(field)" :class="isConnectionDialogLayout ? 'justify-self-start pt-2 text-left' : 'text-xs'">
+ {{ field.label }}
+ <span v-if="field.required" class="text-destructive">*</span>
+ </Label>
+ <div :class="isConnectionDialogLayout ? 'col-span-3 min-w-0 space-y-1.5' : ''">
+ <Input v-if="field.type === 'text' || field.type === 'number'" :id="fieldId(field)" :type="field.type === 'number' ? 'number' : 'text'" :model-value="fieldValue(field) as string | number | undefined" :placeholder="field.placeholder" @update:model-value="updateTextField(field, $event)" />
+ <PasswordInput v-else-if="field.type === 'password'" :id="fieldId(field)" :model-value="String(fieldValue(field) ?? '')" :placeholder="field.placeholder" @update:model-value="updateField(field, $event)" />
+ <textarea
+ v-else-if="field.type === 'textarea'"
+ :id="fieldId(field)"
+ :value="String(fieldValue(field) ?? '')"
+ :placeholder="field.placeholder"
+ class="min-h-20 w-full resize-y rounded-md border border-input bg-transparent px-2.5 py-2 text-sm outline-none transition-colors placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50"
+ @input="updateField(field, ($event.target as HTMLTextAreaElement).value)"
+ />
+ <Select v-else-if="field.type === 'select'" :model-value="String(fieldValue(field) ?? '')" @update:model-value="updateSelectField(field, $event)">
+ <SelectTrigger :id="fieldId(field)" :class="isConnectionDialogLayout ? 'h-9' : 'h-8 text-xs'">
+ <SelectValue :placeholder="field.placeholder" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="option in field.options || []" :key="option.value" :value="option.value">
+ {{ option.label }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <div v-else-if="field.type === 'radio'" :id="fieldId(field)" class="flex min-h-9 flex-wrap items-center gap-x-4 gap-y-2" role="radiogroup" :aria-label="field.label">
+ <label v-for="option in field.options || []" :key="option.value" class="inline-flex cursor-pointer items-center gap-2 text-sm">
+ <input type="radio" :name="fieldId(field)" :value="option.value" :checked="String(fieldValue(field) ?? '') === option.value" class="size-4 accent-primary" @change="updateField(field, option.value)" />
+ <span>{{ option.label }}</span>
+ </label>
+ </div>
+ <div v-else-if="field.type === 'boolean'" class="flex h-9 items-center">
+ <Switch :id="fieldId(field)" :model-value="Boolean(fieldValue(field))" size="sm" @update:model-value="updateBooleanField(field, $event)" />
+ </div>
+ <div v-if="field.description" class="text-[11px] leading-5 text-muted-foreground">{{ field.description }}</div>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/plugins/PluginContributionsPanel.vue b/apps/desktop/src/components/plugins/PluginContributionsPanel.vue
new file mode 100644
index 0000000000..03d70a9b5e
--- /dev/null
+++ b/apps/desktop/src/components/plugins/PluginContributionsPanel.vue
@@ -0,0 +1,871 @@
+<script setup lang="ts">
+import { computed, h, onBeforeUnmount, onMounted, ref, watch } from "vue";
+import { Check, ChevronRight, CircleAlert, Download, ExternalLink, FileUp, FolderTree, Globe, LayoutGrid, List, Loader2, PackageCheck, Pencil, Plus, RefreshCw, RotateCcw, Search, Settings2, ShieldCheck, Store, Trash2 } from "@lucide/vue";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { useToast } from "@/composables/useToast";
+import PluginIcon from "@/components/plugins/PluginIcon.vue";
+import * as api from "@/lib/backend/api";
+import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
+import { physicalDropPositionInsideRect } from "@/lib/ai/aiAttachments";
+import { createFrontendPluginRegistry, pluginConnectionProviderIcon } from "@/lib/plugins/frontendPlugin";
+import { buildMarketplacePluginListings, filterMarketplacePluginListings, type MarketplacePluginListing } from "@/lib/plugins/pluginMarketplace";
+import type { PluginCenterFocus } from "@/lib/plugins/pluginCenterNavigation";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useQueryStore } from "@/stores/queryStore";
+import type { InstalledPlugin, PluginRepository, PluginRepositoryCatalogResult, PluginTrustedKey } from "@/types/database";
+import { useI18n } from "vue-i18n";
+
+const props = defineProps<{
+ focusTarget?: PluginCenterFocus | null;
+}>();
+
+const emit = defineEmits<{
+ newConnection: [pluginId: string, providerId: string];
+}>();
+
+// lucide no longer ships brand icons; mirror the inline glyph used in AppToolbar.
+const GithubIcon = {
+ render() {
+ return h("svg", { class: "size-3", viewBox: "0 0 24 24", fill: "currentColor" }, [
+ h("path", {
+ d: "M12 0C5.37 0 0 5.37 0 12c0 5.3 3.438 9.8 8.205 11.387.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61-.546-1.387-1.333-1.756-1.333-1.756-1.09-.745.083-.729.083-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 21.795 24 17.295 24 12 24 5.37 18.627 0 12 0z",
+ }),
+ ]);
+ },
+};
+
+const PLUGIN_ALLOW_UNSIGNED_STORAGE_KEY = "dbx-plugin-allow-unsigned";
+
+type TauriFileDropPayload = { type: "enter"; paths: string[]; position: { x: number; y: number } } | { type: "over"; position: { x: number; y: number } } | { type: "drop"; paths: string[]; position: { x: number; y: number } } | { type: "leave" };
+
+const { t, locale: appLocale } = useI18n();
+const { toast } = useToast();
+const connectionStore = useConnectionStore();
+const queryStore = useQueryStore();
+const activeSection = ref<"marketplace" | "installed" | "settings">("marketplace");
+const installedPlugins = ref<InstalledPlugin[]>([]);
+const trustedKeys = ref<PluginTrustedKey[]>([]);
+const repositories = ref<PluginRepository[]>([]);
+const catalogResults = ref<PluginRepositoryCatalogResult[]>([]);
+const loading = ref(false);
+const marketplaceLoading = ref(false);
+const installing = ref(false);
+const marketplaceInstallingKey = ref("");
+const operating = ref(false);
+const error = ref("");
+const selectedPluginId = ref("");
+const selectedContributionId = ref("");
+const selectedConnectionId = ref("");
+const allowUnsigned = ref(
+ ((): boolean => {
+ try {
+ return localStorage.getItem(PLUGIN_ALLOW_UNSIGNED_STORAGE_KEY) === "1";
+ } catch {
+ return false;
+ }
+ })(),
+);
+const trustedKeyId = ref("");
+const trustedPublicKey = ref("");
+const repositoryId = ref("");
+const repositoryName = ref("");
+const repositoryCatalogUrl = ref("");
+const marketplaceQuery = ref("");
+const marketplaceRepositoryId = ref("all");
+const marketplaceViewMode = ref<"grid" | "list">("grid");
+const webFileInput = ref<HTMLInputElement | null>(null);
+const panelRootRef = ref<HTMLElement | null>(null);
+const draggingPackage = ref(false);
+let webDragDepth = 0;
+
+const registry = computed(() => createFrontendPluginRegistry(installedPlugins.value, appLocale.value));
+const definitions = computed(() => registry.value.listPlugins());
+const connectionProviders = computed(() => registry.value.listConnectionProviders());
+const selectedEntry = computed(() => connectionProviders.value.find((entry) => entry.plugin.manifest.id === selectedPluginId.value && entry.contribution.id === selectedContributionId.value) || null);
+const selectedDefinition = computed(() => definitions.value.find((definition) => definition.plugin.manifest.id === selectedPluginId.value) || null);
+const selectedWorkbenches = computed(() => registry.value.listWorkbenches().filter((entry) => entry.plugin.manifest.id === selectedPluginId.value));
+const selectedFilesystems = computed(() => registry.value.listFilesystemProviders().filter((entry) => entry.plugin.manifest.id === selectedPluginId.value));
+const providerConnections = computed(() => {
+ const entry = selectedEntry.value;
+ if (!entry) return [];
+ return connectionStore.connections.filter((connection) => connection.db_type === "plugin" && connection.plugin_id === entry.plugin.manifest.id && connection.plugin_connection_provider === entry.contribution.id);
+});
+const selectedConnection = computed(() => providerConnections.value.find((connection) => connection.id === selectedConnectionId.value));
+const marketplaceListings = computed(() => buildMarketplacePluginListings(catalogResults.value, installedPlugins.value, appLocale.value));
+const filteredMarketplaceListings = computed(() => filterMarketplacePluginListings(marketplaceListings.value, marketplaceQuery.value, marketplaceRepositoryId.value));
+const catalogErrors = computed(() => catalogResults.value.filter((result) => result.error));
+const customRepositories = computed(() => repositories.value.filter((repository) => !repository.managed));
+const showCustomRepositoryTrustSettings = computed(() => customRepositories.value.length > 0 || trustedKeys.value.length > 0);
+
+function openExternal(url?: string) {
+ const target = url?.trim();
+ if (!target) return;
+ try {
+ const parsed = new URL(target);
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return;
+ } catch {
+ return;
+ }
+ if (isTauriRuntime()) void import("@tauri-apps/plugin-shell").then(({ open }) => open(target));
+ else window.open(target, "_blank", "noopener,noreferrer");
+}
+
+async function refresh(preferredPluginId = props.focusTarget?.pluginId || selectedPluginId.value) {
+ loading.value = true;
+ error.value = "";
+ try {
+ [installedPlugins.value, trustedKeys.value, repositories.value] = await Promise.all([api.listPlugins(), api.listPluginTrustedKeys(), api.listPluginRepositories()]);
+ await refreshMarketplace();
+ if (props.focusTarget) applyFocusTarget(props.focusTarget);
+ else selectFirstProvider(preferredPluginId);
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ } finally {
+ loading.value = false;
+ }
+}
+
+async function refreshMarketplace() {
+ marketplaceLoading.value = true;
+ try {
+ catalogResults.value = await api.fetchPluginMarketplaceCatalogs();
+ } catch (cause) {
+ catalogResults.value = [];
+ toast(cause instanceof Error ? cause.message : String(cause), 5000);
+ } finally {
+ marketplaceLoading.value = false;
+ }
+}
+
+function applyFocusTarget(focus: PluginCenterFocus) {
+ activeSection.value = "installed";
+ if (!focus.pluginId) return selectFirstProvider();
+ const provider = connectionProviders.value.find((entry) => entry.plugin.manifest.id === focus.pluginId && (!focus.providerId || entry.contribution.id === focus.providerId));
+ if (!provider) {
+ selectPlugin(focus.pluginId);
+ return;
+ }
+ selectProvider(focus.pluginId, provider.contribution.id);
+}
+
+async function installMarketplaceListing(listing: MarketplacePluginListing) {
+ if (!listing.artifact || listing.status === "installed") return;
+ marketplaceInstallingKey.value = listing.key;
+ try {
+ const result = await api.installMarketplacePlugin({
+ repositoryId: listing.repository.id,
+ pluginId: listing.plugin.id,
+ version: listing.plugin.latestVersion,
+ });
+ toast(t(listing.status === "update" ? "pluginPlatform.updateSuccess" : "pluginPlatform.installSuccess", { name: result.plugin.manifest.name, version: result.plugin.manifest.version }));
+ installedPlugins.value = await api.listPlugins();
+ selectPlugin(result.plugin.manifest.id);
+ } catch (cause) {
+ toast(cause instanceof Error ? cause.message : String(cause), 8000);
+ } finally {
+ marketplaceInstallingKey.value = "";
+ }
+}
+
+async function saveRepository() {
+ const id = repositoryId.value.trim();
+ const name = repositoryName.value.trim();
+ const catalogUrl = repositoryCatalogUrl.value.trim();
+ if (!id || !name || !catalogUrl) return toast(t("pluginPlatform.repositoryFieldsRequired"));
+ operating.value = true;
+ try {
+ repositories.value = await api.savePluginRepository({ id, name, catalogUrl, kind: "custom", enabled: true, managed: false });
+ repositoryId.value = "";
+ repositoryName.value = "";
+ repositoryCatalogUrl.value = "";
+ toast(t("pluginPlatform.repositorySaved", { name }));
+ await refreshMarketplace();
+ } catch (cause) {
+ toast(cause instanceof Error ? cause.message : String(cause), 5000);
+ } finally {
+ operating.value = false;
+ }
+}
+
+async function toggleRepository(repository: PluginRepository) {
+ if (repository.managed) return;
+ operating.value = true;
+ try {
+ repositories.value = await api.savePluginRepository({ ...repository, enabled: !repository.enabled });
+ await refreshMarketplace();
+ } catch (cause) {
+ toast(cause instanceof Error ? cause.message : String(cause), 5000);
+ } finally {
+ operating.value = false;
+ }
+}
+
+async function removeRepository(repository: PluginRepository) {
+ if (repository.managed || !window.confirm(t("pluginPlatform.removeRepositoryConfirm", { name: repository.name }))) return;
+ operating.value = true;
+ try {
+ repositories.value = await api.removePluginRepository(repository.id);
+ if (marketplaceRepositoryId.value === repository.id) marketplaceRepositoryId.value = "all";
+ toast(t("pluginPlatform.repositoryRemoved", { name: repository.name }));
+ await refreshMarketplace();
+ } catch (cause) {
+ toast(cause instanceof Error ? cause.message : String(cause), 5000);
+ } finally {
+ operating.value = false;
+ }
+}
+
+async function saveTrustedKey() {
+ const keyId = trustedKeyId.value.trim();
+ const publicKey = trustedPublicKey.value.trim();
+ if (!keyId || !publicKey) return;
+ operating.value = true;
+ try {
+ trustedKeys.value = await api.savePluginTrustedKey(keyId, publicKey);
+ trustedKeyId.value = "";
+ trustedPublicKey.value = "";
+ toast(t("pluginPlatform.repositoryKeyAdded", { keyId }));
+ } catch (cause) {
+ toast(cause instanceof Error ? cause.message : String(cause), 5000);
+ } finally {
+ operating.value = false;
+ }
+}
+
+async function removeTrustedKey(keyId: string) {
+ if (!window.confirm(t("pluginPlatform.removeRepositoryKeyConfirm", { keyId }))) return;
+ operating.value = true;
+ try {
+ trustedKeys.value = await api.removePluginTrustedKey(keyId);
+ toast(t("pluginPlatform.repositoryKeyRemoved", { keyId }));
+ } catch (cause) {
+ toast(cause instanceof Error ? cause.message : String(cause), 5000);
+ } finally {
+ operating.value = false;
+ }
+}
+
+function abbreviatedPublicKey(publicKey: string): string {
+ return publicKey.length <= 24 ? publicKey : `${publicKey.slice(0, 12)}…${publicKey.slice(-8)}`;
+}
+
+function selectFirstProvider(preferredPluginId = "") {
+ const first = connectionProviders.value.find((entry) => entry.plugin.manifest.id === preferredPluginId) || connectionProviders.value[0];
+ if (first) return selectProvider(first.plugin.manifest.id, first.contribution.id);
+ selectedPluginId.value = definitions.value.find((definition) => definition.plugin.manifest.id === preferredPluginId)?.plugin.manifest.id || definitions.value[0]?.plugin.manifest.id || "";
+ selectedContributionId.value = "";
+ selectedConnectionId.value = "";
+}
+
+function selectProvider(pluginId: string, contributionId: string) {
+ selectedPluginId.value = pluginId;
+ selectedContributionId.value = contributionId;
+ const existing = connectionStore.connections.find((connection) => connection.db_type === "plugin" && connection.plugin_id === pluginId && connection.plugin_connection_provider === contributionId);
+ selectedConnectionId.value = existing?.id || "";
+}
+
+function selectPlugin(pluginId: string) {
+ const first = connectionProviders.value.find((entry) => entry.plugin.manifest.id === pluginId);
+ if (first) return selectProvider(pluginId, first.contribution.id);
+ selectedPluginId.value = pluginId;
+ selectedContributionId.value = "";
+ selectedConnectionId.value = "";
+}
+
+function selectConnection(connectionId: string) {
+ selectedConnectionId.value = connectionId;
+}
+
+function editConnection(connectionId: string) {
+ connectionStore.startEditing(connectionId);
+}
+
+function createConnection() {
+ const entry = selectedEntry.value;
+ if (!entry) return toast(t("pluginPlatform.selectConnectionProvider"));
+ emit("newConnection", entry.plugin.manifest.id, entry.contribution.id);
+}
+
+async function openFilesystem(pluginId: string, providerId: string, label: string, rootUri?: string) {
+ const connection = selectedConnection.value;
+ try {
+ if (connection) await connectionStore.ensureConnected(connection.id);
+ queryStore.openPluginFilesystem(pluginId, providerId, {
+ title: connection ? `${connection.name} · ${label}` : label,
+ connectionId: connection?.id,
+ rootUri,
+ });
+ } catch (cause) {
+ toast(cause instanceof Error ? cause.message : String(cause), 5000);
+ }
+}
+
+function openWorkbench(pluginId: string, contributionId: string, label: string) {
+ const connection = selectedConnection.value;
+ queryStore.openPluginWorkbench(pluginId, contributionId, {
+ title: connection ? `${connection.name} · ${label}` : label,
+ connectionId: connection?.id,
+ context: connection
+ ? {
+ connectionId: connection.id,
+ providerId: connection.plugin_connection_provider,
+ connectionType: connection.plugin_connection_type,
+ }
+ : undefined,
+ });
+}
+
+async function choosePluginPackage() {
+ if (!isTauriRuntime()) {
+ webFileInput.value?.click();
+ return;
+ }
+ const { open } = await import("@tauri-apps/plugin-dialog");
+ const path = await open({ multiple: false, filters: [{ name: t("pluginPlatform.packageFileType"), extensions: ["dbxp"] }] });
+ if (typeof path === "string") await installPlugin(path);
+}
+
+async function handleWebPackage(event: Event) {
+ const input = event.target as HTMLInputElement;
+ const file = input.files?.[0];
+ input.value = "";
+ if (file) await installPlugin(file);
+}
+
+async function installPlugin(source: string | File) {
+ installing.value = true;
+ try {
+ const result = await api.installPluginPackage(source, allowUnsigned.value);
+ toast(t("pluginPlatform.installSuccess", { name: result.plugin.manifest.name, version: result.plugin.manifest.version }));
+ installedPlugins.value = await api.listPlugins();
+ selectPlugin(result.plugin.manifest.id);
+ activeSection.value = "installed";
+ } catch (cause) {
+ toast(cause instanceof Error ? cause.message : String(cause), 8000);
+ } finally {
+ installing.value = false;
+ }
+}
+
+function isPluginPackagePath(path: string): boolean {
+ return /\.dbxp$/i.test(path);
+}
+
+function webDropPluginPackage(event: DragEvent): File | null {
+ const files = event.dataTransfer?.files;
+ if (!files) return null;
+ for (let i = 0; i < files.length; i++) {
+ if (isPluginPackagePath(files[i].name)) return files[i];
+ }
+ return null;
+}
+
+function onWebDragEnter(event: DragEvent) {
+ if (!webDropPluginPackage(event)) return;
+ event.preventDefault();
+ webDragDepth++;
+ draggingPackage.value = true;
+}
+
+function onWebDragOver(event: DragEvent) {
+ if (!webDropPluginPackage(event)) return;
+ event.preventDefault();
+}
+
+function onWebDragLeave() {
+ if (webDragDepth > 0 && --webDragDepth === 0) draggingPackage.value = false;
+}
+
+function onWebDrop(event: DragEvent) {
+ const claimed = draggingPackage.value;
+ webDragDepth = 0;
+ draggingPackage.value = false;
+ const file = webDropPluginPackage(event);
+ if (!file) {
+ if (claimed) event.preventDefault();
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ if (installing.value) return;
+ void installPlugin(file);
+}
+
+function dropInsidePanel(payload: Exclude<TauriFileDropPayload, { type: "leave" }>): boolean {
+ const root = panelRootRef.value;
+ if (!root) return false;
+ return physicalDropPositionInsideRect(payload.position, root.getBoundingClientRect(), window.devicePixelRatio);
+}
+
+function onTauriPluginDrop(event: Event) {
+ const routedEvent = event as CustomEvent<TauriFileDropPayload>;
+ const payload = routedEvent.detail;
+ if (!payload) return;
+ if (payload.type === "leave") {
+ draggingPackage.value = false;
+ return;
+ }
+ const inside = dropInsidePanel(payload);
+ if (payload.type === "enter" || payload.type === "over") {
+ const relevant = payload.type === "enter" ? inside && payload.paths.some(isPluginPackagePath) : inside;
+ if (relevant) routedEvent.preventDefault();
+ draggingPackage.value = relevant;
+ return;
+ }
+ draggingPackage.value = false;
+ const path = payload.paths.find(isPluginPackagePath);
+ if (!inside || !path || installing.value) return;
+ routedEvent.preventDefault();
+ void installPlugin(path);
+}
+
+async function rollbackSelectedPlugin() {
+ if (!selectedPluginId.value || !window.confirm(t("pluginPlatform.rollbackConfirm"))) return;
+ operating.value = true;
+ try {
+ const result = await api.rollbackPlugin(selectedPluginId.value);
+ toast(t("pluginPlatform.rollbackSuccess", { version: result.plugin.manifest.version }));
+ installedPlugins.value = await api.listPlugins();
+ selectPlugin(result.plugin.manifest.id);
+ } catch (cause) {
+ toast(cause instanceof Error ? cause.message : String(cause), 5000);
+ } finally {
+ operating.value = false;
+ }
+}
+
+async function uninstallSelectedPlugin() {
+ const definition = selectedDefinition.value;
+ if (!definition || !window.confirm(t("pluginPlatform.uninstallConfirm", { name: definition.plugin.manifest.name }))) return;
+ operating.value = true;
+ try {
+ installedPlugins.value = await api.uninstallPlugin(definition.plugin.manifest.id);
+ toast(t("pluginPlatform.uninstallSuccess", { name: definition.plugin.manifest.name }));
+ selectFirstProvider();
+ } catch (cause) {
+ toast(cause instanceof Error ? cause.message : String(cause), 5000);
+ } finally {
+ operating.value = false;
+ }
+}
+
+watch(connectionProviders, (providers) => {
+ if (!providers.some((entry) => entry.plugin.manifest.id === selectedPluginId.value && entry.contribution.id === selectedContributionId.value)) selectFirstProvider(selectedPluginId.value);
+});
+watch(providerConnections, (connections) => {
+ if (selectedConnectionId.value && connections.some((connection) => connection.id === selectedConnectionId.value)) return;
+ selectedConnectionId.value = connections[0]?.id || "";
+});
+watch(
+ () => props.focusTarget,
+ (focus) => {
+ if (focus && installedPlugins.value.length) applyFocusTarget(focus);
+ },
+ { deep: true },
+);
+watch(allowUnsigned, (value) => {
+ try {
+ localStorage.setItem(PLUGIN_ALLOW_UNSIGNED_STORAGE_KEY, value ? "1" : "0");
+ } catch {
+ // storage unavailable (private mode); the flag stays session-only
+ }
+});
+onMounted(() => {
+ void refresh();
+ if (isTauriRuntime()) document.addEventListener("dbx:tauri-file-drop", onTauriPluginDrop);
+});
+onBeforeUnmount(() => {
+ if (isTauriRuntime()) document.removeEventListener("dbx:tauri-file-drop", onTauriPluginDrop);
+});
+</script>
+
+<template>
+ <div ref="panelRootRef" class="plugin-center-view relative mx-auto flex h-full w-full max-w-6xl flex-col gap-4 overflow-hidden px-6 py-6" @dragenter="onWebDragEnter" @dragover="onWebDragOver" @dragleave="onWebDragLeave" @drop="onWebDrop">
+ <input ref="webFileInput" type="file" accept=".dbxp" class="hidden" @change="handleWebPackage" />
+ <div v-if="error" class="shrink-0 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive">{{ error }}</div>
+
+ <Tabs v-model="activeSection" class="min-h-0 flex-1 gap-3">
+ <TabsList class="grid h-9 w-full grid-cols-3">
+ <TabsTrigger value="marketplace" class="gap-1.5 text-xs"><Store class="size-3.5" />{{ t("pluginPlatform.marketplace") }}</TabsTrigger>
+ <TabsTrigger value="installed" class="gap-1.5 text-xs"><PackageCheck class="size-3.5" />{{ t("pluginPlatform.installed") }}</TabsTrigger>
+ <TabsTrigger value="settings" class="gap-1.5 text-xs"><Settings2 class="size-3.5" />{{ t("pluginPlatform.settings") }}</TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="marketplace" class="m-0 min-h-0 flex-1 overflow-y-auto">
+ <div class="flex min-h-full w-full flex-col gap-4 pb-2">
+ <div class="flex w-full flex-col gap-2 rounded-xl border bg-card/70 p-3 sm:flex-row sm:items-center">
+ <div class="relative">
+ <Search class="pointer-events-none absolute left-2.5 top-2.5 size-3.5 text-muted-foreground" />
+ <Input v-model="marketplaceQuery" class="h-8 min-w-0 pl-8 text-xs sm:w-[min(100%,28rem)]" :placeholder="t('pluginPlatform.searchMarketplace')" />
+ </div>
+ <div class="flex min-w-0 items-center gap-2 sm:ml-auto">
+ <Select v-model="marketplaceRepositoryId">
+ <SelectTrigger class="h-8 min-w-0 flex-1 text-xs sm:w-52 sm:flex-none"><SelectValue :placeholder="t('pluginPlatform.allRepositories')" /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">{{ t("pluginPlatform.allRepositories") }}</SelectItem>
+ <SelectItem v-for="repository in repositories.filter((entry) => entry.enabled)" :key="repository.id" :value="repository.id">{{ repository.name }}</SelectItem>
+ </SelectContent>
+ </Select>
+ <div class="flex shrink-0 items-center rounded-md border bg-muted/20 p-0.5">
+ <button
+ type="button"
+ class="inline-flex size-7 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-background hover:text-foreground"
+ :class="marketplaceViewMode === 'grid' ? 'bg-background text-foreground shadow-sm' : ''"
+ :aria-label="t('structure.viewGrid')"
+ :aria-pressed="marketplaceViewMode === 'grid'"
+ @click="marketplaceViewMode = 'grid'"
+ >
+ <LayoutGrid class="size-3.5" />
+ </button>
+ <button
+ type="button"
+ class="inline-flex size-7 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-background hover:text-foreground"
+ :class="marketplaceViewMode === 'list' ? 'bg-background text-foreground shadow-sm' : ''"
+ :aria-label="t('structure.viewList')"
+ :aria-pressed="marketplaceViewMode === 'list'"
+ @click="marketplaceViewMode = 'list'"
+ >
+ <List class="size-3.5" />
+ </button>
+ </div>
+ <Button variant="ghost" size="icon-sm" class="shrink-0" :disabled="marketplaceLoading" :title="t('common.refresh')" :aria-label="t('common.refresh')" @click="refreshMarketplace"><RefreshCw class="size-3.5" :class="marketplaceLoading ? 'animate-spin' : ''" /></Button>
+ </div>
+ </div>
+
+ <div v-for="result in catalogErrors" :key="result.repository.id" class="flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-800 dark:text-amber-200">
+ <CircleAlert class="mt-0.5 size-3.5 shrink-0" />
+ <div>
+ <span class="font-medium">{{ result.repository.name }}:</span> {{ result.error }}
+ </div>
+ </div>
+
+ <div v-if="marketplaceLoading" class="flex min-h-[440px] flex-1 items-center justify-center gap-2 rounded-lg border border-dashed p-12 text-xs text-muted-foreground"><Loader2 class="size-4 animate-spin" />{{ t("pluginPlatform.loadingMarketplace") }}</div>
+ <div v-else-if="!filteredMarketplaceListings.length" class="flex min-h-[440px] flex-1 flex-col items-center justify-center rounded-lg border border-dashed p-12 text-center">
+ <Store class="size-7 text-muted-foreground" />
+ <div class="mt-3 text-sm font-medium">{{ t("pluginPlatform.noMarketplacePlugins") }}</div>
+ <div class="mt-1 text-xs text-muted-foreground">{{ t("pluginPlatform.noMarketplacePluginsDescription") }}</div>
+ </div>
+ <div v-else-if="marketplaceViewMode === 'grid'" class="grid w-full grid-cols-[repeat(auto-fit,minmax(220px,1fr))] gap-3">
+ <article v-for="listing in filteredMarketplaceListings" :key="listing.key" class="group flex min-w-0 min-h-48 flex-col rounded-xl border bg-card p-4 transition-colors hover:border-primary/40">
+ <div class="flex items-start gap-3">
+ <PluginIcon :plugin-id="listing.plugin.id" :icon="listing.plugin.icon" class="size-11 rounded-xl border bg-background p-1.5" />
+ <div class="min-w-0 flex-1">
+ <div class="flex flex-wrap items-center gap-1.5">
+ <span class="truncate text-sm font-semibold">{{ listing.name }}</span>
+ <Badge v-if="listing.verified" variant="secondary" class="h-5 gap-1 px-1.5 text-[10px]"><ShieldCheck class="size-3" />{{ t("pluginPlatform.verified") }}</Badge>
+ </div>
+ <div class="mt-1 flex min-w-0 items-center gap-1 text-[11px] text-muted-foreground">
+ <span class="truncate">{{ listing.plugin.publisher }} · {{ listing.repository.name }}</span>
+ <button v-if="listing.plugin.source" type="button" class="shrink-0 rounded p-0.5 opacity-60 transition-opacity hover:opacity-100" :title="t('pluginPlatform.sourceRepository')" :aria-label="t('pluginPlatform.sourceRepository')" @click.stop="openExternal(listing.plugin.source)">
+ <GithubIcon />
+ </button>
+ <button v-if="listing.plugin.homepage" type="button" class="shrink-0 rounded p-0.5 opacity-60 transition-opacity hover:opacity-100" :title="t('pluginPlatform.pluginHomepage')" :aria-label="t('pluginPlatform.pluginHomepage')" @click.stop="openExternal(listing.plugin.homepage)">
+ <Globe class="size-3" />
+ </button>
+ </div>
+ </div>
+ <Badge variant="outline" class="h-5 px-1.5 text-[10px]">v{{ listing.plugin.latestVersion }}</Badge>
+ </div>
+ <p class="mt-3 line-clamp-3 text-xs leading-5 text-muted-foreground">{{ listing.description || t("pluginPlatform.noDescription") }}</p>
+ <div class="mt-3 flex flex-wrap gap-1.5">
+ <Badge v-for="tag in listing.plugin.tags.slice(0, 3)" :key="tag" variant="outline" class="h-5 px-1.5 text-[10px]">{{ tag }}</Badge>
+ <Badge v-if="listing.plugin.permissions.length" variant="outline" class="h-5 px-1.5 text-[10px]">{{ t("pluginPlatform.permissionsCount", { count: listing.plugin.permissions.length }) }}</Badge>
+ </div>
+ <div class="mt-auto flex items-end justify-between gap-3 pt-4">
+ <div class="text-[10px] text-muted-foreground">
+ <span v-if="listing.status === 'unsupported'">{{ t("pluginPlatform.unsupportedTarget", { target: listing.target }) }}</span>
+ <span v-else-if="listing.installed">{{ t("pluginPlatform.installedVersion", { version: listing.installed.manifest.version }) }}</span>
+ <span v-else>{{ listing.plugin.license || t("pluginPlatform.licenseUnknown") }}</span>
+ </div>
+ <button
+ type="button"
+ class="inline-flex h-7 items-center justify-center gap-1.5 rounded-full border-0 bg-gray-100 px-4 py-1 text-xs font-semibold transition-colors disabled:opacity-50 dark:bg-gray-800"
+ :class="listing.status === 'installed' || listing.status === 'unsupported' ? 'cursor-default text-gray-600 dark:text-gray-400' : 'text-blue-600 hover:bg-gray-200 dark:text-blue-400 dark:hover:bg-gray-700'"
+ :disabled="listing.status === 'installed' || listing.status === 'unsupported' || !!marketplaceInstallingKey"
+ @click="installMarketplaceListing(listing)"
+ >
+ <Loader2 v-if="marketplaceInstallingKey === listing.key" class="size-3.5 animate-spin" />
+ <Check v-else-if="listing.status === 'installed'" class="size-3.5" />
+ <CircleAlert v-else-if="listing.status === 'unsupported'" class="size-3.5" />
+ <RefreshCw v-else-if="listing.status === 'update'" class="size-3.5" />
+ <Download v-else class="size-3.5" />
+ {{ t(`pluginPlatform.marketplaceStatus.${listing.status}`) }}
+ </button>
+ </div>
+ </article>
+ </div>
+ <div v-else class="flex w-full flex-col gap-2">
+ <article v-for="listing in filteredMarketplaceListings" :key="listing.key" class="flex items-center gap-3 rounded-xl border bg-card p-3 transition-colors hover:border-primary/40">
+ <PluginIcon :plugin-id="listing.plugin.id" :icon="listing.plugin.icon" class="size-10 rounded-lg border bg-background p-1.5" />
+ <div class="min-w-0 flex-1">
+ <div class="flex min-w-0 items-center gap-2">
+ <span class="truncate text-sm font-semibold">{{ listing.name }}</span>
+ <Badge v-if="listing.verified" variant="secondary" class="hidden h-5 shrink-0 gap-1 px-1.5 text-[10px] sm:inline-flex"><ShieldCheck class="size-3" />{{ t("pluginPlatform.verified") }}</Badge>
+ <Badge variant="outline" class="h-5 shrink-0 px-1.5 text-[10px]">v{{ listing.plugin.latestVersion }}</Badge>
+ </div>
+ <div class="mt-0.5 flex min-w-0 items-center gap-1 text-[11px] text-muted-foreground">
+ <span class="truncate">{{ listing.plugin.publisher }} · {{ listing.repository.name }}</span>
+ <button v-if="listing.plugin.source" type="button" class="shrink-0 rounded p-0.5 opacity-60 transition-opacity hover:opacity-100" :title="t('pluginPlatform.sourceRepository')" :aria-label="t('pluginPlatform.sourceRepository')" @click.stop="openExternal(listing.plugin.source)">
+ <GithubIcon />
+ </button>
+ <button v-if="listing.plugin.homepage" type="button" class="shrink-0 rounded p-0.5 opacity-60 transition-opacity hover:opacity-100" :title="t('pluginPlatform.pluginHomepage')" :aria-label="t('pluginPlatform.pluginHomepage')" @click.stop="openExternal(listing.plugin.homepage)">
+ <Globe class="size-3" />
+ </button>
+ </div>
+ <p class="mt-1 truncate text-xs text-muted-foreground">{{ listing.description || t("pluginPlatform.noDescription") }}</p>
+ </div>
+ <div class="hidden max-w-52 shrink-0 gap-1.5 lg:flex">
+ <Badge v-for="tag in listing.plugin.tags.slice(0, 3)" :key="tag" variant="outline" class="h-5 px-1.5 text-[10px]">{{ tag }}</Badge>
+ </div>
+ <button
+ type="button"
+ class="inline-flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-full border-0 bg-gray-100 px-4 py-1 text-xs font-semibold transition-colors disabled:opacity-50 dark:bg-gray-800"
+ :class="listing.status === 'installed' || listing.status === 'unsupported' ? 'cursor-default text-gray-600 dark:text-gray-400' : 'text-blue-600 hover:bg-gray-200 dark:text-blue-400 dark:hover:bg-gray-700'"
+ :disabled="listing.status === 'installed' || listing.status === 'unsupported' || !!marketplaceInstallingKey"
+ @click="installMarketplaceListing(listing)"
+ >
+ <Loader2 v-if="marketplaceInstallingKey === listing.key" class="size-3.5 animate-spin" />
+ <Check v-else-if="listing.status === 'installed'" class="size-3.5" />
+ <CircleAlert v-else-if="listing.status === 'unsupported'" class="size-3.5" />
+ <RefreshCw v-else-if="listing.status === 'update'" class="size-3.5" />
+ <Download v-else class="size-3.5" />
+ <span class="hidden sm:inline">{{ t(`pluginPlatform.marketplaceStatus.${listing.status}`) }}</span>
+ </button>
+ </article>
+ </div>
+ </div>
+ </TabsContent>
+
+ <TabsContent value="installed" class="m-0 min-h-0 flex-1 overflow-y-auto">
+ <div v-if="loading && !installedPlugins.length" class="py-10 text-center text-xs text-muted-foreground">{{ t("common.loading") }}</div>
+ <div v-else-if="!installedPlugins.length" class="rounded-lg border border-dashed p-10 text-center">
+ <PackageCheck class="mx-auto size-7 text-muted-foreground" />
+ <div class="mt-3 text-sm font-medium">{{ t("pluginPlatform.noInstalledPlugins") }}</div>
+ <div class="mt-1 text-xs text-muted-foreground">{{ t("pluginPlatform.noInstalledPluginsDescription") }}</div>
+ <Button class="mt-4 gap-1.5" size="sm" @click="activeSection = 'marketplace'"><Store class="size-3.5" />{{ t("pluginPlatform.browseMarketplace") }}</Button>
+ </div>
+ <div v-else class="grid min-h-[440px] gap-4 lg:grid-cols-[260px_minmax(0,1fr)]">
+ <div class="space-y-1 rounded-lg border bg-muted/10 p-2">
+ <button
+ v-for="definition in definitions"
+ :key="definition.plugin.manifest.id"
+ type="button"
+ class="flex w-full items-start gap-2 rounded-md px-2 py-2 text-left hover:bg-muted"
+ :class="selectedPluginId === definition.plugin.manifest.id ? 'bg-muted ring-1 ring-primary/30' : ''"
+ @click="selectPlugin(definition.plugin.manifest.id)"
+ >
+ <Check v-if="selectedPluginId === definition.plugin.manifest.id" class="mt-0.5 size-3.5 shrink-0 text-primary" /><span v-else class="mt-0.5 size-3.5 shrink-0" />
+ <PluginIcon :plugin-id="definition.plugin.manifest.id" :icon="definition.plugin.manifest.icon" class="size-8 rounded-md border bg-background p-1" />
+ <span class="min-w-0 flex-1">
+ <span class="block truncate text-sm font-medium">{{ definition.plugin.manifest.name }}</span>
+ <span class="mt-1 flex flex-wrap gap-1">
+ <Badge variant="outline" class="h-4 px-1.5 text-[10px]">v{{ definition.plugin.manifest.version || "-" }}</Badge>
+ <Badge :variant="definition.plugin.compatibility.compatible ? 'secondary' : 'destructive'" class="h-4 px-1.5 text-[10px]">{{ definition.plugin.compatibility.compatible ? t("pluginPlatform.compatible") : t("pluginPlatform.blocked") }}</Badge>
+ </span>
+ </span>
+ </button>
+ </div>
+
+ <div class="space-y-4 rounded-lg border p-4">
+ <template v-if="selectedDefinition">
+ <div class="flex flex-wrap items-start justify-between gap-3 border-b pb-4">
+ <div class="flex min-w-0 items-start gap-3">
+ <PluginIcon :plugin-id="selectedDefinition.plugin.manifest.id" :icon="selectedDefinition.plugin.manifest.icon" class="size-10 rounded-lg border bg-background p-1.5" />
+ <div class="min-w-0">
+ <div class="text-sm font-medium">{{ selectedDefinition.plugin.manifest.name }}</div>
+ <div class="mt-1 text-xs leading-5 text-muted-foreground">{{ selectedDefinition.plugin.manifest.description }}</div>
+ <div class="mt-1 flex flex-wrap items-center gap-1.5">
+ <span class="font-mono text-[10px] text-muted-foreground">{{ selectedDefinition.plugin.manifest.id }}</span>
+ <button
+ v-if="selectedDefinition.plugin.manifest.source"
+ type="button"
+ class="rounded p-0.5 text-muted-foreground opacity-70 transition-opacity hover:text-foreground hover:opacity-100"
+ :title="t('pluginPlatform.sourceRepository')"
+ :aria-label="t('pluginPlatform.sourceRepository')"
+ @click="openExternal(selectedDefinition.plugin.manifest.source)"
+ >
+ <GithubIcon />
+ </button>
+ <button
+ v-if="selectedDefinition.plugin.manifest.homepage"
+ type="button"
+ class="rounded p-0.5 text-muted-foreground opacity-70 transition-opacity hover:text-foreground hover:opacity-100"
+ :title="t('pluginPlatform.pluginHomepage')"
+ :aria-label="t('pluginPlatform.pluginHomepage')"
+ @click="openExternal(selectedDefinition.plugin.manifest.homepage)"
+ >
+ <Globe class="size-3" />
+ </button>
+ </div>
+ </div>
+ </div>
+ <div class="flex gap-2">
+ <Button size="sm" variant="outline" class="gap-1.5" :disabled="operating" @click="rollbackSelectedPlugin"><RotateCcw class="size-3.5" />{{ t("pluginPlatform.rollback") }}</Button>
+ <Button size="sm" variant="outline" class="gap-1.5 text-destructive" :disabled="operating" @click="uninstallSelectedPlugin"><Trash2 class="size-3.5" />{{ t("pluginPlatform.uninstall") }}</Button>
+ </div>
+ </div>
+
+ <div v-if="connectionProviders.some((entry) => entry.plugin.manifest.id === selectedPluginId)" class="space-y-3">
+ <div class="flex flex-wrap gap-2">
+ <Button
+ v-for="entry in connectionProviders.filter((candidate) => candidate.plugin.manifest.id === selectedPluginId)"
+ :key="entry.contribution.id"
+ size="sm"
+ :variant="selectedContributionId === entry.contribution.id ? 'secondary' : 'outline'"
+ @click="selectProvider(entry.plugin.manifest.id, entry.contribution.id)"
+ ><PluginIcon :plugin-id="entry.plugin.manifest.id" :icon="pluginConnectionProviderIcon(entry)" class="mr-1 size-3.5" />{{ entry.contribution.label }}</Button
+ >
+ </div>
+ <div v-if="selectedEntry" class="space-y-4 rounded-lg border p-4">
+ <div class="flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <div class="text-sm font-medium">{{ selectedEntry.contribution.label }}</div>
+ <div class="mt-1 text-xs text-muted-foreground">{{ selectedEntry.contribution.description || selectedEntry.contribution.database_type }}</div>
+ </div>
+ <Badge variant="outline">{{ t("pluginPlatform.connectionProvider") }}</Badge>
+ </div>
+ <div class="flex flex-wrap gap-2">
+ <Button size="sm" class="gap-1.5" @click="createConnection"><Plus class="size-3.5" />{{ t("pluginPlatform.newConnection") }}</Button>
+ <div v-for="connection in providerConnections" :key="connection.id" class="inline-flex items-center">
+ <Button size="sm" class="rounded-r-none" :variant="selectedConnectionId === connection.id ? 'secondary' : 'outline'" @click="selectConnection(connection.id)">{{ connection.name }}</Button>
+ <Button size="icon" variant="outline" class="h-8 w-8 rounded-l-none border-l-0" :title="t('common.edit')" :aria-label="t('common.edit')" @click="editConnection(connection.id)"><Pencil class="size-3.5" /></Button>
+ </div>
+ </div>
+ <div class="rounded-md border border-dashed bg-muted/20 p-3 text-xs leading-5 text-muted-foreground">{{ t("pluginPlatform.connectionManagedInDialog") }}</div>
+ </div>
+ </div>
+
+ <div v-if="selectedWorkbenches.length" class="space-y-2">
+ <div class="text-xs font-medium uppercase tracking-wide text-muted-foreground">{{ t("pluginPlatform.workbenches") }}</div>
+ <div v-for="entry in selectedWorkbenches" :key="entry.contribution.id" class="flex items-center justify-between gap-3 rounded-lg border p-3">
+ <div>
+ <div class="text-sm font-medium">{{ entry.contribution.label }}</div>
+ <div class="text-xs text-muted-foreground">{{ entry.contribution.description || entry.contribution.id }}</div>
+ </div>
+ <Button size="sm" variant="outline" class="gap-1.5" @click="openWorkbench(entry.plugin.manifest.id, entry.contribution.id, entry.contribution.label)"><ExternalLink class="size-3.5" />{{ t("pluginPlatform.open") }}</Button>
+ </div>
+ </div>
+
+ <div v-if="selectedFilesystems.length" class="space-y-2">
+ <div class="text-xs font-medium uppercase tracking-wide text-muted-foreground">{{ t("pluginPlatform.filesystemProviders") }}</div>
+ <div v-for="entry in selectedFilesystems" :key="entry.contribution.id" class="flex items-center justify-between gap-3 rounded-lg border p-3">
+ <div>
+ <div class="text-sm font-medium">{{ entry.contribution.label }}</div>
+ <div class="mt-1 text-xs text-muted-foreground">{{ entry.contribution.schemes.join(", ") }} · {{ (entry.contribution.capabilities || []).join(", ") }}</div>
+ </div>
+ <Button size="sm" variant="outline" class="gap-1.5" @click="openFilesystem(entry.plugin.manifest.id, entry.contribution.id, entry.contribution.label, entry.contribution.root_uri)"><FolderTree class="size-3.5" />{{ t("pluginPlatform.browse") }}</Button>
+ </div>
+ </div>
+ </template>
+ </div>
+ </div>
+ </TabsContent>
+
+ <TabsContent value="settings" class="m-0 min-h-0 flex-1 overflow-y-auto">
+ <div class="space-y-4 pb-2">
+ <section class="space-y-3 rounded-xl border p-4">
+ <div class="flex items-start gap-3">
+ <div class="rounded-md bg-primary/10 p-2 text-primary"><FileUp class="size-4" /></div>
+ <div>
+ <div class="text-sm font-medium">{{ t("pluginPlatform.localInstallTitle") }}</div>
+ <div class="mt-1 text-xs leading-5 text-muted-foreground">{{ t("pluginPlatform.localInstallDescription") }}</div>
+ </div>
+ </div>
+ <div class="flex flex-wrap items-center gap-3">
+ <Button variant="outline" size="sm" class="h-8 gap-1.5" :disabled="installing" @click="choosePluginPackage"><Loader2 v-if="installing" class="size-3.5 animate-spin" /><FileUp v-else class="size-3.5" />{{ t("pluginPlatform.installPackage") }}</Button>
+ <div class="flex items-center gap-1.5 text-[11px] text-muted-foreground"><ShieldCheck class="size-3.5 text-emerald-600 dark:text-emerald-400" />{{ t("pluginPlatform.signedPackagesVerifiedAutomatically") }}</div>
+ <div class="flex items-center gap-1.5 text-[11px] text-muted-foreground"><FileUp class="size-3.5" />{{ t("pluginPlatform.dropInstallHint") }}</div>
+ </div>
+ </section>
+
+ <section class="space-y-3 rounded-xl border p-4">
+ <div class="flex items-start gap-3">
+ <div class="rounded-md bg-primary/10 p-2 text-primary"><Store class="size-4" /></div>
+ <div>
+ <div class="text-sm font-medium">{{ t("pluginPlatform.repositoriesTitle") }}</div>
+ <div class="mt-1 text-xs leading-5 text-muted-foreground">{{ t("pluginPlatform.repositoriesDescription") }}</div>
+ </div>
+ </div>
+ <div class="divide-y rounded-md border">
+ <div v-for="repository in repositories" :key="repository.id" class="flex flex-wrap items-center gap-3 px-3 py-2.5">
+ <div class="min-w-0 flex-1">
+ <div class="flex items-center gap-2 text-xs font-medium">
+ <span>{{ repository.name }}</span
+ ><Badge variant="outline" class="h-4 px-1.5 text-[9px]">{{ t(`pluginPlatform.repositoryKind.${repository.kind}`) }}</Badge>
+ </div>
+ <div class="mt-1 truncate font-mono text-[10px] text-muted-foreground">{{ repository.catalogUrl || t("pluginPlatform.repositoryNotConfigured") }}</div>
+ </div>
+ <Badge :variant="repository.enabled ? 'secondary' : 'outline'" class="h-5 px-1.5 text-[10px]">{{ repository.enabled ? t("pluginPlatform.enabled") : t("pluginPlatform.disabled") }}</Badge>
+ <Button v-if="!repository.managed" size="sm" variant="ghost" class="h-7" :disabled="operating" @click="toggleRepository(repository)">{{ repository.enabled ? t("pluginPlatform.disable") : t("pluginPlatform.enable") }}</Button>
+ <Button v-if="!repository.managed" size="icon" variant="ghost" class="size-7 text-destructive" :disabled="operating" @click="removeRepository(repository)"><Trash2 class="size-3.5" /></Button>
+ </div>
+ </div>
+ <div class="grid gap-2 lg:grid-cols-[180px_220px_minmax(260px,1fr)_auto]">
+ <Input v-model="repositoryId" class="h-8 text-xs" :placeholder="t('pluginPlatform.repositoryIdPlaceholder')" />
+ <Input v-model="repositoryName" class="h-8 text-xs" :placeholder="t('pluginPlatform.repositoryNamePlaceholder')" />
+ <Input v-model="repositoryCatalogUrl" class="h-8 text-xs" :placeholder="t('pluginPlatform.repositoryCatalogUrlPlaceholder')" />
+ <Button size="sm" class="h-8 gap-1.5" :disabled="operating" @click="saveRepository"><Plus class="size-3.5" />{{ t("pluginPlatform.addRepository") }}</Button>
+ </div>
+ </section>
+
+ <details class="group rounded-xl border bg-muted/15" open>
+ <summary class="flex cursor-pointer list-none items-start gap-3 p-4 marker:content-none">
+ <div class="rounded-md bg-muted p-2 text-muted-foreground"><Settings2 class="size-4" /></div>
+ <div class="min-w-0 flex-1">
+ <div class="text-sm font-medium">{{ t("pluginPlatform.developerOptionsTitle") }}</div>
+ <div class="mt-1 text-xs leading-5 text-muted-foreground">{{ t("pluginPlatform.developerOptionsDescription") }}</div>
+ </div>
+ <ChevronRight class="mt-2 size-4 shrink-0 text-muted-foreground transition-transform group-open:rotate-90" />
+ </summary>
+ <div class="space-y-4 border-t p-4">
+ <div class="flex gap-2.5 rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 text-amber-800 dark:text-amber-200">
+ <CircleAlert class="mt-0.5 size-4 shrink-0" />
+ <div class="text-xs leading-5">{{ t("pluginPlatform.developerOptionsWarning") }}</div>
+ </div>
+
+ <div class="flex items-start justify-between gap-4 rounded-lg border bg-background p-3">
+ <div class="min-w-0">
+ <Label for="allow-unsigned-plugin-package" class="text-xs font-medium">{{ t("pluginPlatform.allowUnsignedDevelopmentPackage") }}</Label>
+ <div class="mt-1 text-[11px] leading-5 text-muted-foreground">{{ t("pluginPlatform.allowUnsignedDevelopmentPackageDescription") }}</div>
+ </div>
+ <Switch id="allow-unsigned-plugin-package" v-model="allowUnsigned" size="sm" class="mt-0.5 shrink-0" />
+ </div>
+
+ <template v-if="showCustomRepositoryTrustSettings">
+ <div>
+ <div class="text-sm font-medium">{{ t("pluginPlatform.repositoryTrustTitle") }}</div>
+ <div class="mt-1 text-xs leading-5 text-muted-foreground">{{ t("pluginPlatform.repositoryTrustDescription") }}</div>
+ </div>
+ <div v-if="trustedKeys.length" class="divide-y rounded-md border bg-background">
+ <div v-for="key in trustedKeys" :key="key.keyId" class="flex items-center gap-3 px-3 py-2">
+ <div class="min-w-0 flex-1">
+ <div class="text-xs font-medium">{{ key.keyId }}</div>
+ <div class="truncate font-mono text-[10px] text-muted-foreground" :title="key.publicKey">{{ abbreviatedPublicKey(key.publicKey) }}</div>
+ </div>
+ <Button size="icon" variant="ghost" class="size-7 text-destructive" :disabled="operating" @click="removeTrustedKey(key.keyId)"><Trash2 class="size-3.5" /></Button>
+ </div>
+ </div>
+ <div class="grid gap-2 md:grid-cols-[180px_minmax(260px,1fr)_auto]">
+ <Input v-model="trustedKeyId" class="h-8 text-xs" :placeholder="t('pluginPlatform.repositoryKeyIdPlaceholder')" />
+ <Input v-model="trustedPublicKey" class="h-8 font-mono text-xs" :placeholder="t('pluginPlatform.repositoryPublicKeyPlaceholder')" />
+ <Button size="sm" class="h-8 gap-1.5" :disabled="operating" @click="saveTrustedKey"><ShieldCheck class="size-3.5" />{{ t("pluginPlatform.trustRepository") }}</Button>
+ </div>
+ </template>
+ </div>
+ </details>
+ </div>
+ </TabsContent>
+ </Tabs>
+
+ <div v-if="draggingPackage" class="pointer-events-none absolute inset-0 z-20 flex flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed border-primary/60 bg-primary/5">
+ <FileUp class="size-8 text-primary" />
+ <div class="text-sm font-medium text-primary">{{ t("pluginPlatform.dropToInstall") }}</div>
+ </div>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/plugins/PluginFileManager.vue b/apps/desktop/src/components/plugins/PluginFileManager.vue
new file mode 100644
index 0000000000..9efd22f48d
--- /dev/null
+++ b/apps/desktop/src/components/plugins/PluginFileManager.vue
@@ -0,0 +1,234 @@
+<script setup lang="ts">
+import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
+import { RecycleScroller } from "vue-virtual-scroller";
+import { AlertTriangle, ArrowUp, File, FileCode2, Folder, Loader2, RefreshCw } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import * as api from "@/lib/backend/api";
+import { pluginFilesystemParentUri, pluginFilesystemRootUri, sortPluginFilesystemEntries, uniquePluginFilesystemEntries } from "@/lib/plugins/pluginFilesystem";
+import type { PluginFilesystemEntry, PluginFilesystemProviderContribution } from "@/types/database";
+import { useI18n } from "vue-i18n";
+
+const props = defineProps<{
+ pluginId: string;
+ provider: PluginFilesystemProviderContribution;
+ connectionId?: string;
+ initialUri?: string;
+}>();
+
+const { t } = useI18n();
+
+const currentUri = ref("");
+const address = ref("");
+const entries = ref<PluginFilesystemEntry[]>([]);
+const nextCursor = ref<string>();
+const loading = ref(false);
+const loadingMore = ref(false);
+const error = ref("");
+const selected = ref<PluginFilesystemEntry>();
+const preview = ref("");
+const previewImageUrl = ref("");
+const previewKind = ref<"text" | "image" | "binary">("text");
+const previewContentType = ref("");
+const previewTruncated = ref(false);
+const previewLoading = ref(false);
+const previewError = ref("");
+let listGeneration = 0;
+let previewGeneration = 0;
+
+const rootUri = computed(() => pluginFilesystemRootUri(props.provider));
+const canRead = computed(() => (props.provider.capabilities || []).includes("read"));
+const sortedEntries = computed(() => sortPluginFilesystemEntries(entries.value));
+const parentUri = computed(() => pluginFilesystemParentUri(currentUri.value, rootUri.value));
+
+async function load(uri = address.value || currentUri.value || rootUri.value, append = false) {
+ const targetUri = uri.trim() || rootUri.value;
+ const generation = ++listGeneration;
+ if (append) loadingMore.value = true;
+ else loading.value = true;
+ error.value = "";
+ try {
+ const result = await api.listPluginFilesystemEntries(props.pluginId, props.provider.id, {
+ connectionId: props.connectionId,
+ uri: targetUri,
+ cursor: append ? nextCursor.value : undefined,
+ limit: 200,
+ });
+ if (generation !== listGeneration) return;
+ currentUri.value = targetUri;
+ address.value = targetUri;
+ entries.value = append ? uniquePluginFilesystemEntries([...entries.value, ...result.entries]) : uniquePluginFilesystemEntries(result.entries);
+ nextCursor.value = result.nextCursor;
+ if (!append) clearPreview();
+ } catch (cause) {
+ if (generation !== listGeneration) return;
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ } finally {
+ if (generation === listGeneration) {
+ loading.value = false;
+ loadingMore.value = false;
+ }
+ }
+}
+
+async function activateEntry(entry: PluginFilesystemEntry) {
+ selected.value = entry;
+ if (entry.kind === "directory") {
+ await load(entry.uri);
+ return;
+ }
+ if (!canRead.value || entry.kind !== "file") {
+ preview.value = "";
+ previewContentType.value = "";
+ previewTruncated.value = false;
+ previewError.value = canRead.value ? t("pluginPlatform.entryCannotPreview") : t("pluginPlatform.providerNoReadCapability");
+ return;
+ }
+ const generation = ++previewGeneration;
+ previewLoading.value = true;
+ previewError.value = "";
+ revokePreviewImage();
+ preview.value = "";
+ previewKind.value = "text";
+ try {
+ const contentType = (entry.contentType || "").split(";", 1)[0].toLowerCase();
+ const isImage = contentType.startsWith("image/") || /\.(avif|bmp|gif|jpe?g|png|webp)$/i.test(entry.name);
+ const result = await api.readPluginFilesystemFile(props.pluginId, props.provider.id, entry.uri, {
+ connectionId: props.connectionId,
+ maxBytes: 256 * 1024,
+ });
+ if (generation !== previewGeneration) return;
+ const bytes = Uint8Array.from(atob(result.dataBase64), (character) => character.charCodeAt(0));
+ const resolvedContentType = (result.contentType || entry.contentType || "application/octet-stream").split(";", 1)[0].toLowerCase();
+ previewContentType.value = resolvedContentType;
+ if (isImage || resolvedContentType.startsWith("image/")) {
+ if (result.truncated) {
+ previewError.value = t("pluginPlatform.entryCannotPreview");
+ } else {
+ previewImageUrl.value = URL.createObjectURL(new Blob([bytes], { type: resolvedContentType }));
+ previewKind.value = "image";
+ }
+ } else if (isTextPreview(entry.name, resolvedContentType)) {
+ preview.value = new TextDecoder().decode(bytes);
+ previewKind.value = "text";
+ } else {
+ previewKind.value = "binary";
+ }
+ previewTruncated.value = result.truncated;
+ } catch (cause) {
+ if (generation !== previewGeneration) return;
+ previewError.value = cause instanceof Error ? cause.message : String(cause);
+ preview.value = "";
+ } finally {
+ if (generation === previewGeneration) previewLoading.value = false;
+ }
+}
+
+function clearPreview() {
+ previewGeneration += 1;
+ selected.value = undefined;
+ preview.value = "";
+ revokePreviewImage();
+ previewKind.value = "text";
+ previewContentType.value = "";
+ previewTruncated.value = false;
+ previewLoading.value = false;
+ previewError.value = "";
+}
+
+function revokePreviewImage() {
+ if (previewImageUrl.value) URL.revokeObjectURL(previewImageUrl.value);
+ previewImageUrl.value = "";
+}
+
+function isTextPreview(name: string, contentType: string) {
+ return contentType.startsWith("text/") || /^(application\/(json|javascript|xml|yaml)|image\/svg\+xml)$/.test(contentType) || /\.(cjs|css|csv|html?|js|json|md|mjs|toml|ts|tsx|txt|vue|xml|yaml|yml)$/i.test(name);
+}
+
+function formatSize(size?: number) {
+ if (size === undefined) return "";
+ if (size < 1024) return `${size} B`;
+ if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
+ if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(1)} MB`;
+ return `${(size / (1024 * 1024 * 1024)).toFixed(1)} GB`;
+}
+
+onMounted(() => void load(props.initialUri || rootUri.value));
+onBeforeUnmount(() => {
+ revokePreviewImage();
+});
+watch(
+ () => [props.pluginId, props.provider.id, props.connectionId, props.initialUri, rootUri.value] as const,
+ () => void load(props.initialUri || rootUri.value),
+);
+</script>
+
+<template>
+ <div class="flex size-full min-h-0 flex-col bg-background">
+ <div class="flex shrink-0 items-center gap-2 border-b px-3 py-2">
+ <Button size="icon" variant="ghost" class="size-8" :disabled="!parentUri || loading" :title="t('pluginPlatform.parentDirectory')" @click="parentUri && load(parentUri)">
+ <ArrowUp class="size-4" />
+ </Button>
+ <Input v-model="address" class="h-8 min-w-0 flex-1 font-mono text-xs" :aria-label="t('pluginPlatform.filesystemUri')" @keydown.enter="load(address)" />
+ <Button size="icon" variant="ghost" class="size-8" :disabled="loading" :title="t('pluginPlatform.refresh')" @click="load(currentUri)">
+ <Loader2 v-if="loading" class="size-4 animate-spin" />
+ <RefreshCw v-else class="size-4" />
+ </Button>
+ </div>
+
+ <div v-if="error" class="m-3 flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 p-3 text-sm text-destructive">
+ <AlertTriangle class="mt-0.5 size-4 shrink-0" />
+ <span>{{ error }}</span>
+ </div>
+
+ <div v-else class="grid min-h-0 flex-1 grid-cols-[minmax(18rem,42%)_minmax(0,1fr)] divide-x">
+ <div class="flex min-h-0 flex-col">
+ <div v-if="loading && !entries.length" class="flex h-full items-center justify-center text-sm text-muted-foreground"><Loader2 class="mr-2 size-4 animate-spin" />{{ t("pluginPlatform.loadingFiles") }}</div>
+ <div v-else-if="!sortedEntries.length" class="flex h-full items-center justify-center text-sm text-muted-foreground">{{ t("pluginPlatform.emptyDirectory") }}</div>
+ <RecycleScroller v-else class="min-h-0 flex-1 min-w-[28rem] text-sm" :items="sortedEntries" :item-size="46" :buffer="300" key-field="uri">
+ <template #default="{ item: entry }">
+ <button type="button" class="grid h-[46px] w-full grid-cols-[minmax(0,1fr)_7rem_10rem] items-center gap-3 border-b px-3 text-left hover:bg-muted/50" :class="selected?.uri === entry.uri ? 'bg-muted' : ''" @click="selected = entry" @dblclick="activateEntry(entry)">
+ <span class="flex min-w-0 items-center gap-2">
+ <Folder v-if="entry.kind === 'directory'" class="size-4 shrink-0 text-amber-500" />
+ <FileCode2 v-else-if="entry.contentType?.startsWith('text/')" class="size-4 shrink-0 text-sky-500" />
+ <File v-else class="size-4 shrink-0 text-muted-foreground" />
+ <span class="truncate" :title="entry.name">{{ entry.name }}</span>
+ </span>
+ <span class="text-right text-xs tabular-nums text-muted-foreground">{{ entry.kind === "directory" ? "" : formatSize(entry.size) }}</span>
+ <span class="truncate text-xs text-muted-foreground" :title="entry.modifiedAt">{{ entry.modifiedAt || "" }}</span>
+ </button>
+ </template>
+ </RecycleScroller>
+ <div v-if="nextCursor" class="flex shrink-0 justify-center p-3">
+ <Button size="sm" variant="outline" :disabled="loadingMore" @click="load(currentUri, true)"> <Loader2 v-if="loadingMore" class="mr-2 size-3.5 animate-spin" />{{ t("pluginPlatform.loadMore") }} </Button>
+ </div>
+ </div>
+
+ <div class="flex min-h-0 min-w-0 flex-col">
+ <div v-if="!selected" class="m-auto max-w-sm px-6 text-center text-sm text-muted-foreground">{{ t("pluginPlatform.fileManagerHint") }}</div>
+ <template v-else>
+ <div class="shrink-0 border-b px-4 py-3">
+ <div class="truncate text-sm font-medium" :title="selected.name">{{ selected.name }}</div>
+ <div class="mt-1 truncate font-mono text-[11px] text-muted-foreground" :title="selected.uri">{{ selected.uri }}</div>
+ </div>
+ <div class="min-h-0 flex-1 overflow-auto p-4">
+ <div v-if="previewLoading" class="flex h-full items-center justify-center text-sm text-muted-foreground"><Loader2 class="mr-2 size-4 animate-spin" />{{ t("pluginPlatform.loadingPreview") }}</div>
+ <div v-else-if="previewError" class="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 p-3 text-sm text-destructive"><AlertTriangle class="mt-0.5 size-4 shrink-0" />{{ previewError }}</div>
+ <template v-else-if="previewKind === 'image' && previewImageUrl">
+ <img :src="previewImageUrl" :alt="selected.name" class="max-h-full max-w-full rounded-md object-contain" />
+ </template>
+ <template v-else-if="previewKind === 'text' && preview">
+ <div class="mb-2 flex items-center justify-between gap-3 text-[11px] text-muted-foreground">
+ <span>{{ previewContentType }}</span>
+ <span v-if="previewTruncated">{{ t("pluginPlatform.previewTruncated") }}</span>
+ </div>
+ <pre class="whitespace-pre-wrap break-words rounded-md bg-muted/40 p-3 font-mono text-xs leading-5">{{ preview }}</pre>
+ </template>
+ <div v-else-if="previewKind === 'binary'" class="m-auto max-w-sm text-center text-sm text-muted-foreground">{{ t("pluginPlatform.entryCannotPreview") }}</div>
+ <div v-else class="text-sm text-muted-foreground">{{ t("pluginPlatform.previewSelectedFileHint") }}</div>
+ </div>
+ </template>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/plugins/PluginFilesystemTab.vue b/apps/desktop/src/components/plugins/PluginFilesystemTab.vue
new file mode 100644
index 0000000000..864e5b4c9b
--- /dev/null
+++ b/apps/desktop/src/components/plugins/PluginFilesystemTab.vue
@@ -0,0 +1,64 @@
+<script setup lang="ts">
+import { computed, onMounted, ref, watch } from "vue";
+import { AlertTriangle, Loader2 } from "@lucide/vue";
+import PluginFileManager from "@/components/plugins/PluginFileManager.vue";
+import * as api from "@/lib/backend/api";
+import { createFrontendPluginRegistry } from "@/lib/plugins/frontendPlugin";
+import type { InstalledPlugin } from "@/types/database";
+import { useI18n } from "vue-i18n";
+
+const props = defineProps<{
+ pluginId: string;
+ providerId: string;
+ connectionId?: string;
+ rootUri?: string;
+ initialUri?: string;
+}>();
+
+const { t, locale: appLocale } = useI18n();
+
+const plugins = ref<InstalledPlugin[]>([]);
+const loading = ref(true);
+const error = ref("");
+let loadGeneration = 0;
+const entry = computed(() =>
+ createFrontendPluginRegistry(plugins.value, appLocale.value)
+ .listFilesystemProviders()
+ .find((candidate) => candidate.plugin.manifest.id === props.pluginId && candidate.contribution.id === props.providerId),
+);
+const provider = computed(() => (entry.value ? { ...entry.value.contribution, root_uri: props.rootUri || entry.value.contribution.root_uri } : undefined));
+
+async function load() {
+ const generation = ++loadGeneration;
+ loading.value = true;
+ error.value = "";
+ try {
+ const installed = await api.listPlugins();
+ if (generation !== loadGeneration) return;
+ plugins.value = installed;
+ if (!entry.value) throw new Error(t("pluginPlatform.filesystemUnavailable", { pluginId: props.pluginId, providerId: props.providerId }));
+ } catch (cause) {
+ if (generation !== loadGeneration) return;
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ } finally {
+ if (generation === loadGeneration) loading.value = false;
+ }
+}
+
+onMounted(() => void load());
+watch(
+ () => [props.pluginId, props.providerId],
+ () => void load(),
+);
+</script>
+
+<template>
+ <div class="flex size-full min-h-0">
+ <div v-if="loading" class="m-auto flex items-center text-sm text-muted-foreground"><Loader2 class="mr-2 size-4 animate-spin" />{{ t("pluginPlatform.loadingFilesystem") }}</div>
+ <div v-else-if="error || !provider" class="m-auto flex max-w-lg items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm text-destructive">
+ <AlertTriangle class="mt-0.5 size-4 shrink-0" />
+ <span>{{ error || t("pluginPlatform.filesystemUnavailableFallback") }}</span>
+ </div>
+ <PluginFileManager v-else class="min-h-0 flex-1" :plugin-id="pluginId" :provider="provider" :connection-id="connectionId" :initial-uri="initialUri" />
+ </div>
+</template>
diff --git a/apps/desktop/src/components/plugins/PluginIcon.spec.ts b/apps/desktop/src/components/plugins/PluginIcon.spec.ts
new file mode 100644
index 0000000000..e132b744e1
--- /dev/null
+++ b/apps/desktop/src/components/plugins/PluginIcon.spec.ts
@@ -0,0 +1,75 @@
+// @vitest-environment happy-dom
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createApp, nextTick, type App } from "vue";
+import PluginIcon from "./PluginIcon.vue";
+
+const { readPluginAssetMock } = vi.hoisted(() => ({
+ readPluginAssetMock: vi.fn(),
+}));
+
+vi.mock("@/lib/backend/api", () => ({
+ readPluginAsset: readPluginAssetMock,
+}));
+
+const mountedApps: App[] = [];
+
+async function mountIcon(icon?: string) {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const app = createApp(PluginIcon, { pluginId: "example.plugin", icon });
+ app.mount(container);
+ mountedApps.push(app);
+ await Promise.resolve();
+ await nextTick();
+ return container;
+}
+
+beforeEach(() => {
+ readPluginAssetMock.mockReset();
+ vi.stubGlobal("URL", {
+ ...URL,
+ createObjectURL: vi.fn(() => "blob:plugin-icon"),
+ revokeObjectURL: vi.fn(),
+ });
+});
+
+afterEach(() => {
+ for (const app of mountedApps.splice(0)) app.unmount();
+ document.body.innerHTML = "";
+ vi.unstubAllGlobals();
+});
+
+describe("PluginIcon", () => {
+ it("renders a developer-provided image asset", async () => {
+ readPluginAssetMock.mockResolvedValue({ contentType: "image/svg+xml", dataBase64: "PHN2Zy8+", etag: "icon" });
+
+ const container = await mountIcon("assets/icon.svg");
+
+ expect(readPluginAssetMock).toHaveBeenCalledWith("example.plugin", "assets/icon.svg");
+ expect(container.querySelector("img")?.getAttribute("src")).toBe("blob:plugin-icon");
+ });
+
+ it("falls back when the asset cannot be loaded", async () => {
+ readPluginAssetMock.mockRejectedValue(new Error("missing"));
+
+ const container = await mountIcon("assets/missing.svg");
+
+ expect(container.querySelector("img")).toBeNull();
+ expect(container.querySelector("svg")).not.toBeNull();
+ });
+
+ it("uses the fallback without reading an undeclared asset", async () => {
+ const container = await mountIcon();
+
+ expect(readPluginAssetMock).not.toHaveBeenCalled();
+ expect(container.querySelector("svg")).not.toBeNull();
+ });
+
+ it("renders marketplace icon URLs without reading installed assets", async () => {
+ const container = await mountIcon("https://plugins.example.com/icon.svg");
+
+ expect(readPluginAssetMock).not.toHaveBeenCalled();
+ expect(container.querySelector("img")?.getAttribute("src")).toBe("https://plugins.example.com/icon.svg");
+ });
+});
diff --git a/apps/desktop/src/components/plugins/PluginIcon.vue b/apps/desktop/src/components/plugins/PluginIcon.vue
new file mode 100644
index 0000000000..95648e773d
--- /dev/null
+++ b/apps/desktop/src/components/plugins/PluginIcon.vue
@@ -0,0 +1,72 @@
+<script setup lang="ts">
+import { onBeforeUnmount, ref, watch } from "vue";
+import { PlugZap } from "@lucide/vue";
+import * as api from "@/lib/backend/api";
+
+const props = defineProps<{
+ pluginId: string;
+ icon?: string;
+}>();
+
+const objectUrl = ref("");
+const failed = ref(false);
+let ownsObjectUrl = false;
+let requestSequence = 0;
+
+function clearObjectUrl() {
+ if (!objectUrl.value) return;
+ if (ownsObjectUrl) URL.revokeObjectURL(objectUrl.value);
+ objectUrl.value = "";
+ ownsObjectUrl = false;
+}
+
+function showFallback() {
+ clearObjectUrl();
+ failed.value = true;
+}
+
+watch(
+ () => [props.pluginId, props.icon] as const,
+ async ([pluginId, icon]) => {
+ const sequence = ++requestSequence;
+ clearObjectUrl();
+ if (!pluginId || !icon) {
+ failed.value = true;
+ return;
+ }
+ failed.value = false;
+ if (/^https?:\/\//i.test(icon)) {
+ objectUrl.value = icon;
+ return;
+ }
+ try {
+ const asset = await api.readPluginAsset(pluginId, icon);
+ if (!asset.contentType.startsWith("image/")) throw new Error("Plugin icon is not an image");
+ const binary = atob(asset.dataBase64);
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
+ const url = URL.createObjectURL(new Blob([bytes], { type: asset.contentType }));
+ if (sequence !== requestSequence) {
+ URL.revokeObjectURL(url);
+ return;
+ }
+ objectUrl.value = url;
+ ownsObjectUrl = true;
+ } catch {
+ if (sequence === requestSequence) failed.value = true;
+ }
+ },
+ { immediate: true },
+);
+
+onBeforeUnmount(() => {
+ requestSequence += 1;
+ clearObjectUrl();
+});
+</script>
+
+<template>
+ <span class="inline-flex shrink-0 items-center justify-center">
+ <img v-if="objectUrl && !failed" :src="objectUrl" alt="" class="size-full object-contain" @error="showFallback" />
+ <PlugZap v-else aria-hidden="true" class="size-full text-violet-500" />
+ </span>
+</template>
diff --git a/apps/desktop/src/components/plugins/PluginWorkbenchHost.vue b/apps/desktop/src/components/plugins/PluginWorkbenchHost.vue
new file mode 100644
index 0000000000..d71b451ff5
--- /dev/null
+++ b/apps/desktop/src/components/plugins/PluginWorkbenchHost.vue
@@ -0,0 +1,196 @@
+<script setup lang="ts">
+import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
+import { AlertTriangle, Loader2 } from "@lucide/vue";
+import * as api from "@/lib/backend/api";
+import { PluginHostBridge, pluginSandboxDocument, type PluginBridgeTheme, type PluginWorkbenchContext } from "@/lib/plugins/pluginHostBridge";
+import type { InstalledPlugin, PluginWorkbenchContribution } from "@/types/database";
+import { useI18n } from "vue-i18n";
+import { useTheme } from "@/composables/useTheme";
+
+const props = withDefaults(
+ defineProps<{
+ plugin: InstalledPlugin;
+ contribution: PluginWorkbenchContribution;
+ context?: PluginWorkbenchContext;
+ }>(),
+ { context: () => ({}) },
+);
+
+const emit = defineEmits<{
+ ready: [];
+ error: [message: string];
+ openWorkbench: [pluginId: string, contributionId: string, context?: PluginWorkbenchContext];
+ openFilesystem: [pluginId: string, providerId: string, context?: PluginWorkbenchContext];
+}>();
+
+const { t, locale: appLocale } = useI18n();
+const { isDark, activeCustomUiColors } = useTheme();
+const iframe = ref<HTMLIFrameElement>();
+const source = ref("");
+const loading = ref(true);
+const error = ref("");
+let bridge: PluginHostBridge | undefined;
+let unsubscribeEvents: (() => void) | undefined;
+let disposed = false;
+let loadGeneration = 0;
+
+const title = computed(() => `${props.plugin.manifest.name} · ${props.contribution.label}`);
+
+/** Collect resolved DBX design tokens so the sandbox can theme itself with the same values. */
+function currentBridgeTheme(): PluginBridgeTheme {
+ const tokens: Record<string, string> = {};
+ if (typeof document !== "undefined") {
+ const style = getComputedStyle(document.documentElement);
+ for (const name of style) {
+ if (!name.startsWith("--") || name.startsWith("--dbx-")) continue;
+ if (/^--(color|radius|font)/.test(name)) {
+ const value = style.getPropertyValue(name).trim();
+ if (value) tokens[name] = value;
+ }
+ }
+ }
+ return { appearance: isDark.value ? "dark" : "light", tokens };
+}
+
+function createBridge() {
+ bridge = new PluginHostBridge(
+ props.plugin,
+ props.contribution,
+ props.context,
+ () => iframe.value?.contentWindow || null,
+ {
+ invoke: api.invokePlugin,
+ notify: api.notifyPlugin,
+ sendBinary: api.sendPluginBinary,
+ readAsset: api.readPluginUiAsset,
+ openWorkbench: async (pluginId, contributionId, context) => emit("openWorkbench", pluginId, contributionId, context),
+ openFilesystem: async (pluginId, providerId, context) => emit("openFilesystem", pluginId, providerId, context),
+ },
+ appLocale.value,
+ currentBridgeTheme(),
+ );
+}
+
+function localUiAssetPath(source: string): string | undefined {
+ const trimmed = source.trim();
+ if (!trimmed || /^(?:blob:|data:|https?:|\/\/)/i.test(trimmed)) return undefined;
+ try {
+ const resolved = new URL(trimmed, "https://dbx-plugin.invalid/");
+ if (resolved.origin !== "https://dbx-plugin.invalid") return undefined;
+ const path = decodeURIComponent(resolved.pathname).replace(/^\/+/, "");
+ if (!path || path.split("/").some((segment) => segment === "..")) return undefined;
+ return path;
+ } catch {
+ return undefined;
+ }
+}
+
+async function inlineLocalUiAssets(html: string, pluginId: string): Promise<string> {
+ const document = new DOMParser().parseFromString(html, "text/html");
+ const resources = [...document.querySelectorAll("script[src], link[rel='stylesheet'][href]")];
+ for (const resource of resources) {
+ const source = resource.getAttribute(resource.tagName === "SCRIPT" ? "src" : "href");
+ const path = source ? localUiAssetPath(source) : undefined;
+ if (!path) continue;
+ const asset = await api.readPluginUiAsset(pluginId, path);
+ const content = new TextDecoder().decode(Uint8Array.from(atob(asset.dataBase64), (character) => character.charCodeAt(0)));
+ if (resource.tagName === "SCRIPT") {
+ const script = document.createElement("script");
+ for (const attribute of [...resource.attributes]) {
+ if (attribute.name !== "src") script.setAttribute(attribute.name, attribute.value);
+ }
+ script.textContent = content;
+ resource.replaceWith(script);
+ } else {
+ const style = document.createElement("style");
+ style.textContent = content;
+ resource.replaceWith(style);
+ }
+ }
+ return document.documentElement.outerHTML;
+}
+
+async function loadWorkbench() {
+ const generation = ++loadGeneration;
+ bridge = undefined;
+ loading.value = true;
+ error.value = "";
+ try {
+ if (!props.plugin.compatibility.compatible) throw new Error((props.plugin.compatibility.errors || []).join("; ") || t("pluginPlatform.pluginIncompatible"));
+ const asset = await api.readPluginUiEntry(props.plugin.manifest.id);
+ if (disposed || generation !== loadGeneration) return;
+ const bytes = Uint8Array.from(atob(asset.dataBase64), (character) => character.charCodeAt(0));
+ const html = await inlineLocalUiAssets(new TextDecoder().decode(bytes), props.plugin.manifest.id);
+ if (disposed || generation !== loadGeneration) return;
+ source.value = pluginSandboxDocument(html, props.plugin.manifest.permissions);
+ await nextTick();
+ if (disposed || generation !== loadGeneration) return;
+ createBridge();
+ } catch (cause) {
+ if (disposed || generation !== loadGeneration) return;
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ emit("error", error.value);
+ } finally {
+ if (!disposed && generation === loadGeneration) loading.value = false;
+ }
+}
+
+function onMessage(event: MessageEvent) {
+ bridge?.handleWindowMessage(event);
+}
+
+function onFrameLoad() {
+ bridge?.sendInit();
+ emit("ready");
+}
+
+onMounted(async () => {
+ window.addEventListener("message", onMessage);
+ const unsubscribe = await api.subscribePluginEvents(
+ (event) => bridge?.forwardEvent(event),
+ (event) => bridge?.forwardBinary(event),
+ );
+ if (disposed) {
+ unsubscribe();
+ return;
+ }
+ unsubscribeEvents = unsubscribe;
+ await loadWorkbench();
+});
+
+// Identity changes require rebuilding the sandbox document; context and locale
+// changes are pushed through the bridge so plugin UI state survives them.
+watch(
+ () => [props.plugin.manifest.id, props.plugin.manifest.version, props.contribution.id] as const,
+ () => void loadWorkbench(),
+);
+watch(
+ () => props.context,
+ (context) => bridge?.updateContext(context ?? {}),
+ { deep: true },
+);
+watch(appLocale, (locale) => bridge?.updateLocale(locale));
+watch([isDark, activeCustomUiColors], () => bridge?.updateTheme(currentBridgeTheme()), { deep: true });
+
+onBeforeUnmount(() => {
+ disposed = true;
+ loadGeneration += 1;
+ bridge = undefined;
+ window.removeEventListener("message", onMessage);
+ unsubscribeEvents?.();
+});
+</script>
+
+<template>
+ <div class="relative flex size-full min-h-40 overflow-hidden bg-background">
+ <div v-if="loading" class="absolute inset-0 z-10 flex items-center justify-center bg-background/80 text-sm text-muted-foreground backdrop-blur-sm">
+ <Loader2 class="mr-2 size-4 animate-spin" />
+ {{ t("pluginPlatform.loadingTitle", { title }) }}
+ </div>
+ <div v-else-if="error" class="m-auto flex max-w-lg items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm text-destructive">
+ <AlertTriangle class="mt-0.5 size-4 shrink-0" />
+ <span>{{ error }}</span>
+ </div>
+ <iframe v-else ref="iframe" :title="title" :srcdoc="source" sandbox="allow-scripts" referrerpolicy="no-referrer" class="size-full border-0 bg-transparent" @load="onFrameLoad" />
+ </div>
+</template>
diff --git a/apps/desktop/src/components/plugins/PluginWorkbenchTab.vue b/apps/desktop/src/components/plugins/PluginWorkbenchTab.vue
new file mode 100644
index 0000000000..1356258ca5
--- /dev/null
+++ b/apps/desktop/src/components/plugins/PluginWorkbenchTab.vue
@@ -0,0 +1,77 @@
+<script setup lang="ts">
+import { computed, onMounted, ref, watch } from "vue";
+import { AlertTriangle, Loader2 } from "@lucide/vue";
+import PluginWorkbenchHost from "@/components/plugins/PluginWorkbenchHost.vue";
+import * as api from "@/lib/backend/api";
+import { createFrontendPluginRegistry } from "@/lib/plugins/frontendPlugin";
+import type { PluginWorkbenchContext } from "@/lib/plugins/pluginHostBridge";
+import type { InstalledPlugin } from "@/types/database";
+import { useQueryStore } from "@/stores/queryStore";
+import { useI18n } from "vue-i18n";
+
+const props = defineProps<{
+ pluginId: string;
+ contributionId: string;
+ context?: PluginWorkbenchContext;
+}>();
+
+const { t, locale: appLocale } = useI18n();
+const queryStore = useQueryStore();
+const plugins = ref<InstalledPlugin[]>([]);
+const loading = ref(true);
+const error = ref("");
+let loadGeneration = 0;
+const entry = computed(() => createFrontendPluginRegistry(plugins.value, appLocale.value).findWorkbench(props.pluginId, props.contributionId));
+
+async function load() {
+ const generation = ++loadGeneration;
+ loading.value = true;
+ error.value = "";
+ try {
+ const installed = await api.listPlugins();
+ if (generation !== loadGeneration) return;
+ plugins.value = installed;
+ if (!entry.value) throw new Error(t("pluginPlatform.workbenchUnavailable", { pluginId: props.pluginId, contributionId: props.contributionId }));
+ } catch (cause) {
+ if (generation !== loadGeneration) return;
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ } finally {
+ if (generation === loadGeneration) loading.value = false;
+ }
+}
+
+function openWorkbench(pluginId: string, contributionId: string, context?: PluginWorkbenchContext) {
+ const target = createFrontendPluginRegistry(plugins.value, appLocale.value).findWorkbench(pluginId, contributionId);
+ queryStore.openPluginWorkbench(pluginId, contributionId, { title: target?.contribution.label || contributionId, context });
+}
+
+function openFilesystem(pluginId: string, providerId: string, context?: PluginWorkbenchContext) {
+ const target = createFrontendPluginRegistry(plugins.value, appLocale.value)
+ .listFilesystemProviders()
+ .find((entry) => entry.plugin.manifest.id === pluginId && entry.contribution.id === providerId);
+ if (!target) throw new Error(t("pluginPlatform.filesystemUnavailable", { pluginId, providerId }));
+ queryStore.openPluginFilesystem(pluginId, providerId, {
+ title: target.contribution.label,
+ connectionId: typeof context?.connectionId === "string" ? context.connectionId : undefined,
+ rootUri: target.contribution.root_uri,
+ currentUri: typeof context?.uri === "string" ? context.uri : undefined,
+ });
+}
+
+onMounted(() => void load());
+watch(
+ () => [props.pluginId, props.contributionId],
+ () => void load(),
+);
+</script>
+
+<template>
+ <div class="flex size-full min-h-0">
+ <div v-if="loading" class="m-auto flex items-center text-sm text-muted-foreground"><Loader2 class="mr-2 size-4 animate-spin" />{{ t("pluginPlatform.loadingWorkbench") }}</div>
+ <div v-else-if="error || !entry" class="m-auto flex max-w-lg items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm text-destructive">
+ <AlertTriangle class="mt-0.5 size-4 shrink-0" />
+ <span>{{ error || t("pluginPlatform.workbenchUnavailableFallback") }}</span>
+ </div>
+ <PluginWorkbenchHost v-else class="min-h-0 flex-1" :plugin="entry.plugin" :contribution="entry.contribution" :context="context" @open-workbench="openWorkbench" @open-filesystem="openFilesystem" />
+ </div>
+</template>
diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
index a406133fe3..81c0973356 100644
--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
@@ -28,6 +28,7 @@ import {
Plug,
Unplug,
Pin,
+ PlugZap,
ArrowRightLeft,
Download,
Eye,
@@ -70,6 +71,8 @@ import { useSettingsStore } from "@/stores/settingsStore";
import { useSavedSqlStore } from "@/stores/savedSqlStore";
import { savedSqlErrorMessage } from "@/lib/savedSql/savedSqlErrors";
import { useToast } from "@/composables/useToast";
+import { createFrontendPluginRegistry } from "@/lib/plugins/frontendPlugin";
+import type { InstalledPlugin } from "@/types/database";
import { useDatabaseOptions } from "@/composables/useDatabaseOptions";
import type { ColumnInfo, ConnectionConfig, DatabaseType, TreeNode, TreeNodeType } from "@/types/database";
import * as api from "@/lib/backend/api";
@@ -339,7 +342,7 @@ import {
type DuplicateStructureSource,
} from "./sidebarTreeDialogState";
-const { t } = useI18n();
+const { t, locale: appLocale } = useI18n();
const connectionStore = useConnectionStore();
@@ -350,6 +353,15 @@ const settingsStore = useSettingsStore();
const savedSqlStore = useSavedSqlStore();
const { toast } = useToast();
+const installedPlugins = ref<InstalledPlugin[]>([]);
+const sidebarPluginRegistry = computed(() => createFrontendPluginRegistry(installedPlugins.value, appLocale.value));
+
+void api.listPlugins().then(
+ (plugins) => {
+ installedPlugins.value = plugins.filter((plugin) => plugin.compatibility.compatible);
+ },
+ () => {},
+);
const { highlight } = useSqlHighlighter();
@@ -924,6 +936,9 @@ async function toggle(requestId = beginNavigationRequest()) {
await connectionStore.loadNacosNamespaces(node.connectionId, treeLoadSearchOptions);
} else if (config?.db_type === "mqtt") {
await connectionStore.loadMqttTopics(node.connectionId);
+ } else if (config?.db_type === "plugin") {
+ await queryStore.openPluginConnection(node.connectionId);
+ return;
} else {
await connectionStore.loadDatabases(node.connectionId, treeLoadSearchOptions);
}
@@ -1628,13 +1643,16 @@ async function openObjectBrowser(eventReadOnly = false, openEventEditor: boolean
const eventCreateRequestId = openEventEditor === "create" && node.type === "group-events" ? ++mysqlEventCreateRequestSeq : undefined;
const objectFilter = node.type === "event" || node.type === "group-events" ? "events" : undefined;
+ const connection = connectionStore.getConfig(node.connectionId);
+ if (!connection) return;
+ if (connection.db_type === "plugin") {
+ await queryStore.openPluginConnection(node.connectionId);
+ return;
+ }
if (hasTreeNodeDatabaseContext(node)) {
queryStore.openObjectBrowser(node.connectionId, node.database, node.schema, node.catalog, eventName, eventReadOnly, objectFilter, eventCreateRequestId);
return;
}
-
- const connection = connectionStore.getConfig(node.connectionId);
- if (!connection) return;
const options = await getDatabaseOptions(node.connectionId);
const database = resolveDefaultDatabase(connection, options);
if (database) {
@@ -6453,9 +6471,40 @@ function treeItemMenuItems(): ContextMenuItem[] {
items.push({ label: t("contextMenu.copyName"), action: copyName, icon: Copy, shortcut: shortcutCopyName.value });
}
+ appendPluginConnectionMenuItems(items, node);
+
return items;
}
+/** Plugin-contributed native menu entries for saved connections. */
+function appendPluginConnectionMenuItems(items: ContextMenuItem[], node: TreeNode) {
+ if (node.type !== "connection") return;
+ const pluginItems = sidebarPluginRegistry.value.listContextMenuItems("connection");
+ if (pluginItems.length === 0) return;
+ const config = node.connectionId ? connectionStore.getConfig(node.connectionId) : undefined;
+ if (!config) return;
+ items.push({ label: "", separator: true });
+ for (const { plugin, contribution } of pluginItems) {
+ items.push({
+ label: contribution.label,
+ icon: PlugZap,
+ action: () => {
+ api
+ .invokePlugin(plugin.manifest.id, `contextMenu/${contribution.id}`, {
+ connection: { id: config.id, dbType: config.db_type, name: config.name, database: config.database || "" },
+ })
+ .then((result) => {
+ const message = (result as { message?: unknown } | null | undefined)?.message;
+ if (typeof message === "string" && message.trim()) toast(message, 4000);
+ })
+ .catch((error: unknown) => {
+ toast(String((error as Error)?.message || error), 5000);
+ });
+ },
+ });
+ }
+}
+
function activateRuntimeNode(node: TreeNode) {
activeNode.value = node;
}
diff --git a/apps/desktop/src/components/ui/PasswordInput.vue b/apps/desktop/src/components/ui/PasswordInput.vue
index a6603f3b6a..23fc155dbd 100644
--- a/apps/desktop/src/components/ui/PasswordInput.vue
+++ b/apps/desktop/src/components/ui/PasswordInput.vue
@@ -4,6 +4,8 @@ import { useI18n } from "vue-i18n";
import { Eye, EyeOff } from "@lucide/vue";
import { Input } from "@/components/ui/input";
+defineOptions({ inheritAttrs: false });
+
const model = defineModel<string>();
const props = withDefaults(
diff --git a/apps/desktop/src/composables/__tests__/useTauriEvents.spec.ts b/apps/desktop/src/composables/__tests__/useTauriEvents.spec.ts
new file mode 100644
index 0000000000..e569cca8b0
--- /dev/null
+++ b/apps/desktop/src/composables/__tests__/useTauriEvents.spec.ts
@@ -0,0 +1,47 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const listeners = new Map<string, (event: { payload: unknown }) => void>();
+const unlisten = vi.fn();
+
+vi.mock("@tauri-apps/api/event", () => ({
+ listen: vi.fn(async (event: string, handler: (event: { payload: unknown }) => void) => {
+ listeners.set(event, handler);
+ return unlisten;
+ }),
+}));
+
+vi.mock("@/stores/connectionStore", () => ({
+ useConnectionStore: () => ({ connections: [], initFromDisk: vi.fn(), getConfig: vi.fn(), ensureConnected: vi.fn() }),
+}));
+
+vi.mock("@/stores/queryStore", () => ({
+ useQueryStore: () => ({ createTab: vi.fn(), showExecutedQueryResults: vi.fn() }),
+}));
+
+import { useTauriEvents } from "@/composables/useTauriEvents";
+
+describe("useTauriEvents", () => {
+ beforeEach(() => {
+ listeners.clear();
+ unlisten.mockClear();
+ });
+
+ it("routes the native macOS close-tab menu event to the active surface", async () => {
+ const closeActiveSurface = vi.fn();
+ const events = useTauriEvents({
+ openTableTarget: vi.fn(),
+ openSqlFilePath: vi.fn(),
+ openDbFilePath: vi.fn(),
+ openConnectionDeepLink: vi.fn(),
+ closeActiveSurface,
+ });
+
+ events.setupTauriListeners();
+ await vi.waitFor(() => expect(listeners.has("dbx-close-active-tab")).toBe(true));
+ listeners.get("dbx-close-active-tab")!({ payload: undefined });
+
+ expect(closeActiveSurface).toHaveBeenCalledOnce();
+ events.cleanupTauriListeners();
+ expect(unlisten).toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/composables/useTauriEvents.ts b/apps/desktop/src/composables/useTauriEvents.ts
index a3325497f6..a6fd2a4f90 100644
--- a/apps/desktop/src/composables/useTauriEvents.ts
+++ b/apps/desktop/src/composables/useTauriEvents.ts
@@ -9,6 +9,7 @@ export function useTauriEvents(deps: {
openDbFilePath: (path: string) => Promise<void>;
openConnectionDeepLink: (url: string) => Promise<void>;
openAiConfigDeepLink: (url: string) => Promise<void>;
+ closeActiveSurface: () => void;
}) {
const connectionStore = useConnectionStore();
const queryStore = useQueryStore();
@@ -116,6 +117,10 @@ export function useTauriEvents(deps: {
console.error("[DBX] dbx-open-ai-config-links error:", e);
}
}).then((unlisten) => unlistenHandles.push(unlisten));
+
+ listen("dbx-close-active-tab", () => {
+ deps.closeActiveSurface();
+ }).then((unlisten) => unlistenHandles.push(unlisten));
})
.catch(() => {});
}
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 39ffeaf841..ee075b2e89 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -164,6 +164,114 @@ export default {
name: "DBX",
},
docs,
+ pluginPlatform: {
+ openResultView: "Open with {label}",
+ centerTitle: "Plugin Center",
+ centerDescription: "Discover optional DBX capabilities in one marketplace, then manage installed plugins and repositories separately.",
+ marketplace: "Marketplace",
+ installed: "Installed",
+ settings: "Settings",
+ searchMarketplace: "Search plugins, publishers, or tags",
+ allRepositories: "All repositories",
+ loadingMarketplace: "Loading plugin marketplace",
+ noMarketplacePlugins: "No plugins to show",
+ noMarketplacePluginsDescription: "Configure a repository in Settings, or adjust the current search and filters.",
+ verified: "Verified",
+ noDescription: "No description provided.",
+ permissionsCount: "{count} permissions",
+ unsupportedTarget: "Not available for {target}",
+ installedVersion: "Installed v{version}",
+ licenseUnknown: "License not specified",
+ sourceRepository: "Source repository",
+ pluginHomepage: "Homepage",
+ marketplaceStatus: {
+ install: "Install",
+ installed: "Installed",
+ update: "Update",
+ unsupported: "Unsupported",
+ },
+ updateSuccess: "Updated {name} to {version}",
+ noInstalledPlugins: "No plugins installed",
+ browseMarketplace: "Browse Marketplace",
+ localInstallTitle: "Install a local package",
+ localInstallDescription: "Install a signed .dbxp obtained outside the marketplace. DBX verifies package integrity and repository signatures automatically.",
+ repositoriesTitle: "Plugin repositories",
+ repositoriesDescription: "The official source is signed and managed by DBX. Custom repositories use one repository-level trust key configured below.",
+ repositoryFieldsRequired: "Repository ID, name, and catalog URL are required",
+ repositorySaved: "Plugin repository '{name}' saved",
+ removeRepositoryConfirm: "Remove plugin repository '{name}'? Installed plugins remain installed.",
+ repositoryRemoved: "Plugin repository '{name}' removed",
+ repositoryKind: {
+ official: "Official",
+ custom: "Custom",
+ enterprise: "Enterprise",
+ },
+ repositoryNotConfigured: "Catalog URL is not configured in this build",
+ enabled: "Enabled",
+ disabled: "Disabled",
+ enable: "Enable",
+ disable: "Disable",
+ repositoryIdPlaceholder: "Repository ID",
+ repositoryNamePlaceholder: "Repository name",
+ repositoryCatalogUrlPlaceholder: "https://plugins.example.com/catalog/index.json",
+ addRepository: "Add repository",
+ signedPackagesVerifiedAutomatically: "Signatures are verified automatically",
+ developerOptionsTitle: "Third-party and developer options",
+ developerOptionsDescription: "Use only for custom repositories or local plugin development.",
+ developerOptionsWarning: "Unsigned plugins can run native code with your user permissions. Enable this only for packages you built and trust.",
+ connectionManagedInDialog: "Create and edit connections in the unified New Connection dialog. This page only manages plugins and shows their capabilities.",
+ allowUnsignedDevelopmentPackage: "Allow unsigned development packages",
+ allowUnsignedDevelopmentPackageDescription: "Applies only to manual .dbxp installation and never relaxes official marketplace verification.",
+ installPackage: "Install .dbxp",
+ dropToInstall: "Drop to install the plugin package",
+ dropInstallHint: "You can also drop a .dbxp file onto this page",
+ packageFileType: "DBX plugin package",
+ repositoryTrustTitle: "Custom repository trust",
+ repositoryTrustDescription: "A custom repository operator signs all approved packages with its repository key. Obtain that public key through a separate trusted channel.",
+ repositoryKeyAdded: "Repository signing key '{keyId}' added",
+ removeRepositoryKeyConfirm: "Remove repository signing key '{keyId}'? Installed plugins remain installed.",
+ repositoryKeyRemoved: "Repository signing key '{keyId}' removed",
+ repositoryKeyIdPlaceholder: "Repository key ID",
+ repositoryPublicKeyPlaceholder: "Base64 Ed25519 repository public key (32 bytes)",
+ trustRepository: "Trust repository",
+ noInstalledPluginsDescription: "Install a signed .dbxp, or explicitly enable unsigned packages for local development.",
+ compatible: "Compatible",
+ blocked: "Blocked",
+ rollback: "Rollback",
+ uninstall: "Uninstall",
+ rollbackConfirm: "Roll back this plugin to the previous installed version?",
+ rollbackSuccess: "Rolled back to {version}",
+ uninstallConfirm: "Uninstall {name}?",
+ uninstallSuccess: "Uninstalled {name}",
+ installSuccess: "Installed {name} {version}",
+ selectConnectionProvider: "Select a connection provider first",
+ connectionProvider: "Connection provider",
+ newConnection: "New",
+ workbenches: "Workbenches",
+ filesystemProviders: "Filesystem providers",
+ open: "Open",
+ browse: "Browse",
+ parentDirectory: "Parent directory",
+ filesystemUri: "Filesystem URI",
+ refresh: "Refresh",
+ loadingFiles: "Loading files",
+ emptyDirectory: "This directory is empty.",
+ loadMore: "Load more",
+ fileManagerHint: "Double-click a directory to open it, or a file to preview up to 256 KB.",
+ loadingPreview: "Loading preview",
+ previewTruncated: "Preview truncated at 256 KB",
+ previewSelectedFileHint: "Double-click the selected file to load its preview.",
+ entryCannotPreview: "This entry cannot be previewed.",
+ providerNoReadCapability: "The provider does not declare read capability.",
+ filesystemUnavailable: "Plugin filesystem '{pluginId}/{providerId}' is unavailable",
+ loadingFilesystem: "Loading plugin filesystem",
+ filesystemUnavailableFallback: "Plugin filesystem is unavailable",
+ workbenchUnavailable: "Plugin workbench '{pluginId}/{contributionId}' is unavailable",
+ loadingWorkbench: "Loading plugin workbench",
+ workbenchUnavailableFallback: "Plugin workbench is unavailable",
+ pluginIncompatible: "Plugin is incompatible",
+ loadingTitle: "Loading {title}",
+ },
auth: {
rateLimited: "Please try again in {seconds}s",
setupTitle: "Set up access password",
@@ -229,6 +337,7 @@ export default {
sqlOpenFailed: "Failed to open file: {message}",
sqlSaveFailed: "Failed to save file: {message}",
driverManager: "Driver Manager",
+ pluginCenter: "Plugin Center",
updatableDriverCount: "Updatable driver count",
mcpUpdateAvailable: "MCP server update available",
blockDangerousRedisCommands: "Block dangerous commands",
@@ -1005,6 +1114,9 @@ export default {
databaseCategoryTimeseries: "Time series",
databaseCategoryMq: "Message queues",
databaseCategoryRegistryConfig: "Registry/Config",
+ databaseCategoryPlugins: "Plugins",
+ pluginProviderUnavailable: "This plugin connection provider is unavailable. Reinstall or enable the plugin, then try again.",
+ pluginRequiredField: "{field} is required",
jdbcConnection: "JDBC connection",
iconView: "Icon view",
listView: "List view",
@@ -7961,6 +8073,13 @@ export default {
localInstall: "Local install",
localInstallHint: "For air-gapped machines: on another computer with internet access, download the official dbx-jdbc-plugin-*.zip from the DBX GitHub Releases page, transfer it here, and select it — no network access is needed on this machine.",
runtimeDrivers: "Runtime",
+ pluginsTab: "Plugins",
+ pluginContributionsTitle: "Frontend plugin contributions",
+ pluginContributionsDescription: "Installed plugins can describe connection forms and other UI contributions without injecting code into the main DBX window.",
+ noInstalledPlugins: "No installed plugins",
+ noInstalledPluginsDescription: "Install a backend plugin to preview its frontend contributions here.",
+ pluginHostPreview: "Host API preview",
+ pluginNoFrontendContribution: "This plugin does not declare a frontend contribution yet.",
storageTab: "Storage",
runtimeTitle: "Driver runtime",
runtimeHint: "Runtime metrics are collected only while this panel is open.",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 6c80cbdd51..ce2c1a50de 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -166,6 +166,105 @@ export default withEnglishFallback({
name: "DBX",
},
docs,
+ pluginPlatform: {
+ openResultView: "Abrir con {label}",
+ centerTitle: "Centro de plugins",
+ centerDescription: "Descubre capacidades opcionales de DBX en un marketplace unificado y administra por separado los plugins instalados y los repositorios.",
+ marketplace: "Marketplace",
+ installed: "Instalados",
+ settings: "Ajustes",
+ searchMarketplace: "Buscar plugins, editores o etiquetas",
+ allRepositories: "Todos los repositorios",
+ loadingMarketplace: "Cargando marketplace de plugins",
+ noMarketplacePlugins: "No hay plugins para mostrar",
+ noMarketplacePluginsDescription: "Configura un repositorio en Ajustes o cambia la búsqueda y los filtros.",
+ verified: "Verificado",
+ noDescription: "Sin descripción.",
+ permissionsCount: "{count} permisos",
+ unsupportedTarget: "No disponible para {target}",
+ installedVersion: "Instalado v{version}",
+ licenseUnknown: "Licencia no especificada",
+ sourceRepository: "Repositorio de código fuente",
+ pluginHomepage: "Página principal",
+ marketplaceStatus: { install: "Instalar", installed: "Instalado", update: "Actualizar", unsupported: "No compatible" },
+ updateSuccess: "Se actualizó {name} a {version}",
+ noInstalledPlugins: "No hay plugins instalados",
+ browseMarketplace: "Explorar Marketplace",
+ localInstallTitle: "Instalar un paquete local",
+ localInstallDescription: "Instala un .dbxp firmado obtenido fuera del marketplace. DBX verifica automáticamente la integridad y la firma del repositorio.",
+ repositoriesTitle: "Repositorios de plugins",
+ repositoriesDescription: "DBX administra la fuente oficial. Los repositorios propios o de terceros usan la configuración de confianza del repositorio.",
+ repositoryFieldsRequired: "El ID, el nombre y la URL del catálogo son obligatorios",
+ repositorySaved: "Se guardó el repositorio de plugins '{name}'",
+ removeRepositoryConfirm: "¿Eliminar el repositorio de plugins '{name}'? Los plugins instalados permanecerán.",
+ repositoryRemoved: "Se eliminó el repositorio de plugins '{name}'",
+ repositoryKind: { official: "Oficial", custom: "Personalizado", enterprise: "Empresarial" },
+ repositoryNotConfigured: "La URL del catálogo no está configurada en esta compilación",
+ enabled: "Activado",
+ disabled: "Desactivado",
+ enable: "Activar",
+ disable: "Desactivar",
+ repositoryIdPlaceholder: "ID del repositorio",
+ repositoryNamePlaceholder: "Nombre del repositorio",
+ repositoryCatalogUrlPlaceholder: "https://plugins.example.com/catalog/index.json",
+ addRepository: "Añadir repositorio",
+ signedPackagesVerifiedAutomatically: "Integridad y firmas verificadas automáticamente",
+ developerOptionsTitle: "Opciones de terceros y desarrollo",
+ developerOptionsDescription: "Úsalas solo para repositorios personalizados o desarrollo local de plugins.",
+ developerOptionsWarning: "Los plugins sin firma pueden ejecutar código nativo con tus permisos de usuario. Actívalo solo para paquetes creados y verificados por ti.",
+ connectionManagedInDialog: "Crea y edita conexiones en el cuadro unificado Nueva conexión. Esta página solo administra plugins y muestra sus capacidades.",
+ allowUnsignedDevelopmentPackage: "Permitir paquetes de desarrollo sin firmar",
+ allowUnsignedDevelopmentPackageDescription: "Solo afecta a la instalación manual de .dbxp y nunca reduce la verificación del marketplace oficial.",
+ installPackage: "Instalar .dbxp",
+ dropToInstall: "Suelta para instalar el paquete del plugin",
+ dropInstallHint: "También puedes soltar un archivo .dbxp en esta página",
+ packageFileType: "Paquete de plugin de DBX",
+ repositoryTrustTitle: "Confianza del repositorio personalizado",
+ repositoryTrustDescription: "El operador del repositorio firma todos los paquetes aprobados con una única clave. Obtén la clave pública mediante un canal independiente y confiable.",
+ repositoryKeyAdded: "Se añadió la clave de firma del repositorio '{keyId}'",
+ removeRepositoryKeyConfirm: "¿Quitar la clave de firma del repositorio '{keyId}'? Los plugins instalados permanecerán instalados.",
+ repositoryKeyRemoved: "Se quitó la clave de firma del repositorio '{keyId}'",
+ repositoryKeyIdPlaceholder: "ID de clave del repositorio",
+ repositoryPublicKeyPlaceholder: "Clave pública Ed25519 del repositorio en Base64 (32 bytes)",
+ trustRepository: "Confiar en el repositorio",
+ noInstalledPluginsDescription: "Instala un .dbxp firmado o permite explícitamente paquetes sin firmar para desarrollo local.",
+ compatible: "Compatible",
+ blocked: "Bloqueado",
+ rollback: "Revertir",
+ uninstall: "Desinstalar",
+ rollbackConfirm: "¿Revertir este plugin a la versión instalada anterior?",
+ rollbackSuccess: "Se revirtió a {version}",
+ uninstallConfirm: "¿Desinstalar {name}?",
+ uninstallSuccess: "Se desinstaló {name}",
+ installSuccess: "Se instaló {name} {version}",
+ selectConnectionProvider: "Selecciona primero un proveedor de conexión",
+ connectionProvider: "Proveedor de conexión",
+ newConnection: "Nueva",
+ workbenches: "Áreas de trabajo",
+ filesystemProviders: "Proveedores de sistema de archivos",
+ open: "Abrir",
+ browse: "Explorar",
+ parentDirectory: "Directorio superior",
+ filesystemUri: "URI del sistema de archivos",
+ refresh: "Actualizar",
+ loadingFiles: "Cargando archivos",
+ emptyDirectory: "Este directorio está vacío.",
+ loadMore: "Cargar más",
+ fileManagerHint: "Haz doble clic en un directorio para abrirlo o en un archivo para previsualizar hasta 256 KB.",
+ loadingPreview: "Cargando vista previa",
+ previewTruncated: "Vista previa truncada a 256 KB",
+ previewSelectedFileHint: "Haz doble clic en el archivo seleccionado para cargar su vista previa.",
+ entryCannotPreview: "No se puede previsualizar este elemento.",
+ providerNoReadCapability: "El proveedor no declara capacidad de lectura.",
+ filesystemUnavailable: "El sistema de archivos del plugin '{pluginId}/{providerId}' no está disponible",
+ loadingFilesystem: "Cargando sistema de archivos del plugin",
+ filesystemUnavailableFallback: "El sistema de archivos del plugin no está disponible",
+ workbenchUnavailable: "El área de trabajo del plugin '{pluginId}/{contributionId}' no está disponible",
+ loadingWorkbench: "Cargando área de trabajo del plugin",
+ workbenchUnavailableFallback: "El área de trabajo del plugin no está disponible",
+ pluginIncompatible: "El plugin no es compatible",
+ loadingTitle: "Cargando {title}",
+ },
auth: {
rateLimited: "Vuelva a intentarlo en {seconds} s",
setupTitle: "Configurar contraseña de acceso",
@@ -231,6 +330,7 @@ export default withEnglishFallback({
sqlOpenFailed: "Error al abrir el archivo: {message}",
sqlSaveFailed: "Error al guardar el archivo: {message}",
driverManager: "Administrador de drivers",
+ pluginCenter: "Centro de plugins",
updatableDriverCount: "Cantidad de drivers actualizables",
mcpUpdateAvailable: "Actualización del servidor MCP disponible",
blockDangerousRedisCommands: "Bloquear comandos peligrosos",
@@ -815,6 +915,9 @@ export default withEnglishFallback({
databaseCategoryTimeseries: "Temporal",
databaseCategoryMq: "Colas",
databaseCategoryRegistryConfig: "Registro/config.",
+ databaseCategoryPlugins: "Plugins",
+ pluginProviderUnavailable: "Este proveedor de conexión del plugin no está disponible. Reinstala o habilita el plugin e inténtalo de nuevo.",
+ pluginRequiredField: "{field} es obligatorio",
jdbcConnection: "Conexión JDBC",
iconView: "Vista de íconos",
listView: "Vista de lista",
@@ -7518,6 +7621,13 @@ export default withEnglishFallback({
localInstall: "Instalación local",
localInstallHint: "Para entornos sin acceso a internet: en otro equipo con conexión, descarga el dbx-jdbc-plugin-*.zip oficial desde la página de Releases de DBX en GitHub, transfiérelo a esta máquina y selecciónalo; no se necesita acceso a la red en este equipo.",
runtimeDrivers: "Runtime",
+ pluginsTab: "Plugins",
+ pluginContributionsTitle: "Contribuciones de frontend de plugins",
+ pluginContributionsDescription: "Los plugins instalados pueden describir formularios de conexión y otras contribuciones de UI sin inyectar código en la ventana principal de DBX.",
+ noInstalledPlugins: "No hay plugins instalados",
+ noInstalledPluginsDescription: "Instala un plugin de backend para previsualizar aquí sus contribuciones de frontend.",
+ pluginHostPreview: "Vista previa de la API del host",
+ pluginNoFrontendContribution: "Este plugin aún no declara ninguna contribución de frontend.",
storageTab: "Almacenamiento",
runtimeTitle: "Runtime de drivers",
runtimeHint: "Las métricas de runtime se recopilan solo mientras este panel está abierto.",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 68a6fe3bfb..020b0cfa28 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -165,6 +165,105 @@ export default withEnglishFallback({
name: "DBX",
},
docs,
+ pluginPlatform: {
+ openResultView: "Apri con {label}",
+ centerTitle: "Centro plugin",
+ centerDescription: "Scopri funzionalità DBX opzionali in un marketplace unico e gestisci separatamente plugin installati e repository.",
+ marketplace: "Marketplace",
+ installed: "Installati",
+ settings: "Impostazioni",
+ searchMarketplace: "Cerca plugin, autori o tag",
+ allRepositories: "Tutti i repository",
+ loadingMarketplace: "Caricamento marketplace plugin",
+ noMarketplacePlugins: "Nessun plugin da mostrare",
+ noMarketplacePluginsDescription: "Configura un repository nelle Impostazioni oppure modifica ricerca e filtri.",
+ verified: "Verificato",
+ noDescription: "Nessuna descrizione.",
+ permissionsCount: "{count} autorizzazioni",
+ unsupportedTarget: "Non disponibile per {target}",
+ installedVersion: "Installato v{version}",
+ licenseUnknown: "Licenza non specificata",
+ sourceRepository: "Repository del codice sorgente",
+ pluginHomepage: "Sito web",
+ marketplaceStatus: { install: "Installa", installed: "Installato", update: "Aggiorna", unsupported: "Non supportato" },
+ updateSuccess: "{name} aggiornato alla versione {version}",
+ noInstalledPlugins: "Nessun plugin installato",
+ browseMarketplace: "Sfoglia Marketplace",
+ localInstallTitle: "Installa un pacchetto locale",
+ localInstallDescription: "Installa un .dbxp firmato ottenuto fuori dal marketplace. DBX verifica automaticamente integrità e firma del repository.",
+ repositoriesTitle: "Repository dei plugin",
+ repositoriesDescription: "La sorgente ufficiale è gestita da DBX. I repository self-hosted o di terze parti usano le impostazioni di attendibilità del repository.",
+ repositoryFieldsRequired: "ID, nome e URL del catalogo sono obbligatori",
+ repositorySaved: "Repository plugin '{name}' salvato",
+ removeRepositoryConfirm: "Rimuovere il repository plugin '{name}'? I plugin installati resteranno disponibili.",
+ repositoryRemoved: "Repository plugin '{name}' rimosso",
+ repositoryKind: { official: "Ufficiale", custom: "Personalizzato", enterprise: "Enterprise" },
+ repositoryNotConfigured: "URL del catalogo non configurato in questa build",
+ enabled: "Abilitato",
+ disabled: "Disabilitato",
+ enable: "Abilita",
+ disable: "Disabilita",
+ repositoryIdPlaceholder: "ID repository",
+ repositoryNamePlaceholder: "Nome repository",
+ repositoryCatalogUrlPlaceholder: "https://plugins.example.com/catalog/index.json",
+ addRepository: "Aggiungi repository",
+ signedPackagesVerifiedAutomatically: "Integrità e firme verificate automaticamente",
+ developerOptionsTitle: "Opzioni di terze parti e sviluppo",
+ developerOptionsDescription: "Usale solo per repository personalizzati o sviluppo locale di plugin.",
+ developerOptionsWarning: "I plugin non firmati possono eseguire codice nativo con i permessi dell'utente corrente. Abilitali solo per pacchetti creati e verificati da te.",
+ connectionManagedInDialog: "Crea e modifica le connessioni nella finestra unificata Nuova connessione. Questa pagina gestisce solo i plugin e ne mostra le capacità.",
+ allowUnsignedDevelopmentPackage: "Consenti pacchetti di sviluppo non firmati",
+ allowUnsignedDevelopmentPackageDescription: "Si applica solo all'installazione manuale di .dbxp e non riduce mai la verifica del marketplace ufficiale.",
+ installPackage: "Installa .dbxp",
+ dropToInstall: "Rilascia per installare il pacchetto del plugin",
+ dropInstallHint: "Puoi anche rilasciare un file .dbxp su questa pagina",
+ packageFileType: "Pacchetto plugin DBX",
+ repositoryTrustTitle: "Attendibilità del repository personalizzato",
+ repositoryTrustDescription: "Il gestore del repository firma tutti i pacchetti approvati con una singola chiave. Ottieni la chiave pubblica tramite un canale separato e attendibile.",
+ repositoryKeyAdded: "Chiave di firma del repository '{keyId}' aggiunta",
+ removeRepositoryKeyConfirm: "Rimuovere la chiave di firma del repository '{keyId}'? I plugin installati resteranno installati.",
+ repositoryKeyRemoved: "Chiave di firma del repository '{keyId}' rimossa",
+ repositoryKeyIdPlaceholder: "ID chiave repository",
+ repositoryPublicKeyPlaceholder: "Chiave pubblica Ed25519 Base64 del repository (32 byte)",
+ trustRepository: "Considera attendibile il repository",
+ noInstalledPluginsDescription: "Installa un .dbxp firmato oppure abilita esplicitamente i pacchetti non firmati per lo sviluppo locale.",
+ compatible: "Compatibile",
+ blocked: "Bloccato",
+ rollback: "Ripristina",
+ uninstall: "Disinstalla",
+ rollbackConfirm: "Ripristinare questo plugin alla versione installata precedente?",
+ rollbackSuccess: "Ripristinata la versione {version}",
+ uninstallConfirm: "Disinstallare {name}?",
+ uninstallSuccess: "{name} disinstallato",
+ installSuccess: "Installato {name} {version}",
+ selectConnectionProvider: "Seleziona prima un provider di connessione",
+ connectionProvider: "Provider di connessione",
+ newConnection: "Nuova",
+ workbenches: "Aree di lavoro",
+ filesystemProviders: "Provider del file system",
+ open: "Apri",
+ browse: "Sfoglia",
+ parentDirectory: "Directory superiore",
+ filesystemUri: "URI del file system",
+ refresh: "Aggiorna",
+ loadingFiles: "Caricamento file",
+ emptyDirectory: "Questa directory è vuota.",
+ loadMore: "Carica altro",
+ fileManagerHint: "Fai doppio clic su una directory per aprirla o su un file per visualizzare fino a 256 KB.",
+ loadingPreview: "Caricamento anteprima",
+ previewTruncated: "Anteprima troncata a 256 KB",
+ previewSelectedFileHint: "Fai doppio clic sul file selezionato per caricarne l'anteprima.",
+ entryCannotPreview: "Questo elemento non può essere visualizzato in anteprima.",
+ providerNoReadCapability: "Il provider non dichiara la capacità di lettura.",
+ filesystemUnavailable: "Il file system del plugin '{pluginId}/{providerId}' non è disponibile",
+ loadingFilesystem: "Caricamento file system del plugin",
+ filesystemUnavailableFallback: "Il file system del plugin non è disponibile",
+ workbenchUnavailable: "L'area di lavoro del plugin '{pluginId}/{contributionId}' non è disponibile",
+ loadingWorkbench: "Caricamento area di lavoro del plugin",
+ workbenchUnavailableFallback: "L'area di lavoro del plugin non è disponibile",
+ pluginIncompatible: "Il plugin non è compatibile",
+ loadingTitle: "Caricamento di {title}",
+ },
auth: {
rateLimited: "Riprova tra {seconds} s",
setupTitle: "Imposta la password di accesso",
@@ -230,6 +329,7 @@ export default withEnglishFallback({
sqlOpenFailed: "Impossibile aprire il file: {message}",
sqlSaveFailed: "Impossibile salvare il file: {message}",
driverManager: "Gestione Driver",
+ pluginCenter: "Centro plugin",
updatableDriverCount: "Driver aggiornabili",
mcpUpdateAvailable: "Aggiornamento server MCP disponibile",
blockDangerousRedisCommands: "Blocca comandi pericolosi",
@@ -814,6 +914,9 @@ export default withEnglishFallback({
databaseCategoryTimeseries: "Temporali",
databaseCategoryMq: "Code messaggi",
databaseCategoryRegistryConfig: "Registro/config.",
+ databaseCategoryPlugins: "Plugin",
+ pluginProviderUnavailable: "Questo provider di connessione del plugin non è disponibile. Reinstalla o abilita il plugin e riprova.",
+ pluginRequiredField: "{field} è obbligatorio",
jdbcConnection: "Connessione JDBC",
iconView: "Vista icone",
listView: "Vista elenco",
@@ -7519,6 +7622,13 @@ export default withEnglishFallback({
localInstallHint:
"Per ambienti completamente isolati: su un altro computer con accesso a internet, scarica il pacchetto ufficiale dbx-jdbc-plugin-*.zip dalla pagina Releases di DBX su GitHub, trasferiscilo su questa macchina e selezionalo: non è richiesto alcun accesso alla rete su questa macchina.",
runtimeDrivers: "Runtime",
+ pluginsTab: "Plugin",
+ pluginContributionsTitle: "Contributi frontend dei plugin",
+ pluginContributionsDescription: "I plugin installati possono descrivere moduli di connessione e altri contributi UI senza iniettare codice nella finestra principale di DBX.",
+ noInstalledPlugins: "Nessun plugin installato",
+ noInstalledPluginsDescription: "Installa un plugin backend per visualizzare qui l'anteprima dei suoi contributi frontend.",
+ pluginHostPreview: "Anteprima API host",
+ pluginNoFrontendContribution: "Questo plugin non dichiara ancora alcun contributo frontend.",
storageTab: "Archiviazione",
runtimeTitle: "Runtime del driver",
runtimeHint: "Le metriche di runtime vengono raccolte solo mentre questo pannello è aperto.",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index d977f8053e..e5a1f0cd8b 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -166,6 +166,105 @@ export default withEnglishFallback({
name: "DBX",
},
docs,
+ pluginPlatform: {
+ openResultView: "{label} で開く",
+ centerTitle: "プラグインセンター",
+ centerDescription: "統合マーケットプレイスで DBX の追加機能を探し、インストール済みプラグインとリポジトリを個別に管理します。",
+ marketplace: "マーケットプレイス",
+ installed: "インストール済み",
+ settings: "設定",
+ searchMarketplace: "プラグイン、発行者、タグを検索",
+ allRepositories: "すべてのリポジトリ",
+ loadingMarketplace: "プラグインマーケットプレイスを読み込み中",
+ noMarketplacePlugins: "表示できるプラグインがありません",
+ noMarketplacePluginsDescription: "設定でリポジトリを追加するか、検索条件を変更してください。",
+ verified: "認証済み",
+ noDescription: "説明はありません。",
+ permissionsCount: "権限 {count} 件",
+ unsupportedTarget: "{target} では利用できません",
+ installedVersion: "インストール済み v{version}",
+ licenseUnknown: "ライセンス未指定",
+ sourceRepository: "ソースリポジトリ",
+ pluginHomepage: "ホームページ",
+ marketplaceStatus: { install: "インストール", installed: "インストール済み", update: "更新", unsupported: "非対応" },
+ updateSuccess: "{name} を {version} に更新しました",
+ noInstalledPlugins: "プラグインはまだありません",
+ browseMarketplace: "マーケットプレイスを見る",
+ localInstallTitle: "ローカルパッケージをインストール",
+ localInstallDescription: "マーケットプレイス外で入手した署名済み .dbxp をインストールします。DBX が整合性とリポジトリ署名を自動検証します。",
+ repositoriesTitle: "プラグインリポジトリ",
+ repositoriesDescription: "公式ソースは DBX が管理します。セルフホストまたは第三者のリポジトリでは、リポジトリの信頼設定を使用します。",
+ repositoryFieldsRequired: "リポジトリ ID、名前、カタログ URL は必須です",
+ repositorySaved: "プラグインリポジトリ「{name}」を保存しました",
+ removeRepositoryConfirm: "プラグインリポジトリ「{name}」を削除しますか?インストール済みプラグインは残ります。",
+ repositoryRemoved: "プラグインリポジトリ「{name}」を削除しました",
+ repositoryKind: { official: "公式", custom: "カスタム", enterprise: "エンタープライズ" },
+ repositoryNotConfigured: "このビルドにはカタログ URL が設定されていません",
+ enabled: "有効",
+ disabled: "無効",
+ enable: "有効化",
+ disable: "無効化",
+ repositoryIdPlaceholder: "リポジトリ ID",
+ repositoryNamePlaceholder: "リポジトリ名",
+ repositoryCatalogUrlPlaceholder: "https://plugins.example.com/catalog/index.json",
+ addRepository: "リポジトリを追加",
+ signedPackagesVerifiedAutomatically: "整合性と署名を自動検証",
+ developerOptionsTitle: "サードパーティと開発者向けオプション",
+ developerOptionsDescription: "カスタムリポジトリまたはローカルプラグイン開発時のみ使用してください。",
+ developerOptionsWarning: "未署名プラグインは現在のユーザー権限でネイティブコードを実行できます。自分でビルドし信頼できる開発パッケージにのみ有効化してください。",
+ connectionManagedInDialog: "接続の作成と編集は共通の「新しい接続」ダイアログで行います。この画面はプラグイン管理と機能表示専用です。",
+ allowUnsignedDevelopmentPackage: "未署名の開発パッケージを許可",
+ allowUnsignedDevelopmentPackageDescription: "手動での .dbxp インストールにのみ適用され、公式マーケットプレイスの検証は緩和されません。",
+ installPackage: ".dbxp をインストール",
+ dropToInstall: "ドロップしてプラグインをインストール",
+ dropInstallHint: ".dbxp ファイルをこのページにドロップしてもインストールできます",
+ packageFileType: "DBX プラグインパッケージ",
+ repositoryTrustTitle: "カスタムリポジトリの信頼",
+ repositoryTrustDescription: "カスタムリポジトリ運営者は、承認したすべてのパッケージを単一のリポジトリ鍵で署名します。公開鍵は別の信頼できる経路で取得してください。",
+ repositoryKeyAdded: "リポジトリ署名鍵「{keyId}」を追加しました",
+ removeRepositoryKeyConfirm: "リポジトリ署名鍵「{keyId}」を削除しますか?インストール済みプラグインは残ります。",
+ repositoryKeyRemoved: "リポジトリ署名鍵「{keyId}」を削除しました",
+ repositoryKeyIdPlaceholder: "リポジトリ鍵 ID",
+ repositoryPublicKeyPlaceholder: "Base64 Ed25519 リポジトリ公開鍵(32 バイト)",
+ trustRepository: "リポジトリを信頼",
+ noInstalledPluginsDescription: "署名済み .dbxp をインストールするか、ローカル開発時のみ未署名パッケージを明示的に許可してください。",
+ compatible: "互換",
+ blocked: "ブロック済み",
+ rollback: "ロールバック",
+ uninstall: "アンインストール",
+ rollbackConfirm: "このプラグインを前のインストール済みバージョンへ戻しますか?",
+ rollbackSuccess: "{version} にロールバックしました",
+ uninstallConfirm: "{name} をアンインストールしますか?",
+ uninstallSuccess: "{name} をアンインストールしました",
+ installSuccess: "{name} {version} をインストールしました",
+ selectConnectionProvider: "先に接続プロバイダーを選択してください",
+ connectionProvider: "接続プロバイダー",
+ newConnection: "新規",
+ workbenches: "ワークベンチ",
+ filesystemProviders: "ファイルシステムプロバイダー",
+ open: "開く",
+ browse: "参照",
+ parentDirectory: "親ディレクトリ",
+ filesystemUri: "ファイルシステム URI",
+ refresh: "更新",
+ loadingFiles: "ファイルを読み込み中",
+ emptyDirectory: "このディレクトリは空です。",
+ loadMore: "さらに読み込む",
+ fileManagerHint: "ディレクトリをダブルクリックして開くか、ファイルをダブルクリックして最大 256 KB までプレビューします。",
+ loadingPreview: "プレビューを読み込み中",
+ previewTruncated: "プレビューは 256 KB で切り捨てられました",
+ previewSelectedFileHint: "選択したファイルをダブルクリックしてプレビューを読み込みます。",
+ entryCannotPreview: "この項目はプレビューできません。",
+ providerNoReadCapability: "プロバイダーは読み取り機能を宣言していません。",
+ filesystemUnavailable: "プラグインファイルシステム「{pluginId}/{providerId}」は利用できません",
+ loadingFilesystem: "プラグインファイルシステムを読み込み中",
+ filesystemUnavailableFallback: "プラグインファイルシステムは利用できません",
+ workbenchUnavailable: "プラグインワークベンチ「{pluginId}/{contributionId}」は利用できません",
+ loadingWorkbench: "プラグインワークベンチを読み込み中",
+ workbenchUnavailableFallback: "プラグインワークベンチは利用できません",
+ pluginIncompatible: "プラグインに互換性がありません",
+ loadingTitle: "{title} を読み込み中",
+ },
auth: {
rateLimited: "{seconds} 秒後に再試行してください",
setupTitle: "アクセスパスワードを設定",
@@ -231,6 +330,7 @@ export default withEnglishFallback({
sqlOpenFailed: "ファイルを開けませんでした: {message}",
sqlSaveFailed: "ファイルの保存に失敗しました: {message}",
driverManager: "ドライバーマネージャー",
+ pluginCenter: "プラグインセンター",
updatableDriverCount: "更新可能なドライバー数",
mcpUpdateAvailable: "MCPサーバーの更新があります",
blockDangerousRedisCommands: "危険なコマンドをブロック",
@@ -780,6 +880,9 @@ export default withEnglishFallback({
databaseCategoryTimeseries: "時系列DB",
databaseCategoryMq: "メッセージキュー",
databaseCategoryRegistryConfig: "登録/設定",
+ databaseCategoryPlugins: "プラグイン",
+ pluginProviderUnavailable: "このプラグイン接続プロバイダーは利用できません。プラグインを再インストールまたは有効化してください。",
+ pluginRequiredField: "{field} は必須です",
jdbcConnection: "JDBC 接続",
iconView: "アイコン表示",
listView: "リスト表示",
@@ -7570,6 +7673,13 @@ export default withEnglishFallback({
localInstall: "ローカルインストール",
localInstallHint: "完全に隔離されたネットワーク環境の場合:インターネットに接続できる別のコンピューターで DBX の GitHub Releases ページから公式の dbx-jdbc-plugin-*.zip をダウンロードし、このマシンに転送して選択してください。このマシンはネットワークに接続する必要はありません。",
runtimeDrivers: "ランタイム",
+ pluginsTab: "プラグイン",
+ pluginContributionsTitle: "フロントエンドプラグインコントリビューション",
+ pluginContributionsDescription: "インストール済みプラグインは、DBX のメインウィンドウにコードを注入せず、接続フォームやその他の UI コントリビューションを記述できます。",
+ noInstalledPlugins: "インストール済みプラグインはありません",
+ noInstalledPluginsDescription: "バックエンドプラグインをインストールすると、ここでフロントエンドコントリビューションをプレビューできます。",
+ pluginHostPreview: "ホスト API プレビュー",
+ pluginNoFrontendContribution: "このプラグインはまだフロントエンドコントリビューションを宣言していません。",
storageTab: "ストレージ",
runtimeTitle: "ドライバーランタイム",
runtimeHint: "ランタイムメトリクスはこのパネルが開いている間のみ収集されます。",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index f2d7971ff0..5451a36424 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -165,6 +165,114 @@ export default withEnglishFallback({
name: "DBX",
},
docs,
+ pluginPlatform: {
+ openResultView: "{label}(으)로 열기",
+ centerTitle: "플러그인 센터",
+ centerDescription: "하나의 마켓플레이스에서 선택적 DBX 기능을 찾고, 설치된 플러그인과 저장소를 별도로 관리하세요.",
+ marketplace: "마켓플레이스",
+ installed: "설치됨",
+ settings: "설정",
+ searchMarketplace: "플러그인, 게시자 또는 태그 검색",
+ allRepositories: "모든 저장소",
+ loadingMarketplace: "플러그인 마켓플레이스 로드 중",
+ noMarketplacePlugins: "표시할 플러그인이 없습니다",
+ noMarketplacePluginsDescription: "설정에서 저장소를 구성하거나 현재 검색 및 필터를 조정하세요.",
+ verified: "검증됨",
+ noDescription: "설명이 제공되지 않았습니다.",
+ permissionsCount: "권한 {count}개",
+ unsupportedTarget: "{target}에서는 사용할 수 없음",
+ installedVersion: "설치된 버전 v{version}",
+ licenseUnknown: "라이선스 미지정",
+ sourceRepository: "소스 저장소",
+ pluginHomepage: "홈페이지",
+ marketplaceStatus: {
+ install: "설치",
+ installed: "설치됨",
+ update: "업데이트",
+ unsupported: "지원되지 않음",
+ },
+ updateSuccess: "{name} 업데이트 완료: {version}",
+ noInstalledPlugins: "설치된 플러그인이 없습니다",
+ browseMarketplace: "마켓플레이스 둘러보기",
+ localInstallTitle: "로컬 패키지 설치",
+ localInstallDescription: "마켓플레이스 외부에서 받은 서명된 .dbxp를 설치합니다. DBX가 패키지 무결성과 저장소 서명을 자동으로 검증합니다.",
+ repositoriesTitle: "플러그인 저장소",
+ repositoriesDescription: "공식 소스는 DBX에서 관리합니다. 자체 호스팅 또는 타사 저장소는 저장소 신뢰 설정을 사용합니다.",
+ repositoryFieldsRequired: "저장소 ID, 이름 및 카탈로그 URL은 필수입니다",
+ repositorySaved: "플러그인 저장소 '{name}'을 저장했습니다",
+ removeRepositoryConfirm: "플러그인 저장소 '{name}'을 제거하시겠습니까? 설치된 플러그인은 유지됩니다.",
+ repositoryRemoved: "플러그인 저장소 '{name}'을 제거했습니다",
+ repositoryKind: {
+ official: "공식",
+ custom: "사용자 지정",
+ enterprise: "엔터프라이즈",
+ },
+ repositoryNotConfigured: "이 빌드에는 카탈로그 URL이 구성되어 있지 않습니다",
+ enabled: "활성화됨",
+ disabled: "비활성화됨",
+ enable: "활성화",
+ disable: "비활성화",
+ repositoryIdPlaceholder: "저장소 ID",
+ repositoryNamePlaceholder: "저장소 이름",
+ repositoryCatalogUrlPlaceholder: "https://plugins.example.com/catalog/index.json",
+ addRepository: "저장소 추가",
+ signedPackagesVerifiedAutomatically: "서명이 자동으로 검증됩니다",
+ developerOptionsTitle: "타사 및 개발자 옵션",
+ developerOptionsDescription: "사용자 지정 저장소 또는 로컬 플러그인 개발에만 사용하세요.",
+ developerOptionsWarning: "서명되지 않은 플러그인은 사용자 권한으로 네이티브 코드를 실행할 수 있습니다. 직접 빌드하고 신뢰하는 패키지에만 활성화하세요.",
+ connectionManagedInDialog: "통합된 새 연결 대화상자에서 연결을 만들고 편집하세요. 이 페이지는 플러그인 관리와 기능 표시에만 사용됩니다.",
+ allowUnsignedDevelopmentPackage: "서명되지 않은 개발 패키지 허용",
+ allowUnsignedDevelopmentPackageDescription: "수동 .dbxp 설치에만 적용되며 공식 마켓플레이스 검증은 완화하지 않습니다.",
+ installPackage: ".dbxp 설치",
+ dropToInstall: "놓아서 플러그인 패키지 설치",
+ dropInstallHint: ".dbxp 파일을 이 페이지에 끌어다 놓아도 설치할 수 있습니다",
+ packageFileType: "DBX 플러그인 패키지",
+ repositoryTrustTitle: "사용자 지정 저장소 신뢰",
+ repositoryTrustDescription: "사용자 지정 저장소 운영자는 하나의 저장소 키로 승인된 모든 패키지에 서명합니다. 별도의 신뢰할 수 있는 채널을 통해 공개 키를 받으세요.",
+ repositoryKeyAdded: "저장소 서명 키 '{keyId}'을 추가했습니다",
+ removeRepositoryKeyConfirm: "저장소 서명 키 '{keyId}'을 제거하시겠습니까? 설치된 플러그인은 유지됩니다.",
+ repositoryKeyRemoved: "저장소 서명 키 '{keyId}'을 제거했습니다",
+ repositoryKeyIdPlaceholder: "저장소 키 ID",
+ repositoryPublicKeyPlaceholder: "Base64 Ed25519 저장소 공개 키(32바이트)",
+ trustRepository: "저장소 신뢰",
+ noInstalledPluginsDescription: "서명된 .dbxp를 설치하거나 로컬 개발용 서명되지 않은 패키지를 명시적으로 허용하세요.",
+ compatible: "호환됨",
+ blocked: "차단됨",
+ rollback: "롤백",
+ uninstall: "제거",
+ rollbackConfirm: "이 플러그인을 이전 설치 버전으로 되돌리시겠습니까?",
+ rollbackSuccess: "{version}(으)로 롤백했습니다",
+ uninstallConfirm: "{name}을 제거하시겠습니까?",
+ uninstallSuccess: "{name}을 제거했습니다",
+ installSuccess: "{name} {version}을 설치했습니다",
+ selectConnectionProvider: "먼저 연결 제공자를 선택하세요",
+ connectionProvider: "연결 제공자",
+ newConnection: "새 연결",
+ workbenches: "워크벤치",
+ filesystemProviders: "파일 시스템 제공자",
+ open: "열기",
+ browse: "찾아보기",
+ parentDirectory: "상위 디렉터리",
+ filesystemUri: "파일 시스템 URI",
+ refresh: "새로 고침",
+ loadingFiles: "파일 로드 중",
+ emptyDirectory: "이 디렉터리는 비어 있습니다.",
+ loadMore: "더 불러오기",
+ fileManagerHint: "디렉터리를 두 번 클릭해 열거나 파일을 두 번 클릭해 최대 256KB까지 미리 봅니다.",
+ loadingPreview: "미리보기 로드 중",
+ previewTruncated: "미리보기가 256KB에서 잘렸습니다",
+ previewSelectedFileHint: "선택한 파일을 두 번 클릭해 미리보기를 로드하세요.",
+ entryCannotPreview: "이 항목은 미리 볼 수 없습니다.",
+ providerNoReadCapability: "제공자가 읽기 기능을 선언하지 않았습니다.",
+ filesystemUnavailable: "플러그인 파일 시스템 '{pluginId}/{providerId}'을 사용할 수 없습니다",
+ loadingFilesystem: "플러그인 파일 시스템 로드 중",
+ filesystemUnavailableFallback: "플러그인 파일 시스템을 사용할 수 없습니다",
+ workbenchUnavailable: "플러그인 워크벤치 '{pluginId}/{contributionId}'을 사용할 수 없습니다",
+ loadingWorkbench: "플러그인 워크벤치 로드 중",
+ workbenchUnavailableFallback: "플러그인 워크벤치를 사용할 수 없습니다",
+ pluginIncompatible: "플러그인이 호환되지 않습니다",
+ loadingTitle: "{title} 로드 중",
+ },
auth: {
rateLimited: "{seconds}초 후에 다시 시도해 주세요",
setupTitle: "접속 비밀번호 설정",
@@ -233,6 +341,7 @@ export default withEnglishFallback({
mcpUpdateAvailable: "MCP 서버 업데이트 가능",
blockDangerousRedisCommands: "위험한 명령 차단",
saveSqlFile: "원본 파일에 저장",
+ pluginCenter: "플러그인 센터",
},
multiDbExecute: {
title: "다중 데이터베이스 실행",
@@ -1191,6 +1300,9 @@ export default withEnglishFallback({
sshTotpCancelled: "일회용 코드 입력이 취소되었습니다",
mqttSearchPayloadPlaceholder: "메시지 Payload 검색...",
mqttNoMatchingMessages: "현재 Payload 필터 조건과 일치하는 로드된 메시지가 없습니다.",
+ databaseCategoryPlugins: "플러그인",
+ pluginProviderUnavailable: "이 플러그인 연결 제공자를 사용할 수 없습니다. 플러그인을 다시 설치하거나 활성화한 후 다시 시도하세요.",
+ pluginRequiredField: "{field}을(를) 입력하세요.",
},
editor: {
duckdbDraining: "이전 DuckDB 쿼리가 아직 중지 중입니다. 잠시 후 다시 시도해 주세요.",
@@ -7242,6 +7354,13 @@ export default withEnglishFallback({
localInstall: "로컬 설치",
localInstallHint: "완전한 폐쇄망 환경의 경우: 인터넷에 연결된 다른 컴퓨터에서 DBX GitHub Releases 페이지의 공식 dbx-jdbc-plugin-*.zip을 다운로드한 뒤 이 기기로 옮겨 선택하세요. 이 기기는 네트워크에 연결할 필요가 없습니다.",
runtimeDrivers: "런타임",
+ pluginsTab: "플러그인",
+ pluginContributionsTitle: "프론트엔드 플러그인 확장",
+ pluginContributionsDescription: "설치된 플러그인은 DBX 기본 창에 코드를 주입하지 않고 연결 양식과 기타 UI 확장을 선언할 수 있습니다.",
+ noInstalledPlugins: "설치된 플러그인이 없습니다",
+ noInstalledPluginsDescription: "백엔드 플러그인을 설치하면 여기에서 프론트엔드 확장을 미리 볼 수 있습니다.",
+ pluginHostPreview: "호스트 API 미리보기",
+ pluginNoFrontendContribution: "이 플러그인은 아직 프론트엔드 확장을 선언하지 않았습니다.",
storageTab: "저장 공간",
runtimeTitle: "드라이버 런타임",
runtimeHint: "런타임 메트릭은 이 패널이 열려 있는 동안에만 수집됩니다.",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 183484db99..d7cce92adc 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -166,6 +166,105 @@ export default withEnglishFallback({
name: "DBX",
},
docs,
+ pluginPlatform: {
+ openResultView: "Abrir com {label}",
+ centerTitle: "Central de plugins",
+ centerDescription: "Descubra recursos opcionais do DBX em um marketplace unificado e gerencie separadamente plugins instalados e repositórios.",
+ marketplace: "Marketplace",
+ installed: "Instalados",
+ settings: "Configurações",
+ searchMarketplace: "Buscar plugins, publicadores ou tags",
+ allRepositories: "Todos os repositórios",
+ loadingMarketplace: "Carregando marketplace de plugins",
+ noMarketplacePlugins: "Nenhum plugin para exibir",
+ noMarketplacePluginsDescription: "Configure um repositório nas Configurações ou ajuste a busca e os filtros.",
+ verified: "Verificado",
+ noDescription: "Nenhuma descrição fornecida.",
+ permissionsCount: "{count} permissões",
+ unsupportedTarget: "Indisponível para {target}",
+ installedVersion: "Instalado v{version}",
+ licenseUnknown: "Licença não informada",
+ sourceRepository: "Repositório do código-fonte",
+ pluginHomepage: "Página inicial",
+ marketplaceStatus: { install: "Instalar", installed: "Instalado", update: "Atualizar", unsupported: "Não compatível" },
+ updateSuccess: "{name} atualizado para {version}",
+ noInstalledPlugins: "Nenhum plugin instalado",
+ browseMarketplace: "Explorar Marketplace",
+ localInstallTitle: "Instalar pacote local",
+ localInstallDescription: "Instale um .dbxp assinado obtido fora do marketplace. O DBX verifica automaticamente a integridade e a assinatura do repositório.",
+ repositoriesTitle: "Repositórios de plugins",
+ repositoriesDescription: "A fonte oficial é gerenciada pelo DBX. Repositórios próprios ou de terceiros usam as configurações de confiança do repositório.",
+ repositoryFieldsRequired: "ID, nome e URL do catálogo são obrigatórios",
+ repositorySaved: "Repositório de plugins '{name}' salvo",
+ removeRepositoryConfirm: "Remover o repositório de plugins '{name}'? Os plugins instalados permanecerão.",
+ repositoryRemoved: "Repositório de plugins '{name}' removido",
+ repositoryKind: { official: "Oficial", custom: "Personalizado", enterprise: "Empresarial" },
+ repositoryNotConfigured: "A URL do catálogo não está configurada nesta compilação",
+ enabled: "Ativado",
+ disabled: "Desativado",
+ enable: "Ativar",
+ disable: "Desativar",
+ repositoryIdPlaceholder: "ID do repositório",
+ repositoryNamePlaceholder: "Nome do repositório",
+ repositoryCatalogUrlPlaceholder: "https://plugins.example.com/catalog/index.json",
+ addRepository: "Adicionar repositório",
+ signedPackagesVerifiedAutomatically: "Integridade e assinaturas verificadas automaticamente",
+ developerOptionsTitle: "Opções de terceiros e desenvolvimento",
+ developerOptionsDescription: "Use somente para repositórios personalizados ou desenvolvimento local de plugins.",
+ developerOptionsWarning: "Plugins sem assinatura podem executar código nativo com suas permissões de usuário. Ative apenas para pacotes criados e verificados por você.",
+ connectionManagedInDialog: "Crie e edite conexões na janela unificada Nova conexão. Esta página apenas gerencia plugins e exibe seus recursos.",
+ allowUnsignedDevelopmentPackage: "Permitir pacotes de desenvolvimento não assinados",
+ allowUnsignedDevelopmentPackageDescription: "Afeta apenas a instalação manual de .dbxp e nunca reduz a verificação do marketplace oficial.",
+ installPackage: "Instalar .dbxp",
+ dropToInstall: "Solte para instalar o pacote do plugin",
+ dropInstallHint: "Você também pode soltar um arquivo .dbxp nesta página",
+ packageFileType: "Pacote de plugin do DBX",
+ repositoryTrustTitle: "Confiança do repositório personalizado",
+ repositoryTrustDescription: "O operador do repositório assina todos os pacotes aprovados com uma única chave. Obtenha a chave pública por um canal separado e confiável.",
+ repositoryKeyAdded: "Chave de assinatura do repositório '{keyId}' adicionada",
+ removeRepositoryKeyConfirm: "Remover a chave de assinatura do repositório '{keyId}'? Os plugins instalados permanecerão instalados.",
+ repositoryKeyRemoved: "Chave de assinatura do repositório '{keyId}' removida",
+ repositoryKeyIdPlaceholder: "ID da chave do repositório",
+ repositoryPublicKeyPlaceholder: "Chave pública Ed25519 do repositório em Base64 (32 bytes)",
+ trustRepository: "Confiar no repositório",
+ noInstalledPluginsDescription: "Instale um .dbxp assinado ou permita explicitamente pacotes não assinados para desenvolvimento local.",
+ compatible: "Compatível",
+ blocked: "Bloqueado",
+ rollback: "Reverter",
+ uninstall: "Desinstalar",
+ rollbackConfirm: "Reverter este plugin para a versão instalada anterior?",
+ rollbackSuccess: "Revertido para {version}",
+ uninstallConfirm: "Desinstalar {name}?",
+ uninstallSuccess: "{name} desinstalado",
+ installSuccess: "{name} {version} instalado",
+ selectConnectionProvider: "Selecione primeiro um provedor de conexão",
+ connectionProvider: "Provedor de conexão",
+ newConnection: "Nova",
+ workbenches: "Áreas de trabalho",
+ filesystemProviders: "Provedores de sistema de arquivos",
+ open: "Abrir",
+ browse: "Explorar",
+ parentDirectory: "Diretório superior",
+ filesystemUri: "URI do sistema de arquivos",
+ refresh: "Atualizar",
+ loadingFiles: "Carregando arquivos",
+ emptyDirectory: "Este diretório está vazio.",
+ loadMore: "Carregar mais",
+ fileManagerHint: "Clique duas vezes em um diretório para abri-lo ou em um arquivo para visualizar até 256 KB.",
+ loadingPreview: "Carregando visualização",
+ previewTruncated: "Visualização truncada em 256 KB",
+ previewSelectedFileHint: "Clique duas vezes no arquivo selecionado para carregar sua visualização.",
+ entryCannotPreview: "Este item não pode ser visualizado.",
+ providerNoReadCapability: "O provedor não declara capacidade de leitura.",
+ filesystemUnavailable: "O sistema de arquivos do plugin '{pluginId}/{providerId}' não está disponível",
+ loadingFilesystem: "Carregando sistema de arquivos do plugin",
+ filesystemUnavailableFallback: "O sistema de arquivos do plugin não está disponível",
+ workbenchUnavailable: "A área de trabalho do plugin '{pluginId}/{contributionId}' não está disponível",
+ loadingWorkbench: "Carregando área de trabalho do plugin",
+ workbenchUnavailableFallback: "A área de trabalho do plugin não está disponível",
+ pluginIncompatible: "O plugin não é compatível",
+ loadingTitle: "Carregando {title}",
+ },
auth: {
rateLimited: "Tente novamente em {seconds}s",
setupTitle: "Configurar senha de acesso",
@@ -231,6 +330,7 @@ export default withEnglishFallback({
sqlOpenFailed: "Falha ao abrir o arquivo: {message}",
sqlSaveFailed: "Falha ao salvar o arquivo: {message}",
driverManager: "Gerenciador de Drivers",
+ pluginCenter: "Central de plugins",
updatableDriverCount: "Quantidade de drivers atualizáveis",
mcpUpdateAvailable: "Atualização do servidor MCP disponível",
blockDangerousRedisCommands: "Bloquear comandos perigosos",
@@ -815,6 +915,9 @@ export default withEnglishFallback({
databaseCategoryTimeseries: "Séries",
databaseCategoryMq: "Filas",
databaseCategoryRegistryConfig: "Registro/config.",
+ databaseCategoryPlugins: "Plugins",
+ pluginProviderUnavailable: "Este provedor de conexão do plugin não está disponível. Reinstale ou habilite o plugin e tente novamente.",
+ pluginRequiredField: "{field} é obrigatório",
jdbcConnection: "Conexão JDBC",
iconView: "Visualização em ícones",
listView: "Visualização em lista",
@@ -7520,6 +7623,13 @@ export default withEnglishFallback({
localInstall: "Instalação local",
localInstallHint: "Para ambientes sem acesso à internet: em outro computador com internet, baixe o dbx-jdbc-plugin-*.zip oficial na página de Releases do DBX no GitHub, transfira-o para esta máquina e selecione-o — nenhum acesso à rede é necessário aqui.",
runtimeDrivers: "Runtime",
+ pluginsTab: "Plugins",
+ pluginContributionsTitle: "Contribuições de frontend de plugins",
+ pluginContributionsDescription: "Plugins instalados podem descrever formulários de conexão e outras contribuições de UI sem injetar código na janela principal do DBX.",
+ noInstalledPlugins: "Nenhum plugin instalado",
+ noInstalledPluginsDescription: "Instale um plugin de backend para visualizar aqui suas contribuições de frontend.",
+ pluginHostPreview: "Prévia da API do host",
+ pluginNoFrontendContribution: "Este plugin ainda não declara uma contribuição de frontend.",
storageTab: "Armazenamento",
runtimeTitle: "Runtime do driver",
runtimeHint: "As métricas de runtime são coletadas apenas enquanto este painel está aberto.",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 1d0c47c65f..04a8373cdc 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -89,6 +89,105 @@ export default withEnglishFallback({
name: "DBX",
},
docs,
+ pluginPlatform: {
+ openResultView: "用 {label} 打开",
+ centerTitle: "插件中心",
+ centerDescription: "在统一商店中发现可选的 DBX 能力,并分别管理已安装插件和插件仓库。",
+ marketplace: "插件商店",
+ installed: "已安装",
+ settings: "设置",
+ searchMarketplace: "搜索插件、发布者或标签",
+ allRepositories: "全部仓库",
+ loadingMarketplace: "正在加载插件商店",
+ noMarketplacePlugins: "暂无可展示的插件",
+ noMarketplacePluginsDescription: "请在设置中配置插件仓库,或调整当前搜索与筛选条件。",
+ verified: "已认证",
+ noDescription: "开发者未提供说明。",
+ permissionsCount: "{count} 项权限",
+ unsupportedTarget: "暂不支持 {target}",
+ installedVersion: "已安装 v{version}",
+ licenseUnknown: "未声明许可证",
+ sourceRepository: "源码仓库",
+ pluginHomepage: "主页",
+ marketplaceStatus: { install: "安装", installed: "已安装", update: "更新", unsupported: "不支持" },
+ updateSuccess: "已将 {name} 更新到 {version}",
+ noInstalledPlugins: "尚未安装插件",
+ browseMarketplace: "浏览插件商店",
+ localInstallTitle: "安装本地插件包",
+ localInstallDescription: "安装从插件商店之外获得的已签名 .dbxp,DBX 会自动校验包完整性和仓库签名。",
+ repositoriesTitle: "插件仓库",
+ repositoriesDescription: "官方源由 DBX 管理;添加自托管或第三方仓库后,才会显示对应的仓库信任设置。",
+ repositoryFieldsRequired: "仓库 ID、名称和目录地址不能为空",
+ repositorySaved: "已保存插件仓库“{name}”",
+ removeRepositoryConfirm: "移除插件仓库“{name}”?已安装插件不会被卸载。",
+ repositoryRemoved: "已移除插件仓库“{name}”",
+ repositoryKind: { official: "官方", custom: "自定义", enterprise: "企业" },
+ repositoryNotConfigured: "当前构建未配置目录地址",
+ enabled: "已启用",
+ disabled: "已停用",
+ enable: "启用",
+ disable: "停用",
+ repositoryIdPlaceholder: "仓库 ID",
+ repositoryNamePlaceholder: "仓库名称",
+ repositoryCatalogUrlPlaceholder: "https://plugins.example.com/catalog/index.json",
+ addRepository: "添加仓库",
+ signedPackagesVerifiedAutomatically: "自动校验完整性和签名",
+ developerOptionsTitle: "第三方与开发者选项",
+ developerOptionsDescription: "在接入第三方仓库或开发本地插件时使用。",
+ developerOptionsWarning: "未签名插件可以使用当前用户权限运行原生代码。只应为自己构建且确认可信的开发包开启。",
+ connectionManagedInDialog: "连接统一在“新建连接”对话框中创建和编辑;这里仅负责插件管理与能力展示。",
+ allowUnsignedDevelopmentPackage: "允许安装未签名开发包",
+ allowUnsignedDevelopmentPackageDescription: "仅影响手动安装的 .dbxp,不会放宽官方插件商店的签名校验。",
+ installPackage: "安装 .dbxp",
+ dropToInstall: "释放以安装插件包",
+ dropInstallHint: "也可拖放 .dbxp 到插件中心页面安装",
+ packageFileType: "DBX 插件包",
+ repositoryTrustTitle: "自定义仓库信任",
+ repositoryTrustDescription: "自定义仓库运营方使用一个仓库密钥签署其审核通过的插件。请通过独立可信渠道获取仓库公钥。",
+ repositoryKeyAdded: "已添加仓库签名密钥“{keyId}”",
+ removeRepositoryKeyConfirm: "移除仓库签名密钥“{keyId}”?已安装的插件不会被卸载。",
+ repositoryKeyRemoved: "已移除仓库签名密钥“{keyId}”",
+ repositoryKeyIdPlaceholder: "仓库密钥 ID",
+ repositoryPublicKeyPlaceholder: "Base64 Ed25519 仓库公钥(32 字节)",
+ trustRepository: "信任仓库",
+ noInstalledPluginsDescription: "安装已签名的 .dbxp,或仅在本地开发时明确允许未签名包。",
+ compatible: "兼容",
+ blocked: "已阻止",
+ rollback: "回滚",
+ uninstall: "卸载",
+ rollbackConfirm: "将此插件回滚到上一个已安装版本?",
+ rollbackSuccess: "已回滚到 {version}",
+ uninstallConfirm: "卸载 {name}?",
+ uninstallSuccess: "已卸载 {name}",
+ installSuccess: "已安装 {name} {version}",
+ selectConnectionProvider: "请先选择连接提供者",
+ connectionProvider: "连接提供者",
+ newConnection: "新建",
+ workbenches: "工作台",
+ filesystemProviders: "文件系统提供者",
+ open: "打开",
+ browse: "浏览",
+ parentDirectory: "上级目录",
+ filesystemUri: "文件系统 URI",
+ refresh: "刷新",
+ loadingFiles: "正在加载文件",
+ emptyDirectory: "此目录为空。",
+ loadMore: "加载更多",
+ fileManagerHint: "双击目录可打开,双击文件可预览最多 256 KB 的内容。",
+ loadingPreview: "正在加载预览",
+ previewTruncated: "预览已在 256 KB 处截断",
+ previewSelectedFileHint: "双击所选文件以加载预览。",
+ entryCannotPreview: "此项目无法预览。",
+ providerNoReadCapability: "该提供者未声明读取能力。",
+ filesystemUnavailable: "插件文件系统“{pluginId}/{providerId}”不可用",
+ loadingFilesystem: "正在加载插件文件系统",
+ filesystemUnavailableFallback: "插件文件系统不可用",
+ workbenchUnavailable: "插件工作台“{pluginId}/{contributionId}”不可用",
+ loadingWorkbench: "正在加载插件工作台",
+ workbenchUnavailableFallback: "插件工作台不可用",
+ pluginIncompatible: "插件不兼容",
+ loadingTitle: "正在加载 {title}",
+ },
auth: {
rateLimited: "请 {seconds} 秒后再试",
setupTitle: "设置访问密码",
@@ -154,6 +253,7 @@ export default withEnglishFallback({
sqlOpenFailed: "打开文件失败:{message}",
sqlSaveFailed: "保存文件失败:{message}",
driverManager: "驱动管理",
+ pluginCenter: "插件中心",
updatableDriverCount: "可更新驱动数量",
mcpUpdateAvailable: "MCP 服务有可用更新",
blockDangerousRedisCommands: "拦截危险命令",
@@ -929,6 +1029,9 @@ export default withEnglishFallback({
databaseCategoryTimeseries: "时序数据库",
databaseCategoryMq: "消息队列",
databaseCategoryRegistryConfig: "注册与配置",
+ databaseCategoryPlugins: "插件",
+ pluginProviderUnavailable: "此插件连接提供者不可用,请重新安装或启用插件后再试。",
+ pluginRequiredField: "请填写{field}",
jdbcConnection: "JDBC 连接",
iconView: "图标视图",
listView: "列表视图",
@@ -7942,6 +8045,13 @@ export default withEnglishFallback({
localInstall: "本地安装",
localInstallHint: "适用于完全内网环境:在另一台可联网的电脑上,从 DBX 的 GitHub Releases 页面下载官方 dbx-jdbc-plugin-*.zip 安装包,拷贝到本机后在此选择该文件——本机无需联网即可完成安装。",
runtimeDrivers: "运行时",
+ pluginsTab: "插件",
+ pluginContributionsTitle: "前端插件贡献",
+ pluginContributionsDescription: "已安装插件可以声明连接表单和其他 UI 贡献点,不需要把第三方代码注入 DBX 主窗口。",
+ noInstalledPlugins: "暂无已安装插件",
+ noInstalledPluginsDescription: "安装后端插件后,可以在这里预览它声明的前端贡献。",
+ pluginHostPreview: "宿主 API 预览",
+ pluginNoFrontendContribution: "这个插件暂时还没有声明前端贡献点。",
storageTab: "存储",
runtimeTitle: "驱动运行时",
runtimeHint: "仅在打开此面板时采集运行时指标。",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index b51dbfb330..abd30a7888 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -166,6 +166,105 @@ export default withEnglishFallback({
name: "DBX",
},
docs,
+ pluginPlatform: {
+ openResultView: "用 {label} 開啟",
+ centerTitle: "外掛中心",
+ centerDescription: "在統一商店中探索選用的 DBX 能力,並分別管理已安裝外掛與外掛倉庫。",
+ marketplace: "外掛商店",
+ installed: "已安裝",
+ settings: "設定",
+ searchMarketplace: "搜尋外掛、發佈者或標籤",
+ allRepositories: "全部倉庫",
+ loadingMarketplace: "正在載入外掛商店",
+ noMarketplacePlugins: "沒有可顯示的外掛",
+ noMarketplacePluginsDescription: "請在設定中配置外掛倉庫,或調整目前的搜尋與篩選條件。",
+ verified: "已驗證",
+ noDescription: "開發者未提供說明。",
+ permissionsCount: "{count} 項權限",
+ unsupportedTarget: "暫不支援 {target}",
+ installedVersion: "已安裝 v{version}",
+ licenseUnknown: "未指定授權條款",
+ sourceRepository: "原始碼倉庫",
+ pluginHomepage: "主頁",
+ marketplaceStatus: { install: "安裝", installed: "已安裝", update: "更新", unsupported: "不支援" },
+ updateSuccess: "已將 {name} 更新至 {version}",
+ noInstalledPlugins: "尚未安裝外掛",
+ browseMarketplace: "瀏覽外掛商店",
+ localInstallTitle: "安裝本機外掛套件",
+ localInstallDescription: "安裝從外掛商店之外取得的已簽署 .dbxp,DBX 會自動驗證套件完整性與倉庫簽章。",
+ repositoriesTitle: "外掛倉庫",
+ repositoriesDescription: "官方來源由 DBX 管理;加入自託管或第三方倉庫後,才會顯示對應的倉庫信任設定。",
+ repositoryFieldsRequired: "倉庫 ID、名稱和目錄網址皆為必填",
+ repositorySaved: "已儲存外掛倉庫「{name}」",
+ removeRepositoryConfirm: "移除外掛倉庫「{name}」?已安裝的外掛不會被解除安裝。",
+ repositoryRemoved: "已移除外掛倉庫「{name}」",
+ repositoryKind: { official: "官方", custom: "自訂", enterprise: "企業" },
+ repositoryNotConfigured: "目前版本未配置目錄網址",
+ enabled: "已啟用",
+ disabled: "已停用",
+ enable: "啟用",
+ disable: "停用",
+ repositoryIdPlaceholder: "倉庫 ID",
+ repositoryNamePlaceholder: "倉庫名稱",
+ repositoryCatalogUrlPlaceholder: "https://plugins.example.com/catalog/index.json",
+ addRepository: "加入倉庫",
+ signedPackagesVerifiedAutomatically: "自動驗證完整性與簽章",
+ developerOptionsTitle: "第三方與開發者選項",
+ developerOptionsDescription: "在接入第三方倉庫或開發本機外掛時使用。",
+ developerOptionsWarning: "未簽署外掛可以使用目前使用者權限執行原生程式碼。只應為自行建置且確認可信的開發套件啟用。",
+ connectionManagedInDialog: "連線統一在「新增連線」對話框中建立與編輯;此處僅負責外掛管理與能力展示。",
+ allowUnsignedDevelopmentPackage: "允許安裝未簽署開發套件",
+ allowUnsignedDevelopmentPackageDescription: "僅影響手動安裝的 .dbxp,不會放寬官方外掛商店的簽章驗證。",
+ installPackage: "安裝 .dbxp",
+ dropToInstall: "放開以安裝外掛套件",
+ dropInstallHint: "也可拖放 .dbxp 到外掛中心頁面安裝",
+ packageFileType: "DBX 外掛套件",
+ repositoryTrustTitle: "自訂倉庫信任",
+ repositoryTrustDescription: "自訂倉庫營運方使用一個倉庫金鑰簽署其審核通過的外掛。請透過獨立可信管道取得倉庫公鑰。",
+ repositoryKeyAdded: "已新增倉庫簽署金鑰「{keyId}」",
+ removeRepositoryKeyConfirm: "移除倉庫簽署金鑰「{keyId}」?已安裝的外掛不會被解除安裝。",
+ repositoryKeyRemoved: "已移除倉庫簽署金鑰「{keyId}」",
+ repositoryKeyIdPlaceholder: "倉庫金鑰 ID",
+ repositoryPublicKeyPlaceholder: "Base64 Ed25519 倉庫公鑰(32 位元組)",
+ trustRepository: "信任倉庫",
+ noInstalledPluginsDescription: "安裝已簽署的 .dbxp,或僅在本機開發時明確允許未簽署套件。",
+ compatible: "相容",
+ blocked: "已阻擋",
+ rollback: "回復版本",
+ uninstall: "解除安裝",
+ rollbackConfirm: "將此外掛回復到上一個已安裝版本?",
+ rollbackSuccess: "已回復到 {version}",
+ uninstallConfirm: "解除安裝 {name}?",
+ uninstallSuccess: "已解除安裝 {name}",
+ installSuccess: "已安裝 {name} {version}",
+ selectConnectionProvider: "請先選擇連線提供者",
+ connectionProvider: "連線提供者",
+ newConnection: "新增",
+ workbenches: "工作台",
+ filesystemProviders: "檔案系統提供者",
+ open: "開啟",
+ browse: "瀏覽",
+ parentDirectory: "上層目錄",
+ filesystemUri: "檔案系統 URI",
+ refresh: "重新整理",
+ loadingFiles: "正在載入檔案",
+ emptyDirectory: "此目錄為空。",
+ loadMore: "載入更多",
+ fileManagerHint: "按兩下目錄可開啟,按兩下檔案可預覽最多 256 KB 的內容。",
+ loadingPreview: "正在載入預覽",
+ previewTruncated: "預覽已在 256 KB 處截斷",
+ previewSelectedFileHint: "按兩下所選檔案以載入預覽。",
+ entryCannotPreview: "此項目無法預覽。",
+ providerNoReadCapability: "此提供者未宣告讀取能力。",
+ filesystemUnavailable: "外掛檔案系統「{pluginId}/{providerId}」無法使用",
+ loadingFilesystem: "正在載入外掛檔案系統",
+ filesystemUnavailableFallback: "外掛檔案系統無法使用",
+ workbenchUnavailable: "外掛工作台「{pluginId}/{contributionId}」無法使用",
+ loadingWorkbench: "正在載入外掛工作台",
+ workbenchUnavailableFallback: "外掛工作台無法使用",
+ pluginIncompatible: "外掛不相容",
+ loadingTitle: "正在載入 {title}",
+ },
auth: {
rateLimited: "請 {seconds} 秒後再試",
setupTitle: "設定存取密碼",
@@ -231,6 +330,7 @@ export default withEnglishFallback({
sqlOpenFailed: "開啟檔案失敗:{message}",
sqlSaveFailed: "儲存檔案失敗:{message}",
driverManager: "驅動程式管理器",
+ pluginCenter: "外掛中心",
updatableDriverCount: "可更新驅動程式數量",
mcpUpdateAvailable: "MCP 服務有可用更新",
blockDangerousRedisCommands: "攔截危險命令",
@@ -814,6 +914,9 @@ export default withEnglishFallback({
databaseCategoryTimeseries: "時序資料庫",
databaseCategoryMq: "訊息佇列",
databaseCategoryRegistryConfig: "註冊與設定",
+ databaseCategoryPlugins: "外掛",
+ pluginProviderUnavailable: "此外掛連線提供者不可用,請重新安裝或啟用外掛後再試。",
+ pluginRequiredField: "請填寫{field}",
jdbcConnection: "JDBC 連線",
iconView: "圖示檢視",
listView: "清單檢視",
@@ -6822,6 +6925,13 @@ export default withEnglishFallback({
localInstall: "本機安裝",
localInstallHint: "適用於完全內網環境:在另一台可連網的電腦上,從 DBX 的 GitHub Releases 頁面下載官方 dbx-jdbc-plugin-*.zip 安裝包,傳輸到本機後在此選取該檔案——本機不需要連網即可完成安裝。",
runtimeDrivers: "執行環境",
+ pluginsTab: "外掛程式",
+ pluginContributionsTitle: "前端外掛程式貢獻",
+ pluginContributionsDescription: "已安裝的外掛程式可以描述連線表單和其他 UI 貢獻,而無需將程式碼注入 DBX 主視窗。",
+ noInstalledPlugins: "尚未安裝外掛程式",
+ noInstalledPluginsDescription: "安裝後端外掛程式後,可在此預覽其前端貢獻。",
+ pluginHostPreview: "宿主 API 預覽",
+ pluginNoFrontendContribution: "此外掛程式尚未宣告前端貢獻。",
storageTab: "儲存",
runtimeTitle: "驅動程式執行環境",
runtimeHint: "僅在開啟此面板時收集執行環境指標。",
diff --git a/apps/desktop/src/lib/__tests__/app/openTabsPersistence.spec.ts b/apps/desktop/src/lib/__tests__/app/openTabsPersistence.spec.ts
index c3d91efa31..d25a55cc8a 100644
--- a/apps/desktop/src/lib/__tests__/app/openTabsPersistence.spec.ts
+++ b/apps/desktop/src/lib/__tests__/app/openTabsPersistence.spec.ts
@@ -177,4 +177,62 @@ describe("openTabsPersistence originalSql round-trip", () => {
expect(restored.originalSql).toBe("SELECT 1");
expect(restored.externalSqlFileMissing).toBe(true);
});
+
+ it("preserves plugin workbench identity and connection-safe context", () => {
+ const [restored] = roundTrip([
+ queryTab({
+ id: "plugin-tab",
+ title: "Hello connection · Workbench",
+ connectionId: "plugin-connection",
+ database: "",
+ mode: "plugin-workbench",
+ pluginWorkbench: {
+ pluginId: "dbx.example.hello",
+ contributionId: "dbx.example.hello.main",
+ context: {
+ connectionId: "plugin-connection",
+ providerId: "hello.connection",
+ connectionType: "hello",
+ },
+ },
+ }),
+ ]);
+
+ expect(restored.mode).toBe("plugin-workbench");
+ expect(restored.pluginWorkbench).toEqual({
+ pluginId: "dbx.example.hello",
+ contributionId: "dbx.example.hello.main",
+ context: {
+ connectionId: "plugin-connection",
+ providerId: "hello.connection",
+ connectionType: "hello",
+ },
+ });
+ });
+
+ it("preserves host-owned plugin filesystem navigation", () => {
+ const [restored] = roundTrip([
+ queryTab({
+ id: "plugin-files",
+ title: "Object storage · Files",
+ connectionId: "plugin-connection",
+ database: "",
+ mode: "plugin-filesystem",
+ pluginFilesystem: {
+ pluginId: "dbx.example.storage",
+ providerId: "dbx.example.storage.files",
+ rootUri: "s3://bucket/",
+ currentUri: "s3://bucket/reports/",
+ },
+ }),
+ ]);
+
+ expect(restored.mode).toBe("plugin-filesystem");
+ expect(restored.pluginFilesystem).toEqual({
+ pluginId: "dbx.example.storage",
+ providerId: "dbx.example.storage.files",
+ rootUri: "s3://bucket/",
+ currentUri: "s3://bucket/reports/",
+ });
+ });
});
diff --git a/apps/desktop/src/lib/__tests__/connection/connectionDialog.deepLinkServices.spec.ts b/apps/desktop/src/lib/__tests__/connection/connectionDialog.deepLinkServices.spec.ts
index 6646a3b188..3ceaa8b02a 100644
--- a/apps/desktop/src/lib/__tests__/connection/connectionDialog.deepLinkServices.spec.ts
+++ b/apps/desktop/src/lib/__tests__/connection/connectionDialog.deepLinkServices.spec.ts
@@ -33,7 +33,7 @@ describe("ConnectionDialog service deep-link hydration", () => {
});
it("keeps failed one-time connections available for error inspection and retry", () => {
- const saveStart = source.indexOf("async function save()");
+ const saveStart = source.indexOf("async function save(");
const saveEnd = source.indexOf('const dialogTitle = ref("")', saveStart);
const saveBody = source.slice(saveStart, saveEnd);
diff --git a/apps/desktop/src/lib/__tests__/connection/connectionDialogDriverProfileConfig.spec.ts b/apps/desktop/src/lib/__tests__/connection/connectionDialogDriverProfileConfig.spec.ts
index 895eceb4c2..6916f401d3 100644
--- a/apps/desktop/src/lib/__tests__/connection/connectionDialogDriverProfileConfig.spec.ts
+++ b/apps/desktop/src/lib/__tests__/connection/connectionDialogDriverProfileConfig.spec.ts
@@ -22,6 +22,12 @@ describe("ConnectionDialog driver profile configuration", () => {
const submitConfig = connectionConfigForSubmitSource();
expect(submitConfig).toContain("setGaussdbTargetServerType(config, targetServerType)");
- expect(submitConfig).toContain("else if (!isDoltDriverProfile(config.driver_profile))");
+ expect(submitConfig).toContain('else if (config.db_type !== "plugin" && !isDoltDriverProfile(config.driver_profile))');
+ });
+
+ it("preserves plugin external configuration on submit", () => {
+ const submitConfig = connectionConfigForSubmitSource();
+
+ expect(submitConfig).toContain('else if (config.db_type !== "plugin" && !isDoltDriverProfile(config.driver_profile))');
});
});
diff --git a/apps/desktop/src/lib/__tests__/plugins/pluginCenterIntegration.spec.ts b/apps/desktop/src/lib/__tests__/plugins/pluginCenterIntegration.spec.ts
new file mode 100644
index 0000000000..7a06fb5cdc
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/plugins/pluginCenterIntegration.spec.ts
@@ -0,0 +1,58 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
+const toolbarSource = readFileSync(new URL("../../../components/layout/AppToolbar.vue", import.meta.url), "utf8");
+const tabBarSource = readFileSync(new URL("../../../components/layout/AppTabBar.vue", import.meta.url), "utf8");
+const driverStoreSource = readFileSync(new URL("../../../components/config/DriverStoreDialog.vue", import.meta.url), "utf8");
+const appDialogsSource = readFileSync(new URL("../../../components/layout/AppDialogs.vue", import.meta.url), "utf8");
+const connectionDialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
+const pluginCenterSource = readFileSync(new URL("../../../components/plugins/PluginContributionsPanel.vue", import.meta.url), "utf8");
+
+describe("plugin center integration", () => {
+ it("opens from the top toolbar as an independent app surface", () => {
+ expect(toolbarSource).toContain("toolbarItems.pluginCenter");
+ expect(toolbarSource).toContain("emit('open-plugin-center')");
+ expect(appSource).toContain('@open-plugin-center="openPluginCenterPage()"');
+ expect(appSource).toContain("<PluginCenterPage");
+ expect(tabBarSource).toContain("data-plugin-center-tab");
+ });
+
+ it("keeps plugin management out of Driver Manager", () => {
+ expect(driverStoreSource).not.toContain('value="plugins"');
+ expect(driverStoreSource).not.toContain("PluginContributionsPanel");
+ });
+
+ it("creates and edits plugin connections in the unified connection dialog", () => {
+ expect(appDialogsSource).toContain(':edit-config="editConfig"');
+ expect(appDialogsSource).toContain(':plugin-provider="connectionPluginProvider"');
+ expect(appDialogsSource).not.toContain("pluginEditConfig");
+ expect(connectionDialogSource).toContain("pluginConnectionProviderOptionValue");
+ expect(connectionDialogSource).toContain("<PluginConnectionFields");
+ expect(connectionDialogSource).toContain("buildPluginConnectionConfig");
+ });
+
+ it("keeps marketplace security automatic and developer controls hidden", () => {
+ const template = pluginCenterSource.split("<template>")[1];
+ const settingsIndex = template.indexOf('value="settings"');
+ const developerOptionsIndex = template.indexOf("pluginPlatform.developerOptionsTitle");
+ const allowUnsignedIndex = template.indexOf("pluginPlatform.allowUnsignedDevelopmentPackage");
+ expect(template).toContain('value="marketplace"');
+ expect(template).toContain('value="installed"');
+ expect(template).toContain('value="settings"');
+ expect(settingsIndex).toBeLessThan(developerOptionsIndex);
+ expect(developerOptionsIndex).toBeLessThan(allowUnsignedIndex);
+ expect(template).toContain("pluginPlatform.signedPackagesVerifiedAutomatically");
+ expect(template).toContain('<template v-if="showCustomRepositoryTrustSettings">');
+ expect(pluginCenterSource).toContain("customRepositories.value.length > 0 || trustedKeys.value.length > 0");
+ expect(template).not.toContain("pluginPlatform.advancedSecurityTitle");
+ expect(pluginCenterSource).toContain("fetchPluginMarketplaceCatalogs");
+ expect(template).not.toContain("pluginPlatform.centerTitle");
+ expect(template).not.toContain("marketplaceTarget");
+ expect(template).not.toContain("<select");
+ expect(template).toContain("<SelectTrigger");
+ expect(template).not.toContain("max-w-md grid-cols-3");
+ expect(template).not.toContain("marketplaceCategory");
+ expect(template).toContain("repeat(auto-fit");
+ });
+});
diff --git a/apps/desktop/src/lib/app/openTabsPersistence.ts b/apps/desktop/src/lib/app/openTabsPersistence.ts
index 257b394d49..eb0585908b 100644
--- a/apps/desktop/src/lib/app/openTabsPersistence.ts
+++ b/apps/desktop/src/lib/app/openTabsPersistence.ts
@@ -47,6 +47,8 @@ export interface SavedOpenTab {
whereInput?: string;
pinned?: boolean;
mode?: QueryTab["mode"];
+ pluginWorkbench?: QueryTab["pluginWorkbench"];
+ pluginFilesystem?: QueryTab["pluginFilesystem"];
autoCommit?: boolean;
mqTenant?: string;
mqInitialTab?: QueryTab["mqInitialTab"];
@@ -180,6 +182,8 @@ export function serializeOpenTabs(tabs: QueryTab[]): SavedOpenTab[] {
...(tab.whereInput !== undefined ? { whereInput: tab.whereInput } : {}),
pinned: tab.pinned,
mode: tab.mode,
+ ...(tab.pluginWorkbench ? { pluginWorkbench: tab.pluginWorkbench } : {}),
+ ...(tab.pluginFilesystem ? { pluginFilesystem: tab.pluginFilesystem } : {}),
...(tab.mode === "query" && tab.autoCommit !== undefined ? { autoCommit: tab.autoCommit } : {}),
...(tab.mqTenant !== undefined ? { mqTenant: tab.mqTenant } : {}),
...(tab.mqInitialTab !== undefined ? { mqInitialTab: tab.mqInitialTab } : {}),
@@ -213,6 +217,7 @@ export function serializeOpenTabs(tabs: QueryTab[]): SavedOpenTab[] {
...(tab.mode === "query" && tab.activeResultRunId !== undefined ? { activeResultRunId: tab.activeResultRunId } : {}),
...(tab.mode === "query" && typeof tab.resultAutoSave === "boolean" ? { resultAutoSave: tab.resultAutoSave } : {}),
...(tab.uiState ? { uiState: sanitizeTabUiState(tab.uiState) } : {}),
+ ...(tab.mode === "query" && tab.resultAutoSave ? { resultAutoSave: true } : {}),
}));
}
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index 92ebeae9f6..8c4caf54d6 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -79,6 +79,34 @@ export const readKeychainPassword = forward("readKeychainPassword");
export const readKeychainPasswords = forward("readKeychainPasswords");
export const decryptConfig = forward("decryptConfig");
export const listPlugins = forward("listPlugins");
+export const listPluginTrustedKeys = forward("listPluginTrustedKeys");
+export const savePluginTrustedKey = forward("savePluginTrustedKey");
+export const removePluginTrustedKey = forward("removePluginTrustedKey");
+export const listPluginRepositories = forward("listPluginRepositories");
+export const savePluginRepository = forward("savePluginRepository");
+export const removePluginRepository = forward("removePluginRepository");
+export const fetchPluginMarketplaceCatalogs = forward("fetchPluginMarketplaceCatalogs");
+export const installMarketplacePlugin = forward("installMarketplacePlugin");
+export const installPluginPackage = forward("installPluginPackage");
+export const rollbackPlugin = forward("rollbackPlugin");
+export const uninstallPlugin = forward("uninstallPlugin");
+export const activatePlugin = forward("activatePlugin");
+export const listActivePlugins = forward("listActivePlugins");
+export const stopPlugin = forward("stopPlugin");
+export const invokePlugin = forward("invokePlugin");
+export const invokePluginConnectionAction = forward("invokePluginConnectionAction");
+export const notifyPlugin = forward("notifyPlugin");
+export const sendPluginBinary = forward("sendPluginBinary");
+export const listPluginFilesystemEntries = forward("listPluginFilesystemEntries");
+export const readPluginFilesystemFile = forward("readPluginFilesystemFile");
+export const writePluginFilesystemFile = forward("writePluginFilesystemFile");
+export const createPluginFilesystemDirectory = forward("createPluginFilesystemDirectory");
+export const deletePluginFilesystemEntry = forward("deletePluginFilesystemEntry");
+export const renamePluginFilesystemEntry = forward("renamePluginFilesystemEntry");
+export const readPluginAsset = forward("readPluginAsset");
+export const readPluginUiEntry = forward("readPluginUiEntry");
+export const readPluginUiAsset = forward("readPluginUiAsset");
+export const subscribePluginEvents = forward("subscribePluginEvents");
export const listJdbcDrivers = forward("listJdbcDrivers");
export const listJdbcMavenBundles = forward("listJdbcMavenBundles");
export const listJdbcLocalBundles = forward("listJdbcLocalBundles");
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index ab863990ae..fed3767061 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -203,6 +203,22 @@ import type { BuildDatabaseSqlExportOptions, BuildExportInsertStatementsOptions
import { loadBrowserAppState, saveBrowserAppState } from "@/lib/backend/browserAppStateStorage";
import type { DataCompareFromTablesOptions, DataCompareFromTablesPreparation, DataCompareSyncPlan, DataCompareSyncPlanOptions, DataComparePreparation, DataComparePreparationOptions } from "@/lib/dataGrid/dataCompare";
import { apiUrl, apiWebSocketUrl } from "@/lib/common/webPath";
+import type {
+ ActivePluginSession,
+ PluginBinaryEvent,
+ PluginConnectionActionResult,
+ PluginEvent,
+ PluginFilesystemListResult,
+ PluginFilesystemMutationResult,
+ PluginFilesystemReadResult,
+ PluginInstallResult,
+ PluginMarketplaceInstallRequest,
+ PluginRepository,
+ PluginRepositoryCatalogResult,
+ PluginRollbackResult,
+ PluginTrustedKey,
+ PluginUiAssetPayload,
+} from "@/types/database";
import type { DataGridSavePreparation } from "@/lib/backend/tauri";
import type {
NacosBatchPreview,
@@ -519,6 +535,158 @@ export async function listPlugins(): Promise<InstalledPlugin[]> {
return get("/api/plugins");
}
+export async function listPluginTrustedKeys(): Promise<PluginTrustedKey[]> {
+ return get("/api/plugins/trusted-keys");
+}
+
+export async function savePluginTrustedKey(keyId: string, publicKey: string): Promise<PluginTrustedKey[]> {
+ return post("/api/plugins/trusted-keys/save", { keyId, publicKey });
+}
+
+export async function removePluginTrustedKey(keyId: string): Promise<PluginTrustedKey[]> {
+ return post("/api/plugins/trusted-keys/remove", { keyId });
+}
+
+export async function listPluginRepositories(): Promise<PluginRepository[]> {
+ return get("/api/plugins/repositories");
+}
+
+export async function savePluginRepository(repository: PluginRepository): Promise<PluginRepository[]> {
+ return post("/api/plugins/repositories/save", repository);
+}
+
+export async function removePluginRepository(repositoryId: string): Promise<PluginRepository[]> {
+ return post("/api/plugins/repositories/remove", { repositoryId });
+}
+
+export async function fetchPluginMarketplaceCatalogs(): Promise<PluginRepositoryCatalogResult[]> {
+ return get("/api/plugins/marketplace/catalogs");
+}
+
+export async function installMarketplacePlugin(request: PluginMarketplaceInstallRequest): Promise<PluginInstallResult> {
+ return post("/api/plugins/marketplace/install", request);
+}
+
+export async function installPluginPackage(pathOrFile: string | File, allowUnsigned = false): Promise<PluginInstallResult> {
+ let blob: Blob;
+ let fileName: string;
+ if (pathOrFile instanceof File) {
+ blob = pathOrFile;
+ fileName = pathOrFile.name;
+ } else {
+ fileName = pathOrFile.split("/").pop() || "plugin.dbxp";
+ blob = await (await fetch(pathOrFile)).blob();
+ }
+ const formData = new FormData();
+ formData.append("file", blob, fileName);
+ const response = await fetch(apiUrl(`/api/plugins/install?allow_unsigned=${allowUnsigned}`), { method: "POST", body: formData });
+ if (!response.ok) throw new Error(await response.text());
+ return response.json();
+}
+
+export async function rollbackPlugin(pluginId: string): Promise<PluginRollbackResult> {
+ return post("/api/plugins/rollback", { plugin_id: pluginId });
+}
+
+export async function uninstallPlugin(pluginId: string): Promise<InstalledPlugin[]> {
+ return post("/api/plugins/uninstall", { plugin_id: pluginId });
+}
+
+export async function activatePlugin(pluginId: string): Promise<ActivePluginSession[]> {
+ return post("/api/plugins/activate", { plugin_id: pluginId });
+}
+
+export async function listActivePlugins(): Promise<ActivePluginSession[]> {
+ return get("/api/plugins/active");
+}
+
+export async function stopPlugin(pluginId: string): Promise<void> {
+ await post("/api/plugins/stop", { plugin_id: pluginId });
+}
+
+export async function invokePlugin<T = unknown>(pluginId: string, method: string, params: unknown = null, timeoutMs?: number): Promise<T> {
+ return post("/api/plugins/invoke", { pluginId, method, params, timeoutMs });
+}
+
+export async function invokePluginConnectionAction(config: ConnectionConfig, actionId: string): Promise<PluginConnectionActionResult> {
+ return post("/api/plugins/connection-action", { config, actionId });
+}
+
+export async function notifyPlugin(pluginId: string, method: string, params: unknown = null): Promise<void> {
+ await post("/api/plugins/notify", { pluginId, method, params });
+}
+
+export async function sendPluginBinary(pluginId: string, channel: string, dataBase64: string): Promise<void> {
+ await post("/api/plugins/binary", { pluginId, channel, dataBase64 });
+}
+
+export async function listPluginFilesystemEntries(pluginId: string, providerId: string, options: { connectionId?: string; uri?: string; cursor?: string; limit?: number } = {}): Promise<PluginFilesystemListResult> {
+ return post("/api/plugins/filesystem/list", { pluginId, providerId, ...options });
+}
+
+export async function readPluginFilesystemFile(pluginId: string, providerId: string, uri: string, options: { connectionId?: string; maxBytes?: number } = {}): Promise<PluginFilesystemReadResult> {
+ return post("/api/plugins/filesystem/read", { pluginId, providerId, uri, ...options });
+}
+
+export async function writePluginFilesystemFile(pluginId: string, providerId: string, uri: string, dataBase64: string, options: { connectionId?: string; create?: boolean; overwrite?: boolean; etag?: string } = {}): Promise<PluginFilesystemMutationResult> {
+ return post("/api/plugins/filesystem/write", { pluginId, providerId, uri, dataBase64, create: options.create === true, overwrite: options.overwrite === true, connectionId: options.connectionId, etag: options.etag });
+}
+
+export async function createPluginFilesystemDirectory(pluginId: string, providerId: string, uri: string, connectionId?: string): Promise<PluginFilesystemMutationResult> {
+ return post("/api/plugins/filesystem/create-directory", { pluginId, providerId, uri, connectionId });
+}
+
+export async function deletePluginFilesystemEntry(pluginId: string, providerId: string, uri: string, options: { connectionId?: string; recursive?: boolean } = {}): Promise<PluginFilesystemMutationResult> {
+ return post("/api/plugins/filesystem/delete", { pluginId, providerId, uri, connectionId: options.connectionId, recursive: options.recursive === true });
+}
+
+export async function renamePluginFilesystemEntry(pluginId: string, providerId: string, sourceUri: string, targetUri: string, options: { connectionId?: string; overwrite?: boolean } = {}): Promise<PluginFilesystemMutationResult> {
+ return post("/api/plugins/filesystem/rename", { pluginId, providerId, sourceUri, targetUri, connectionId: options.connectionId, overwrite: options.overwrite === true });
+}
+
+export async function readPluginAsset(pluginId: string, path: string): Promise<PluginUiAssetPayload> {
+ const encodedPath = path
+ .split("/")
+ .map((part) => encodeURIComponent(part))
+ .join("/");
+ return pluginAssetPayload(`/api/plugins/${encodeURIComponent(pluginId)}/assets/${encodedPath}`);
+}
+
+export async function readPluginUiEntry(pluginId: string): Promise<PluginUiAssetPayload> {
+ return pluginAssetPayload(`/api/plugins/${encodeURIComponent(pluginId)}/ui`);
+}
+
+export async function readPluginUiAsset(pluginId: string, path: string): Promise<PluginUiAssetPayload> {
+ const encodedPath = path
+ .split("/")
+ .map((part) => encodeURIComponent(part))
+ .join("/");
+ return pluginAssetPayload(`/api/plugins/${encodeURIComponent(pluginId)}/ui/${encodedPath}`);
+}
+
+export async function subscribePluginEvents(onEvent: (event: PluginEvent) => void, onBinary?: (event: PluginBinaryEvent) => void): Promise<() => void> {
+ const source = new EventSource(apiUrl("/api/plugins/events"));
+ source.onmessage = (message) => {
+ const payload = JSON.parse(message.data) as ({ kind: "event" } & PluginEvent) | ({ kind: "binary" } & PluginBinaryEvent) | { kind: "lagged" };
+ if (payload.kind === "event") onEvent(payload);
+ if (payload.kind === "binary") onBinary?.(payload);
+ };
+ return () => source.close();
+}
+
+async function pluginAssetPayload(path: string): Promise<PluginUiAssetPayload> {
+ const response = await fetch(apiUrl(path));
+ if (!response.ok) throw new Error(await response.text());
+ const bytes = new Uint8Array(await response.arrayBuffer());
+ let binary = "";
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return {
+ contentType: response.headers.get("content-type") || "application/octet-stream",
+ dataBase64: btoa(binary),
+ etag: response.headers.get("etag") || "",
+ };
+}
+
export async function listJdbcDrivers(): Promise<JdbcDriverInfo[]> {
return get("/api/jdbc/drivers");
}
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 1cf9997949..3c89f93189 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -82,6 +82,22 @@ import type { SidebarObjectKind } from "@/lib/database/databaseObjectCapabilitie
import type { AiChatSelectionState, AiConfig, AiConfigItem, AiEffortCapability, AiEffortLevel, AiTestConnectionResult } from "@/types/ai";
import type { QueryEditability } from "@/lib/sql/sqlAnalysis";
import { isTerminalTransferProgress } from "@/lib/backend/transferProgress";
+import type {
+ ActivePluginSession,
+ PluginBinaryEvent,
+ PluginConnectionActionResult,
+ PluginEvent,
+ PluginFilesystemListResult,
+ PluginFilesystemMutationResult,
+ PluginFilesystemReadResult,
+ PluginInstallResult,
+ PluginMarketplaceInstallRequest,
+ PluginRepository,
+ PluginRepositoryCatalogResult,
+ PluginRollbackResult,
+ PluginTrustedKey,
+ PluginUiAssetPayload,
+} from "@/types/database";
import type {
DataGridColumnDistinctValuesSqlOptions,
DataGridColumnValueFilterConditionOptions,
@@ -2234,6 +2250,124 @@ export async function listPlugins(): Promise<InstalledPlugin[]> {
return invoke("list_plugins");
}
+export async function listPluginTrustedKeys(): Promise<PluginTrustedKey[]> {
+ return invoke("list_plugin_trusted_keys");
+}
+
+export async function savePluginTrustedKey(keyId: string, publicKey: string): Promise<PluginTrustedKey[]> {
+ return invoke("save_plugin_trusted_key", { keyId, publicKey });
+}
+
+export async function removePluginTrustedKey(keyId: string): Promise<PluginTrustedKey[]> {
+ return invoke("remove_plugin_trusted_key", { keyId });
+}
+
+export async function listPluginRepositories(): Promise<PluginRepository[]> {
+ return invoke("list_plugin_repositories");
+}
+
+export async function savePluginRepository(repository: PluginRepository): Promise<PluginRepository[]> {
+ return invoke("save_plugin_repository", { repository });
+}
+
+export async function removePluginRepository(repositoryId: string): Promise<PluginRepository[]> {
+ return invoke("remove_plugin_repository", { repositoryId });
+}
+
+export async function fetchPluginMarketplaceCatalogs(): Promise<PluginRepositoryCatalogResult[]> {
+ return invoke("fetch_plugin_marketplace_catalogs");
+}
+
+export async function installMarketplacePlugin(request: PluginMarketplaceInstallRequest): Promise<PluginInstallResult> {
+ return invoke("install_marketplace_plugin", { request });
+}
+
+export async function installPluginPackage(pathOrFile: string | File, allowUnsigned = false): Promise<PluginInstallResult> {
+ if (typeof pathOrFile !== "string") throw new Error("Desktop plugin installation requires a local .dbxp file path");
+ return invoke("install_plugin_package", { path: pathOrFile, allowUnsigned });
+}
+
+export async function rollbackPlugin(pluginId: string): Promise<PluginRollbackResult> {
+ return invoke("rollback_plugin", { pluginId });
+}
+
+export async function uninstallPlugin(pluginId: string): Promise<InstalledPlugin[]> {
+ return invoke("uninstall_plugin", { pluginId });
+}
+
+export async function activatePlugin(pluginId: string): Promise<ActivePluginSession[]> {
+ return invoke("activate_plugin", { pluginId });
+}
+
+export async function listActivePlugins(): Promise<ActivePluginSession[]> {
+ return invoke("list_active_plugins");
+}
+
+export async function stopPlugin(pluginId: string): Promise<void> {
+ return invoke("stop_plugin", { pluginId });
+}
+
+export async function invokePlugin<T = unknown>(pluginId: string, method: string, params: unknown = null, timeoutMs?: number): Promise<T> {
+ return invoke("invoke_plugin", { pluginId, method, params, timeoutMs });
+}
+
+export async function invokePluginConnectionAction(config: ConnectionConfig, actionId: string): Promise<PluginConnectionActionResult> {
+ return invoke("invoke_plugin_connection_action", { config, actionId });
+}
+
+export async function notifyPlugin(pluginId: string, method: string, params: unknown = null): Promise<void> {
+ return invoke("notify_plugin", { pluginId, method, params });
+}
+
+export async function sendPluginBinary(pluginId: string, channel: string, dataBase64: string): Promise<void> {
+ return invoke("send_plugin_binary", { pluginId, channel, dataBase64 });
+}
+
+export async function listPluginFilesystemEntries(pluginId: string, providerId: string, options: { connectionId?: string; uri?: string; cursor?: string; limit?: number } = {}): Promise<PluginFilesystemListResult> {
+ return invoke("list_plugin_filesystem_entries", { pluginId, providerId, ...options });
+}
+
+export async function readPluginFilesystemFile(pluginId: string, providerId: string, uri: string, options: { connectionId?: string; maxBytes?: number } = {}): Promise<PluginFilesystemReadResult> {
+ return invoke("read_plugin_filesystem_file", { pluginId, providerId, uri, ...options });
+}
+
+export async function writePluginFilesystemFile(pluginId: string, providerId: string, uri: string, dataBase64: string, options: { connectionId?: string; create?: boolean; overwrite?: boolean; etag?: string } = {}): Promise<PluginFilesystemMutationResult> {
+ return invoke("write_plugin_filesystem_file", { pluginId, providerId, uri, dataBase64, create: options.create === true, overwrite: options.overwrite === true, connectionId: options.connectionId, etag: options.etag });
+}
+
+export async function createPluginFilesystemDirectory(pluginId: string, providerId: string, uri: string, connectionId?: string): Promise<PluginFilesystemMutationResult> {
+ return invoke("create_plugin_filesystem_directory", { pluginId, providerId, uri, connectionId });
+}
+
+export async function deletePluginFilesystemEntry(pluginId: string, providerId: string, uri: string, options: { connectionId?: string; recursive?: boolean } = {}): Promise<PluginFilesystemMutationResult> {
+ return invoke("delete_plugin_filesystem_entry", { pluginId, providerId, uri, connectionId: options.connectionId, recursive: options.recursive === true });
+}
+
+export async function renamePluginFilesystemEntry(pluginId: string, providerId: string, sourceUri: string, targetUri: string, options: { connectionId?: string; overwrite?: boolean } = {}): Promise<PluginFilesystemMutationResult> {
+ return invoke("rename_plugin_filesystem_entry", { pluginId, providerId, sourceUri, targetUri, connectionId: options.connectionId, overwrite: options.overwrite === true });
+}
+
+export async function readPluginAsset(pluginId: string, path: string): Promise<PluginUiAssetPayload> {
+ return invoke("read_plugin_asset", { pluginId, path });
+}
+
+export async function readPluginUiEntry(pluginId: string): Promise<PluginUiAssetPayload> {
+ return invoke("read_plugin_ui_entry", { pluginId });
+}
+
+export async function readPluginUiAsset(pluginId: string, path: string): Promise<PluginUiAssetPayload> {
+ return invoke("read_plugin_ui_asset", { pluginId, path });
+}
+
+export async function subscribePluginEvents(onEvent: (event: PluginEvent) => void, onBinary?: (event: PluginBinaryEvent) => void): Promise<UnlistenFn> {
+ const unlistenEvent = await listen<PluginEvent>("dbx-plugin-event", (event) => onEvent(event.payload));
+ const unlistenBinary = await listen<PluginBinaryEvent>("dbx-plugin-binary", (event) => onBinary?.(event.payload));
+ return () => {
+ unlistenEvent();
+ unlistenBinary();
+ };
+}
+
export async function listJdbcDrivers(): Promise<JdbcDriverInfo[]> {
return invoke("list_jdbc_drivers");
}
diff --git a/apps/desktop/src/lib/connection/connectionOpenTarget.ts b/apps/desktop/src/lib/connection/connectionOpenTarget.ts
index 930f604456..dd5c1cdf99 100644
--- a/apps/desktop/src/lib/connection/connectionOpenTarget.ts
+++ b/apps/desktop/src/lib/connection/connectionOpenTarget.ts
@@ -1,7 +1,7 @@
import type { ConnectionConfig } from "@/types/database";
import { resolveDefaultDatabase } from "@/lib/database/defaultDatabase";
-export type QuickConnectionOpenTarget = { kind: "mq-admin" } | { kind: "nacos-admin" } | { kind: "etcd" } | { kind: "zookeeper" } | { kind: "consul" } | { kind: "query"; database: string };
+export type QuickConnectionOpenTarget = { kind: "mq-admin" } | { kind: "nacos-admin" } | { kind: "plugin-workbench" } | { kind: "etcd" } | { kind: "zookeeper" } | { kind: "consul" } | { kind: "query"; database: string };
export function quickConnectionOpenTarget(connection: Pick<ConnectionConfig, "db_type" | "database">, databaseOptions: string[] = []): QuickConnectionOpenTarget {
if (connection.db_type === "mq") {
@@ -10,6 +10,9 @@ export function quickConnectionOpenTarget(connection: Pick<ConnectionConfig, "db
if (connection.db_type === "nacos") {
return { kind: "nacos-admin" };
}
+ if (connection.db_type === "plugin") {
+ return { kind: "plugin-workbench" };
+ }
if (connection.db_type === "etcd") {
return { kind: "etcd" };
}
diff --git a/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts b/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts
index 2c4e2fc9cc..5b8627cc9f 100644
--- a/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts
+++ b/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts
@@ -5,7 +5,7 @@ const DRAFT_VISIBLE_DATABASES_PREFIX = "__visible_draft_";
// Turso and Cloudflare D1 target one fixed SQLite-compatible `main` namespace;
// non-database services expose their own root objects rather than database namespaces.
-const UNSUPPORTED_VISIBLE_DATABASE_TYPES = new Set<DatabaseType>(["turso", "cloudflare-d1", "dynamodb", "elasticsearch", "easysearch", "meilisearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos", "consul"]);
+const UNSUPPORTED_VISIBLE_DATABASE_TYPES = new Set<DatabaseType>(["turso", "cloudflare-d1", "dynamodb", "elasticsearch", "easysearch", "meilisearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos", "consul", "plugin"]);
type VisibleDatabaseConnectionFields = Pick<
ConnectionConfig,
diff --git a/apps/desktop/src/lib/database/databaseFeatureSupport.ts b/apps/desktop/src/lib/database/databaseFeatureSupport.ts
index b806d4630e..ac8b3e026f 100644
--- a/apps/desktop/src/lib/database/databaseFeatureSupport.ts
+++ b/apps/desktop/src/lib/database/databaseFeatureSupport.ts
@@ -125,6 +125,7 @@ export function supportsClearableQuerySchema(dbType?: DatabaseType): boolean {
*/
export function supportsConnectionQueryActions(dbType?: DatabaseType): boolean {
return dbType !== "nacos" && dbType !== "consul" && dbType !== "hbase" && dbType !== "zookeeper" && dbType !== "mq" && dbType !== "mqtt";
+ return dbType !== "nacos" && dbType !== "consul" && dbType !== "hbase";
}
/**
diff --git a/apps/desktop/src/lib/database/databaseNamespaceCreation.ts b/apps/desktop/src/lib/database/databaseNamespaceCreation.ts
index 8b68f5a33a..3c616ae657 100644
--- a/apps/desktop/src/lib/database/databaseNamespaceCreation.ts
+++ b/apps/desktop/src/lib/database/databaseNamespaceCreation.ts
@@ -93,6 +93,7 @@ export const DATABASE_NAMESPACE_CREATION_MATRIX = {
influxdb3: { deferred: "database creation on InfluxDB 3.x goes through the /api/v3/configure/database admin endpoint, which is not part of the SQL execution path" },
victoriametrics: { deferred: "metric namespaces are managed by VictoriaMetrics deployment configuration" },
jdbc: { deferred: "generic JDBC does not expose a reliable dialect-specific create target" },
+ plugin: { deferred: "plugin-owned namespaces are managed by the provider workbench" },
mq: { deferred: "message queue namespaces are handled by MQ admin panels" },
nacos: { deferred: "Nacos namespace creation already uses the Nacos admin flow" },
consul: { deferred: "Consul namespaces and partitions are connection scopes, not KV resources" },
diff --git a/apps/desktop/src/lib/database/databasePropertyEditing.ts b/apps/desktop/src/lib/database/databasePropertyEditing.ts
index 631ffa7197..ad0efa218d 100644
--- a/apps/desktop/src/lib/database/databasePropertyEditing.ts
+++ b/apps/desktop/src/lib/database/databasePropertyEditing.ts
@@ -93,6 +93,7 @@ export const DATABASE_PROPERTY_EDITING_MATRIX = {
influxdb3: { deferred: "database retention policies need a dedicated workflow" },
victoriametrics: { deferred: "metric and retention settings are managed by VictoriaMetrics deployment configuration" },
jdbc: { deferred: "generic JDBC does not expose reliable dialect-specific properties" },
+ plugin: { deferred: "plugin-owned properties are managed by the provider workbench" },
mq: { deferred: "message queue namespaces are handled by MQ admin panels" },
nacos: { deferred: "Nacos namespace editing already uses the Nacos admin flow" },
consul: { deferred: "Consul KV scopes are configured on the connection" },
diff --git a/apps/desktop/src/lib/plugins/frontendPlugin.spec.ts b/apps/desktop/src/lib/plugins/frontendPlugin.spec.ts
new file mode 100644
index 0000000000..faf3a7bd89
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/frontendPlugin.spec.ts
@@ -0,0 +1,330 @@
+import { describe, expect, it } from "vitest";
+import type { InstalledPlugin, PluginConnectionProviderContribution } from "@/types/database";
+import { buildPluginConnectionConfig, createFrontendPluginRegistry, initialPluginFormValues, parsePluginConnectionProviderOptionValue, pluginConnectionActionsForDialog, pluginConnectionFormValues, pluginConnectionProviderIcon, pluginConnectionProviderOptionValue } from "./frontendPlugin";
+
+function installedPlugin(id: string, contributions: InstalledPlugin["manifest"]["contributions"] = []): InstalledPlugin {
+ return {
+ compatibility: { compatible: true },
+ manifest: {
+ id,
+ name: id,
+ version: "1.0.0",
+ drivers: [],
+ contributions,
+ },
+ };
+}
+
+function connectionProvider(overrides: Partial<PluginConnectionProviderContribution> = {}): PluginConnectionProviderContribution {
+ return {
+ type: "connection-provider",
+ id: "connection",
+ label: "Example",
+ database_type: "example",
+ fields: [
+ { key: "host", label: "Host", type: "text", required: true },
+ { key: "port", label: "Port", type: "number", default: 1234 },
+ { key: "tls", label: "TLS", type: "boolean", default: false },
+ ],
+ ...overrides,
+ };
+}
+
+describe("FrontendPluginRegistry", () => {
+ it("round-trips plugin connection provider picker values", () => {
+ const value = pluginConnectionProviderOptionValue("example/plugin", "ssh:main");
+ expect(parsePluginConnectionProviderOptionValue(value)).toEqual({ pluginId: "example/plugin", providerId: "ssh:main" });
+ expect(parsePluginConnectionProviderOptionValue("mysql")).toBeNull();
+ });
+
+ it("indexes declarative connection providers", () => {
+ const registry = createFrontendPluginRegistry([installedPlugin("com.example.plugin", [connectionProvider()])]);
+
+ expect(registry.listConnectionProviders()).toHaveLength(1);
+ expect(registry.listConnectionProviders()[0]?.contribution.database_type).toBe("example");
+ });
+
+ it("indexes workbench, connection provider, and filesystem contributions", () => {
+ const registry = createFrontendPluginRegistry([
+ installedPlugin("com.example.plugin", [
+ {
+ type: "connection-provider",
+ id: "example.connection",
+ label: "Example",
+ database_type: "example",
+ fields: [],
+ workbench: "example.main",
+ filesystem_provider: "example.files",
+ },
+ { type: "workbench", id: "example.main", label: "Example Workbench" },
+ { type: "filesystem-provider", id: "example.files", label: "Example Files", schemes: ["example"], root_uri: "example:/home", capabilities: ["read", "write"] },
+ ]),
+ ]);
+
+ expect(registry.listConnectionProviders()).toHaveLength(1);
+ expect(registry.listWorkbenches()[0]?.contribution.id).toBe("example.main");
+ expect(registry.listFilesystemProviders()[0]?.contribution.schemes).toEqual(["example"]);
+ expect(registry.listFilesystemProviders()[0]?.contribution.root_uri).toBe("example:/home");
+ expect(registry.listConnectionProviders()[0]?.contribution.filesystem_provider).toBe("example.files");
+ });
+
+ it("indexes result-view contributions", () => {
+ const registry = createFrontendPluginRegistry([installedPlugin("com.example.plugin", [{ type: "result-view", id: "example.graph", label: "Graph" }])]);
+
+ const views = registry.listResultViews();
+ expect(views).toHaveLength(1);
+ expect(views[0]?.contribution.id).toBe("example.graph");
+ expect(views[0]?.contribution.label).toBe("Graph");
+ });
+
+ it("indexes context-menu contributions per menu surface", () => {
+ const registry = createFrontendPluginRegistry([
+ installedPlugin("com.example.plugin", [
+ { type: "context-menu", id: "example.inspect", label: "Inspect endpoint", menu: "connection" },
+ { type: "context-menu", id: "example.other", label: "Wrong surface", menu: "tree" },
+ ]),
+ ]);
+
+ const items = registry.listContextMenuItems("connection");
+ expect(items).toHaveLength(1);
+ expect(items[0]?.contribution.id).toBe("example.inspect");
+ expect(items[0]?.plugin.manifest.id).toBe("com.example.plugin");
+ expect(registry.listContextMenuItems("tree")).toHaveLength(1);
+ expect(registry.listContextMenuItems("missing")).toHaveLength(0);
+ });
+
+ it("prefers provider display metadata and falls back to plugin metadata", () => {
+ const explicit = installedPlugin("com.example.explicit", [
+ {
+ type: "connection-provider",
+ id: "explicit.connection",
+ label: "Explicit connection",
+ icon: "assets/provider.svg",
+ database_type: "explicit",
+ fields: [],
+ },
+ ]);
+ explicit.manifest.name = "Explicit plugin";
+ explicit.manifest.icon = "assets/plugin.svg";
+ const fallback = installedPlugin("com.example.fallback", [
+ {
+ type: "connection-provider",
+ id: "fallback.connection",
+ label: "",
+ database_type: "fallback",
+ fields: [],
+ },
+ ]);
+ fallback.manifest.name = "Fallback plugin";
+ fallback.manifest.icon = "assets/fallback.svg";
+
+ const registry = createFrontendPluginRegistry([explicit, fallback]);
+ const [explicitEntry, fallbackEntry] = registry.listConnectionProviders();
+
+ expect(explicitEntry?.contribution.label).toBe("Explicit connection");
+ expect(pluginConnectionProviderIcon(explicitEntry!)).toBe("assets/provider.svg");
+ expect(fallbackEntry?.contribution.label).toBe("Fallback plugin");
+ expect(pluginConnectionProviderIcon(fallbackEntry!)).toBe("assets/fallback.svg");
+ });
+
+ it("falls back to provider id and the generic icon when metadata is absent", () => {
+ const plugin = installedPlugin("com.example.minimal", [
+ {
+ type: "connection-provider",
+ id: "minimal.connection",
+ label: "",
+ database_type: "minimal",
+ fields: [],
+ },
+ ]);
+ plugin.manifest.name = "";
+
+ const entry = createFrontendPluginRegistry([plugin]).listConnectionProviders()[0]!;
+
+ expect(entry.contribution.label).toBe("minimal.connection");
+ expect(pluginConnectionProviderIcon(entry)).toBeUndefined();
+ });
+
+ it("drops unsafe icon paths before rendering", () => {
+ const plugin = installedPlugin("com.example.unsafe", [
+ {
+ type: "connection-provider",
+ id: "unsafe.connection",
+ label: "Unsafe",
+ icon: "../outside.svg",
+ database_type: "unsafe",
+ fields: [],
+ },
+ ]);
+ plugin.manifest.icon = "\\outside.svg";
+
+ const definition = createFrontendPluginRegistry([plugin]).listPlugins()[0]!;
+ const entry = createFrontendPluginRegistry([plugin]).listConnectionProviders()[0]!;
+
+ expect(definition.plugin.manifest.icon).toBeUndefined();
+ expect(pluginConnectionProviderIcon(entry)).toBeUndefined();
+ });
+
+ it("localizes plugin metadata, contributions, and form fields", () => {
+ const plugin = installedPlugin("com.example.plugin", [connectionProvider({ id: "example.connection", description: "English description" })]);
+ plugin.manifest.localizations = {
+ "zh-CN": {
+ name: "示例插件",
+ description: "插件说明",
+ contributions: {
+ "example.connection": {
+ label: "示例连接",
+ description: "连接说明",
+ fields: {
+ host: { label: "主机", placeholder: "请输入主机" },
+ },
+ },
+ },
+ },
+ };
+
+ const registry = createFrontendPluginRegistry([plugin], "zh-CN");
+ const definition = registry.listPlugins()[0]!;
+ const contribution = registry.listConnectionProviders()[0]!.contribution;
+
+ expect(definition.plugin.manifest.name).toBe("示例插件");
+ expect(definition.plugin.manifest.description).toBe("插件说明");
+ expect(contribution.label).toBe("示例连接");
+ expect(contribution.description).toBe("连接说明");
+ expect(contribution.fields[0]).toMatchObject({ label: "主机", placeholder: "请输入主机" });
+ expect(plugin.manifest.name).toBe("com.example.plugin");
+ });
+
+ it("normalizes connection actions in manifest order and localizes their labels", () => {
+ const plugin = installedPlugin("com.example.actions", [
+ {
+ type: "connection-provider",
+ id: "example.connection",
+ label: "Example",
+ database_type: "example",
+ fields: [],
+ capabilities: ["test"],
+ actions: [
+ {
+ id: "discover",
+ label: "Discover",
+ description: "Discover an endpoint",
+ variant: "outline",
+ requires_valid_form: false,
+ },
+ { id: "edit", label: "Edit", variant: "secondary", when: "edit" },
+ ],
+ },
+ ]);
+ plugin.manifest.localizations = {
+ "zh-CN": {
+ contributions: {
+ "example.connection": {
+ actions: {
+ discover: { label: "发现地址", description: "自动发现连接地址" },
+ },
+ },
+ },
+ },
+ };
+
+ const actions = createFrontendPluginRegistry([plugin], "zh-CN").listConnectionProviders()[0]?.contribution.actions;
+
+ expect(actions?.map((action) => action.id)).toEqual(["discover", "edit"]);
+ expect(actions?.[0]).toMatchObject({
+ label: "发现地址",
+ description: "自动发现连接地址",
+ requires_valid_form: false,
+ });
+ expect(actions?.[1]).toMatchObject({ label: "Edit", variant: "secondary", when: "edit" });
+ });
+
+ it("treats omitted and explicitly empty custom action lists equivalently", () => {
+ const registry = createFrontendPluginRegistry([
+ installedPlugin("com.example.defaults", [{ type: "connection-provider", id: "default.connection", label: "Default", database_type: "default", fields: [] }]),
+ installedPlugin("com.example.empty", [{ type: "connection-provider", id: "empty.connection", label: "Empty", database_type: "empty", fields: [], actions: [] }]),
+ ]);
+
+ const [defaults, empty] = registry.listConnectionProviders();
+ expect(defaults?.contribution.actions).toBeUndefined();
+ expect(empty?.contribution.actions).toEqual([]);
+ expect(pluginConnectionActionsForDialog(defaults!.contribution, false)).toEqual(pluginConnectionActionsForDialog(empty!.contribution, false));
+ });
+
+ it("builds compatible default footer actions and filters create/edit actions", () => {
+ const provider: PluginConnectionProviderContribution = {
+ type: "connection-provider",
+ id: "example.connection",
+ label: "Example",
+ database_type: "example",
+ fields: [],
+ capabilities: ["test"],
+ };
+
+ expect(pluginConnectionActionsForDialog(provider, false).map((action) => action.kind)).toEqual(["test", "save-and-connect"]);
+ expect(pluginConnectionActionsForDialog(provider, true).map((action) => action.kind)).toEqual(["test", "save"]);
+ expect(
+ pluginConnectionActionsForDialog(
+ {
+ ...provider,
+ actions: [
+ { id: "create", label: "Create", when: "create" },
+ { id: "edit", label: "Edit", when: "edit" },
+ { id: "always", label: "Always", when: "always" },
+ ],
+ },
+ true,
+ ).map((action) => action.id),
+ ).toEqual(["edit", "always", "test", "save"]);
+ });
+
+ it("creates initial values only from declared defaults", () => {
+ const values = initialPluginFormValues(connectionProvider());
+
+ expect(values).toEqual({ port: 1234, tls: false });
+ expect(values).not.toHaveProperty("host");
+ });
+
+ it("maps provider fields into common, config, and secret storage", () => {
+ const provider: PluginConnectionProviderContribution = {
+ type: "connection-provider",
+ id: "example.ssh",
+ label: "SSH",
+ database_type: "ssh",
+ fields: [
+ { key: "display_name", label: "Name", type: "text", binding: "name" },
+ { key: "host", label: "Host", type: "text", binding: "host" },
+ { key: "port", label: "Port", type: "number", binding: "port", default: 22 },
+ { key: "private_key", label: "Private key", type: "password" },
+ { key: "keepalive", label: "Keepalive", type: "boolean", default: true },
+ ],
+ };
+
+ const config = buildPluginConnectionConfig("example.plugin", provider, {
+ display_name: "Production SSH",
+ host: "example.com",
+ port: 2222,
+ private_key: "secret-key",
+ keepalive: false,
+ });
+
+ expect(config).toMatchObject({
+ name: "Production SSH",
+ db_type: "plugin",
+ host: "example.com",
+ port: 2222,
+ plugin_id: "example.plugin",
+ plugin_connection_provider: "example.ssh",
+ plugin_connection_type: "ssh",
+ external_config: { keepalive: false },
+ connection_secrets: { private_key: "secret-key" },
+ });
+ expect(pluginConnectionFormValues(provider, config)).toMatchObject({
+ display_name: "Production SSH",
+ host: "example.com",
+ port: 2222,
+ private_key: "secret-key",
+ keepalive: false,
+ });
+ });
+});
diff --git a/apps/desktop/src/lib/plugins/frontendPlugin.ts b/apps/desktop/src/lib/plugins/frontendPlugin.ts
new file mode 100644
index 0000000000..92a53a4e0c
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/frontendPlugin.ts
@@ -0,0 +1,302 @@
+import type {
+ ConnectionConfig,
+ InstalledPlugin,
+ PluginConnectionAction,
+ PluginConnectionProviderContribution,
+ PluginContribution,
+ PluginContributionLocalization,
+ PluginContextMenuContribution,
+ PluginResultViewContribution,
+ PluginFilesystemProviderContribution,
+ PluginFormField,
+ PluginFormFieldLocalization,
+ PluginFormFieldValue,
+ PluginManifestLocalization,
+ PluginWorkbenchContribution,
+} from "@/types/database";
+import { uuid } from "@/lib/common/utils";
+import { clonePluginData } from "./pluginData";
+
+const PLUGIN_CONNECTION_PROVIDER_OPTION_PREFIX = "plugin-provider:";
+
+export interface FrontendPluginDefinition {
+ plugin: InstalledPlugin;
+ contributions: PluginContribution[];
+ diagnostics: string[];
+}
+
+export interface PluginContributionEntry<T extends PluginContribution> {
+ plugin: InstalledPlugin;
+ contribution: T;
+}
+
+export class FrontendPluginRegistry {
+ private readonly definitions: FrontendPluginDefinition[];
+
+ constructor(plugins: readonly InstalledPlugin[] = [], locale = "en") {
+ this.definitions = plugins.map((plugin) => normalizeFrontendPlugin(plugin, locale));
+ }
+
+ listPlugins(): FrontendPluginDefinition[] {
+ return [...this.definitions];
+ }
+
+ findPlugin(pluginId: string): FrontendPluginDefinition | undefined {
+ return this.definitions.find((definition) => definition.plugin.manifest.id === pluginId);
+ }
+
+ listConnectionProviders(): PluginContributionEntry<PluginConnectionProviderContribution>[] {
+ return this.listContributions("connection-provider");
+ }
+
+ listWorkbenches(): PluginContributionEntry<PluginWorkbenchContribution>[] {
+ return this.listContributions("workbench");
+ }
+
+ listFilesystemProviders(): PluginContributionEntry<PluginFilesystemProviderContribution>[] {
+ return this.listContributions("filesystem-provider");
+ }
+
+ /** Native context-menu entries declared for a specific menu surface such as `connection`. */
+ listContextMenuItems(menu: string): PluginContributionEntry<PluginContextMenuContribution>[] {
+ return this.listContributions("context-menu").filter((entry) => entry.contribution.menu === menu);
+ }
+
+ /** Plugin-rendered query-result views offered from the results toolbar. */
+ listResultViews(): PluginContributionEntry<PluginResultViewContribution>[] {
+ return this.listContributions("result-view");
+ }
+
+ findWorkbench(pluginId: string, contributionId: string): PluginContributionEntry<PluginWorkbenchContribution> | undefined {
+ return this.listWorkbenches().find((entry) => entry.plugin.manifest.id === pluginId && entry.contribution.id === contributionId);
+ }
+
+ private listContributions<T extends PluginContribution["type"]>(type: T): Array<PluginContributionEntry<Extract<PluginContribution, { type: T }>>> {
+ return this.definitions
+ .filter((definition) => definition.plugin.compatibility.compatible)
+ .flatMap((definition) => definition.contributions.filter((contribution): contribution is Extract<PluginContribution, { type: T }> => contribution.type === type).map((contribution) => ({ plugin: definition.plugin, contribution })))
+ .sort((left, right) => `${left.plugin.manifest.name}:${left.contribution.label || left.contribution.id}`.localeCompare(`${right.plugin.manifest.name}:${right.contribution.label || right.contribution.id}`));
+ }
+}
+
+export function createFrontendPluginRegistry(plugins: readonly InstalledPlugin[], locale = "en"): FrontendPluginRegistry {
+ return new FrontendPluginRegistry(plugins, locale);
+}
+
+export function pluginConnectionProviderOptionValue(pluginId: string, providerId: string): string {
+ return `${PLUGIN_CONNECTION_PROVIDER_OPTION_PREFIX}${encodeURIComponent(pluginId)}/${encodeURIComponent(providerId)}`;
+}
+
+export function parsePluginConnectionProviderOptionValue(value: string): { pluginId: string; providerId: string } | null {
+ if (!value.startsWith(PLUGIN_CONNECTION_PROVIDER_OPTION_PREFIX)) return null;
+ const encoded = value.slice(PLUGIN_CONNECTION_PROVIDER_OPTION_PREFIX.length);
+ const separator = encoded.indexOf("/");
+ if (separator <= 0 || separator === encoded.length - 1) return null;
+ try {
+ const pluginId = decodeURIComponent(encoded.slice(0, separator));
+ const providerId = decodeURIComponent(encoded.slice(separator + 1));
+ return pluginId && providerId ? { pluginId, providerId } : null;
+ } catch {
+ return null;
+ }
+}
+
+export function pluginConnectionProviderIcon(entry: PluginContributionEntry<PluginConnectionProviderContribution>): string | undefined {
+ return entry.contribution.icon || entry.plugin.manifest.icon;
+}
+
+export function pluginConnectionActionsForDialog(contribution: PluginConnectionProviderContribution, editing: boolean): PluginConnectionAction[] {
+ const actions: PluginConnectionAction[] = [
+ ...(contribution.actions || []).map((action) => ({ ...action, kind: "custom" as const })),
+ ...((contribution.capabilities || []).includes("test") ? [{ id: "test", kind: "test" as const, variant: "outline" as const }] : []),
+ editing ? ({ id: "save", kind: "save", variant: "default", close_on_success: true } satisfies PluginConnectionAction) : ({ id: "save-and-connect", kind: "save-and-connect", variant: "default", close_on_success: true } satisfies PluginConnectionAction),
+ ];
+ return actions.filter((action) => action.when === undefined || action.when === "always" || (action.when === "edit" ? editing : !editing));
+}
+
+export function initialPluginFormValues(contribution: PluginConnectionProviderContribution): Record<string, PluginFormFieldValue> {
+ return Object.fromEntries(contribution.fields.filter((field) => field.default !== undefined).map((field) => [field.key, field.default])) as Record<string, PluginFormFieldValue>;
+}
+
+export function pluginConnectionFormValues(contribution: PluginConnectionProviderContribution, config?: ConnectionConfig): Record<string, PluginFormFieldValue> {
+ const values = initialPluginFormValues(contribution);
+ if (!config) return values;
+ const externalConfig = isRecord(config.external_config) ? config.external_config : {};
+ const secrets = config.connection_secrets || {};
+ for (const field of contribution.fields) {
+ const binding = effectiveFieldBinding(field);
+ const value =
+ binding === "name"
+ ? config.name
+ : binding === "host"
+ ? config.host
+ : binding === "port"
+ ? config.port
+ : binding === "username"
+ ? config.username
+ : binding === "password"
+ ? config.password
+ : binding === "database"
+ ? config.database
+ : binding === "secret"
+ ? secrets[field.key]
+ : externalConfig[field.key];
+ if (isPluginFormFieldValue(value)) values[field.key] = value;
+ }
+ return values;
+}
+
+export function buildPluginConnectionConfig(pluginId: string, contribution: PluginConnectionProviderContribution, values: Record<string, PluginFormFieldValue>, existing?: ConnectionConfig): ConnectionConfig {
+ const externalConfig: Record<string, unknown> = isRecord(existing?.external_config) ? clonePluginData(existing.external_config) : {};
+ const connectionSecrets = { ...existing?.connection_secrets };
+ const config: ConnectionConfig = {
+ id: existing?.id || uuid(),
+ name: existing?.name || contribution.label,
+ note: existing?.note,
+ db_type: "plugin",
+ driver_profile: existing?.driver_profile || "plugin",
+ driver_label: contribution.label,
+ host: existing?.host || "",
+ port: existing?.port || 0,
+ username: existing?.username || "",
+ password: existing?.password || "",
+ database: existing?.database,
+ external_config: externalConfig,
+ plugin_id: pluginId,
+ plugin_connection_provider: contribution.id,
+ plugin_connection_type: contribution.database_type,
+ connection_secrets: connectionSecrets,
+ transport_layers: existing?.transport_layers || [],
+ connect_timeout_secs: existing?.connect_timeout_secs || 10,
+ query_timeout_secs: existing?.query_timeout_secs || 60,
+ idle_timeout_secs: existing?.idle_timeout_secs || 60,
+ keepalive_interval_secs: existing?.keepalive_interval_secs || 30,
+ read_only: existing?.read_only || false,
+ is_production: existing?.is_production || false,
+ production_databases: existing?.production_databases || [],
+ };
+ for (const field of contribution.fields) {
+ const value = values[field.key] ?? field.default;
+ const binding = effectiveFieldBinding(field);
+ if (binding === "config") {
+ if (value === undefined) delete externalConfig[field.key];
+ else externalConfig[field.key] = value;
+ } else if (binding === "secret") {
+ if (value === undefined || value === "") delete connectionSecrets[field.key];
+ else connectionSecrets[field.key] = String(value);
+ } else if (binding === "name") {
+ config.name = String(value || contribution.label);
+ } else if (binding === "host") {
+ config.host = String(value || "");
+ } else if (binding === "port") {
+ config.port = typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.min(65535, Math.trunc(value))) : 0;
+ } else if (binding === "username") {
+ config.username = String(value || "");
+ } else if (binding === "password") {
+ config.password = String(value || "");
+ } else if (binding === "database") {
+ config.database = value === undefined || value === "" ? undefined : String(value);
+ }
+ }
+ return config;
+}
+
+function effectiveFieldBinding(field: PluginFormField): NonNullable<PluginFormField["binding"]> {
+ return field.binding || (field.type === "password" ? "secret" : "config");
+}
+
+function normalizeFrontendPlugin(plugin: InstalledPlugin, locale: string): FrontendPluginDefinition {
+ const localization = pluginLocalization(plugin, locale);
+ const localizedPlugin = localizePluginMetadata(plugin, localization);
+ const contributions = (localizedPlugin.manifest.contributions || []).map((contribution) => localizeContribution(contribution, localization?.contributions?.[contribution.id], localizedPlugin.manifest.name));
+ const diagnostics: string[] = [];
+ if (!plugin.compatibility.compatible) diagnostics.push(...(plugin.compatibility.errors || []));
+ return { plugin: localizedPlugin, contributions, diagnostics };
+}
+
+function pluginLocalization(plugin: InstalledPlugin, locale: string): PluginManifestLocalization | undefined {
+ const localizations = plugin.manifest.localizations;
+ if (!localizations || !locale) return undefined;
+ const normalizedLocale = locale.replace("_", "-").toLowerCase();
+ const exact = Object.entries(localizations).find(([key]) => key.replace("_", "-").toLowerCase() === normalizedLocale)?.[1];
+ if (exact) return exact;
+ const language = normalizedLocale.split("-")[0];
+ return Object.entries(localizations).find(([key]) => key.replace("_", "-").toLowerCase() === language)?.[1];
+}
+
+function localizePluginMetadata(plugin: InstalledPlugin, localization?: PluginManifestLocalization): InstalledPlugin {
+ return {
+ ...plugin,
+ manifest: {
+ ...plugin.manifest,
+ name: localizedRequiredText(plugin.manifest.name, localization?.name),
+ icon: optionalPluginAssetPath(plugin.manifest.icon),
+ description: localizedOptionalText(plugin.manifest.description, localization?.description),
+ },
+ };
+}
+
+function localizeContribution(contribution: PluginContribution, localization: PluginContributionLocalization | undefined, pluginName: string): PluginContribution {
+ const fallbackLabel = contribution.type === "connection-provider" ? optionalTrimmed(contribution.label) || optionalTrimmed(pluginName) || contribution.id : contribution.label;
+ const localized = {
+ ...contribution,
+ label: localizedRequiredText(fallbackLabel, localization?.label),
+ description: localizedOptionalText(contribution.description, localization?.description),
+ } as PluginContribution;
+ if (localized.type === "connection-provider") {
+ localized.icon = optionalPluginAssetPath(localized.icon);
+ localized.fields = localized.fields.map((field) => localizeField(field, localization?.fields?.[field.key]));
+ localized.actions = localized.actions?.map((action) => ({
+ ...action,
+ label: localizedRequiredText(action.label, localization?.actions?.[action.id]?.label),
+ description: localizedOptionalText(action.description, localization?.actions?.[action.id]?.description),
+ }));
+ } else if (localized.type === "workbench") {
+ localized.icon = optionalPluginAssetPath(localized.icon);
+ }
+ return localized;
+}
+
+function localizeField(field: PluginFormField, localization?: PluginFormFieldLocalization): PluginFormField {
+ if (!localization) return field;
+ return {
+ ...field,
+ label: localizedRequiredText(field.label, localization.label),
+ description: localizedOptionalText(field.description, localization.description),
+ placeholder: localizedOptionalText(field.placeholder, localization.placeholder),
+ options: field.options?.map((option) => ({ ...option, label: localizedRequiredText(option.label, localization.options?.[option.value]) })),
+ };
+}
+
+function localizedRequiredText(fallback: string, localized: unknown): string {
+ return nonEmptyString(localized) ? localized.trim() : fallback;
+}
+
+function localizedOptionalText(fallback: string | undefined, localized: unknown): string | undefined {
+ return typeof localized === "string" ? localized.trim() : fallback;
+}
+
+function optionalTrimmed(value: unknown): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const trimmed = value.trim();
+ return trimmed || undefined;
+}
+
+function optionalPluginAssetPath(value: unknown): string | undefined {
+ const path = optionalTrimmed(value);
+ if (!path || path.startsWith("/") || path.startsWith("\\") || path.includes("\\")) return undefined;
+ const parts = path.split("/");
+ return parts.some((part) => !part || part === "." || part === "..") ? undefined : path;
+}
+
+function nonEmptyString(value: unknown): value is string {
+ return typeof value === "string" && value.trim().length > 0;
+}
+
+function isPluginFormFieldValue(value: unknown): value is PluginFormFieldValue {
+ return value === undefined || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
+}
+
+function isRecord(value: unknown): value is Record<string, any> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/apps/desktop/src/lib/plugins/pluginCenterNavigation.ts b/apps/desktop/src/lib/plugins/pluginCenterNavigation.ts
new file mode 100644
index 0000000000..eeac2ea8d5
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/pluginCenterNavigation.ts
@@ -0,0 +1,4 @@
+export interface PluginCenterFocus {
+ pluginId?: string;
+ providerId?: string;
+}
diff --git a/apps/desktop/src/lib/plugins/pluginData.ts b/apps/desktop/src/lib/plugins/pluginData.ts
new file mode 100644
index 0000000000..cc8aa8a4c5
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/pluginData.ts
@@ -0,0 +1,103 @@
+import { isProxy, toRaw } from "vue";
+
+export const MAX_PLUGIN_WORKBENCH_CONTEXT_BYTES = 2 * 1024 * 1024;
+
+export function clonePluginData<T>(value: T): T {
+ const unwrapped = unwrapVueProxies(value);
+ try {
+ if (typeof structuredClone === "function") return structuredClone(unwrapped);
+ return JSON.parse(JSON.stringify(unwrapped)) as T;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ throw new Error(`Plugin data cannot be cloned: ${message}`);
+ }
+}
+
+export function snapshotPluginWorkbenchContext<T extends object>(value: T): T {
+ const snapshot = snapshotValue(value, "context", new WeakSet<object>());
+ if (!snapshot || Array.isArray(snapshot) || typeof snapshot !== "object") {
+ throw new Error("Plugin workbench context must be an object");
+ }
+ const size = new TextEncoder().encode(JSON.stringify(snapshot)).byteLength;
+ if (size > MAX_PLUGIN_WORKBENCH_CONTEXT_BYTES) {
+ throw new Error(`Plugin workbench context exceeds ${MAX_PLUGIN_WORKBENCH_CONTEXT_BYTES} bytes`);
+ }
+ return snapshot as T;
+}
+
+type PluginContextValue = boolean | number | string | null | PluginContextValue[] | { [key: string]: PluginContextValue } | undefined;
+
+function snapshotValue(value: unknown, path: string, ancestors: WeakSet<object>): PluginContextValue {
+ if (value === undefined) return undefined;
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
+ if (typeof value === "number") {
+ if (Number.isFinite(value)) return value;
+ throw new Error(`Plugin workbench context contains a non-finite number at ${path}`);
+ }
+ if (typeof value !== "object") throw new Error(`Plugin workbench context contains an unsupported value at ${path}`);
+
+ const raw = isProxy(value) ? toRaw(value) : value;
+ if (ancestors.has(raw)) throw new Error(`Plugin workbench context contains a circular reference at ${path}`);
+ const prototype = Object.getPrototypeOf(raw);
+ if (!Array.isArray(raw) && prototype !== Object.prototype && prototype !== null) {
+ throw new Error(`Plugin workbench context requires plain data at ${path}`);
+ }
+
+ ancestors.add(raw);
+ try {
+ if (Array.isArray(raw)) {
+ return raw.map((item, index) => snapshotValue(item, `${path}[${index}]`, ancestors) ?? null);
+ }
+ const result: { [key: string]: PluginContextValue } = {};
+ for (const [key, item] of Object.entries(raw)) {
+ const snapshot = snapshotValue(item, `${path}.${key}`, ancestors);
+ if (snapshot !== undefined) result[key] = snapshot;
+ }
+ return result;
+ } finally {
+ ancestors.delete(raw);
+ }
+}
+
+function unwrapVueProxies<T>(value: T, seen = new WeakMap<object, unknown>()): T {
+ const rawValue = isProxy(value) ? toRaw(value) : value;
+ if (!rawValue || typeof rawValue !== "object") return rawValue;
+
+ const object = rawValue as object;
+ const existing = seen.get(object);
+ if (existing) return existing as T;
+ if (rawValue instanceof Date || rawValue instanceof RegExp || rawValue instanceof ArrayBuffer || ArrayBuffer.isView(rawValue)) {
+ return rawValue;
+ }
+ if (Array.isArray(rawValue)) {
+ const result: unknown[] = [];
+ seen.set(object, result);
+ rawValue.forEach((item, index) => {
+ result[index] = unwrapVueProxies(item, seen);
+ });
+ return result as T;
+ }
+ if (rawValue instanceof Map) {
+ const result = new Map<unknown, unknown>();
+ seen.set(object, result);
+ rawValue.forEach((item, key) => result.set(unwrapVueProxies(key, seen), unwrapVueProxies(item, seen)));
+ return result as T;
+ }
+ if (rawValue instanceof Set) {
+ const result = new Set<unknown>();
+ seen.set(object, result);
+ rawValue.forEach((item) => result.add(unwrapVueProxies(item, seen)));
+ return result as T;
+ }
+ const prototype = Object.getPrototypeOf(rawValue);
+ if (prototype !== Object.prototype && prototype !== null) return rawValue;
+
+ const result = Object.create(prototype) as Record<PropertyKey, unknown>;
+ seen.set(object, result);
+ for (const key of Reflect.ownKeys(rawValue)) {
+ const descriptor = Object.getOwnPropertyDescriptor(rawValue, key);
+ if (!descriptor || !("value" in descriptor)) continue;
+ Object.defineProperty(result, key, { ...descriptor, value: unwrapVueProxies(descriptor.value, seen) });
+ }
+ return result as T;
+}
diff --git a/apps/desktop/src/lib/plugins/pluginFilesystem.spec.ts b/apps/desktop/src/lib/plugins/pluginFilesystem.spec.ts
new file mode 100644
index 0000000000..9ef118ae1e
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/pluginFilesystem.spec.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+import { pluginFilesystemParentUri, pluginFilesystemRootUri, sortPluginFilesystemEntries, uniquePluginFilesystemEntries } from "./pluginFilesystem";
+
+describe("plugin filesystem navigation", () => {
+ it("derives a default root from the first declared scheme", () => {
+ expect(pluginFilesystemRootUri({ schemes: ["sftp"] })).toBe("sftp:/");
+ expect(pluginFilesystemRootUri({ schemes: ["s3"], root_uri: "s3://bucket/" })).toBe("s3://bucket/");
+ });
+
+ it("keeps parent navigation inside the declared root", () => {
+ expect(pluginFilesystemParentUri("sftp:/home/user/files/", "sftp:/")).toBe("sftp:/home/user/");
+ expect(pluginFilesystemParentUri("s3://bucket/reports/2026/", "s3://bucket/")).toBe("s3://bucket/reports/");
+ expect(pluginFilesystemParentUri("s3://bucket/reports/", "s3://bucket/reports/")).toBeUndefined();
+ });
+
+ it("sorts directories before naturally ordered files", () => {
+ const sorted = sortPluginFilesystemEntries([
+ { name: "file10.txt", uri: "sample:/file10.txt", kind: "file" },
+ { name: "folder", uri: "sample:/folder/", kind: "directory" },
+ { name: "file2.txt", uri: "sample:/file2.txt", kind: "file" },
+ ]);
+ expect(sorted.map((entry) => entry.name)).toEqual(["folder", "file2.txt", "file10.txt"]);
+ });
+
+ it("removes duplicate entries by URI while preserving the latest metadata", () => {
+ expect(
+ uniquePluginFilesystemEntries([
+ { name: "object.txt", uri: "s3:/object.txt", kind: "file", size: 1 },
+ { name: "object.txt", uri: "s3:/object.txt", kind: "file", size: 2 },
+ { name: "other.txt", uri: "s3:/other.txt", kind: "file" },
+ ]),
+ ).toEqual([
+ { name: "object.txt", uri: "s3:/object.txt", kind: "file", size: 2 },
+ { name: "other.txt", uri: "s3:/other.txt", kind: "file" },
+ ]);
+ });
+});
diff --git a/apps/desktop/src/lib/plugins/pluginFilesystem.ts b/apps/desktop/src/lib/plugins/pluginFilesystem.ts
new file mode 100644
index 0000000000..7de3e96e0c
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/pluginFilesystem.ts
@@ -0,0 +1,34 @@
+import type { PluginFilesystemEntry, PluginFilesystemProviderContribution } from "@/types/database";
+
+export function pluginFilesystemRootUri(provider: Pick<PluginFilesystemProviderContribution, "root_uri" | "schemes">): string {
+ return provider.root_uri || `${provider.schemes[0]}:/`;
+}
+
+export function pluginFilesystemParentUri(uri: string, root: string): string | undefined {
+ if (!uri || uri === root) return undefined;
+ const schemeEnd = uri.indexOf(":");
+ if (schemeEnd < 1) return root;
+ const minimumEnd = uri.startsWith("//", schemeEnd + 1)
+ ? (() => {
+ const authorityEnd = uri.indexOf("/", schemeEnd + 3);
+ return authorityEnd < 0 ? uri.length : authorityEnd + 1;
+ })()
+ : schemeEnd + 2;
+ const normalized = uri.endsWith("/") && uri.length > minimumEnd ? uri.slice(0, -1) : uri;
+ const separator = normalized.lastIndexOf("/");
+ const parent = separator < minimumEnd ? uri.slice(0, minimumEnd) : uri.slice(0, separator + 1);
+ return parent.length < root.length ? root : parent;
+}
+
+export function sortPluginFilesystemEntries(entries: readonly PluginFilesystemEntry[]): PluginFilesystemEntry[] {
+ return [...entries].sort((left, right) => {
+ const leftDirectory = left.kind === "directory";
+ const rightDirectory = right.kind === "directory";
+ if (leftDirectory !== rightDirectory) return leftDirectory ? -1 : 1;
+ return left.name.localeCompare(right.name, undefined, { numeric: true, sensitivity: "base" });
+ });
+}
+
+export function uniquePluginFilesystemEntries(entries: readonly PluginFilesystemEntry[]): PluginFilesystemEntry[] {
+ return [...new Map(entries.map((entry) => [entry.uri, entry])).values()];
+}
diff --git a/apps/desktop/src/lib/plugins/pluginHostBridge.spec.ts b/apps/desktop/src/lib/plugins/pluginHostBridge.spec.ts
new file mode 100644
index 0000000000..4337d89a74
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/pluginHostBridge.spec.ts
@@ -0,0 +1,321 @@
+import { describe, expect, it, vi } from "vitest";
+import { reactive, readonly } from "vue";
+import { PluginHostBridge, pluginSandboxDocument } from "./pluginHostBridge";
+import type { InstalledPlugin, PluginWorkbenchContribution } from "@/types/database";
+
+function plugin(permissions: string[] = []): InstalledPlugin {
+ return {
+ manifest: { id: "sample", name: "Sample", version: "1.0.0", permissions, drivers: [], contributions: [] },
+ compatibility: { compatible: true },
+ };
+}
+
+const workbench: PluginWorkbenchContribution = { type: "workbench", id: "sample.main", label: "Sample" };
+
+describe("PluginHostBridge", () => {
+ it("binds backend calls to the owning plugin identity", async () => {
+ const messages: unknown[] = [];
+ const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
+ const invoke = vi.fn().mockResolvedValue({ ok: true });
+ const bridge = new PluginHostBridge(plugin(), workbench, {}, () => target, {
+ invoke,
+ notify: vi.fn(),
+ sendBinary: vi.fn(),
+ readAsset: vi.fn(),
+ });
+
+ expect(
+ bridge.handleWindowMessage({
+ source: target,
+ data: { source: "dbx-plugin", version: 1, type: "request", id: "1", method: "backend.invoke", params: { method: "sample/hello", params: { name: "DBX" } } },
+ } as MessageEvent),
+ ).toBe(true);
+ await vi.waitFor(() => expect(messages).toHaveLength(1));
+
+ expect(invoke).toHaveBeenCalledWith("sample", "sample/hello", { name: "DBX" }, undefined);
+ expect(messages[0]).toMatchObject({ source: "dbx-host", type: "response", id: "1", result: { ok: true } });
+ });
+
+ it("sends the current DBX locale in the init message", () => {
+ const messages: unknown[] = [];
+ const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
+ const bridge = new PluginHostBridge(
+ plugin(),
+ workbench,
+ { connectionId: "connection" },
+ () => target,
+ {
+ invoke: vi.fn(),
+ notify: vi.fn(),
+ sendBinary: vi.fn(),
+ readAsset: vi.fn(),
+ },
+ "zh-CN",
+ );
+
+ bridge.sendInit();
+
+ expect(messages[0]).toMatchObject({ source: "dbx-host", type: "init", locale: "zh-CN", context: { connectionId: "connection" } });
+ });
+
+ it("snapshots nested Vue reactive context values before sending them to the plugin", () => {
+ const messages: unknown[] = [];
+ const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
+ const context = {
+ connectionId: "connection",
+ values: reactive({ path: "/tmp", options: readonly({ recursive: true }) }),
+ };
+ const bridge = new PluginHostBridge(plugin(), workbench, context, () => target, {
+ invoke: vi.fn(),
+ notify: vi.fn(),
+ sendBinary: vi.fn(),
+ readAsset: vi.fn(),
+ });
+
+ bridge.sendInit();
+
+ expect(messages[0]).toMatchObject({
+ type: "init",
+ context: { connectionId: "connection", values: { path: "/tmp", options: { recursive: true } } },
+ });
+ expect((messages[0] as { context: typeof context }).context).not.toBe(context);
+ });
+
+ it("reports unsupported plugin context values", () => {
+ expect(
+ () =>
+ new PluginHostBridge(plugin(), workbench, { value: () => undefined }, () => null, {
+ invoke: vi.fn(),
+ notify: vi.fn(),
+ sendBinary: vi.fn(),
+ readAsset: vi.fn(),
+ }),
+ ).toThrow("Plugin workbench context contains an unsupported value");
+ });
+
+ it("rejects circular and oversized plugin contexts", () => {
+ const circular: Record<string, unknown> = {};
+ circular.self = circular;
+ expect(
+ () =>
+ new PluginHostBridge(plugin(), workbench, circular, () => null, {
+ invoke: vi.fn(),
+ notify: vi.fn(),
+ sendBinary: vi.fn(),
+ readAsset: vi.fn(),
+ }),
+ ).toThrow("circular reference");
+
+ expect(
+ () =>
+ new PluginHostBridge(plugin(), workbench, { value: "x".repeat(2 * 1024 * 1024) }, () => null, {
+ invoke: vi.fn(),
+ notify: vi.fn(),
+ sendBinary: vi.fn(),
+ readAsset: vi.fn(),
+ }),
+ ).toThrow("exceeds");
+ });
+
+ it("rejects privileged host calls without manifest permission", async () => {
+ const messages: unknown[] = [];
+ const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
+ const bridge = new PluginHostBridge(plugin(), workbench, {}, () => target, {
+ invoke: vi.fn(),
+ notify: vi.fn(),
+ sendBinary: vi.fn(),
+ readAsset: vi.fn(),
+ openWorkbench: vi.fn(),
+ });
+ bridge.handleWindowMessage({
+ source: target,
+ data: { source: "dbx-plugin", version: 1, type: "request", id: "2", method: "host.openWorkbench", params: { contributionId: "sample.other" } },
+ } as MessageEvent);
+ await vi.waitFor(() => expect(messages).toHaveLength(1));
+ expect(messages[0]).toMatchObject({ id: "2", error: "Plugin has not declared permission 'host.workbench'" });
+ });
+
+ it("opens only the owning plugin filesystem with explicit permission", async () => {
+ const messages: unknown[] = [];
+ const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
+ const openFilesystem = vi.fn();
+ const bridge = new PluginHostBridge(plugin(["host.filesystem"]), workbench, {}, () => target, {
+ invoke: vi.fn(),
+ notify: vi.fn(),
+ sendBinary: vi.fn(),
+ readAsset: vi.fn(),
+ openFilesystem,
+ });
+ bridge.handleWindowMessage({
+ source: target,
+ data: {
+ source: "dbx-plugin",
+ version: 1,
+ type: "request",
+ id: "filesystem",
+ method: "host.openFilesystem",
+ params: { providerId: "sample.files", context: { connectionId: "connection" } },
+ },
+ } as MessageEvent);
+ await vi.waitFor(() => expect(messages).toHaveLength(1));
+
+ expect(openFilesystem).toHaveBeenCalledWith("sample", "sample.files", { connectionId: "connection" });
+ expect(messages[0]).toMatchObject({ id: "filesystem", result: null });
+ });
+
+ it("forwards events and binary traffic only with declared permissions", async () => {
+ const messages: unknown[] = [];
+ const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
+ const sendBinary = vi.fn().mockResolvedValue(undefined);
+ const bridge = new PluginHostBridge(plugin(["host.events", "host.binary"]), workbench, {}, () => target, {
+ invoke: vi.fn(),
+ notify: vi.fn(),
+ sendBinary,
+ readAsset: vi.fn(),
+ });
+
+ bridge.forwardEvent({ pluginId: "sample", method: "sample/progress", params: { value: 50 } });
+ bridge.forwardBinary({ pluginId: "sample", channel: "pty", dataBase64: "AQI=" });
+ bridge.handleWindowMessage({
+ source: target,
+ data: { source: "dbx-plugin", version: 1, type: "request", id: "3", method: "backend.sendBinary", params: { channel: "pty", dataBase64: "AQI=" } },
+ } as MessageEvent);
+ await vi.waitFor(() => expect(messages).toHaveLength(3));
+
+ expect(messages[0]).toMatchObject({ type: "event", method: "sample/progress" });
+ expect(messages[1]).toMatchObject({ type: "binary", channel: "pty" });
+ expect(sendBinary).toHaveBeenCalledWith("sample", "pty", "AQI=");
+ expect(messages[2]).toMatchObject({ type: "response", id: "3", result: null });
+ });
+
+ it("returns delayed responses to the iframe that issued the request", async () => {
+ const firstMessages: unknown[] = [];
+ const secondMessages: unknown[] = [];
+ const first = { postMessage: (message: unknown) => firstMessages.push(message) } as unknown as Window;
+ const second = { postMessage: (message: unknown) => secondMessages.push(message) } as unknown as Window;
+ let current = first;
+ let resolveInvoke: (value: unknown) => void = () => {};
+ const invoke = vi.fn().mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveInvoke = resolve;
+ }),
+ );
+ const bridge = new PluginHostBridge(plugin(), workbench, {}, () => current, {
+ invoke,
+ notify: vi.fn(),
+ sendBinary: vi.fn(),
+ readAsset: vi.fn(),
+ });
+
+ bridge.handleWindowMessage({
+ source: first,
+ data: { source: "dbx-plugin", version: 1, type: "request", id: "4", method: "backend.invoke", params: { method: "sample/slow" } },
+ } as MessageEvent);
+ current = second;
+ resolveInvoke({ ok: true });
+ await vi.waitFor(() => expect(firstMessages).toHaveLength(1));
+
+ expect(firstMessages[0]).toMatchObject({ type: "response", id: "4", result: { ok: true } });
+ expect(secondMessages).toHaveLength(0);
+ });
+
+ it("pushes context and locale updates without rebuilding the iframe", async () => {
+ const messages: unknown[] = [];
+ const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
+ const bridge = new PluginHostBridge(plugin(), workbench, { connectionId: "first" }, () => target, {
+ invoke: vi.fn(),
+ notify: vi.fn(),
+ sendBinary: vi.fn(),
+ readAsset: vi.fn(),
+ });
+
+ bridge.updateContext({ connectionId: "second", values: { path: "/tmp" } });
+ bridge.updateLocale("ja");
+
+ expect(messages[0]).toMatchObject({ source: "dbx-host", type: "context", context: { connectionId: "second" } });
+ expect(messages[1]).toMatchObject({ source: "dbx-host", type: "env", locale: "ja" });
+
+ bridge.handleWindowMessage({ source: target, data: { source: "dbx-plugin", version: 1, type: "request", id: "ctx", method: "host.getContext" } } as MessageEvent);
+ await vi.waitFor(() => expect(messages).toHaveLength(3));
+ expect(messages[2]).toMatchObject({ type: "response", id: "ctx", result: { connectionId: "second", values: { path: "/tmp" } } });
+ });
+
+ it("accepts zero-copy binary requests and forwards binary frames as raw buffers", async () => {
+ const messages: unknown[] = [];
+ const target = {
+ postMessage: (message: unknown, _origin?: string, _transfer?: Transferable[]) => messages.push(message),
+ } as unknown as Window;
+ const sendBinary = vi.fn().mockResolvedValue(undefined);
+ const bridge = new PluginHostBridge(plugin(["host.binary"]), workbench, {}, () => target, {
+ invoke: vi.fn(),
+ notify: vi.fn(),
+ sendBinary,
+ readAsset: vi.fn(),
+ });
+
+ bridge.forwardBinary({ pluginId: "sample", channel: "pty", dataBase64: "AQID" });
+ expect(messages[0]).toMatchObject({ type: "binary", channel: "pty" });
+ expect((messages[0] as { data: ArrayBuffer }).data).toBeInstanceOf(ArrayBuffer);
+ expect(Array.from(new Uint8Array((messages[0] as { data: ArrayBuffer }).data))).toEqual([1, 2, 3]);
+
+ const bytes = new Uint8Array([4, 5, 6]).buffer;
+ bridge.handleWindowMessage({
+ source: target,
+ data: { source: "dbx-plugin", version: 1, type: "request", id: "bin", method: "backend.sendBinary", params: { channel: "pty" }, data: bytes },
+ } as MessageEvent);
+ await vi.waitFor(() => expect(messages).toHaveLength(2));
+ expect(sendBinary).toHaveBeenCalledWith("sample", "pty", "BAUG");
+ expect(messages[1]).toMatchObject({ type: "response", id: "bin", result: null });
+ });
+
+ it("rejects binary transfer requests without the host.binary permission", async () => {
+ const messages: unknown[] = [];
+ const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
+ const bridge = new PluginHostBridge(plugin(), workbench, {}, () => target, {
+ invoke: vi.fn(),
+ notify: vi.fn(),
+ sendBinary: vi.fn(),
+ readAsset: vi.fn(),
+ });
+ bridge.handleWindowMessage({
+ source: target,
+ data: { source: "dbx-plugin", version: 1, type: "request", id: "denied", method: "backend.sendBinary", params: { channel: "pty" }, data: new Uint8Array([1]).buffer },
+ } as MessageEvent);
+ await vi.waitFor(() => expect(messages).toHaveLength(1));
+ expect(messages[0]).toMatchObject({ id: "denied", error: "Plugin has not declared permission 'host.binary'" });
+ });
+
+ it("injects the SDK, the official UI kit, and a restrictive sandbox CSP", () => {
+ const document = pluginSandboxDocument("<html><head></head><body>Hello</body></html>");
+ expect(document).toContain("window.dbxPlugin");
+ expect(document).toContain("get locale() { return locale; }");
+ expect(document).toContain("openFilesystem");
+ expect(document).toContain("connect-src 'none'");
+ expect(document).toContain(".dbx-btn");
+ expect(document).toContain("var(--color-background");
+ });
+
+ it("opens connect-src only for declared host.network origins", () => {
+ const allowed = pluginSandboxDocument("<html><head></head><body></body></html>", ["host.events", "host.network:https://api.vendor.com", "host.network:https://metrics.vendor.com:8443", "host.network:http://insecure.vendor.com", "host.network:https://evil.vendor.com/path"]);
+ expect(allowed).toContain("connect-src https://api.vendor.com https://metrics.vendor.com:8443;");
+ expect(allowed).not.toContain("insecure.vendor.com");
+ expect(allowed).not.toContain("evil.vendor.com");
+
+ const closed = pluginSandboxDocument("<html><head></head><body></body></html>", ["host.events"]);
+ expect(closed).toContain("connect-src 'none';");
+ });
+
+ it("sends the theme in init and pushes theme updates through env messages", () => {
+ const messages: unknown[] = [];
+ const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
+ const theme = { appearance: "dark" as const, tokens: { "--color-background": "#09090b" } };
+ const bridge = new PluginHostBridge(plugin(), workbench, {}, () => target, { invoke: vi.fn(), notify: vi.fn(), sendBinary: vi.fn(), readAsset: vi.fn() }, "en", theme);
+
+ bridge.sendInit();
+ expect(messages[0]).toMatchObject({ type: "init", theme: { appearance: "dark", tokens: { "--color-background": "#09090b" } } });
+
+ bridge.updateTheme({ appearance: "light", tokens: {} });
+ expect(messages[1]).toMatchObject({ type: "env", locale: "en", theme: { appearance: "light" } });
+ });
+});
diff --git a/apps/desktop/src/lib/plugins/pluginHostBridge.ts b/apps/desktop/src/lib/plugins/pluginHostBridge.ts
new file mode 100644
index 0000000000..1deb29f95b
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/pluginHostBridge.ts
@@ -0,0 +1,457 @@
+import type { InstalledPlugin, PluginBinaryEvent, PluginEvent, PluginUiAssetPayload, PluginWorkbenchContribution } from "@/types/database";
+import { clonePluginData, snapshotPluginWorkbenchContext } from "./pluginData";
+
+const PLUGIN_MESSAGE_SOURCE = "dbx-plugin";
+const HOST_MESSAGE_SOURCE = "dbx-host";
+const BRIDGE_VERSION = 1;
+const MAX_BRIDGE_PAYLOAD_BYTES = 2 * 1024 * 1024;
+const MAX_BRIDGE_BINARY_BYTES = 8 * 1024 * 1024;
+
+export interface PluginBridgeTheme {
+ appearance: "light" | "dark";
+ /** Resolved DBX design tokens (`--color-*`, `--radius-*`, ...) for the current theme. */
+ tokens: Record<string, string>;
+}
+
+export interface PluginWorkbenchContext {
+ connectionId?: string;
+ database?: string;
+ schema?: string;
+ values?: Record<string, unknown>;
+ [key: string]: unknown;
+}
+
+export interface PluginHostBridgeApi {
+ invoke<T = unknown>(pluginId: string, method: string, params?: unknown, timeoutMs?: number): Promise<T>;
+ notify(pluginId: string, method: string, params?: unknown): Promise<void>;
+ sendBinary(pluginId: string, channel: string, dataBase64: string): Promise<void>;
+ readAsset(pluginId: string, path: string): Promise<PluginUiAssetPayload>;
+ openWorkbench?(pluginId: string, contributionId: string, context?: PluginWorkbenchContext): Promise<void> | void;
+ openFilesystem?(pluginId: string, providerId: string, context?: PluginWorkbenchContext): Promise<void> | void;
+}
+
+interface PluginRequestMessage {
+ source: typeof PLUGIN_MESSAGE_SOURCE;
+ version: typeof BRIDGE_VERSION;
+ type: "request";
+ id: string;
+ method: string;
+ params?: unknown;
+ /** Optional zero-copy binary payload transferred with the request. */
+ data?: ArrayBuffer;
+}
+
+export class PluginHostBridge {
+ private context: PluginWorkbenchContext;
+ private locale: string;
+ private theme?: PluginBridgeTheme;
+
+ constructor(
+ private readonly plugin: InstalledPlugin,
+ private readonly workbench: PluginWorkbenchContribution,
+ context: PluginWorkbenchContext,
+ private readonly targetWindow: () => Window | null,
+ private readonly api: PluginHostBridgeApi,
+ locale = "en",
+ theme?: PluginBridgeTheme,
+ ) {
+ this.context = snapshotPluginWorkbenchContext(context);
+ this.locale = locale;
+ this.theme = theme ? clonePluginData(theme) : undefined;
+ }
+
+ handleWindowMessage(event: MessageEvent): boolean {
+ const target = this.targetWindow();
+ if (!target || event.source !== target || !isRecord(event.data)) return false;
+ if (event.data.source !== PLUGIN_MESSAGE_SOURCE || event.data.version !== BRIDGE_VERSION) return false;
+ if (event.data.type === "ready") {
+ this.sendInit();
+ return true;
+ }
+ if (event.data.type !== "request" || !validRequestMessage(event.data)) return false;
+ void this.handleRequest(event.data, target);
+ return true;
+ }
+
+ sendInit(): void {
+ this.post({
+ source: HOST_MESSAGE_SOURCE,
+ version: BRIDGE_VERSION,
+ type: "init",
+ pluginId: this.plugin.manifest.id,
+ contributionId: this.workbench.id,
+ locale: this.locale,
+ theme: this.theme ? clonePluginData(this.theme) : undefined,
+ permissions: [...(this.plugin.manifest.permissions || [])],
+ context: snapshotPluginWorkbenchContext(this.context),
+ });
+ }
+
+ /**
+ * Push a new workbench context into the already-loaded plugin UI instead of
+ * rebuilding the iframe. Identity changes (plugin/contribution) still require
+ * a full reload; context-only changes must not lose plugin state.
+ */
+ updateContext(context: PluginWorkbenchContext): void {
+ this.context = snapshotPluginWorkbenchContext(context);
+ this.post({ source: HOST_MESSAGE_SOURCE, version: BRIDGE_VERSION, type: "context", context: snapshotPluginWorkbenchContext(this.context) });
+ }
+
+ /** Notify the plugin UI about a locale change without a reload. */
+ updateLocale(locale: string): void {
+ this.locale = locale;
+ this.post({ source: HOST_MESSAGE_SOURCE, version: BRIDGE_VERSION, type: "env", locale });
+ }
+
+ /** Push resolved theme tokens so the plugin UI can follow DBX light/dark and palette changes. */
+ updateTheme(theme: PluginBridgeTheme): void {
+ this.theme = clonePluginData(theme);
+ this.post({ source: HOST_MESSAGE_SOURCE, version: BRIDGE_VERSION, type: "env", locale: this.locale, theme: this.theme });
+ }
+
+ forwardEvent(event: PluginEvent): void {
+ if (event.pluginId !== this.plugin.manifest.id || !this.hasPermission("host.events")) return;
+ this.post({ source: HOST_MESSAGE_SOURCE, version: BRIDGE_VERSION, type: "event", method: event.method, params: event.params });
+ }
+
+ forwardBinary(event: PluginBinaryEvent): void {
+ if (event.pluginId !== this.plugin.manifest.id || !this.hasPermission("host.binary")) return;
+ const target = this.targetWindow();
+ if (!target) return;
+ const buffer = base64ToBytes(event.dataBase64);
+ target.postMessage({ source: HOST_MESSAGE_SOURCE, version: BRIDGE_VERSION, type: "binary", channel: event.channel, data: buffer }, "*", [buffer]);
+ }
+
+ private async handleRequest(request: PluginRequestMessage, target: Window): Promise<void> {
+ try {
+ enforcePayloadLimit(request.params);
+ const result = await this.dispatch(request.method, request.params, request.data);
+ this.respond(target, request.id, { result: result ?? null });
+ } catch (error) {
+ this.respond(target, request.id, { error: error instanceof Error ? error.message : String(error) });
+ }
+ }
+
+ private async dispatch(method: string, params: unknown, binary?: ArrayBuffer): Promise<unknown> {
+ if (method === "host.getContext") return snapshotPluginWorkbenchContext(this.context);
+ if (method === "backend.invoke") {
+ const input = requireRecord(params, "backend.invoke params");
+ const backendMethod = requireProtocolName(input.method, "backend method");
+ const timeoutMs = input.timeoutMs === undefined ? undefined : requireTimeout(input.timeoutMs);
+ return this.api.invoke(this.plugin.manifest.id, backendMethod, input.params ?? null, timeoutMs);
+ }
+ if (method === "backend.notify") {
+ const input = requireRecord(params, "backend.notify params");
+ await this.api.notify(this.plugin.manifest.id, requireProtocolName(input.method, "backend method"), input.params ?? null);
+ return null;
+ }
+ if (method === "backend.sendBinary") {
+ this.requirePermission("host.binary");
+ const input = requireRecord(params, "backend.sendBinary params");
+ const channel = requireProtocolName(input.channel, "binary channel");
+ if (binary instanceof ArrayBuffer) {
+ if (binary.byteLength > MAX_BRIDGE_BINARY_BYTES) throw new Error("Plugin binary payload exceeds 8 MiB; chunk the transfer");
+ await this.api.sendBinary(this.plugin.manifest.id, channel, bytesToBase64(new Uint8Array(binary)));
+ return null;
+ }
+ await this.api.sendBinary(this.plugin.manifest.id, channel, requireBase64(input.dataBase64));
+ return null;
+ }
+ if (method === "ui.readAsset") {
+ const input = requireRecord(params, "ui.readAsset params");
+ return this.api.readAsset(this.plugin.manifest.id, requireSafeAssetPath(input.path));
+ }
+ if (method === "host.openWorkbench") {
+ this.requirePermission("host.workbench");
+ if (!this.api.openWorkbench) throw new Error("Host workbench navigation is unavailable");
+ const input = requireRecord(params, "host.openWorkbench params");
+ await this.api.openWorkbench(this.plugin.manifest.id, requireProtocolName(input.contributionId, "workbench contribution"), isRecord(input.context) ? input.context : undefined);
+ return null;
+ }
+ if (method === "host.openFilesystem") {
+ this.requirePermission("host.filesystem");
+ if (!this.api.openFilesystem) throw new Error("Host filesystem navigation is unavailable");
+ const input = requireRecord(params, "host.openFilesystem params");
+ await this.api.openFilesystem(this.plugin.manifest.id, requireProtocolName(input.providerId, "filesystem provider"), isRecord(input.context) ? input.context : undefined);
+ return null;
+ }
+ throw new Error(`Unsupported plugin host method '${method}'`);
+ }
+
+ private requirePermission(permission: string): void {
+ if (!this.hasPermission(permission)) throw new Error(`Plugin has not declared permission '${permission}'`);
+ }
+
+ private hasPermission(permission: string): boolean {
+ return (this.plugin.manifest.permissions || []).includes(permission);
+ }
+
+ private respond(target: Window, id: string, payload: { result?: unknown; error?: string }): void {
+ target.postMessage({ source: HOST_MESSAGE_SOURCE, version: BRIDGE_VERSION, type: "response", id, ...payload }, "*");
+ }
+
+ private post(message: Record<string, unknown>): void {
+ this.targetWindow()?.postMessage(message, "*");
+ }
+}
+
+/**
+ * Parse `host.network:<origin>` permission entries into CSP connect-src
+ * origins. Must stay aligned with `parse_host_network_permission` in
+ * crates/dbx-core/src/plugins/manifest.rs.
+ */
+export function pluginNetworkOrigins(permissions: readonly string[] | undefined): string[] {
+ const origins = new Set<string>();
+ for (const permission of permissions || []) {
+ if (!permission.startsWith("host.network:")) continue;
+ const origin = permission.slice("host.network:".length);
+ if (!/^https:\/\/[A-Za-z0-9._-]+(?::[0-9]+)?$/.test(origin)) continue;
+ origins.add(origin);
+ if (origins.size >= 8) break;
+ }
+ return [...origins];
+}
+
+export function pluginSandboxDocument(html: string, permissions?: readonly string[]): string {
+ const networkOrigins = pluginNetworkOrigins(permissions);
+ const connectSrc = networkOrigins.length > 0 ? `connect-src ${networkOrigins.join(" ")};` : "connect-src 'none';";
+ const csp = `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' blob:; style-src 'unsafe-inline' blob:; img-src data: blob:; font-src data: blob:; ${connectSrc} media-src data: blob:;">`;
+ const sdk = `<script>${pluginSdkSource()}</script>`;
+ const uiKit = `<style>${pluginUiKitCss()}</style>`;
+ const injection = `${csp}${uiKit}${sdk}`;
+ if (/<head(?:\s[^>]*)?>/i.test(html)) return html.replace(/<head(?:\s[^>]*)?>/i, (head) => `${head}${injection}`);
+ return `<!doctype html><html><head>${injection}</head><body>${html}</body></html>`;
+}
+
+/**
+ * Minimal official component kit for plugin workbenches. Every class is built
+ * on the DBX design tokens the host pushes through the bridge, so plugin UI
+ * follows light/dark and palette changes without any plugin-side logic.
+ */
+export function pluginUiKitCss(): string {
+ return `
+:root { color-scheme: light dark; }
+* { box-sizing: border-box; }
+body {
+ margin: 0;
+ font-family: var(--font-sans, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif);
+ font-size: 13px;
+ line-height: 1.5;
+ color: var(--color-foreground, #18181b);
+ background: var(--color-background, #ffffff);
+}
+.dbx-card {
+ border: 1px solid var(--color-border, #e4e4e7);
+ border-radius: var(--radius-lg, 10px);
+ background: var(--color-card, #ffffff);
+ padding: 14px 16px;
+}
+.dbx-section-title {
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--color-muted-foreground, #71717a);
+ margin: 0 0 10px;
+}
+.dbx-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ height: 30px;
+ padding: 0 12px;
+ border-radius: var(--radius-md, 8px);
+ border: 1px solid var(--color-border, #d4d4d8);
+ background: var(--color-background, #ffffff);
+ color: var(--color-foreground, #18181b);
+ font-size: 13px;
+ cursor: pointer;
+}
+.dbx-btn:hover { background: var(--color-muted, #f4f4f5); }
+.dbx-btn--primary { background: var(--color-primary, #2563eb); border-color: var(--color-primary, #2563eb); color: var(--color-primary-foreground, #ffffff); }
+.dbx-btn--primary:hover { background: var(--color-primary, #2563eb); opacity: 0.9; }
+.dbx-btn--danger { background: var(--color-destructive, #dc2626); border-color: var(--color-destructive, #dc2626); color: var(--color-destructive-foreground, #ffffff); }
+.dbx-btn--ghost { border-color: transparent; background: transparent; }
+.dbx-btn:disabled { opacity: 0.5; cursor: not-allowed; }
+.dbx-label { display: inline-flex; font-size: 12px; font-weight: 500; color: var(--color-foreground, #18181b); }
+.dbx-input, .dbx-select, .dbx-textarea {
+ width: 100%;
+ height: 30px;
+ padding: 0 10px;
+ border-radius: var(--radius-md, 8px);
+ border: 1px solid var(--color-input, #d4d4d8);
+ background: var(--color-background, #ffffff);
+ color: var(--color-foreground, #18181b);
+ font-size: 13px;
+ font-family: inherit;
+}
+.dbx-textarea { height: auto; min-height: 64px; padding: 6px 10px; resize: vertical; }
+.dbx-input:focus, .dbx-select:focus, .dbx-textarea:focus { outline: 2px solid var(--color-ring, #93c5fd); outline-offset: 1px; border-color: var(--color-ring, #93c5fd); }
+.dbx-hint { font-size: 12px; color: var(--color-muted-foreground, #71717a); }
+.dbx-row { display: grid; grid-template-columns: minmax(96px, auto) minmax(0, 1fr); gap: 8px 12px; align-items: center; margin-bottom: 10px; }
+.dbx-table { width: 100%; border-collapse: collapse; font-size: 12px; }
+.dbx-table th { text-align: left; font-weight: 600; color: var(--color-muted-foreground, #71717a); border-bottom: 1px solid var(--color-border, #e4e4e7); padding: 6px 8px; }
+.dbx-table td { border-bottom: 1px solid var(--color-border, #e4e4e7); padding: 6px 8px; }
+.dbx-badge { display: inline-flex; align-items: center; height: 20px; padding: 0 8px; border-radius: 999px; background: var(--color-primary-alpha, rgba(37, 99, 235, 0.12)); color: var(--color-primary, #2563eb); font-size: 11px; font-weight: 500; }
+.dbx-link { color: var(--color-primary, #2563eb); text-decoration: none; cursor: pointer; }
+.dbx-link:hover { text-decoration: underline; }
+`.trim();
+}
+
+function pluginSdkSource(): string {
+ return `(() => {
+ const pending = new Map();
+ const listeners = { event: new Set(), binary: new Set(), init: new Set(), context: new Set() };
+ let sequence = 0;
+ let context;
+ let locale = 'en';
+ let theme;
+ let resolveReady;
+ const applyTheme = (value) => {
+ if (!value || typeof value !== 'object') return;
+ theme = value;
+ const root = document.documentElement;
+ root.dataset.dbxTheme = value.appearance === 'dark' ? 'dark' : 'light';
+ const tokens = value.tokens && typeof value.tokens === 'object' ? value.tokens : {};
+ for (const [name, tokenValue] of Object.entries(tokens)) {
+ if (/^--[a-z0-9-]+$/i.test(name) && typeof tokenValue === 'string') root.style.setProperty(name, tokenValue);
+ }
+ };
+ const ready = new Promise((resolve) => { resolveReady = resolve; });
+ const request = (method, params, options = {}) => new Promise((resolve, reject) => {
+ const id = String(++sequence);
+ pending.set(id, { resolve, reject });
+ const message = { source: '${PLUGIN_MESSAGE_SOURCE}', version: ${BRIDGE_VERSION}, type: 'request', id, method, params };
+ if (options.transfer) {
+ message.data = options.transfer;
+ parent.postMessage(message, '*', [options.transfer]);
+ } else {
+ parent.postMessage(message, '*');
+ }
+ });
+ const decode = (value) => Uint8Array.from(atob(value), (character) => character.charCodeAt(0));
+ const encode = (value) => {
+ const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);
+ let binary = '';
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return btoa(binary);
+ };
+ window.dbxPlugin = Object.freeze({
+ ready,
+ get context() { return context; },
+ get locale() { return locale; },
+ get theme() { return theme; },
+ request,
+ invoke: (method, params, options = {}) => request('backend.invoke', { method, params, timeoutMs: options.timeoutMs }),
+ notify: (method, params) => request('backend.notify', { method, params }),
+ sendBinary: (channel, data) => {
+ if (typeof data === 'string') return request('backend.sendBinary', { channel, dataBase64: data });
+ const bytes = data instanceof ArrayBuffer ? data : (data instanceof Uint8Array ? data.buffer : new Uint8Array(data).buffer);
+ return request('backend.sendBinary', { channel }, { transfer: bytes });
+ },
+ readAsset: (path) => request('ui.readAsset', { path }),
+ readAssetUrl: async (path) => {
+ const asset = await request('ui.readAsset', { path });
+ return URL.createObjectURL(new Blob([decode(asset.dataBase64)], { type: asset.contentType }));
+ },
+ openWorkbench: (contributionId, childContext) => request('host.openWorkbench', { contributionId, context: childContext }),
+ openFilesystem: (providerId, childContext) => request('host.openFilesystem', { providerId, context: childContext }),
+ onEvent: (listener) => { listeners.event.add(listener); return () => listeners.event.delete(listener); },
+ onBinary: (listener) => { listeners.binary.add(listener); return () => listeners.binary.delete(listener); },
+ onContext: (listener) => { listeners.context.add(listener); return () => listeners.context.delete(listener); },
+ onInit: (listener) => { listeners.init.add(listener); if (context !== undefined) listener(context); return () => listeners.init.delete(listener); },
+ decodeBase64: decode,
+ encodeBase64: encode,
+ });
+ addEventListener('message', (event) => {
+ if (event.source !== parent || !event.data || event.data.source !== '${HOST_MESSAGE_SOURCE}' || event.data.version !== ${BRIDGE_VERSION}) return;
+ const message = event.data;
+ if (message.type === 'response') {
+ const handler = pending.get(message.id);
+ if (!handler) return;
+ pending.delete(message.id);
+ if (message.error) handler.reject(new Error(message.error)); else handler.resolve(message.result);
+ } else if (message.type === 'init') {
+ context = message.context;
+ locale = typeof message.locale === 'string' ? message.locale : 'en';
+ applyTheme(message.theme);
+ resolveReady(context);
+ listeners.init.forEach((listener) => listener(context));
+ dispatchEvent(new CustomEvent('dbx-plugin-init', { detail: message }));
+ } else if (message.type === 'context') {
+ context = message.context;
+ listeners.context.forEach((listener) => listener(context));
+ dispatchEvent(new CustomEvent('dbx-plugin-context', { detail: context }));
+ } else if (message.type === 'env') {
+ if (typeof message.locale === 'string') locale = message.locale;
+ if (message.theme) applyTheme(message.theme);
+ listeners.event.forEach((listener) => listener(message));
+ dispatchEvent(new CustomEvent('dbx-plugin-env', { detail: message }));
+ } else if (message.type === 'event') {
+ listeners.event.forEach((listener) => listener(message));
+ dispatchEvent(new CustomEvent('dbx-plugin-event', { detail: message }));
+ } else if (message.type === 'binary') {
+ const payload = { channel: message.channel, data: message.data ? new Uint8Array(message.data) : new Uint8Array(0) };
+ listeners.binary.forEach((listener) => listener(payload));
+ dispatchEvent(new CustomEvent('dbx-plugin-binary', { detail: payload }));
+ }
+ });
+ parent.postMessage({ source: '${PLUGIN_MESSAGE_SOURCE}', version: ${BRIDGE_VERSION}, type: 'ready' }, '*');
+ })();`;
+}
+
+function validRequestMessage(value: Record<string, unknown>): value is Record<string, unknown> & PluginRequestMessage {
+ return typeof value.id === "string" && value.id.length > 0 && value.id.length <= 128 && typeof value.method === "string" && value.method.length > 0 && value.method.length <= 128;
+}
+
+function requireRecord(value: unknown, label: string): Record<string, unknown> {
+ if (!isRecord(value)) throw new Error(`${label} must be an object`);
+ return value;
+}
+
+function requireProtocolName(value: unknown, label: string): string {
+ if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/.test(value)) throw new Error(`${label} is invalid`);
+ return value;
+}
+
+function requireTimeout(value: unknown): number {
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new Error("timeoutMs must be a number");
+ return Math.min(120_000, Math.max(1, Math.round(value)));
+}
+
+function base64ToBytes(value: string): ArrayBuffer {
+ const binary = atob(value);
+ const bytes = new Uint8Array(binary.length);
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
+ return bytes.buffer;
+}
+
+function bytesToBase64(bytes: Uint8Array): string {
+ let binary = "";
+ const chunkSize = 0x8000;
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
+ }
+ return btoa(binary);
+}
+
+function requireBase64(value: unknown): string {
+ if (typeof value !== "string" || value.length > MAX_BRIDGE_PAYLOAD_BYTES * 2 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) throw new Error("Binary payload must be base64");
+ return value;
+}
+
+function requireSafeAssetPath(value: unknown): string {
+ if (typeof value !== "string" || !value || value.startsWith("/") || value.split("/").some((part) => !part || part === "." || part === "..")) throw new Error("Plugin asset path is invalid");
+ return value;
+}
+
+function enforcePayloadLimit(value: unknown): void {
+ if (value === undefined) return;
+ const bytes = new TextEncoder().encode(JSON.stringify(value)).byteLength;
+ if (bytes > MAX_BRIDGE_PAYLOAD_BYTES) throw new Error("Plugin bridge request is too large");
+}
+
+function isRecord(value: unknown): value is Record<string, any> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/apps/desktop/src/lib/plugins/pluginMarketplace.spec.ts b/apps/desktop/src/lib/plugins/pluginMarketplace.spec.ts
new file mode 100644
index 0000000000..de45c6155e
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/pluginMarketplace.spec.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from "vitest";
+import { buildMarketplacePluginListings, filterMarketplacePluginListings, selectMarketplaceArtifact } from "./pluginMarketplace";
+import type { InstalledPlugin, PluginRepositoryCatalogResult } from "@/types/database";
+
+const result: PluginRepositoryCatalogResult = {
+ repository: { id: "dbx-official", name: "DBX Marketplace", kind: "official", enabled: true, managed: true },
+ target: "darwin-arm64",
+ catalog: {
+ catalogVersion: 1,
+ repository: { id: "dbx-official", name: "DBX Marketplace" },
+ plugins: [
+ {
+ id: "example.hello",
+ name: "Hello",
+ description: "Greets the user",
+ publisher: "DBX",
+ verified: true,
+ tags: ["sample"],
+ permissions: [],
+ latestVersion: "1.1.0",
+ versions: [
+ {
+ version: "1.1.0",
+ artifacts: [{ target: "darwin-arm64", url: "https://plugins.example.com/hello.dbxp", sha256: "a".repeat(64), signingKeyId: "dbx.release" }],
+ },
+ ],
+ localizations: { "zh-CN": { name: "你好工作台", description: "用于验证插件工作台" } },
+ },
+ ],
+ },
+};
+
+function installed(version: string): InstalledPlugin {
+ return {
+ manifest: {
+ manifest_version: 1,
+ id: "example.hello",
+ name: "Hello",
+ version,
+ publisher: "DBX",
+ description: "",
+ engines: { dbx: "", host_api: "" },
+ permissions: [],
+ entrypoints: {},
+ contributions: [],
+ drivers: [],
+ protocol_version: 1,
+ },
+ compatibility: { compatible: true, errors: [], warnings: [], target: "darwin-arm64" },
+ };
+}
+
+describe("plugin marketplace listings", () => {
+ it("localizes, detects updates, and filters by repository", () => {
+ const listings = buildMarketplacePluginListings([result], [installed("1.0.0")], "zh-CN");
+
+ expect(listings[0]).toMatchObject({ name: "你好工作台", status: "update", target: "darwin-arm64" });
+ expect(filterMarketplacePluginListings(listings, "验证", "dbx-official")).toHaveLength(1);
+ });
+
+ it("marks a plugin unsupported when the current target has no artifact", () => {
+ const unsupported = structuredClone(result);
+ unsupported.target = "linux-x64";
+
+ expect(buildMarketplacePluginListings([unsupported], [], "en")[0].status).toBe("unsupported");
+ });
+
+ it("uses a universal artifact when the current target has no exact artifact", () => {
+ const universal = structuredClone(result);
+ universal.target = "linux-x64";
+ universal.catalog!.plugins[0].versions[0].artifacts = [{ target: "universal", url: "https://plugins.example.com/hello-universal.dbxp", sha256: "b".repeat(64), signingKeyId: "dbx.release" }];
+
+ expect(buildMarketplacePluginListings([universal], [], "en")[0]).toMatchObject({ status: "install", artifact: { target: "universal" } });
+ });
+
+ it("prefers an exact artifact over the universal fallback", () => {
+ const artifacts = [
+ { target: "universal", url: "https://plugins.example.com/hello-universal.dbxp", sha256: "a".repeat(64), signingKeyId: "dbx.release" },
+ { target: "darwin-arm64", url: "https://plugins.example.com/hello-darwin.dbxp", sha256: "b".repeat(64), signingKeyId: "dbx.release" },
+ ];
+
+ expect(selectMarketplaceArtifact(artifacts, "darwin-arm64")?.target).toBe("darwin-arm64");
+ });
+});
diff --git a/apps/desktop/src/lib/plugins/pluginMarketplace.ts b/apps/desktop/src/lib/plugins/pluginMarketplace.ts
new file mode 100644
index 0000000000..506bfaee65
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/pluginMarketplace.ts
@@ -0,0 +1,90 @@
+import type { InstalledPlugin, PluginMarketplaceArtifact, PluginMarketplacePlugin, PluginRepository, PluginRepositoryCatalogResult } from "@/types/database";
+
+export type MarketplacePluginStatus = "install" | "installed" | "update" | "unsupported";
+
+export const UNIVERSAL_PLUGIN_TARGET = "universal";
+
+export interface MarketplacePluginListing {
+ key: string;
+ repository: PluginRepository;
+ plugin: PluginMarketplacePlugin;
+ name: string;
+ description: string;
+ target: string;
+ artifact?: PluginMarketplaceArtifact;
+ installed?: InstalledPlugin;
+ verified: boolean;
+ status: MarketplacePluginStatus;
+}
+
+export function buildMarketplacePluginListings(results: readonly PluginRepositoryCatalogResult[], installedPlugins: readonly InstalledPlugin[], locale: string): MarketplacePluginListing[] {
+ const installedById = new Map(installedPlugins.map((plugin) => [plugin.manifest.id, plugin]));
+ return results
+ .flatMap((result) =>
+ (result.catalog?.plugins || []).map((plugin) => {
+ const localized = marketplacePluginLocalization(plugin, locale);
+ const latestVersion = plugin.versions.find((version) => version.version === plugin.latestVersion);
+ const artifact = latestVersion ? selectMarketplaceArtifact(latestVersion.artifacts, result.target) : undefined;
+ const installed = installedById.get(plugin.id);
+ const status: MarketplacePluginStatus = !artifact ? "unsupported" : !installed ? "install" : compareVersions(plugin.latestVersion, installed.manifest.version || "0.0.0") > 0 ? "update" : "installed";
+ return {
+ key: `${result.repository.id}:${plugin.id}`,
+ repository: result.repository,
+ plugin,
+ name: localized.name,
+ description: localized.description,
+ target: result.target,
+ artifact,
+ installed,
+ verified: plugin.verified && listingRepositoryCanVerify(result.repository),
+ status,
+ };
+ }),
+ )
+ .sort((left, right) => left.name.localeCompare(right.name));
+}
+
+export function selectMarketplaceArtifact(artifacts: readonly PluginMarketplaceArtifact[], target: string): PluginMarketplaceArtifact | undefined {
+ return artifacts.find((candidate) => candidate.target === target) || artifacts.find((candidate) => candidate.target === UNIVERSAL_PLUGIN_TARGET);
+}
+
+function listingRepositoryCanVerify(repository: PluginRepository): boolean {
+ return repository.kind === "official" || repository.kind === "enterprise";
+}
+
+export function filterMarketplacePluginListings(listings: readonly MarketplacePluginListing[], query: string, repositoryId: string): MarketplacePluginListing[] {
+ const normalizedQuery = query.trim().toLocaleLowerCase();
+ return listings.filter((listing) => {
+ if (repositoryId !== "all" && listing.repository.id !== repositoryId) return false;
+ if (!normalizedQuery) return true;
+ return [listing.plugin.id, listing.name, listing.description, listing.plugin.publisher, listing.repository.name, ...listing.plugin.tags].join("\n").toLocaleLowerCase().includes(normalizedQuery);
+ });
+}
+
+function marketplacePluginLocalization(plugin: PluginMarketplacePlugin, locale: string): { name: string; description: string } {
+ const normalizedLocale = locale.replace("_", "-").toLowerCase();
+ const entries = Object.entries(plugin.localizations || {});
+ const localization = entries.find(([key]) => key.replace("_", "-").toLowerCase() === normalizedLocale)?.[1] || entries.find(([key]) => key.replace("_", "-").toLowerCase() === normalizedLocale.split("-")[0])?.[1];
+ return {
+ name: localization?.name?.trim() || plugin.name,
+ description: localization?.description?.trim() || plugin.description,
+ };
+}
+
+function compareVersions(left: string, right: string): number {
+ const leftParts = parseVersion(left);
+ const rightParts = parseVersion(right);
+ if (!leftParts || !rightParts) return left.localeCompare(right, undefined, { numeric: true, sensitivity: "base" });
+ const leftNumbers = leftParts.slice(0, 3) as [number, number, number];
+ const rightNumbers = rightParts.slice(0, 3) as [number, number, number];
+ for (let index = 0; index < leftNumbers.length; index += 1) {
+ if (leftNumbers[index] !== rightNumbers[index]) return leftNumbers[index] - rightNumbers[index];
+ }
+ return leftParts[3].localeCompare(rightParts[3]);
+}
+
+function parseVersion(version: string): [number, number, number, string] | null {
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?/.exec(version);
+ if (!match) return null;
+ return [Number(match[1]), Number(match[2]), Number(match[3]), match[4] || "~"];
+}
diff --git a/apps/desktop/src/lib/settings/__tests__/settingsPageNavigation.spec.ts b/apps/desktop/src/lib/settings/__tests__/settingsPageNavigation.spec.ts
index 37d7aedb61..73dbc60750 100644
--- a/apps/desktop/src/lib/settings/__tests__/settingsPageNavigation.spec.ts
+++ b/apps/desktop/src/lib/settings/__tests__/settingsPageNavigation.spec.ts
@@ -6,8 +6,8 @@ const settingsDialogSource = readFileSync(new URL("../../../components/editor/Ed
describe("settings page navigation", () => {
it("keeps query, settings, and driver-manager surfaces mutually exclusive", () => {
- expect(appSource).toContain('type MainContentSurface = "query" | "settings" | "driverStore";');
- expect(appSource).toMatch(/function activateMainContentSurface\(surface: MainContentSurface\) \{\s*settingsStore\.settingsPageActive = surface === "settings";\s*driverStoreActive\.value = surface === "driverStore";/);
+ expect(appSource).toContain('type MainContentSurface = "query" | "settings" | "driverStore" | "pluginCenter";');
+ expect(appSource).toMatch(/function activateMainContentSurface\(surface: MainContentSurface\) \{\s*settingsStore\.settingsPageActive = surface === "settings";\s*driverStoreActive\.value = surface === "driverStore";\s*pluginCenterActive\.value = surface === "pluginCenter";/);
expect(appSource).toMatch(/function activateSettingsPage\(\) \{\s*settingsPageTabOpen\.value = true;\s*activateMainContentSurface\("settings"\);/);
expect(appSource).toMatch(/function activateQuerySurface\(\) \{\s*activateMainContentSurface\("query"\);/);
expect(appSource).toMatch(/driverStoreTabOpen\.value = true;\s*activateMainContentSurface\("driverStore"\);/);
diff --git a/apps/desktop/src/lib/settings/settingsSearch.ts b/apps/desktop/src/lib/settings/settingsSearch.ts
index faeb95f876..44fbe6e148 100644
--- a/apps/desktop/src/lib/settings/settingsSearch.ts
+++ b/apps/desktop/src/lib/settings/settingsSearch.ts
@@ -48,7 +48,7 @@ export interface SettingsSearchRoute {
export type Translate = (key: string) => string;
-type ToolbarVisibilityItemKey = "dataTransfer" | "driverManager" | "sqlFile" | "schemaDiff" | "dataCompare" | "checkUpdates" | "sqlLibrary" | "sqlFileTree" | "history" | "ai" | "theme" | "github";
+type ToolbarVisibilityItemKey = "dataTransfer" | "driverManager" | "pluginCenter" | "sqlFile" | "schemaDiff" | "dataCompare" | "checkUpdates" | "sqlLibrary" | "sqlFileTree" | "history" | "ai" | "theme" | "github";
export type ToolbarVisibilityItem = { key: ToolbarVisibilityItemKey; titleKey: string; title?: never } | { key: ToolbarVisibilityItemKey; title: string; titleKey?: never };
@@ -60,6 +60,7 @@ export type ToolbarVisibilityItem = { key: ToolbarVisibilityItemKey; titleKey: s
export const TOOLBAR_VISIBILITY_ITEMS: readonly ToolbarVisibilityItem[] = [
{ key: "dataTransfer", titleKey: "transfer.dataTransfer" },
{ key: "driverManager", titleKey: "toolbar.driverManager" },
+ { key: "pluginCenter", titleKey: "toolbar.pluginCenter" },
{ key: "sqlFile", titleKey: "sqlFile.title" },
{ key: "schemaDiff", titleKey: "diff.title" },
{ key: "dataCompare", titleKey: "dataCompare.title" },
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index db07c2118c..b8c607bef2 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -3868,6 +3868,8 @@ export const useConnectionStore = defineStore("connection", () => {
await loadMqttTopics(connectionId);
} else if (config.db_type === "nacos") {
await loadNacosNamespaces(connectionId, { force: true });
+ } else if (config.db_type === "plugin") {
+ return;
} else {
await loadDatabases(connectionId, { force: true });
}
@@ -3964,8 +3966,10 @@ export const useConnectionStore = defineStore("connection", () => {
await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id);
activeConnectionId.value = id;
connectedIds.value.add(id);
- void refreshConnectedDatabaseInfo(id, { ...config, id });
- await refreshConnectionIdentifierQuote(id, { ...config, id });
+ if (config.db_type !== "plugin") {
+ void refreshConnectedDatabaseInfo(id, { ...config, id });
+ await refreshConnectionIdentifierQuote(id, { ...config, id });
+ }
if (id !== config.id) markSuccessfulLocalConnectionAttempt(config.id, localAttempt);
markSuccessfulLocalConnectionAttempt(id, localAttempt);
markConnectionHealthChecked(id);
@@ -4221,8 +4225,10 @@ export const useConnectionStore = defineStore("connection", () => {
await syncMongoLegacyDriverFallback(connectionId, config);
await ensureLocalConnectionAttemptActiveAfterConnectResult(connectionId, localAttempt, id);
connectedIds.value.add(connectionId);
- void refreshConnectedDatabaseInfo(connectionId, config);
- await refreshConnectionIdentifierQuote(connectionId, config);
+ if (config.db_type !== "plugin") {
+ void refreshConnectedDatabaseInfo(connectionId, config);
+ await refreshConnectionIdentifierQuote(connectionId, config);
+ }
markSuccessfulLocalConnectionAttempt(connectionId, localAttempt);
markConnectionHealthChecked(connectionId);
clearConnectionError(connectionId);
diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.ts
index f1b31f03bc..7a67ef6a8c 100644
--- a/apps/desktop/src/stores/queryStore.ts
+++ b/apps/desktop/src/stores/queryStore.ts
@@ -4,8 +4,8 @@ import { isRedisMonitorCommand, startRedisMonitor } from "@/lib/redis/redisMonit
import { uuid } from "@/lib/common/utils";
import { computed, markRaw, nextTick, onScopeDispose, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
-import type { BatchSqlExecution, ConnectionConfig, DatabaseType, IndexInfo, NacosConfigEditorViewport, ObjectBrowserFilter, ObjectBrowserViewport, QueryResult, QueryResultSourceColumnRef, QueryTab, TableInfoTab, TableStructureEditorTarget } from "@/types/database";
import { sanitizeTabPageUiState } from "@/lib/tabs/tabUiState";
+import type { BatchSqlExecution, ConnectionConfig, DatabaseType, IndexInfo, NacosConfigEditorViewport, ObjectBrowserFilter, ObjectBrowserViewport, QueryResult, QueryResultSourceColumnRef, QueryTab, TableInfoTab, TableStructureEditorTarget } from "@/types/database";
import { orderPinnedFirst } from "@/lib/app/pinnedItems";
import { canCancelQueryExecution } from "@/lib/sql/queryExecutionState";
import { buildExplainSql, parseExplainResult, parseDamengExplainText, parseOracleExplainText, sqlServerExplainResult, type BuildExplainSqlResult, type ExplainPlanDatabaseType } from "@/lib/diagram/explainPlan";
@@ -74,6 +74,8 @@ import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";
import { batchSqlRecoverySql, batchSqlRecoveryState, mergeBatchQueryResults, offsetBatchQueryResultIndexes, prepareBatchSqlRecovery, type BatchSqlRecoveryAction } from "@/lib/query/batchSqlRecovery";
import { decodeQueryResultArchive, encodeQueryResultArchive, type DecodedQueryResultArchive } from "@/lib/query/queryResultArchive";
import * as api from "@/lib/backend/api";
+import { createFrontendPluginRegistry } from "@/lib/plugins/frontendPlugin";
+import { snapshotPluginWorkbenchContext } from "@/lib/plugins/pluginData";
import { useConnectionStore } from "@/stores/connectionStore";
import { useSettingsStore } from "@/stores/settingsStore";
import { useSavedSqlStore } from "@/stores/savedSqlStore";
@@ -91,7 +93,7 @@ import { safeLocalStorageGet, safeLocalStorageRemove } from "@/lib/backend/safeS
import { sqlTextFingerprint } from "@/lib/sql/sqlTextFingerprint";
import { disposeAllSqlServerActivityTraces, disposeSqlServerActivityTrace } from "@/lib/sqlserver/sqlServerActivityTraceRuntime";
import type { SavedSqlFile } from "@/types/database";
-import i18n from "@/i18n";
+import i18n, { currentLocale } from "@/i18n";
import { translateBackendError } from "@/i18n/backend-errors";
import type { SqlExecutionTargetContext } from "@/lib/database/sqlExecutionTargetRegistry";
import type { DriverProfileWorkspaceScope } from "@/lib/database/driverProfileExtensions";
@@ -3145,6 +3147,100 @@ export const useQueryStore = defineStore("query", () => {
tab.nacosTargetKeyword = undefined;
}
+ function openPluginWorkbench(pluginId: string, contributionId: string, options: { title?: string; connectionId?: string; database?: string; context?: Record<string, unknown>; forceNew?: boolean } = {}) {
+ if (!options.forceNew) {
+ const existing = tabs.value.find((tab) => tab.mode === "plugin-workbench" && tab.pluginWorkbench?.pluginId === pluginId && tab.pluginWorkbench?.contributionId === contributionId && tab.connectionId === (options.connectionId || ""));
+ if (existing) {
+ if (options.context) existing.pluginWorkbench = { ...existing.pluginWorkbench!, context: snapshotPluginWorkbenchContext(options.context) };
+ switchTab(existing.id);
+ return existing.id;
+ }
+ }
+
+ const id = uuid();
+ const tab: QueryTab = {
+ id,
+ title: options.title || contributionId,
+ connectionId: options.connectionId || "",
+ database: options.database || "",
+ sql: "",
+ isExecuting: false,
+ isCancelling: false,
+ isExplaining: false,
+ mode: "plugin-workbench",
+ pluginWorkbench: {
+ pluginId,
+ contributionId,
+ context: options.context ? snapshotPluginWorkbenchContext(options.context) : undefined,
+ },
+ };
+ return registerOpenTab(tab);
+ }
+
+ function openPluginFilesystem(pluginId: string, providerId: string, options: { title?: string; connectionId?: string; rootUri?: string; currentUri?: string; forceNew?: boolean } = {}) {
+ if (!options.forceNew) {
+ const existing = tabs.value.find((tab) => tab.mode === "plugin-filesystem" && tab.pluginFilesystem?.pluginId === pluginId && tab.pluginFilesystem?.providerId === providerId && tab.connectionId === (options.connectionId || ""));
+ if (existing) {
+ if (options.currentUri) existing.pluginFilesystem = { ...existing.pluginFilesystem!, currentUri: options.currentUri };
+ switchTab(existing.id);
+ return existing.id;
+ }
+ }
+
+ const id = uuid();
+ const tab: QueryTab = {
+ id,
+ title: options.title || providerId,
+ connectionId: options.connectionId || "",
+ database: "",
+ sql: "",
+ isExecuting: false,
+ isCancelling: false,
+ isExplaining: false,
+ mode: "plugin-filesystem",
+ pluginFilesystem: {
+ pluginId,
+ providerId,
+ rootUri: options.rootUri,
+ currentUri: options.currentUri,
+ },
+ };
+ return registerOpenTab(tab);
+ }
+
+ async function openPluginConnection(connectionId: string) {
+ const connectionStore = useConnectionStore();
+ const connection = connectionStore.getConfig(connectionId);
+ if (!connection || connection.db_type !== "plugin") throw new Error("Plugin connection config not found");
+ const pluginId = connection.plugin_id;
+ const providerId = connection.plugin_connection_provider;
+ if (!pluginId || !providerId) throw new Error("Plugin connection binding is incomplete");
+ const registry = createFrontendPluginRegistry(await api.listPlugins(), currentLocale());
+ const provider = registry.listConnectionProviders().find((entry) => entry.plugin.manifest.id === pluginId && entry.contribution.id === providerId);
+ if (!provider) throw new Error(`Plugin connection provider '${pluginId}/${providerId}' is unavailable`);
+ const workbench = provider.contribution.workbench ? registry.findWorkbench(pluginId, provider.contribution.workbench) : undefined;
+ await connectionStore.ensureConnected(connectionId);
+ if (workbench) {
+ return openPluginWorkbench(pluginId, workbench.contribution.id, {
+ title: `${connection.name} · ${workbench.contribution.label}`,
+ connectionId,
+ context: {
+ connectionId,
+ providerId,
+ connectionType: connection.plugin_connection_type,
+ },
+ });
+ }
+ const filesystemProviderId = provider.contribution.filesystem_provider;
+ const filesystem = filesystemProviderId ? registry.listFilesystemProviders().find((entry) => entry.plugin.manifest.id === pluginId && entry.contribution.id === filesystemProviderId) : undefined;
+ if (!filesystem) throw new Error(`Plugin connection provider '${pluginId}/${providerId}' does not declare a workbench or filesystem provider`);
+ return openPluginFilesystem(pluginId, filesystem.contribution.id, {
+ title: `${connection.name} · ${filesystem.contribution.label}`,
+ connectionId,
+ rootUri: filesystem.contribution.root_uri,
+ });
+ }
+
function applyTableStructureInitialTab(tab: QueryTab, initialTab?: TableInfoTab, initialTarget?: TableStructureEditorTarget) {
if (!initialTab && !initialTarget?.name) return;
if (initialTab) tab.structureInitialTab = initialTab;
@@ -8088,6 +8184,9 @@ export const useQueryStore = defineStore("query", () => {
openMqttAdmin,
openNacosAdmin,
clearNacosNavigationTarget,
+ openPluginWorkbench,
+ openPluginFilesystem,
+ openPluginConnection,
openTableStructure,
linkSavedSql,
linkExternalSqlPath,
diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.ts
index ce263fdba7..de0f1642d2 100644
--- a/apps/desktop/src/stores/settingsStore.ts
+++ b/apps/desktop/src/stores/settingsStore.ts
@@ -900,6 +900,7 @@ export interface EditorSettings {
export interface ToolbarItems {
dataTransfer: boolean;
driverManager: boolean;
+ pluginCenter: boolean;
sqlFile: boolean;
schemaDiff: boolean;
dataCompare: boolean;
@@ -916,6 +917,7 @@ export interface ToolbarItems {
export const DEFAULT_TOOLBAR_ITEMS: ToolbarItems = {
dataTransfer: true,
driverManager: true,
+ pluginCenter: true,
sqlFile: true,
schemaDiff: true,
dataCompare: true,
@@ -1369,6 +1371,7 @@ function normalizeToolbarItems(items: Partial<ToolbarItems> | undefined): Toolba
return {
dataTransfer: items.dataTransfer ?? defaults.dataTransfer,
driverManager: items.driverManager ?? defaults.driverManager,
+ pluginCenter: items.pluginCenter ?? defaults.pluginCenter,
sqlFile: items.sqlFile ?? defaults.sqlFile,
schemaDiff: items.schemaDiff ?? defaults.schemaDiff,
dataCompare: items.dataCompare ?? defaults.dataCompare,
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index 5b16ddf869..a7288722ec 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -131,6 +131,10 @@ export interface ConnectionConfig {
gbase_server?: string;
informix_server?: string;
external_config?: unknown;
+ plugin_id?: string;
+ plugin_connection_provider?: string;
+ plugin_connection_type?: string;
+ connection_secrets?: Record<string, string>;
one_time?: boolean;
/**
* Whether the database password may be persisted locally. When false, the
@@ -260,19 +264,328 @@ export interface PluginDriverManifest {
database_type?: string;
}
+export type PluginFormFieldType = "text" | "password" | "number" | "boolean" | "select" | "radio" | "textarea";
+export type PluginFormFieldBinding = "config" | "secret" | "name" | "host" | "port" | "username" | "password" | "database";
+
+export type PluginFormFieldValue = string | number | boolean | undefined;
+
+export interface PluginFormFieldOption {
+ label: string;
+ value: string;
+}
+
+export interface PluginFormField {
+ key: string;
+ label: string;
+ type: PluginFormFieldType;
+ description?: string;
+ placeholder?: string;
+ required?: boolean;
+ default?: PluginFormFieldValue;
+ options?: PluginFormFieldOption[];
+ binding?: PluginFormFieldBinding;
+}
+
+export type PluginConnectionCapability = "test" | "connect" | "disconnect";
+export type PluginConnectionActionKind = "test" | "save" | "save-and-connect" | "custom";
+export type PluginConnectionActionVariant = "default" | "outline" | "secondary" | "destructive" | "ghost";
+export type PluginConnectionActionWhen = "always" | "create" | "edit";
+
+export interface PluginConnectionActionContribution {
+ id: string;
+ label: string;
+ description?: string;
+ variant?: PluginConnectionActionVariant;
+ when?: PluginConnectionActionWhen;
+ close_on_success?: boolean;
+ requires_valid_form?: boolean;
+ timeout_ms?: number;
+}
+
+export interface PluginConnectionAction {
+ id: string;
+ kind: PluginConnectionActionKind;
+ label?: string;
+ description?: string;
+ variant?: PluginConnectionActionVariant;
+ when?: PluginConnectionActionWhen;
+ close_on_success?: boolean;
+ requires_valid_form?: boolean;
+ timeout_ms?: number;
+}
+
+export interface PluginConnectionProviderContribution {
+ type: "connection-provider";
+ id: string;
+ label: string;
+ icon?: string;
+ database_type: string;
+ description?: string;
+ fields: PluginFormField[];
+ workbench?: string;
+ filesystem_provider?: string;
+ capabilities?: PluginConnectionCapability[];
+ actions?: PluginConnectionActionContribution[];
+}
+
+export interface PluginWorkbenchContribution {
+ type: "workbench";
+ id: string;
+ label: string;
+ description?: string;
+ icon?: string;
+}
+
+export interface PluginFilesystemProviderContribution {
+ type: "filesystem-provider";
+ id: string;
+ label: string;
+ schemes: string[];
+ description?: string;
+ root_uri?: string;
+ capabilities?: Array<"read" | "write" | "delete" | "rename" | "mkdir">;
+}
+
+export type PluginFilesystemEntryKind = "file" | "directory" | "symlink" | "other";
+
+export interface PluginFilesystemEntry {
+ name: string;
+ uri: string;
+ kind: PluginFilesystemEntryKind;
+ size?: number;
+ modifiedAt?: string;
+ contentType?: string;
+}
+
+export interface PluginFilesystemListResult {
+ entries: PluginFilesystemEntry[];
+ nextCursor?: string;
+}
+
+export interface PluginFilesystemReadResult {
+ dataBase64: string;
+ contentType?: string;
+ truncated: boolean;
+ etag?: string;
+}
+
+export interface PluginFilesystemMutationResult {
+ success: boolean;
+ message?: string;
+ entry?: PluginFilesystemEntry;
+}
+
+export interface PluginContextMenuContribution {
+ type: "context-menu";
+ id: string;
+ label: string;
+ description?: string;
+ icon?: string;
+ menu: string;
+}
+
+export interface PluginResultViewContribution {
+ type: "result-view";
+ id: string;
+ label: string;
+ description?: string;
+ icon?: string;
+}
+
+export type PluginContribution = PluginConnectionProviderContribution | PluginWorkbenchContribution | PluginFilesystemProviderContribution | PluginContextMenuContribution | PluginResultViewContribution;
+
+export interface PluginEngines {
+ dbx: string;
+ host_api: string;
+}
+
+export interface PluginBackendEntrypoint {
+ protocol_versions?: number[];
+ transport?: "stdio-jsonl" | "stdio-framed";
+ executable: string;
+}
+
+export interface PluginUiEntrypoint {
+ root?: string;
+ entry: string;
+}
+
+export interface PluginEntrypoints {
+ backend?: PluginBackendEntrypoint;
+ ui?: PluginUiEntrypoint;
+}
+
+export interface PluginFormFieldLocalization {
+ label?: string;
+ description?: string;
+ placeholder?: string;
+ options?: Record<string, string>;
+}
+
+export interface PluginContributionLocalization {
+ label?: string;
+ description?: string;
+ fields?: Record<string, PluginFormFieldLocalization>;
+ actions?: Record<string, { label?: string; description?: string }>;
+}
+
+export interface PluginManifestLocalization {
+ name?: string;
+ description?: string;
+ contributions?: Record<string, PluginContributionLocalization>;
+}
+
+export interface PluginCompatibility {
+ compatible: boolean;
+ errors?: string[];
+ warnings?: string[];
+ target?: string;
+}
+
export interface PluginManifest {
+ manifest_version?: number;
id: string;
name: string;
+ icon?: string;
version?: string;
+ publisher?: string;
+ engines?: PluginEngines;
+ permissions?: string[];
+ entrypoints?: PluginEntrypoints;
protocol_version?: number;
description?: string;
+ source?: string;
+ homepage?: string;
executable?: string;
drivers: PluginDriverManifest[];
+ contributions?: PluginContribution[];
+ localizations?: Record<string, PluginManifestLocalization>;
}
export interface InstalledPlugin {
manifest: PluginManifest;
- path: string;
+ compatibility: PluginCompatibility;
+ path?: string;
+}
+
+export interface PluginTrustedKey {
+ keyId: string;
+ publicKey: string;
+}
+
+export type PluginRepositoryKind = "official" | "custom" | "enterprise";
+
+export interface PluginRepository {
+ id: string;
+ name: string;
+ kind: PluginRepositoryKind;
+ catalogUrl?: string;
+ enabled: boolean;
+ managed: boolean;
+}
+
+export interface PluginMarketplaceRepositoryMetadata {
+ id: string;
+ name: string;
+ homepage?: string;
+}
+
+export interface PluginMarketplaceLocalization {
+ name?: string;
+ description?: string;
+}
+
+export interface PluginMarketplaceArtifact {
+ target: string;
+ url: string;
+ sha256: string;
+ signingKeyId: string;
+ size?: number;
+}
+
+export interface PluginMarketplaceVersion {
+ version: string;
+ releasedAt?: string;
+ releaseNotes?: string;
+ artifacts: PluginMarketplaceArtifact[];
+}
+
+export interface PluginMarketplacePlugin {
+ id: string;
+ name: string;
+ description: string;
+ publisher: string;
+ verified: boolean;
+ icon?: string;
+ tags: string[];
+ permissions: string[];
+ source?: string;
+ homepage?: string;
+ license?: string;
+ latestVersion: string;
+ versions: PluginMarketplaceVersion[];
+ localizations?: Record<string, PluginMarketplaceLocalization>;
+}
+
+export interface PluginMarketplaceCatalog {
+ catalogVersion: number;
+ repository: PluginMarketplaceRepositoryMetadata;
+ generatedAt?: string;
+ plugins: PluginMarketplacePlugin[];
+}
+
+export interface PluginRepositoryCatalogResult {
+ repository: PluginRepository;
+ target: string;
+ catalog?: PluginMarketplaceCatalog;
+ error?: string;
+}
+
+export interface PluginMarketplaceInstallRequest {
+ repositoryId: string;
+ pluginId: string;
+ version?: string;
+}
+
+export interface ActivePluginSession {
+ pluginId: string;
+ processId?: number;
+ state: "starting" | "running" | "stopping" | "stopped" | "exited";
+}
+
+export interface PluginUiAssetPayload {
+ contentType: string;
+ dataBase64: string;
+ etag: string;
+}
+
+export interface PluginConnectionActionResult {
+ message?: string;
+ fieldValues?: Record<string, PluginFormFieldValue | null>;
+}
+
+export interface PluginInstallResult {
+ plugin: InstalledPlugin;
+ previousVersion?: string;
+ packageSha256: string;
+ signature: { status: "trusted"; key_id: string } | { status: "unsigned" };
+}
+
+export interface PluginRollbackResult {
+ plugin: InstalledPlugin;
+ previousVersion: string;
+}
+
+export interface PluginEvent {
+ pluginId: string;
+ method: string;
+ params: unknown;
+}
+
+export interface PluginBinaryEvent {
+ pluginId: string;
+ channel: string;
+ dataBase64: string;
}
export interface JdbcDriverInfo {
@@ -1296,7 +1609,20 @@ export interface QueryTab {
| "mysql-dashboard"
| "postgres-dashboard"
| "xugu-dashboard"
- | "dolt-version-control";
+ | "dolt-version-control"
+ | "plugin-workbench"
+ | "plugin-filesystem";
+ pluginWorkbench?: {
+ pluginId: string;
+ contributionId: string;
+ context?: Record<string, unknown>;
+ };
+ pluginFilesystem?: {
+ pluginId: string;
+ providerId: string;
+ rootUri?: string;
+ currentUri?: string;
+ };
/** Ephemeral navigation intent; it is consumed by HBaseBrowser and is not persisted. */
hbaseCreateTableOnOpen?: boolean;
mqTenant?: string;
diff --git a/apps/desktop/src/types/generated/databaseTypes.ts b/apps/desktop/src/types/generated/databaseTypes.ts
index e4042e03b9..1b933aa03e 100644
--- a/apps/desktop/src/types/generated/databaseTypes.ts
+++ b/apps/desktop/src/types/generated/databaseTypes.ts
@@ -80,6 +80,7 @@ export const DATABASE_TYPES = [
"victoriametrics",
"jdbc",
"spark",
+ "plugin",
] as const;
export type DatabaseType = (typeof DATABASE_TYPES)[number];
diff --git a/crates/dbx-core/Cargo.toml b/crates/dbx-core/Cargo.toml
index 868d2f2882..1486680073 100644
--- a/crates/dbx-core/Cargo.toml
+++ b/crates/dbx-core/Cargo.toml
@@ -20,6 +20,9 @@ system-fonts = ["font-kit"]
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0", features = ["arbitrary_precision", "preserve_order"] }
+semver = "1"
+ed25519-dalek = "2"
+fs2 = "0.4"
utoipa = { version = "5.5", optional = true }
unicode-width = "0.2"
unicode-ident = "1"
diff --git a/crates/dbx-core/assets/database-drivers.manifest.json b/crates/dbx-core/assets/database-drivers.manifest.json
index d58ae13df9..ae7994b534 100644
--- a/crates/dbx-core/assets/database-drivers.manifest.json
+++ b/crates/dbx-core/assets/database-drivers.manifest.json
@@ -2850,6 +2850,35 @@
"userAdmin": false,
"driverManagement": true
}
+ },
+ {
+ "dbType": "plugin",
+ "label": "Plugin",
+ "runtimeMode": "external",
+ "mcpMode": "unsupported",
+ "singleConnectionPool": false,
+ "metadataConnectionScoped": false,
+ "skipTcpProbe": true,
+ "supportLevel": "connect",
+ "specializedSurface": true,
+ "capabilities": {
+ "queryExecution": false,
+ "metadataBrowse": false,
+ "objectBrowser": false,
+ "objectSource": false,
+ "schemaSearch": false,
+ "diagram": false,
+ "tableDataEdit": false,
+ "tableStructureEdit": false,
+ "tableImport": false,
+ "dataTransfer": false,
+ "sqlFileExecution": false,
+ "databaseCreate": false,
+ "fieldLineage": false,
+ "sqlExplain": false,
+ "userAdmin": false,
+ "driverManagement": false
+ }
}
]
}
diff --git a/crates/dbx-core/examples/plugin_marketplace_smoke.rs b/crates/dbx-core/examples/plugin_marketplace_smoke.rs
new file mode 100644
index 0000000000..6f7baff2a7
--- /dev/null
+++ b/crates/dbx-core/examples/plugin_marketplace_smoke.rs
@@ -0,0 +1,56 @@
+use dbx_core::plugins::{
+ PluginMarketplace, PluginMarketplaceInstallRequest, PluginSignatureStatus, OFFICIAL_PLUGIN_REPOSITORY_ID,
+};
+
+const APP_VERSION: &str = "0.5.68";
+
+#[tokio::main]
+async fn main() {
+ if let Err(error) = run().await {
+ eprintln!("plugin marketplace smoke failed: {error}");
+ std::process::exit(1);
+ }
+}
+
+async fn run() -> Result<(), String> {
+ let store = tempfile::tempdir().map_err(|error| error.to_string())?;
+ let marketplace = PluginMarketplace::new(store.path().to_path_buf(), APP_VERSION)?;
+ let results = marketplace.fetch_catalogs().await;
+ let official = results
+ .iter()
+ .find(|result| result.repository.id == OFFICIAL_PLUGIN_REPOSITORY_ID)
+ .ok_or("Official DBX Marketplace result is missing")?;
+ if let Some(error) = &official.error {
+ return Err(error.clone());
+ }
+ let catalog = official.catalog.as_ref().ok_or("Official DBX Marketplace catalog is missing")?;
+ let mut arguments = std::env::args().skip(1);
+ let Some(plugin_id) = arguments.next() else {
+ println!("plugin marketplace smoke passed: fetched {} official catalog entries", catalog.plugins.len());
+ return Ok(());
+ };
+ let version = arguments.next();
+ if arguments.next().is_some() {
+ return Err("Usage: plugin_marketplace_smoke [plugin-id] [version]".to_string());
+ }
+ if !catalog.plugins.iter().any(|plugin| plugin.id == plugin_id) {
+ return Err(format!("Official DBX Marketplace does not list '{plugin_id}'"));
+ }
+ let installed = marketplace
+ .install(PluginMarketplaceInstallRequest {
+ repository_id: OFFICIAL_PLUGIN_REPOSITORY_ID.to_string(),
+ plugin_id: plugin_id.clone(),
+ version,
+ })
+ .await?;
+ if installed.plugin.manifest.id != plugin_id {
+ return Err(format!("Expected plugin '{plugin_id}', got '{}'", installed.plugin.manifest.id));
+ }
+ match installed.signature {
+ PluginSignatureStatus::Trusted { key_id } => {
+ println!("plugin marketplace smoke passed: catalog -> release download -> sha256 -> signature {key_id} -> install");
+ }
+ signature => return Err(format!("Unexpected marketplace signature status: {signature:?}")),
+ }
+ Ok(())
+}
diff --git a/crates/dbx-core/examples/plugin_package_smoke.rs b/crates/dbx-core/examples/plugin_package_smoke.rs
new file mode 100644
index 0000000000..f98180f66f
--- /dev/null
+++ b/crates/dbx-core/examples/plugin_package_smoke.rs
@@ -0,0 +1,160 @@
+use std::collections::BTreeMap;
+use std::path::PathBuf;
+use std::time::Duration;
+
+use dbx_core::models::connection::ConnectionConfig;
+use dbx_core::plugins::{PluginHost, PluginInstallPolicy, PluginPackageInstaller, PluginRegistry, PluginTrustStore};
+use serde_json::{json, Value};
+
+const PLUGIN_ID: &str = "dbx.example.hello";
+const APP_VERSION: &str = "0.5.68";
+
+#[tokio::main]
+async fn main() {
+ if let Err(error) = run().await {
+ eprintln!("plugin package smoke failed: {error}");
+ std::process::exit(1);
+ }
+}
+
+async fn run() -> Result<(), String> {
+ let package = std::env::args().nth(1).map(PathBuf::from).ok_or("Usage: plugin_package_smoke <package.dbxp>")?;
+ let store = tempfile::tempdir().map_err(|error| error.to_string())?;
+ let trusted_keys = std::env::var("DBX_PLUGIN_SMOKE_TRUSTED_KEYS_JSON")
+ .ok()
+ .map(|raw| serde_json::from_str::<BTreeMap<String, String>>(&raw).map_err(|error| error.to_string()))
+ .transpose()?;
+ let (installer, policy) = match trusted_keys {
+ Some(keys) => (
+ PluginPackageInstaller::with_trust_store(
+ store.path().to_path_buf(),
+ APP_VERSION.to_string(),
+ PluginTrustStore::from_base64_keys(keys)?,
+ ),
+ PluginInstallPolicy::LocalSigned,
+ ),
+ None => (
+ PluginPackageInstaller::new(store.path().to_path_buf(), APP_VERSION.to_string())?,
+ PluginInstallPolicy::LocalDevelopment,
+ ),
+ };
+ let installed = installer.install_file(&package, policy)?;
+ if installed.plugin.manifest.id != PLUGIN_ID {
+ return Err(format!("Expected plugin '{PLUGIN_ID}', got '{}'", installed.plugin.manifest.id));
+ }
+
+ let registry = PluginRegistry::new_with_app_version(store.path().to_path_buf(), APP_VERSION);
+ let plugin_icon = installed.plugin.manifest.icon.as_deref().ok_or("Example plugin does not declare an icon")?;
+ let provider_icon = installed
+ .plugin
+ .manifest
+ .connection_provider("dbx.example.hello.connection")?
+ .and_then(|provider| provider.icon)
+ .ok_or("Example connection provider does not declare an icon")?;
+ for icon in [plugin_icon, provider_icon.as_str()] {
+ let asset = registry.read_asset(PLUGIN_ID, icon)?;
+ if !asset.content_type.starts_with("image/") || asset.bytes.is_empty() {
+ return Err(format!("Invalid packaged plugin icon '{icon}'"));
+ }
+ }
+ let host = PluginHost::new(registry);
+ let mut events = host.subscribe_events();
+ let config: ConnectionConfig = serde_json::from_value(json!({
+ "id": "hello-smoke-connection",
+ "name": "Hello smoke connection",
+ "db_type": "plugin",
+ "driver_profile": "plugin",
+ "host": "localhost",
+ "port": 22,
+ "username": "",
+ "password": "",
+ "database": null,
+ "external_config": { "greeting": "Hello" },
+ "plugin_id": PLUGIN_ID,
+ "plugin_connection_provider": "dbx.example.hello.connection",
+ "plugin_connection_type": "hello",
+ "connection_secrets": { "api_token": "smoke-secret" }
+ }))
+ .map_err(|error| error.to_string())?;
+
+ let test = host.test_connection(&config, "localhost", 22).await?;
+ if !test.message.contains("localhost:22") {
+ return Err(format!("Unexpected connection-test result: {}", test.message));
+ }
+
+ let action = host.invoke_connection_action(&config, "suggest-greeting", "localhost", 22).await?;
+ if action.message.as_deref() != Some("Greeting updated by the plugin action.")
+ || action.field_values.get("greeting").and_then(Value::as_str) != Some("Hello from plugin action")
+ {
+ return Err(format!("Unexpected connection-action result: {action:?}"));
+ }
+
+ let handle = host.connect_connection(&config, "localhost", 22).await?;
+ if !handle.is_running() {
+ return Err("Plugin connection handle is not running".to_string());
+ }
+ let greeting: Value = host
+ .invoke(
+ PLUGIN_ID,
+ "hello/greet",
+ json!({ "connectionId": config.id, "name": "Smoke" }),
+ None,
+ Some(Duration::from_secs(5)),
+ )
+ .await?;
+ if greeting.get("message").and_then(Value::as_str) != Some("Hello, Smoke, from Hello smoke connection!") {
+ return Err(format!("Unexpected greeting: {greeting}"));
+ }
+ let files = host
+ .list_filesystem_entries(
+ PLUGIN_ID,
+ "dbx.example.hello.files",
+ Some(&config.id),
+ Some("hello:/"),
+ None,
+ Some(20),
+ )
+ .await?;
+ if !files.entries.iter().any(|entry| entry.name == "README.txt") {
+ return Err(format!("Unexpected filesystem listing: {files:?}"));
+ }
+ let preview = host
+ .read_filesystem_file(PLUGIN_ID, "dbx.example.hello.files", Some(&config.id), "hello:/README.txt", Some(1024))
+ .await?;
+ if preview.truncated || preview.data_base64.is_empty() {
+ return Err(format!("Unexpected filesystem preview: {preview:?}"));
+ }
+
+ let mut saw_connected = false;
+ let mut saw_finished = false;
+ for _ in 0..4 {
+ let event = tokio::time::timeout(Duration::from_secs(2), events.recv())
+ .await
+ .map_err(|_| "Timed out waiting for plugin events".to_string())?
+ .map_err(|error| error.to_string())?;
+ if event.method == "hello/connectionChanged"
+ && event.params.get("state").and_then(Value::as_str) == Some("connected")
+ {
+ saw_connected = true;
+ }
+ if event.method == "hello/progress" && event.params.get("stage").and_then(Value::as_str) == Some("finished") {
+ saw_finished = true;
+ }
+ if saw_connected && saw_finished {
+ break;
+ }
+ }
+ if !saw_connected || !saw_finished {
+ return Err(format!("Missing expected events: connected={saw_connected}, finished={saw_finished}"));
+ }
+
+ handle.disconnect().await?;
+ host.stop_all().await;
+ installer.uninstall(PLUGIN_ID)?;
+ if !PluginRegistry::new_with_app_version(store.path().to_path_buf(), APP_VERSION).list_installed()?.is_empty() {
+ return Err("Plugin store is not empty after uninstall".to_string());
+ }
+
+ println!("plugin package smoke passed: install -> assets -> action -> test -> connect -> invoke -> filesystem -> events -> disconnect -> uninstall");
+ Ok(())
+}
diff --git a/crates/dbx-core/examples/table_import_live_bench.rs b/crates/dbx-core/examples/table_import_live_bench.rs
index 815fd5a3ca..6f4021270d 100644
--- a/crates/dbx-core/examples/table_import_live_bench.rs
+++ b/crates/dbx-core/examples/table_import_live_bench.rs
@@ -204,6 +204,10 @@ fn connection_config(id: &str, database: BenchDatabase) -> Result<ConnectionConf
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/src/agent_connection.rs b/crates/dbx-core/src/agent_connection.rs
index 1528757a94..c396cd945d 100644
--- a/crates/dbx-core/src/agent_connection.rs
+++ b/crates/dbx-core/src/agent_connection.rs
@@ -763,6 +763,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/src/agent_explain.rs b/crates/dbx-core/src/agent_explain.rs
index 955eaceef7..6318c86c51 100644
--- a/crates/dbx-core/src/agent_explain.rs
+++ b/crates/dbx-core/src/agent_explain.rs
@@ -190,13 +190,12 @@ mod tests {
permissions.set_mode(0o755);
std::fs::set_permissions(&executable, permissions).unwrap();
- let plugin = InstalledPlugin {
- manifest: PluginManifest {
+ let plugin = InstalledPlugin::new(
+ PluginManifest {
id: "jdbc".to_string(),
name: "JDBC".to_string(),
version: "test".to_string(),
protocol_version: 1,
- description: String::new(),
executable: Some("plugin.sh".to_string()),
drivers: vec![PluginDriverManifest {
id: "jdbc".to_string(),
@@ -204,9 +203,11 @@ mod tests {
kind: "external".to_string(),
database_type: Some("jdbc".to_string()),
}],
+ ..PluginManifest::default()
},
- path: dir.clone(),
- };
+ dir.clone(),
+ env!("CARGO_PKG_VERSION"),
+ );
let session = Arc::new(
PluginDriverSession::start_for_test(plugin, "jdbc".to_string(), PluginRuntimeEnv::default()).await.unwrap(),
);
diff --git a/crates/dbx-core/src/agent_tools.rs b/crates/dbx-core/src/agent_tools.rs
index 70b84849ee..0f4856437a 100644
--- a/crates/dbx-core/src/agent_tools.rs
+++ b/crates/dbx-core/src/agent_tools.rs
@@ -1490,6 +1490,10 @@ for line in sys.stdin:
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/src/cloud_sync.rs b/crates/dbx-core/src/cloud_sync.rs
index 3b05bf3e85..7951d88de0 100644
--- a/crates/dbx-core/src/cloud_sync.rs
+++ b/crates/dbx-core/src/cloud_sync.rs
@@ -15,7 +15,7 @@ use crate::ai::AiConfigItem;
use crate::connection_secrets::{
CASSANDRA_KEYSTORE_PASSWORD_KEY, CASSANDRA_TRUSTSTORE_PASSWORD_KEY, MQ_AUTH_API_KEY_VALUE_KEY,
MQ_AUTH_CLIENT_SECRET_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY, NACOS_AUTH_PASSWORD_KEY,
- NACOS_RNACOS_CONSOLE_PASSWORD_KEY,
+ NACOS_RNACOS_CONSOLE_PASSWORD_KEY, PLUGIN_CONNECTION_SECRET_PREFIX,
};
use crate::models::connection::{ConnectionConfig, DatabaseType, TransportLayerConfig};
use crate::saved_sql::SavedSqlLibrary;
@@ -973,6 +973,7 @@ fn scrub_connection_secrets(config: &mut ConnectionConfig) {
scrub_mq_external_config_secrets(config);
scrub_nacos_auth_secrets(config);
scrub_cassandra_tls_secrets(config);
+ config.connection_secrets.clear();
}
fn scrub_mqtt_auth_secrets(config: &mut ConnectionConfig) {
@@ -1008,6 +1009,14 @@ async fn build_sensitive_payload(
if config.save_password {
push_secret(&mut connection_secrets, &config.id, "password", &config.password);
}
+ for (key, secret) in &config.connection_secrets {
+ push_secret(
+ &mut connection_secrets,
+ &config.id,
+ &format!("{PLUGIN_CONNECTION_SECRET_PREFIX}{key}"),
+ secret,
+ );
+ }
push_secret(&mut connection_secrets, &config.id, "init_script", config.init_script.as_deref().unwrap_or(""));
for (index, layer) in config.transport_layers.iter().enumerate() {
match layer {
@@ -1225,6 +1234,7 @@ async fn apply_sensitive_payload(
if !SECRET_KEYS.contains(&secret.key.as_str())
&& !secret.key.starts_with(SSH_TUNNEL_SECRET_PREFIX)
&& !secret.key.starts_with(TRANSPORT_LAYER_SECRET_PREFIX)
+ && !secret.key.starts_with(PLUGIN_CONNECTION_SECRET_PREFIX)
{
continue;
}
@@ -1264,6 +1274,7 @@ async fn clear_connection_secrets(storage: &Storage, connections: &[ConnectionCo
for key in SECRET_KEYS {
storage.delete_secret(&config.id, key).await?;
}
+ storage.delete_secret_prefix(&config.id, PLUGIN_CONNECTION_SECRET_PREFIX).await?;
for (index, layer) in config.transport_layers.iter().enumerate() {
match layer {
TransportLayerConfig::Ssh(_) => {
@@ -1654,7 +1665,7 @@ mod tests {
use crate::ai::{AiApiStyle, AiAuthMethod, AiConfig, AiConfigItem};
use crate::connection_secrets::{
CASSANDRA_KEYSTORE_PASSWORD_KEY, CASSANDRA_TRUSTSTORE_PASSWORD_KEY, NACOS_AUTH_PASSWORD_KEY,
- NACOS_RNACOS_CONSOLE_PASSWORD_KEY,
+ NACOS_RNACOS_CONSOLE_PASSWORD_KEY, PLUGIN_CONNECTION_SECRET_PREFIX,
};
use crate::models::connection::{
default_redis_key_separator, ConnectionConfig, DatabaseType, SshTunnelConfig, TransportLayerConfig,
@@ -1847,6 +1858,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
@@ -1934,6 +1949,10 @@ mod tests {
"password": password
}
})),
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
@@ -2187,6 +2206,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
@@ -2649,6 +2672,28 @@ mod tests {
}));
}
+ #[tokio::test]
+ async fn plugin_connection_secrets_are_scrubbed_from_public_sync_metadata() {
+ let storage = Storage::open(&temp_db_path("plugin-public-sync")).await.unwrap();
+ let mut config = postgres_connection("plugin", "");
+ config.db_type = DatabaseType::Plugin;
+ config.plugin_id = Some("example.plugin".to_string());
+ config.plugin_connection_provider = Some("example.connection".to_string());
+ config.connection_secrets.insert("api_token".to_string(), "plugin-secret".to_string());
+ storage.save_connections(std::slice::from_ref(&config)).await.unwrap();
+
+ let snapshot = build_sync_snapshot(&storage, "test-version", None, Some("sync-pass")).await.unwrap();
+ let public_json = serde_json::to_string(&snapshot.connections).unwrap();
+ assert!(!public_json.contains("plugin-secret"));
+ let encrypted = snapshot.encrypted_secrets.as_ref().expect("encrypted secrets");
+ let decrypted = decrypt_sensitive_payload(encrypted, "sync-pass").unwrap();
+ assert!(decrypted.connection_secrets.iter().any(|secret| {
+ secret.connection_id == "plugin"
+ && secret.key == format!("{PLUGIN_CONNECTION_SECRET_PREFIX}api_token")
+ && secret.secret == "plugin-secret"
+ }));
+ }
+
#[tokio::test]
async fn sync_restore_does_not_revive_password_when_connection_disables_saving() {
let source = Storage::open(&temp_db_path("sync-no-save-password-source")).await.unwrap();
diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rs
index 82c9c3954e..fa7305fdae 100644
--- a/crates/dbx-core/src/connection.rs
+++ b/crates/dbx-core/src/connection.rs
@@ -29,7 +29,7 @@ use crate::models::connection::{
use crate::mongo_oidc::MongoOidcBrowserOpener;
use crate::nacos::config::{NACOS_CONSOLE_SESSION_PASSWORD, NACOS_PRIMARY_SESSION_PASSWORD};
use crate::path_utils::expand_tilde;
-use crate::plugins::{PluginDriverSession, PluginRegistry, PluginRuntimeEnv};
+use crate::plugins::{PluginConnectionHandle, PluginDriverSession, PluginHost, PluginRegistry, PluginRuntimeEnv};
use crate::query_cancel::RunningQueries;
use crate::session_credentials::SessionCredentialStore;
use crate::storage::{normalize_duckdb_worker_max_processes, Storage, DUCKDB_WORKER_MAX_PROCESSES_DEFAULT};
@@ -110,6 +110,7 @@ pub enum PoolKind {
config: Arc<ConnectionConfig>,
session: Arc<PluginDriverSession>,
},
+ PluginConnection(PluginConnectionHandle),
/// Message queue admin connection (not a data query pool; serves as a
/// marker that this connection_id is a valid MQ admin connection).
MessageQueue,
@@ -331,6 +332,7 @@ pub struct AppState {
pub http_tunnels: HttpTunnelManager,
pub storage: Storage,
pub plugins: PluginRegistry,
+ pub plugin_host: PluginHost,
pub agent_manager: crate::agent_manager::AgentManager,
pub nacos_registry: crate::nacos::NacosAdminRegistry,
duckdb_worker_process_isolation: AtomicBool,
@@ -1345,6 +1347,7 @@ impl AppState {
app_version: impl Into<String>,
) -> Self {
let data_dir = storage.data_dir().to_path_buf();
+ let app_version = app_version.into();
Self {
connections: Arc::new(RwLock::new(ConnectionPoolRegistry::new())),
task_supervisor: TaskSupervisor::new(),
@@ -1357,7 +1360,8 @@ impl AppState {
proxy_tunnels: ProxyTunnelManager::new(),
http_tunnels: HttpTunnelManager::new(),
storage,
- plugins: PluginRegistry::new(plugin_dir),
+ plugins: PluginRegistry::new_with_app_version(plugin_dir.clone(), app_version.clone()),
+ plugin_host: PluginHost::new(PluginRegistry::new_with_app_version(plugin_dir, app_version.clone())),
agent_manager: crate::agent_manager::AgentManager::new_with_base_dir_and_app_version(
agent_dir,
app_version,
@@ -2777,6 +2781,7 @@ impl AppState {
}
self.external_driver_pool("jdbc", &jdbc_config).await?
}
+ DatabaseType::Plugin => return Err("Plugin-owned connections use the plugin host".to_string()),
#[cfg(feature = "mq-admin")]
DatabaseType::MessageQueue => {
// MQ admin connections don't hold a data query pool. We just test
@@ -3833,6 +3838,7 @@ impl AppState {
| PoolKind::MessageQueue
| PoolKind::Nacos
| PoolKind::Consul(_) => false,
+ PoolKind::PluginConnection(handle) => !handle.is_running(),
#[cfg(feature = "mq-admin")]
PoolKind::Mqtt(_) => false,
}
@@ -4867,6 +4873,7 @@ impl AppState {
| PoolKind::MessageQueue
| PoolKind::Nacos
| PoolKind::Consul(_) => true,
+ PoolKind::PluginConnection(handle) => handle.is_running(),
#[cfg(feature = "mq-admin")]
PoolKind::Mqtt(_) => true,
PoolKind::Redis(redis) => match db::redis_driver::test_connection(redis).await {
@@ -4971,6 +4978,20 @@ impl AppState {
self.pool_routing_control().close_removed(removed).await;
}
+ pub async fn remove_plugin_connection_pools(&self, plugin_id: &str) {
+ let removed = self.drain_plugin_connection_pools(plugin_id).await;
+ self.pool_routing_control().close_removed(removed).await;
+ }
+
+ pub async fn invoke_plugin_connection_action(
+ &self,
+ config: ConnectionConfig,
+ action_id: &str,
+ ) -> Result<crate::plugins::PluginConnectionActionResult, String> {
+ let (host, port) = self.connection_host_port(&config.id, &config).await?;
+ self.plugin_host.invoke_connection_action(&config, action_id, &host, port).await
+ }
+
async fn drain_connection_pools(&self, connection_id: &str) -> Vec<(String, PoolKind)> {
let pool_prefix = format!("{connection_id}:");
let keys_to_remove: Vec<String> = self
@@ -5063,6 +5084,34 @@ impl AppState {
removed
}
+ async fn drain_plugin_connection_pools(&self, plugin_id: &str) -> Vec<(String, PoolKind)> {
+ let keys_to_remove: Vec<String> = self
+ .connections
+ .read()
+ .await
+ .iter()
+ .filter_map(|(key, pool)| match pool {
+ PoolKind::PluginConnection(handle) if handle.plugin_id == plugin_id => Some(key.clone()),
+ _ => None,
+ })
+ .collect();
+ self.stop_keepalive_tasks(&keys_to_remove).await;
+ {
+ let mut activity = self.pool_activity.write().await;
+ for key in &keys_to_remove {
+ activity.remove(key);
+ }
+ }
+ let mut conns = self.connections.write().await;
+ let mut removed = Vec::with_capacity(keys_to_remove.len());
+ for key in keys_to_remove {
+ if let Some(pool) = conns.remove(&key) {
+ removed.push((key, pool));
+ }
+ }
+ removed
+ }
+
async fn uses_forwarded_transport(&self, connection_id: &str) -> bool {
let configs = self.configs.read().await;
configs.get(connection_id).is_some_and(|config| config.has_effective_transport_layers())
@@ -5601,7 +5650,41 @@ fn pool_key_for_session_role(
#[cfg(test)]
fn clone_pool_kind(pool: &PoolKind) -> PoolKind {
- pool.clone()
+ match pool {
+ PoolKind::Mysql(p, mode) => PoolKind::Mysql(p.clone(), *mode),
+ PoolKind::Postgres(p) => PoolKind::Postgres(p.clone()),
+ PoolKind::Sqlite(p) => PoolKind::Sqlite(p.clone()),
+ PoolKind::Rqlite(client) => PoolKind::Rqlite(client.clone()),
+ PoolKind::Turso(client) => PoolKind::Turso(client.clone()),
+ PoolKind::CloudflareD1(client) => PoolKind::CloudflareD1(client.clone()),
+ #[cfg(feature = "duckdb-sidecar")]
+ PoolKind::DuckDbWorker(client) => PoolKind::DuckDbWorker(client.clone()),
+ #[cfg(not(feature = "duckdb-sidecar"))]
+ PoolKind::DuckDbWorker(_) => PoolKind::DuckDbWorker(()),
+ PoolKind::MongoDb(client) => PoolKind::MongoDb(client.clone()),
+ PoolKind::DynamoDb(client) => PoolKind::DynamoDb(client.clone()),
+ PoolKind::ClickHouse(client) => PoolKind::ClickHouse(client.clone()),
+ PoolKind::SqlServer(client) => PoolKind::SqlServer(client.clone()),
+ PoolKind::Elasticsearch(client) => PoolKind::Elasticsearch(client.clone()),
+ PoolKind::Easysearch(client) => PoolKind::Easysearch(client.clone()),
+ PoolKind::Meilisearch(client) => PoolKind::Meilisearch(client.clone()),
+ PoolKind::HBase(client) => PoolKind::HBase(client.clone()),
+ PoolKind::VectorDb(client) => PoolKind::VectorDb(client.clone()),
+ PoolKind::InfluxDb(client) => PoolKind::InfluxDb(client.clone()),
+ PoolKind::InfluxDb3(client) => PoolKind::InfluxDb3(client.clone()),
+ PoolKind::VictoriaMetrics(client) => PoolKind::VictoriaMetrics(client.clone()),
+ PoolKind::Agent(client) => PoolKind::Agent(client.clone()),
+ PoolKind::ExternalDriver { driver_id, config, session } => {
+ PoolKind::ExternalDriver { driver_id: driver_id.clone(), config: config.clone(), session: session.clone() }
+ }
+ PoolKind::PluginConnection(handle) => PoolKind::PluginConnection(handle.clone()),
+ PoolKind::MessageQueue => PoolKind::MessageQueue,
+ PoolKind::Nacos => PoolKind::Nacos,
+ PoolKind::Consul(client) => PoolKind::Consul(client.clone()),
+ #[cfg(feature = "mq-admin")]
+ PoolKind::Mqtt(client) => PoolKind::Mqtt(Arc::clone(client)),
+ PoolKind::Redis(_) => panic!("clone_pool_kind not supported for Redis — handled separately"),
+ }
}
async fn close_pool_kind(pool: PoolKind) -> Result<(), String> {
@@ -5668,6 +5751,9 @@ async fn close_pool_kind(pool: PoolKind) -> Result<(), String> {
PoolKind::ExternalDriver { session, .. } => {
session.shutdown().await;
}
+ PoolKind::PluginConnection(handle) => {
+ handle.disconnect().await?;
+ }
PoolKind::MessageQueue => {}
PoolKind::Nacos => {}
PoolKind::Consul(_) => {}
@@ -6078,6 +6164,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/src/connection_secrets.rs b/crates/dbx-core/src/connection_secrets.rs
index aba9f1abb0..7230105667 100644
--- a/crates/dbx-core/src/connection_secrets.rs
+++ b/crates/dbx-core/src/connection_secrets.rs
@@ -27,6 +27,7 @@ pub const MQTT_AUTH_PASSWORD_KEY: &str = "mqtt.auth.password";
pub const CASSANDRA_TLS_SECRET_PREFIX: &str = "cassandra.tls.";
pub const CASSANDRA_TRUSTSTORE_PASSWORD_KEY: &str = "cassandra.tls.truststore_password";
pub const CASSANDRA_KEYSTORE_PASSWORD_KEY: &str = "cassandra.tls.keystore_password";
+pub const PLUGIN_CONNECTION_SECRET_PREFIX: &str = "plugin_connection.";
pub trait ConnectionSecretStore {
fn set_secret(&self, connection_id: &str, key: &str, secret: &str) -> Result<(), String>;
@@ -947,6 +948,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/src/db/redis_driver.rs b/crates/dbx-core/src/db/redis_driver.rs
index fc31cf162c..5a3d3460f9 100644
--- a/crates/dbx-core/src/db/redis_driver.rs
+++ b/crates/dbx-core/src/db/redis_driver.rs
@@ -7334,6 +7334,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: HashMap::new(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/src/models/connection.rs b/crates/dbx-core/src/models/connection.rs
index 208f2c9189..acccc7282c 100644
--- a/crates/dbx-core/src/models/connection.rs
+++ b/crates/dbx-core/src/models/connection.rs
@@ -196,6 +196,19 @@ pub struct ConnectionConfig {
/// Typed configuration for external tabular sources.
#[serde(default)]
pub external_config: Option<serde_json::Value>,
+ /// Owning plugin for a first-class plugin connection.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub plugin_id: Option<String>,
+ /// `connection-provider` contribution id inside `plugin_id`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub plugin_connection_provider: Option<String>,
+ /// Provider-defined connection kind, such as `ssh` or `s3`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub plugin_connection_type: Option<String>,
+ /// Provider-defined sensitive values. Persistence moves these into the
+ /// connection secret store rather than keeping them in `config_json`.
+ #[serde(default, skip_serializing_if = "HashMap::is_empty")]
+ pub connection_secrets: HashMap<String, String>,
#[serde(default)]
pub jdbc_driver_class: Option<String>,
#[serde(default)]
@@ -632,6 +645,14 @@ struct ConnectionConfigData {
#[serde(default)]
pub external_config: Option<serde_json::Value>,
#[serde(default)]
+ pub plugin_id: Option<String>,
+ #[serde(default)]
+ pub plugin_connection_provider: Option<String>,
+ #[serde(default)]
+ pub plugin_connection_type: Option<String>,
+ #[serde(default)]
+ pub connection_secrets: HashMap<String, String>,
+ #[serde(default)]
pub jdbc_driver_class: Option<String>,
#[serde(default)]
pub jdbc_driver_paths: Vec<String>,
@@ -702,6 +723,10 @@ impl From<ConnectionConfigData> for ConnectionConfig {
gbase_server: data.gbase_server,
informix_server: data.informix_server,
external_config: data.external_config,
+ plugin_id: data.plugin_id,
+ plugin_connection_provider: data.plugin_connection_provider,
+ plugin_connection_type: data.plugin_connection_type,
+ connection_secrets: data.connection_secrets,
jdbc_driver_class: data.jdbc_driver_class,
jdbc_driver_paths: data.jdbc_driver_paths,
one_time: data.one_time,
@@ -1173,6 +1198,11 @@ impl ConnectionConfig {
format!("{scheme}://{host}:{port}")
}
DatabaseType::Jdbc => "jdbc:<redacted>".to_string(),
+ DatabaseType::Plugin => format!(
+ "plugin://{}/{}",
+ self.plugin_id.as_deref().unwrap_or("unknown"),
+ self.plugin_connection_type.as_deref().unwrap_or("unknown")
+ ),
DatabaseType::MessageQueue => self.message_queue_admin_url(),
DatabaseType::Mqtt => self.mqtt_broker_url(),
DatabaseType::Nacos => self.nacos_admin_url(),
@@ -1451,6 +1481,11 @@ impl ConnectionConfig {
DatabaseType::Jdbc => {
self.connection_string.as_deref().filter(|value| !value.is_empty()).unwrap_or("jdbc:").to_string()
}
+ DatabaseType::Plugin => format!(
+ "plugin://{}/{}",
+ self.plugin_id.as_deref().unwrap_or("unknown"),
+ self.plugin_connection_type.as_deref().unwrap_or("unknown")
+ ),
DatabaseType::MessageQueue => self.message_queue_admin_url(),
DatabaseType::Mqtt => self.mqtt_broker_url(),
DatabaseType::Nacos => self.nacos_admin_url(),
@@ -2753,6 +2788,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/src/mq/config.rs b/crates/dbx-core/src/mq/config.rs
index d44c5c7301..343de0455d 100644
--- a/crates/dbx-core/src/mq/config.rs
+++ b/crates/dbx-core/src/mq/config.rs
@@ -228,6 +228,10 @@ mod tests {
etcd_endpoints: String::new(),
gbase_server: String::new(),
informix_server: String::new(),
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
external_config: Some(value),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
diff --git a/crates/dbx-core/src/mq/service.rs b/crates/dbx-core/src/mq/service.rs
index 7d77ea11b1..502ce639ba 100644
--- a/crates/dbx-core/src/mq/service.rs
+++ b/crates/dbx-core/src/mq/service.rs
@@ -948,6 +948,10 @@ mod tests {
etcd_endpoints: String::new(),
gbase_server: String::new(),
informix_server: String::new(),
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
external_config: Some(serde_json::json!({
"systemKind": "pulsar",
"adminUrl": "http://127.0.0.1:8080",
diff --git a/crates/dbx-core/src/nacos/config.rs b/crates/dbx-core/src/nacos/config.rs
index 8e94117f69..5dd0a72fde 100644
--- a/crates/dbx-core/src/nacos/config.rs
+++ b/crates/dbx-core/src/nacos/config.rs
@@ -416,6 +416,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: Some(value),
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/src/nacos/service.rs b/crates/dbx-core/src/nacos/service.rs
index c0c69bfbeb..a5afdc2092 100644
--- a/crates/dbx-core/src/nacos/service.rs
+++ b/crates/dbx-core/src/nacos/service.rs
@@ -692,6 +692,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: Some(serde_json::json!({ "serverAddr": "http://127.0.0.1:9" })),
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: std::collections::HashMap::new(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
@@ -770,6 +774,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: Some(serde_json::json!({ "serverAddr": "http://127.0.0.1:9" })),
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: std::collections::HashMap::new(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/src/plugins.rs b/crates/dbx-core/src/plugins.rs
index e56a3d27f8..3bce359474 100644
--- a/crates/dbx-core/src/plugins.rs
+++ b/crates/dbx-core/src/plugins.rs
@@ -1,52 +1,98 @@
use std::path::{Path, PathBuf};
-use std::process::Stdio;
-use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;
use serde::de::DeserializeOwned;
-use serde::{Deserialize, Serialize};
-use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
-use tokio::process::{Child, ChildStdin, ChildStdout, Command};
-use tokio::sync::Mutex;
-use tokio::time::timeout;
-
-const PLUGIN_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
-pub const SUPPORTED_PLUGIN_PROTOCOL_VERSION: u32 = 1;
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct PluginManifest {
- pub id: String,
- pub name: String,
- #[serde(default)]
- pub version: String,
- #[serde(default = "default_plugin_protocol_version")]
- pub protocol_version: u32,
- #[serde(default)]
- pub description: String,
- #[serde(default)]
- pub executable: Option<String>,
- #[serde(default)]
- pub drivers: Vec<PluginDriverManifest>,
-}
+use serde::Serialize;
+use tokio::process::Command;
+
+mod assets;
+mod filesystem;
+mod host;
+mod installer;
+mod manifest;
+mod marketplace;
+mod runtime;
+
+pub use assets::PluginUiAsset;
+pub use filesystem::{
+ PluginFilesystemEntry, PluginFilesystemEntryKind, PluginFilesystemListResult, PluginFilesystemMutationResult,
+ PluginFilesystemReadResult, DEFAULT_PLUGIN_FILESYSTEM_PAGE_SIZE, DEFAULT_PLUGIN_FILESYSTEM_PREVIEW_BYTES,
+ MAX_PLUGIN_FILESYSTEM_INLINE_WRITE_BYTES, MAX_PLUGIN_FILESYSTEM_PAGE_SIZE, MAX_PLUGIN_FILESYSTEM_PREVIEW_BYTES,
+ PLUGIN_FILESYSTEM_CREATE_DIRECTORY_METHOD, PLUGIN_FILESYSTEM_DELETE_METHOD, PLUGIN_FILESYSTEM_LIST_METHOD,
+ PLUGIN_FILESYSTEM_READ_METHOD, PLUGIN_FILESYSTEM_RENAME_METHOD, PLUGIN_FILESYSTEM_WRITE_METHOD,
+};
+pub use host::{ActivePluginSession, PluginConnectionActionResult, PluginConnectionHandle, PluginHost};
+pub use installer::{
+ PluginInstallPolicy, PluginInstallResponse, PluginInstallResult, PluginPackageInstaller, PluginRollbackResponse,
+ PluginRollbackResult, PluginSignatureStatus, PluginTrustStore, PluginTrustedKey, DBXP_EXTENSION,
+ MAX_PLUGIN_PACKAGE_BYTES, PLUGIN_CHECKSUMS_FILE, PLUGIN_SIGNATURE_FILE,
+};
+pub use marketplace::{
+ PluginMarketplace, PluginMarketplaceArtifact, PluginMarketplaceCatalog, PluginMarketplaceInstallRequest,
+ PluginMarketplaceLocalization, PluginMarketplacePlugin, PluginMarketplaceRepositoryMetadata,
+ PluginMarketplaceVersion, PluginRepository, PluginRepositoryCatalogResult, PluginRepositoryKind,
+ PluginRepositoryStore, MAX_PLUGIN_CATALOG_BYTES, OFFICIAL_PLUGIN_REPOSITORY_ID, SUPPORTED_PLUGIN_CATALOG_VERSION,
+};
+
+pub use manifest::{
+ current_plugin_target, resolve_safe_plugin_path, PluginBackendEntrypoint, PluginBackendTransport,
+ PluginCompatibility, PluginConnectionActionContribution, PluginConnectionActionVariant, PluginConnectionActionWhen,
+ PluginConnectionCapability, PluginConnectionProviderContribution, PluginContribution, PluginDriverManifest,
+ PluginEngines, PluginEntrypoints, PluginFilesystemCapability, PluginFilesystemProviderContribution,
+ PluginFormFieldBinding, PluginFormFieldDefinition, PluginFormFieldOption, PluginFormFieldType, PluginManifest,
+ PluginUiEntrypoint, PluginWorkbenchContribution, PLUGIN_CONNECTION_ACTION_METHOD, PLUGIN_CONNECTION_CONNECT_METHOD,
+ PLUGIN_CONNECTION_DISCONNECT_METHOD, PLUGIN_CONNECTION_TEST_METHOD, SUPPORTED_PLUGIN_HOST_API_VERSION,
+ SUPPORTED_PLUGIN_MANIFEST_VERSION, SUPPORTED_PLUGIN_PERMISSIONS, SUPPORTED_PLUGIN_PROTOCOL_VERSION,
+};
+pub use runtime::{
+ PluginBinaryMessage, PluginEvent, PluginHandshake, PluginHandshakeIdentity, PluginSessionState,
+ PluginSessionStatus, PluginSidecarSession, PLUGIN_REQUEST_TIMEOUT,
+};
-fn default_plugin_protocol_version() -> u32 {
- 1
+#[derive(Debug, Clone)]
+pub struct InstalledPlugin {
+ pub manifest: PluginManifest,
+ pub path: PathBuf,
+ pub compatibility: PluginCompatibility,
}
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct PluginDriverManifest {
- pub id: String,
- pub label: String,
- pub kind: String,
- #[serde(default)]
- pub database_type: Option<String>,
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct InstalledPluginInfo {
+ pub manifest: PluginManifest,
+ pub compatibility: PluginCompatibilityInfo,
}
#[derive(Debug, Clone, Serialize)]
-pub struct InstalledPlugin {
- pub manifest: PluginManifest,
- pub path: PathBuf,
+#[serde(rename_all = "camelCase")]
+pub struct PluginCompatibilityInfo {
+ pub compatible: bool,
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub errors: Vec<String>,
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub warnings: Vec<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub target: Option<String>,
+}
+
+impl InstalledPlugin {
+ pub fn new(manifest: PluginManifest, path: PathBuf, app_version: &str) -> Self {
+ let compatibility = manifest.compatibility(&path, app_version);
+ Self { manifest, path, compatibility }
+ }
+
+ pub fn info(&self) -> InstalledPluginInfo {
+ InstalledPluginInfo {
+ manifest: self.manifest.clone(),
+ compatibility: PluginCompatibilityInfo {
+ compatible: self.compatibility.compatible,
+ errors: self.compatibility.errors.clone(),
+ warnings: self.compatibility.warnings.clone(),
+ target: self.compatibility.target.clone(),
+ },
+ }
+ }
}
#[derive(Debug, Clone, Default)]
@@ -74,17 +120,26 @@ impl PluginRuntimeEnv {
#[derive(Debug, Clone)]
pub struct PluginRegistry {
root_dir: PathBuf,
+ app_version: String,
}
impl PluginRegistry {
pub fn new(root_dir: PathBuf) -> Self {
- Self { root_dir }
+ Self::new_with_app_version(root_dir, env!("CARGO_PKG_VERSION"))
+ }
+
+ pub fn new_with_app_version(root_dir: PathBuf, app_version: impl Into<String>) -> Self {
+ Self { root_dir, app_version: app_version.into() }
}
pub fn root_dir(&self) -> &Path {
&self.root_dir
}
+ pub fn app_version(&self) -> &str {
+ &self.app_version
+ }
+
pub fn list_installed(&self) -> Result<Vec<InstalledPlugin>, String> {
let entries = match std::fs::read_dir(&self.root_dir) {
Ok(entries) => entries,
@@ -95,18 +150,43 @@ impl PluginRegistry {
let mut plugins = Vec::new();
for entry in entries {
let entry = entry.map_err(|err| err.to_string())?;
- let path = entry.path();
- if !path.is_dir() {
+ let container_path = entry.path();
+ if !container_path.is_dir() {
continue;
}
+ let path = match installer::resolve_active_plugin_dir(&container_path) {
+ Ok(Some(path)) => path,
+ Ok(None) => continue,
+ Err(error) => {
+ plugins.push(unavailable_plugin(container_path, error));
+ continue;
+ }
+ };
let manifest_path = path.join("manifest.json");
if !manifest_path.exists() {
continue;
}
- let raw = std::fs::read_to_string(&manifest_path).map_err(|err| err.to_string())?;
- let manifest: PluginManifest = serde_json::from_str(&raw)
- .map_err(|err| format!("Failed to parse plugin manifest {}: {err}", manifest_path.display()))?;
- plugins.push(InstalledPlugin { manifest, path });
+ let raw = match std::fs::read_to_string(&manifest_path) {
+ Ok(raw) => raw,
+ Err(error) => {
+ plugins.push(unavailable_plugin(
+ container_path,
+ format!("Failed to read plugin manifest {}: {error}", manifest_path.display()),
+ ));
+ continue;
+ }
+ };
+ let manifest: PluginManifest = match serde_json::from_str(&raw) {
+ Ok(manifest) => manifest,
+ Err(error) => {
+ plugins.push(unavailable_plugin(
+ container_path,
+ format!("Failed to parse plugin manifest {}: {error}", manifest_path.display()),
+ ));
+ continue;
+ }
+ };
+ plugins.push(InstalledPlugin::new(manifest, path, &self.app_version));
}
plugins.sort_by(|a, b| a.manifest.id.cmp(&b.manifest.id));
Ok(plugins)
@@ -114,14 +194,19 @@ impl PluginRegistry {
pub fn find_driver(&self, driver_id: &str) -> Result<Option<InstalledPlugin>, String> {
Ok(self.list_installed()?.into_iter().find(|plugin| {
- plugin
- .manifest
- .drivers
- .iter()
- .any(|driver| driver.id == driver_id || driver.database_type.as_deref() == Some(driver_id))
+ plugin.compatibility.compatible
+ && plugin
+ .manifest
+ .drivers
+ .iter()
+ .any(|driver| driver.id == driver_id || driver.database_type.as_deref() == Some(driver_id))
}))
}
+ pub fn find_plugin(&self, plugin_id: &str) -> Result<Option<InstalledPlugin>, String> {
+ Ok(self.list_installed()?.into_iter().find(|plugin| plugin.manifest.id == plugin_id))
+ }
+
pub async fn invoke_driver<T>(&self, driver_id: &str, method: &str, params: serde_json::Value) -> Result<T, String>
where
T: DeserializeOwned,
@@ -155,14 +240,11 @@ impl PluginRegistry {
{
let plugin =
self.find_driver(driver_id)?.ok_or_else(|| format!("Plugin driver '{driver_id}' is not installed"))?;
- ensure_plugin_protocol_compatible(&plugin.manifest)?;
- let invoke = invoke_plugin(&plugin, driver_id, method, params, &env);
- match timeout_duration {
- Some(duration) => timeout(duration, invoke).await.map_err(|_| {
- format!("Plugin '{}' timed out after {} seconds", plugin.manifest.id, duration.as_secs())
- })?,
- None => invoke.await,
- }
+ ensure_plugin_compatible(&plugin)?;
+ let session = PluginSidecarSession::start(plugin, self.app_version.clone(), env).await?;
+ let result = session.invoke_with_timeout(method, params, Some(driver_id), timeout_duration).await;
+ session.shutdown().await;
+ result
}
pub async fn start_driver_session(&self, driver_id: &str) -> Result<Arc<PluginDriverSession>, String> {
@@ -176,85 +258,57 @@ impl PluginRegistry {
) -> Result<Arc<PluginDriverSession>, String> {
let plugin =
self.find_driver(driver_id)?.ok_or_else(|| format!("Plugin driver '{driver_id}' is not installed"))?;
- ensure_plugin_protocol_compatible(&plugin.manifest)?;
- PluginDriverSession::start(plugin, driver_id.to_string(), env).await.map(Arc::new)
+ ensure_plugin_compatible(&plugin)?;
+ PluginDriverSession::start(plugin, driver_id.to_string(), self.app_version.clone(), env).await.map(Arc::new)
}
}
-fn ensure_plugin_protocol_compatible(manifest: &PluginManifest) -> Result<(), String> {
- if manifest.protocol_version == SUPPORTED_PLUGIN_PROTOCOL_VERSION {
- return Ok(());
+fn unavailable_plugin(path: PathBuf, error: String) -> InstalledPlugin {
+ let id = path
+ .file_name()
+ .and_then(|name| name.to_str())
+ .filter(|name| !name.is_empty())
+ .unwrap_or("invalid-plugin")
+ .to_string();
+ InstalledPlugin {
+ manifest: PluginManifest {
+ id: id.clone(),
+ name: id,
+ version: "0.0.0-invalid".to_string(),
+ description: error.clone(),
+ ..PluginManifest::default()
+ },
+ path,
+ compatibility: PluginCompatibility {
+ compatible: false,
+ errors: vec![error],
+ target: Some(current_plugin_target()),
+ ..PluginCompatibility::default()
+ },
}
- Err(format!(
- "Plugin '{}' uses protocol version {}, but this DBX build supports protocol version {}",
- manifest.id, manifest.protocol_version, SUPPORTED_PLUGIN_PROTOCOL_VERSION
- ))
}
-#[derive(Debug, Serialize)]
-struct PluginRequest {
- jsonrpc: &'static str,
- id: u64,
- driver: String,
- method: String,
- params: serde_json::Value,
-}
-
-#[derive(Debug, Deserialize)]
-struct PluginResponse {
- id: u64,
- #[serde(default)]
- result: Option<serde_json::Value>,
- #[serde(default)]
- error: Option<PluginError>,
-}
-
-#[derive(Debug, Deserialize)]
-struct PluginError {
- message: String,
+fn ensure_plugin_compatible(plugin: &InstalledPlugin) -> Result<(), String> {
+ if plugin.compatibility.compatible {
+ return Ok(());
+ }
+ Err(format!("Plugin '{}' is incompatible: {}", plugin.manifest.id, plugin.compatibility.errors.join("; ")))
}
pub struct PluginDriverSession {
- plugin: InstalledPlugin,
+ sidecar: Arc<PluginSidecarSession>,
driver_id: String,
- process: Mutex<PluginProcess>,
- next_request_id: AtomicU64,
-}
-
-struct PluginProcess {
- child: Child,
- stdin: ChildStdin,
- stdout: BufReader<ChildStdout>,
}
impl PluginDriverSession {
- async fn start(plugin: InstalledPlugin, driver_id: String, env: PluginRuntimeEnv) -> Result<Self, String> {
- let mut child = spawn_plugin_child(&plugin, &env)?;
- let stdin = child.stdin.take().ok_or("Plugin stdin unavailable")?;
- let stdout = child.stdout.take().ok_or("Plugin stdout unavailable")?;
- if let Some(stderr) = child.stderr.take() {
- let plugin_id = plugin.manifest.id.clone();
- tokio::spawn(async move {
- let mut stderr = BufReader::new(stderr);
- loop {
- match read_plugin_line(&mut stderr, "stderr").await {
- Ok(line) => log::warn!("[plugin:{plugin_id}] {}", line.trim_end()),
- Err(err) if err.contains("end of stream") => break,
- Err(err) => {
- log::warn!("[plugin:{plugin_id}] failed to read stderr: {err}");
- break;
- }
- }
- }
- });
- }
-
- Ok(Self {
- plugin,
- driver_id,
- process: Mutex::new(PluginProcess { child, stdin, stdout: BufReader::new(stdout) }),
- next_request_id: AtomicU64::new(1),
- })
+ async fn start(
+ plugin: InstalledPlugin,
+ driver_id: String,
+ app_version: String,
+ env: PluginRuntimeEnv,
+ ) -> Result<Self, String> {
+ let sidecar = PluginSidecarSession::start(plugin, app_version, env).await?;
+ Ok(Self { sidecar, driver_id })
}
pub async fn invoke<T>(&self, method: &str, params: serde_json::Value) -> Result<T, String>
@@ -273,68 +327,27 @@ impl PluginDriverSession {
where
T: DeserializeOwned,
{
- let request_id = self.next_request_id.fetch_add(1, Ordering::Relaxed);
- let invoke = async {
- let mut process = self.process.lock().await;
- self.invoke_locked(&mut process, request_id, method, params).await
- };
- match timeout_duration {
- Some(duration) => match timeout(duration, invoke).await {
- Ok(result) => result,
- Err(_) => {
- self.kill().await;
- Err(format!("Plugin '{}' timed out after {} seconds", self.plugin.manifest.id, duration.as_secs()))
- }
- },
- None => invoke.await,
- }
+ self.sidecar.invoke_with_timeout(method, params, Some(&self.driver_id), timeout_duration).await
}
- async fn invoke_locked<T>(
- &self,
- process: &mut PluginProcess,
- request_id: u64,
- method: &str,
- params: serde_json::Value,
- ) -> Result<T, String>
- where
- T: DeserializeOwned,
- {
- let request = PluginRequest {
- jsonrpc: "2.0",
- id: request_id,
- driver: self.driver_id.clone(),
- method: method.to_string(),
- params,
- };
- let line = encode_plugin_request_line(&request)?;
- process.stdin.write_all(&line).await.map_err(|err| err.to_string())?;
- process.stdin.flush().await.map_err(|err| err.to_string())?;
-
- let stdout = &mut process.stdout;
- let child = &mut process.child;
- read_decoded_plugin_response(&self.plugin, request_id, stdout, || {
- let status = child.try_wait().map_err(|err| err.to_string())?;
- Ok(match status {
- Some(status) => format!("Plugin '{}' exited with status {}", self.plugin.manifest.id, status),
- None => format!("Plugin '{}' closed stdout without a response", self.plugin.manifest.id),
- })
- })
- .await
+ pub async fn shutdown(&self) {
+ self.sidecar.shutdown().await;
}
- async fn kill(&self) {
- let mut process = self.process.lock().await;
- let _ = process.child.kill().await;
+ pub async fn pid(&self) -> Option<u32> {
+ self.sidecar.pid().await
}
- pub async fn shutdown(&self) {
- self.kill().await;
+ pub fn subscribe_events(&self) -> tokio::sync::broadcast::Receiver<PluginEvent> {
+ self.sidecar.subscribe_events()
}
- pub async fn pid(&self) -> Option<u32> {
- let process = self.process.lock().await;
- process.child.id()
+ pub fn subscribe_binary(&self) -> tokio::sync::broadcast::Receiver<PluginBinaryMessage> {
+ self.sidecar.subscribe_binary()
+ }
+
+ pub async fn send_binary(&self, channel: &str, data: &[u8]) -> Result<(), String> {
+ self.sidecar.send_binary(channel, data).await
}
#[cfg(all(test, unix))]
@@ -343,216 +356,15 @@ impl PluginDriverSession {
driver_id: String,
env: PluginRuntimeEnv,
) -> Result<Self, String> {
- Self::start(plugin, driver_id, env).await
- }
-}
-
-async fn invoke_plugin<T>(
- plugin: &InstalledPlugin,
- driver_id: &str,
- method: &str,
- params: serde_json::Value,
- env: &PluginRuntimeEnv,
-) -> Result<T, String>
-where
- T: DeserializeOwned,
-{
- let mut child = spawn_plugin_child(plugin, env)?;
-
- let request =
- PluginRequest { jsonrpc: "2.0", id: 1, driver: driver_id.to_string(), method: method.to_string(), params };
- let line = encode_plugin_request_line(&request)?;
-
- let mut stdin = child.stdin.take().ok_or("Plugin stdin unavailable")?;
- stdin.write_all(&line).await.map_err(|err| err.to_string())?;
- drop(stdin);
-
- let stdout = child.stdout.take().ok_or("Plugin stdout unavailable")?;
- let mut stderr = child.stderr.take().ok_or("Plugin stderr unavailable")?;
- let mut reader = BufReader::new(stdout);
- let response_result = read_decoded_plugin_response(plugin, request.id, &mut reader, || {
- Ok(format!("Plugin '{}' exited without a response", plugin.manifest.id))
- })
- .await;
- let mut stderr_bytes = Vec::new();
- stderr.read_to_end(&mut stderr_bytes).await.map_err(|err| err.to_string())?;
- let stderr_text = String::from_utf8_lossy(&stderr_bytes).into_owned();
- let status = child.wait().await.map_err(|err| err.to_string())?;
-
- let response = match response_result {
- Ok(response) => response,
- Err(err) if err.contains("end of stream") => {
- let stderr = stderr_text.trim().to_string();
- return Err(if stderr.is_empty() {
- format!("Plugin '{}' exited without a response", plugin.manifest.id)
- } else {
- format!("Plugin '{}' exited without a response: {stderr}", plugin.manifest.id)
- });
- }
- Err(err) => return Err(err),
- };
- if !status.success() {
- let stderr = stderr_text.trim().to_string();
- return Err(if stderr.is_empty() {
- format!("Plugin '{}' exited with status {}", plugin.manifest.id, status)
- } else {
- format!("Plugin '{}' failed: {stderr}", plugin.manifest.id)
- });
- }
-
- Ok(response)
-}
-
-fn encode_plugin_request_line(request: &PluginRequest) -> Result<Vec<u8>, String> {
- let mut bytes = Vec::new();
- serde_json::to_writer(&mut bytes, request).map_err(|err| err.to_string())?;
- bytes.push(b'\n');
- Ok(bytes)
-}
-
-fn spawn_plugin_child(plugin: &InstalledPlugin, env: &PluginRuntimeEnv) -> Result<Child, String> {
- let executable = plugin
- .manifest
- .executable
- .as_deref()
- .filter(|value| !value.is_empty())
- .ok_or_else(|| format!("Plugin '{}' does not declare an executable", plugin.manifest.id))?;
- let executable_path = resolve_plugin_executable(&plugin.path, executable);
-
- let mut command = crate::process::new_tokio_command(&executable_path);
- command
- .current_dir(&plugin.path)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .kill_on_drop(true);
- env.apply_to(&mut command);
-
- command.spawn().map_err(|err| format!("Failed to start plugin '{}': {err}", plugin.manifest.id))
-}
-
-async fn read_plugin_line<R>(reader: &mut R, context: &str) -> Result<String, String>
-where
- R: tokio::io::AsyncBufRead + Unpin,
-{
- let mut bytes = Vec::new();
- reader.read_until(b'\n', &mut bytes).await.map_err(|err| format!("Failed to read plugin {context}: {err}"))?;
- if bytes.is_empty() {
- return Err(format!("Failed to read plugin {context}: end of stream"));
- }
- Ok(String::from_utf8_lossy(&bytes).into_owned())
-}
-
-async fn read_decoded_plugin_response<T, R, F>(
- plugin: &InstalledPlugin,
- request_id: u64,
- reader: &mut R,
- end_of_stream_message: F,
-) -> Result<T, String>
-where
- T: DeserializeOwned,
- R: tokio::io::AsyncBufRead + Unpin,
- F: FnMut() -> Result<String, String>,
-{
- let mut end_of_stream_message = end_of_stream_message;
- const MAX_NOISY_LINES: usize = 20;
- for _ in 0..MAX_NOISY_LINES {
- let line = match read_plugin_line(reader, "response").await {
- Ok(line) => line,
- Err(err) if err.contains("end of stream") => return Err(end_of_stream_message()?),
- Err(err) => return Err(err),
- };
- match decode_plugin_response(plugin, request_id, &line) {
- Ok(response) => return Ok(response),
- Err(err) if err.starts_with(&format!("Failed to parse plugin '{}' response:", plugin.manifest.id)) => {
- log::warn!("[plugin:{}] ignored non-protocol stdout: {}", plugin.manifest.id, line.trim_end());
- }
- Err(err) => return Err(err),
- }
- }
- match read_plugin_line(reader, "response").await {
- Ok(_) => {
- Err(format!("Plugin '{}' wrote too many non-protocol stdout lines before its response", plugin.manifest.id))
- }
- Err(err) if err.contains("end of stream") => Err(end_of_stream_message()?),
- Err(err) => Err(err),
- }
-}
-
-fn decode_plugin_response<T>(plugin: &InstalledPlugin, request_id: u64, response_line: &str) -> Result<T, String>
-where
- T: DeserializeOwned,
-{
- let response: PluginResponse = serde_json::from_str(response_line)
- .map_err(|err| format!("Failed to parse plugin '{}' response: {err}", plugin.manifest.id))?;
- if response.id != request_id {
- return Err(format!("Plugin '{}' returned mismatched response id", plugin.manifest.id));
- }
- if let Some(error) = response.error {
- return Err(error.message);
- }
- let result = response.result.unwrap_or(serde_json::Value::Null);
- serde_json::from_value(result)
- .map_err(|err| format!("Failed to decode plugin '{}' result: {err}", plugin.manifest.id))
-}
-
-fn resolve_plugin_executable(plugin_dir: &Path, executable: &str) -> PathBuf {
- let path = PathBuf::from(executable);
- let resolved = if path.is_absolute() { path } else { plugin_dir.join(path) };
-
- #[cfg(windows)]
- {
- let bat = resolved.with_extension("bat");
- if bat.exists() {
- return bat;
- }
+ Self::start(plugin, driver_id, env!("CARGO_PKG_VERSION").to_string(), env).await
}
-
- resolved
}
#[cfg(test)]
mod tests {
- use super::{read_decoded_plugin_response, read_plugin_line, InstalledPlugin, PluginManifest};
+ use super::{InstalledPlugin, PluginContribution, PluginManifest, PluginRegistry};
#[cfg(unix)]
use super::{PluginDriverManifest, PluginDriverSession, PluginRuntimeEnv};
- use std::path::PathBuf;
- use tokio::io::BufReader;
-
- #[tokio::test]
- async fn reads_non_utf8_plugin_lines_lossily() {
- let bytes = vec![b'{', b'"', b'e', b'r', b'r', b'o', b'r', b'"', b':', 0xB2, 0xE2, b'}', b'\n'];
- let mut reader = BufReader::new(std::io::Cursor::new(bytes));
-
- let line = read_plugin_line(&mut reader, "response").await.expect("line should be readable");
-
- assert_eq!(line, format!("{{\"error\":{}}}\n", "\u{fffd}\u{fffd}"));
- }
-
- #[tokio::test]
- async fn skips_noisy_plugin_stdout_before_json_response() {
- let plugin = InstalledPlugin {
- manifest: PluginManifest {
- id: "jdbc".to_string(),
- name: "JDBC".to_string(),
- version: "test".to_string(),
- protocol_version: 1,
- description: String::new(),
- executable: None,
- drivers: Vec::new(),
- },
- path: PathBuf::new(),
- };
- let bytes = b"driver banner\n{\"id\":1,\"result\":{\"ok\":true}}\n";
- let mut reader = BufReader::new(std::io::Cursor::new(bytes));
-
- let result: serde_json::Value =
- read_decoded_plugin_response(&plugin, 1, &mut reader, || Ok("closed".to_string()))
- .await
- .expect("response should decode after noisy line");
-
- assert_eq!(result["ok"], true);
- }
#[cfg(unix)]
#[tokio::test]
@@ -568,8 +380,8 @@ mod tests {
permissions.set_mode(0o755);
std::fs::set_permissions(&executable, permissions).unwrap();
}
- let plugin = InstalledPlugin {
- manifest: PluginManifest {
+ let plugin = InstalledPlugin::new(
+ PluginManifest {
id: "jdbc".to_string(),
name: "JDBC".to_string(),
version: "test".to_string(),
@@ -582,13 +394,21 @@ mod tests {
kind: "external".to_string(),
database_type: Some("jdbc".to_string()),
}],
+ contributions: Vec::new(),
+ ..PluginManifest::default()
},
- path: dir.clone(),
- };
+ dir.clone(),
+ env!("CARGO_PKG_VERSION"),
+ );
- let session = PluginDriverSession::start(plugin, "jdbc".to_string(), PluginRuntimeEnv::default())
- .await
- .expect("session should start");
+ let session = PluginDriverSession::start(
+ plugin,
+ "jdbc".to_string(),
+ env!("CARGO_PKG_VERSION").to_string(),
+ PluginRuntimeEnv::default(),
+ )
+ .await
+ .expect("session should start");
let pid = session.pid().await.expect("child should have a pid");
session.shutdown().await;
@@ -608,4 +428,113 @@ mod tests {
.map(|status| status.success())
.unwrap_or(false)
}
+
+ #[test]
+ fn preserves_typed_contributions_in_manifest_round_trip() {
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "sample",
+ "name": "Sample",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "host_api": "1" },
+ "contributions": [{
+ "type": "connection-provider",
+ "id": "sample.connection",
+ "database_type": "sample",
+ "fields": []
+ }]
+ }))
+ .expect("manifest should parse");
+
+ assert!(matches!(
+ &manifest.contributions[0],
+ PluginContribution::ConnectionProvider(provider) if provider.id == "sample.connection"
+ ));
+ let serialized = serde_json::to_value(manifest).expect("manifest should serialize");
+ assert_eq!(serialized["contributions"][0]["database_type"], "sample");
+ }
+
+ #[test]
+ fn registry_lists_frontend_contributions_from_disk() {
+ let root = std::env::temp_dir().join(format!("dbx-plugin-registry-test-{}", uuid::Uuid::new_v4()));
+ let plugin_dir = root.join("sample");
+ std::fs::create_dir_all(&plugin_dir).expect("plugin directory should be created");
+ std::fs::write(
+ plugin_dir.join("manifest.json"),
+ serde_json::json!({
+ "manifest_version": 1,
+ "id": "sample",
+ "name": "Sample",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "host_api": "1" },
+ "contributions": [{
+ "type": "connection-provider",
+ "id": "sample.connection",
+ "database_type": "sample",
+ "fields": []
+ }]
+ })
+ .to_string(),
+ )
+ .expect("manifest should be written");
+
+ let plugins = PluginRegistry::new(root.clone()).list_installed().expect("plugins should be listed");
+
+ assert_eq!(plugins.len(), 1);
+ assert!(matches!(
+ &plugins[0].manifest.contributions[0],
+ PluginContribution::ConnectionProvider(provider) if provider.id == "sample.connection"
+ ));
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn registry_keeps_other_plugins_visible_when_one_manifest_is_corrupt() {
+ let root = std::env::temp_dir().join(format!("dbx-plugin-corrupt-registry-test-{}", uuid::Uuid::new_v4()));
+ let valid = root.join("valid");
+ let corrupt = root.join("corrupt");
+ std::fs::create_dir_all(&valid).unwrap();
+ std::fs::create_dir_all(&corrupt).unwrap();
+ std::fs::write(
+ valid.join("manifest.json"),
+ serde_json::json!({ "id": "valid", "name": "Valid", "drivers": [] }).to_string(),
+ )
+ .unwrap();
+ std::fs::write(corrupt.join("manifest.json"), "{").unwrap();
+
+ let plugins = PluginRegistry::new(root.clone()).list_installed().unwrap();
+
+ assert_eq!(plugins.len(), 2);
+ assert!(plugins.iter().any(|plugin| plugin.manifest.id == "valid" && plugin.compatibility.compatible));
+ assert!(plugins.iter().any(|plugin| {
+ plugin.manifest.id == "corrupt"
+ && !plugin.compatibility.compatible
+ && plugin.compatibility.errors.iter().any(|error| error.contains("Failed to parse"))
+ }));
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn installed_plugin_info_hides_runtime_paths() {
+ let plugin = InstalledPlugin::new(
+ PluginManifest {
+ manifest_version: 1,
+ id: "sample".to_string(),
+ name: "Sample".to_string(),
+ version: "1.0.0".to_string(),
+ publisher: "example".to_string(),
+ ..PluginManifest::default()
+ },
+ std::path::PathBuf::from("/private/plugin/install"),
+ env!("CARGO_PKG_VERSION"),
+ );
+ let serialized = serde_json::to_value(plugin.info()).unwrap();
+
+ assert!(serialized.get("path").is_none());
+ assert!(serialized["compatibility"].get("backend_executable").is_none());
+ assert!(serialized["compatibility"].get("ui_entry").is_none());
+ assert!(serialized["compatibility"].get("ui_root").is_none());
+ }
}
diff --git a/crates/dbx-core/src/plugins/assets.rs b/crates/dbx-core/src/plugins/assets.rs
new file mode 100644
index 0000000000..90f923b712
--- /dev/null
+++ b/crates/dbx-core/src/plugins/assets.rs
@@ -0,0 +1,184 @@
+use std::path::{Component, Path, PathBuf};
+
+use sha2::{Digest, Sha256};
+
+use super::{InstalledPlugin, PluginRegistry};
+
+const MAX_PLUGIN_UI_ASSET_BYTES: u64 = 32 * 1024 * 1024;
+
+#[derive(Debug, Clone)]
+pub struct PluginUiAsset {
+ pub content_type: String,
+ pub bytes: Vec<u8>,
+ pub etag: String,
+}
+
+impl PluginRegistry {
+ pub fn read_asset(&self, plugin_id: &str, relative_path: &str) -> Result<PluginUiAsset, String> {
+ let plugin = self.find_plugin(plugin_id)?.ok_or_else(|| format!("Plugin '{plugin_id}' is not installed"))?;
+ let relative = validate_asset_path(relative_path)?;
+ let path = plugin.path.join(relative);
+ read_asset_file(plugin_id, &plugin.path, &path)
+ }
+
+ pub fn read_ui_entry(&self, plugin_id: &str) -> Result<PluginUiAsset, String> {
+ let plugin = self.compatible_ui_plugin(plugin_id)?;
+ let entry = plugin
+ .compatibility
+ .ui_entry
+ .as_ref()
+ .ok_or_else(|| format!("Plugin '{plugin_id}' does not provide a UI entrypoint"))?;
+ let root = plugin
+ .compatibility
+ .ui_root
+ .as_ref()
+ .ok_or_else(|| format!("Plugin '{plugin_id}' does not provide a UI root"))?;
+ read_asset_file(plugin_id, root, entry)
+ }
+
+ pub fn read_ui_asset(&self, plugin_id: &str, relative_path: &str) -> Result<PluginUiAsset, String> {
+ let plugin = self.compatible_ui_plugin(plugin_id)?;
+ let root = plugin
+ .compatibility
+ .ui_root
+ .as_ref()
+ .ok_or_else(|| format!("Plugin '{plugin_id}' does not provide a UI root"))?;
+ let relative = validate_asset_path(relative_path)?;
+ let path = root.join(relative);
+ read_asset_file(plugin_id, root, &path)
+ }
+
+ fn compatible_ui_plugin(&self, plugin_id: &str) -> Result<InstalledPlugin, String> {
+ let plugin = self.find_plugin(plugin_id)?.ok_or_else(|| format!("Plugin '{plugin_id}' is not installed"))?;
+ if !plugin.compatibility.compatible {
+ return Err(format!("Plugin '{plugin_id}' is incompatible: {}", plugin.compatibility.errors.join("; ")));
+ }
+ if plugin.manifest.entrypoints.ui.is_none() {
+ return Err(format!("Plugin '{plugin_id}' does not provide a UI entrypoint"));
+ }
+ Ok(plugin)
+ }
+}
+
+fn read_asset_file(plugin_id: &str, root: &Path, path: &Path) -> Result<PluginUiAsset, String> {
+ let canonical_root = std::fs::canonicalize(root)
+ .map_err(|error| format!("Failed to resolve plugin asset root {}: {error}", root.display()))?;
+ let canonical_path = std::fs::canonicalize(path)
+ .map_err(|error| format!("Plugin UI asset does not exist {}: {error}", path.display()))?;
+ if !canonical_path.starts_with(&canonical_root) {
+ return Err(format!("Plugin asset escapes plugin '{plugin_id}': {}", path.display()));
+ }
+ let metadata = std::fs::metadata(&canonical_path).map_err(|error| error.to_string())?;
+ if !metadata.is_file() {
+ return Err(format!("Plugin UI asset is not a file: {}", canonical_path.display()));
+ }
+ if metadata.len() > MAX_PLUGIN_UI_ASSET_BYTES {
+ return Err(format!("Plugin UI asset exceeds {MAX_PLUGIN_UI_ASSET_BYTES} bytes"));
+ }
+ let bytes = std::fs::read(&canonical_path).map_err(|error| error.to_string())?;
+ let etag = format!("\"{}\"", hex_digest(Sha256::digest(&bytes)));
+ Ok(PluginUiAsset { content_type: content_type(&canonical_path).to_string(), bytes, etag })
+}
+
+fn validate_asset_path(relative_path: &str) -> Result<PathBuf, String> {
+ let path = Path::new(relative_path);
+ if path.as_os_str().is_empty() || path.is_absolute() {
+ return Err("Plugin UI asset path must be a non-empty relative path".to_string());
+ }
+ if path.components().any(|component| !matches!(component, Component::Normal(_))) {
+ return Err(format!("Plugin UI asset path is unsafe: {relative_path}"));
+ }
+ Ok(path.to_path_buf())
+}
+
+fn content_type(path: &Path) -> &'static str {
+ match path.extension().and_then(|extension| extension.to_str()).map(str::to_ascii_lowercase).as_deref() {
+ Some("html" | "htm") => "text/html; charset=utf-8",
+ Some("js" | "mjs") => "text/javascript; charset=utf-8",
+ Some("css") => "text/css; charset=utf-8",
+ Some("json" | "map") => "application/json; charset=utf-8",
+ Some("svg") => "image/svg+xml",
+ Some("png") => "image/png",
+ Some("jpg" | "jpeg") => "image/jpeg",
+ Some("gif") => "image/gif",
+ Some("webp") => "image/webp",
+ Some("ico") => "image/x-icon",
+ Some("woff") => "font/woff",
+ Some("woff2") => "font/woff2",
+ Some("wasm") => "application/wasm",
+ Some("txt") => "text/plain; charset=utf-8",
+ _ => "application/octet-stream",
+ }
+}
+
+fn hex_digest(bytes: impl AsRef<[u8]>) -> String {
+ use std::fmt::Write as _;
+
+ bytes.as_ref().iter().fold(String::with_capacity(64), |mut output, byte| {
+ let _ = write!(output, "{byte:02x}");
+ output
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::PluginRegistry;
+
+ #[test]
+ fn serves_assets_inside_declared_ui_root() {
+ let root = tempfile::tempdir().unwrap();
+ let plugin_dir = root.path().join("sample");
+ std::fs::create_dir_all(plugin_dir.join("ui")).unwrap();
+ std::fs::write(plugin_dir.join("ui/index.html"), "<h1>Hello</h1>").unwrap();
+ std::fs::write(plugin_dir.join("ui/app.js"), "console.log('hello')").unwrap();
+ std::fs::write(
+ plugin_dir.join("manifest.json"),
+ serde_json::json!({
+ "manifest_version": 1,
+ "id": "sample",
+ "name": "Sample",
+ "version": "1.0.0",
+ "publisher": "dbx",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "entrypoints": { "ui": { "root": "ui", "entry": "ui/index.html" } }
+ })
+ .to_string(),
+ )
+ .unwrap();
+ let registry = PluginRegistry::new_with_app_version(root.path().to_path_buf(), "0.5.67");
+
+ let entry = registry.read_ui_entry("sample").unwrap();
+ assert_eq!(entry.content_type, "text/html; charset=utf-8");
+ assert_eq!(entry.bytes, b"<h1>Hello</h1>");
+ assert!(registry.read_ui_asset("sample", "app.js").is_ok());
+ assert!(registry.read_ui_asset("sample", "../manifest.json").is_err());
+ }
+
+ #[test]
+ fn serves_package_assets_without_a_ui_entrypoint() {
+ let root = tempfile::tempdir().unwrap();
+ let plugin_dir = root.path().join("sample");
+ std::fs::create_dir_all(plugin_dir.join("assets")).unwrap();
+ std::fs::write(plugin_dir.join("assets/icon.svg"), "<svg/>").unwrap();
+ std::fs::write(
+ plugin_dir.join("manifest.json"),
+ serde_json::json!({
+ "manifest_version": 1,
+ "id": "sample",
+ "name": "Sample",
+ "version": "1.0.0",
+ "publisher": "dbx",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "icon": "assets/icon.svg"
+ })
+ .to_string(),
+ )
+ .unwrap();
+ let registry = PluginRegistry::new_with_app_version(root.path().to_path_buf(), "0.5.67");
+
+ let icon = registry.read_asset("sample", "assets/icon.svg").unwrap();
+ assert_eq!(icon.content_type, "image/svg+xml");
+ assert_eq!(icon.bytes, b"<svg/>");
+ assert!(registry.read_asset("sample", "../outside.svg").is_err());
+ }
+}
diff --git a/crates/dbx-core/src/plugins/filesystem.rs b/crates/dbx-core/src/plugins/filesystem.rs
new file mode 100644
index 0000000000..64be1a4f28
--- /dev/null
+++ b/crates/dbx-core/src/plugins/filesystem.rs
@@ -0,0 +1,536 @@
+use std::time::Duration;
+
+use base64::Engine;
+use serde::{Deserialize, Serialize};
+
+use super::{PluginFilesystemCapability, PluginFilesystemProviderContribution, PluginHost, PLUGIN_REQUEST_TIMEOUT};
+
+pub const PLUGIN_FILESYSTEM_LIST_METHOD: &str = "filesystem/list";
+pub const PLUGIN_FILESYSTEM_READ_METHOD: &str = "filesystem/read";
+pub const PLUGIN_FILESYSTEM_WRITE_METHOD: &str = "filesystem/write";
+pub const PLUGIN_FILESYSTEM_CREATE_DIRECTORY_METHOD: &str = "filesystem/createDirectory";
+pub const PLUGIN_FILESYSTEM_DELETE_METHOD: &str = "filesystem/delete";
+pub const PLUGIN_FILESYSTEM_RENAME_METHOD: &str = "filesystem/rename";
+pub const DEFAULT_PLUGIN_FILESYSTEM_PAGE_SIZE: u32 = 200;
+pub const MAX_PLUGIN_FILESYSTEM_PAGE_SIZE: u32 = 1_000;
+pub const DEFAULT_PLUGIN_FILESYSTEM_PREVIEW_BYTES: u64 = 256 * 1024;
+pub const MAX_PLUGIN_FILESYSTEM_PREVIEW_BYTES: u64 = 4 * 1024 * 1024;
+pub const MAX_PLUGIN_FILESYSTEM_INLINE_WRITE_BYTES: u64 = 4 * 1024 * 1024;
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PluginFilesystemListRequest<'a> {
+ provider_id: &'a str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ connection_id: Option<&'a str>,
+ uri: &'a str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ cursor: Option<&'a str>,
+ limit: u32,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PluginFilesystemReadRequest<'a> {
+ provider_id: &'a str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ connection_id: Option<&'a str>,
+ uri: &'a str,
+ max_bytes: u64,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PluginFilesystemWriteRequest<'a> {
+ provider_id: &'a str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ connection_id: Option<&'a str>,
+ uri: &'a str,
+ data_base64: &'a str,
+ create: bool,
+ overwrite: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ etag: Option<&'a str>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PluginFilesystemCreateDirectoryRequest<'a> {
+ provider_id: &'a str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ connection_id: Option<&'a str>,
+ uri: &'a str,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PluginFilesystemDeleteRequest<'a> {
+ provider_id: &'a str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ connection_id: Option<&'a str>,
+ uri: &'a str,
+ recursive: bool,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PluginFilesystemRenameRequest<'a> {
+ provider_id: &'a str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ connection_id: Option<&'a str>,
+ source_uri: &'a str,
+ target_uri: &'a str,
+ overwrite: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "kebab-case")]
+pub enum PluginFilesystemEntryKind {
+ File,
+ Directory,
+ Symlink,
+ Other,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginFilesystemEntry {
+ pub name: String,
+ pub uri: String,
+ pub kind: PluginFilesystemEntryKind,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub size: Option<u64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub modified_at: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub content_type: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginFilesystemListResult {
+ #[serde(default)]
+ pub entries: Vec<PluginFilesystemEntry>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub next_cursor: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginFilesystemReadResult {
+ pub data_base64: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub content_type: Option<String>,
+ #[serde(default)]
+ pub truncated: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub etag: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginFilesystemMutationResult {
+ #[serde(default = "default_true")]
+ pub success: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub message: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub entry: Option<PluginFilesystemEntry>,
+}
+
+fn default_true() -> bool {
+ true
+}
+
+impl PluginHost {
+ pub async fn list_filesystem_entries(
+ &self,
+ plugin_id: &str,
+ provider_id: &str,
+ connection_id: Option<&str>,
+ uri: Option<&str>,
+ cursor: Option<&str>,
+ limit: Option<u32>,
+ ) -> Result<PluginFilesystemListResult, String> {
+ let provider = self.resolve_filesystem_provider(plugin_id, provider_id)?;
+ let uri = resolve_filesystem_uri(&provider, uri)?;
+ let limit = limit.unwrap_or(DEFAULT_PLUGIN_FILESYSTEM_PAGE_SIZE).clamp(1, MAX_PLUGIN_FILESYSTEM_PAGE_SIZE);
+ let request = PluginFilesystemListRequest {
+ provider_id,
+ connection_id: normalized_optional_value(connection_id),
+ uri: &uri,
+ cursor: normalized_optional_value(cursor),
+ limit,
+ };
+ let result: PluginFilesystemListResult = self
+ .invoke(
+ plugin_id,
+ PLUGIN_FILESYSTEM_LIST_METHOD,
+ serde_json::to_value(request).map_err(|error| error.to_string())?,
+ None,
+ Some(PLUGIN_REQUEST_TIMEOUT),
+ )
+ .await?;
+ validate_list_result(&provider, &result, limit)?;
+ Ok(result)
+ }
+
+ pub async fn read_filesystem_file(
+ &self,
+ plugin_id: &str,
+ provider_id: &str,
+ connection_id: Option<&str>,
+ uri: &str,
+ max_bytes: Option<u64>,
+ ) -> Result<PluginFilesystemReadResult, String> {
+ let provider = self.resolve_filesystem_provider(plugin_id, provider_id)?;
+ ensure_provider_capability(plugin_id, &provider, PluginFilesystemCapability::Read)?;
+ let uri = resolve_filesystem_uri(&provider, Some(uri))?;
+ let max_bytes =
+ max_bytes.unwrap_or(DEFAULT_PLUGIN_FILESYSTEM_PREVIEW_BYTES).clamp(1, MAX_PLUGIN_FILESYSTEM_PREVIEW_BYTES);
+ let request = PluginFilesystemReadRequest {
+ provider_id,
+ connection_id: normalized_optional_value(connection_id),
+ uri: &uri,
+ max_bytes,
+ };
+ let result: PluginFilesystemReadResult = self
+ .invoke(
+ plugin_id,
+ PLUGIN_FILESYSTEM_READ_METHOD,
+ serde_json::to_value(request).map_err(|error| error.to_string())?,
+ None,
+ Some(Duration::from_secs(30)),
+ )
+ .await?;
+ validate_read_result(&result, max_bytes)?;
+ Ok(result)
+ }
+
+ pub async fn write_filesystem_file(
+ &self,
+ plugin_id: &str,
+ provider_id: &str,
+ connection_id: Option<&str>,
+ uri: &str,
+ data_base64: &str,
+ create: bool,
+ overwrite: bool,
+ etag: Option<&str>,
+ ) -> Result<PluginFilesystemMutationResult, String> {
+ let provider = self.resolve_filesystem_provider(plugin_id, provider_id)?;
+ ensure_provider_capability(plugin_id, &provider, PluginFilesystemCapability::Write)?;
+ let uri = resolve_filesystem_uri(&provider, Some(uri))?;
+ validate_inline_write_data(data_base64)?;
+ let request = PluginFilesystemWriteRequest {
+ provider_id,
+ connection_id: normalized_optional_value(connection_id),
+ uri: &uri,
+ data_base64,
+ create,
+ overwrite,
+ etag: normalized_optional_value(etag),
+ };
+ let result =
+ self.invoke_filesystem_mutation(plugin_id, &provider, PLUGIN_FILESYSTEM_WRITE_METHOD, request).await?;
+ Ok(result)
+ }
+
+ pub async fn create_filesystem_directory(
+ &self,
+ plugin_id: &str,
+ provider_id: &str,
+ connection_id: Option<&str>,
+ uri: &str,
+ ) -> Result<PluginFilesystemMutationResult, String> {
+ let provider = self.resolve_filesystem_provider(plugin_id, provider_id)?;
+ ensure_provider_capability(plugin_id, &provider, PluginFilesystemCapability::Mkdir)?;
+ let uri = resolve_filesystem_uri(&provider, Some(uri))?;
+ let request = PluginFilesystemCreateDirectoryRequest {
+ provider_id,
+ connection_id: normalized_optional_value(connection_id),
+ uri: &uri,
+ };
+ self.invoke_filesystem_mutation(plugin_id, &provider, PLUGIN_FILESYSTEM_CREATE_DIRECTORY_METHOD, request).await
+ }
+
+ pub async fn delete_filesystem_entry(
+ &self,
+ plugin_id: &str,
+ provider_id: &str,
+ connection_id: Option<&str>,
+ uri: &str,
+ recursive: bool,
+ ) -> Result<PluginFilesystemMutationResult, String> {
+ let provider = self.resolve_filesystem_provider(plugin_id, provider_id)?;
+ ensure_provider_capability(plugin_id, &provider, PluginFilesystemCapability::Delete)?;
+ let uri = resolve_filesystem_uri(&provider, Some(uri))?;
+ let request = PluginFilesystemDeleteRequest {
+ provider_id,
+ connection_id: normalized_optional_value(connection_id),
+ uri: &uri,
+ recursive,
+ };
+ self.invoke_filesystem_mutation(plugin_id, &provider, PLUGIN_FILESYSTEM_DELETE_METHOD, request).await
+ }
+
+ pub async fn rename_filesystem_entry(
+ &self,
+ plugin_id: &str,
+ provider_id: &str,
+ connection_id: Option<&str>,
+ source_uri: &str,
+ target_uri: &str,
+ overwrite: bool,
+ ) -> Result<PluginFilesystemMutationResult, String> {
+ let provider = self.resolve_filesystem_provider(plugin_id, provider_id)?;
+ ensure_provider_capability(plugin_id, &provider, PluginFilesystemCapability::Rename)?;
+ let source_uri = resolve_filesystem_uri(&provider, Some(source_uri))?;
+ let target_uri = resolve_filesystem_uri(&provider, Some(target_uri))?;
+ let request = PluginFilesystemRenameRequest {
+ provider_id,
+ connection_id: normalized_optional_value(connection_id),
+ source_uri: &source_uri,
+ target_uri: &target_uri,
+ overwrite,
+ };
+ self.invoke_filesystem_mutation(plugin_id, &provider, PLUGIN_FILESYSTEM_RENAME_METHOD, request).await
+ }
+
+ async fn invoke_filesystem_mutation<T: Serialize>(
+ &self,
+ plugin_id: &str,
+ provider: &PluginFilesystemProviderContribution,
+ method: &str,
+ request: T,
+ ) -> Result<PluginFilesystemMutationResult, String> {
+ let result: PluginFilesystemMutationResult = self
+ .invoke(
+ plugin_id,
+ method,
+ serde_json::to_value(request).map_err(|error| error.to_string())?,
+ None,
+ Some(Duration::from_secs(30)),
+ )
+ .await?;
+ validate_mutation_result(provider, &result)?;
+ Ok(result)
+ }
+
+ fn resolve_filesystem_provider(
+ &self,
+ plugin_id: &str,
+ provider_id: &str,
+ ) -> Result<PluginFilesystemProviderContribution, String> {
+ let plugin =
+ self.registry().find_plugin(plugin_id)?.ok_or_else(|| format!("Plugin '{plugin_id}' is not installed"))?;
+ if !plugin.compatibility.compatible {
+ return Err(format!("Plugin '{plugin_id}' is incompatible: {}", plugin.compatibility.errors.join("; ")));
+ }
+ plugin
+ .manifest
+ .filesystem_provider(provider_id)?
+ .ok_or_else(|| format!("Filesystem provider '{plugin_id}/{provider_id}' is not declared"))
+ }
+}
+
+fn normalized_optional_value(value: Option<&str>) -> Option<&str> {
+ value.map(str::trim).filter(|value| !value.is_empty())
+}
+
+fn resolve_filesystem_uri(
+ provider: &PluginFilesystemProviderContribution,
+ requested_uri: Option<&str>,
+) -> Result<String, String> {
+ let uri = requested_uri
+ .map(str::trim)
+ .filter(|uri| !uri.is_empty())
+ .map(ToOwned::to_owned)
+ .or_else(|| provider.root_uri.clone())
+ .unwrap_or_else(|| format!("{}:/", provider.schemes[0]));
+ if uri.len() > 4_096 || uri.chars().any(char::is_control) {
+ return Err("Plugin filesystem URI is invalid".to_string());
+ }
+ let scheme = uri.split_once(':').map(|(scheme, _)| scheme).unwrap_or_default();
+ if !provider.schemes.iter().any(|candidate| candidate == scheme) {
+ return Err(format!("Filesystem URI scheme '{scheme}' is not handled by provider '{}'", provider.id));
+ }
+ Ok(uri)
+}
+
+fn validate_list_result(
+ provider: &PluginFilesystemProviderContribution,
+ result: &PluginFilesystemListResult,
+ requested_limit: u32,
+) -> Result<(), String> {
+ let maximum_entries = usize::try_from(requested_limit).unwrap_or(usize::MAX);
+ if result.entries.len() > maximum_entries {
+ return Err(format!(
+ "Filesystem provider '{}' returned {} entries for a limit of {requested_limit}",
+ provider.id,
+ result.entries.len()
+ ));
+ }
+ if result.next_cursor.as_ref().is_some_and(|cursor| cursor.is_empty() || cursor.len() > 4_096) {
+ return Err(format!("Filesystem provider '{}' returned an invalid cursor", provider.id));
+ }
+ for entry in &result.entries {
+ validate_entry(provider, entry)?;
+ }
+ Ok(())
+}
+
+fn validate_entry(
+ provider: &PluginFilesystemProviderContribution,
+ entry: &PluginFilesystemEntry,
+) -> Result<(), String> {
+ if entry.name.trim().is_empty() || entry.name.len() > 1_024 || entry.name.chars().any(char::is_control) {
+ return Err(format!("Filesystem provider '{}' returned an invalid entry name", provider.id));
+ }
+ resolve_filesystem_uri(provider, Some(&entry.uri))?;
+ if entry.modified_at.as_ref().is_some_and(|value| value.len() > 128) {
+ return Err(format!("Filesystem provider '{}' returned an invalid modified timestamp", provider.id));
+ }
+ if entry.content_type.as_ref().is_some_and(|value| value.len() > 256 || value.chars().any(char::is_control)) {
+ return Err(format!("Filesystem provider '{}' returned an invalid content type", provider.id));
+ }
+ Ok(())
+}
+
+fn validate_read_result(result: &PluginFilesystemReadResult, max_bytes: u64) -> Result<(), String> {
+ if result.content_type.as_ref().is_some_and(|value| value.len() > 256 || value.chars().any(char::is_control)) {
+ return Err("Filesystem provider returned an invalid content type".to_string());
+ }
+ if result.etag.as_ref().is_some_and(|value| value.len() > 512 || value.chars().any(char::is_control)) {
+ return Err("Filesystem provider returned an invalid etag".to_string());
+ }
+ let estimated_bytes = result.data_base64.len().saturating_mul(3) / 4;
+ if estimated_bytes as u64 > max_bytes.saturating_add(2) {
+ return Err(format!("Filesystem provider returned more than the requested {max_bytes} bytes"));
+ }
+ let decoded = base64::engine::general_purpose::STANDARD
+ .decode(&result.data_base64)
+ .map_err(|error| format!("Filesystem provider returned invalid base64 data: {error}"))?;
+ if decoded.len() as u64 > max_bytes {
+ return Err(format!("Filesystem provider returned more than the requested {max_bytes} bytes"));
+ }
+ Ok(())
+}
+
+fn validate_inline_write_data(data_base64: &str) -> Result<(), String> {
+ let estimated_bytes = data_base64.len().saturating_mul(3) / 4;
+ if estimated_bytes as u64 > MAX_PLUGIN_FILESYSTEM_INLINE_WRITE_BYTES.saturating_add(2) {
+ return Err(format!(
+ "Inline plugin filesystem writes are limited to {MAX_PLUGIN_FILESYSTEM_INLINE_WRITE_BYTES} bytes"
+ ));
+ }
+ let decoded = base64::engine::general_purpose::STANDARD
+ .decode(data_base64)
+ .map_err(|error| format!("Plugin filesystem write contains invalid base64 data: {error}"))?;
+ if decoded.len() as u64 > MAX_PLUGIN_FILESYSTEM_INLINE_WRITE_BYTES {
+ return Err(format!(
+ "Inline plugin filesystem writes are limited to {MAX_PLUGIN_FILESYSTEM_INLINE_WRITE_BYTES} bytes"
+ ));
+ }
+ Ok(())
+}
+
+fn validate_mutation_result(
+ provider: &PluginFilesystemProviderContribution,
+ result: &PluginFilesystemMutationResult,
+) -> Result<(), String> {
+ if !result.success {
+ return Err(result.message.clone().unwrap_or_else(|| "Plugin filesystem operation failed".to_string()));
+ }
+ if result.message.as_ref().is_some_and(|message| message.len() > 4_096 || message.chars().any(char::is_control)) {
+ return Err(format!("Filesystem provider '{}' returned an invalid operation message", provider.id));
+ }
+ if let Some(entry) = &result.entry {
+ validate_entry(provider, entry)?;
+ }
+ Ok(())
+}
+
+fn ensure_provider_capability(
+ plugin_id: &str,
+ provider: &PluginFilesystemProviderContribution,
+ capability: PluginFilesystemCapability,
+) -> Result<(), String> {
+ if provider.has_capability(capability) {
+ Ok(())
+ } else {
+ Err(format!(
+ "Filesystem provider '{plugin_id}/{}' does not declare {} capability",
+ provider.id,
+ capability.as_str()
+ ))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{resolve_filesystem_uri, validate_inline_write_data, validate_list_result, validate_read_result};
+ use crate::plugins::{
+ PluginFilesystemCapability, PluginFilesystemEntry, PluginFilesystemEntryKind, PluginFilesystemListResult,
+ PluginFilesystemProviderContribution, PluginFilesystemReadResult,
+ };
+
+ fn provider() -> PluginFilesystemProviderContribution {
+ PluginFilesystemProviderContribution {
+ id: "sample.files".to_string(),
+ label: "Sample files".to_string(),
+ schemes: vec!["sample".to_string()],
+ description: None,
+ capabilities: vec![PluginFilesystemCapability::Read],
+ root_uri: Some("sample:/home".to_string()),
+ }
+ }
+
+ #[test]
+ fn resolves_declared_root_and_rejects_other_schemes() {
+ assert_eq!(resolve_filesystem_uri(&provider(), None).unwrap(), "sample:/home");
+ assert!(resolve_filesystem_uri(&provider(), Some("other:/tmp")).unwrap_err().contains("not handled"));
+ }
+
+ #[test]
+ fn validates_list_limits_and_entry_uris() {
+ let valid = PluginFilesystemListResult {
+ entries: vec![PluginFilesystemEntry {
+ name: "README.txt".to_string(),
+ uri: "sample:/README.txt".to_string(),
+ kind: PluginFilesystemEntryKind::File,
+ size: Some(5),
+ modified_at: None,
+ content_type: Some("text/plain".to_string()),
+ }],
+ next_cursor: None,
+ };
+ validate_list_result(&provider(), &valid, 1).unwrap();
+ assert!(validate_list_result(&provider(), &valid, 0).unwrap_err().contains("limit of 0"));
+ }
+
+ #[test]
+ fn rejects_invalid_or_oversized_file_preview() {
+ let invalid = PluginFilesystemReadResult {
+ data_base64: "not base64".to_string(),
+ content_type: None,
+ truncated: false,
+ etag: None,
+ };
+ assert!(validate_read_result(&invalid, 16).unwrap_err().contains("invalid base64"));
+
+ let oversized = PluginFilesystemReadResult {
+ data_base64: "YWJjZA==".to_string(),
+ content_type: None,
+ truncated: false,
+ etag: None,
+ };
+ assert!(validate_read_result(&oversized, 3).unwrap_err().contains("more than"));
+ }
+
+ #[test]
+ fn validates_inline_write_base64() {
+ validate_inline_write_data("YWJjZA==").unwrap();
+ assert!(validate_inline_write_data("not base64").unwrap_err().contains("invalid base64"));
+ }
+}
diff --git a/crates/dbx-core/src/plugins/host.rs b/crates/dbx-core/src/plugins/host.rs
new file mode 100644
index 0000000000..48ea8b287b
--- /dev/null
+++ b/crates/dbx-core/src/plugins/host.rs
@@ -0,0 +1,702 @@
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::sync::Arc;
+use std::time::Duration;
+
+use crate::models::connection::{ConnectionConfig, ConnectionTestResult, DatabaseType};
+use serde::de::DeserializeOwned;
+use serde::Serialize;
+use tokio::sync::{broadcast, Mutex, RwLock};
+
+use super::{
+ InstalledPlugin, PluginBinaryMessage, PluginConnectionActionContribution, PluginConnectionCapability,
+ PluginConnectionProviderContribution, PluginEvent, PluginFormFieldBinding, PluginFormFieldDefinition,
+ PluginFormFieldType, PluginRegistry, PluginRuntimeEnv, PluginSessionState, PluginSidecarSession,
+ PLUGIN_CONNECTION_ACTION_METHOD, PLUGIN_CONNECTION_CONNECT_METHOD, PLUGIN_CONNECTION_DISCONNECT_METHOD,
+ PLUGIN_CONNECTION_TEST_METHOD,
+};
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ActivePluginSession {
+ pub plugin_id: String,
+ pub process_id: Option<u32>,
+ pub state: PluginSessionState,
+}
+
+#[derive(Debug, Clone, Default, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginConnectionActionResult {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub message: Option<String>,
+ #[serde(skip_serializing_if = "BTreeMap::is_empty")]
+ pub field_values: BTreeMap<String, serde_json::Value>,
+}
+
+#[derive(Clone)]
+pub struct PluginHost {
+ inner: Arc<PluginHostInner>,
+}
+
+#[derive(Clone)]
+pub struct PluginConnectionHandle {
+ pub plugin_id: String,
+ pub provider_id: String,
+ pub connection_id: String,
+ session: Option<Arc<PluginSidecarSession>>,
+ disconnect: bool,
+ params: serde_json::Value,
+}
+
+impl PluginConnectionHandle {
+ pub fn is_running(&self) -> bool {
+ self.session.as_ref().is_none_or(|session| session.status().state == PluginSessionState::Running)
+ }
+
+ pub async fn disconnect(&self) -> Result<(), String> {
+ let Some(session) = &self.session else {
+ return Ok(());
+ };
+ if !self.disconnect || session.status().state != PluginSessionState::Running {
+ return Ok(());
+ }
+ let result: serde_json::Value = session
+ .invoke_with_timeout(
+ PLUGIN_CONNECTION_DISCONNECT_METHOD,
+ self.params.clone(),
+ None,
+ Some(super::PLUGIN_REQUEST_TIMEOUT),
+ )
+ .await?;
+ ensure_plugin_operation_succeeded(result)
+ }
+}
+
+struct PluginHostInner {
+ registry: PluginRegistry,
+ sessions: RwLock<HashMap<String, Arc<PluginSidecarSession>>>,
+ activation_lock: Mutex<()>,
+ events: broadcast::Sender<PluginEvent>,
+ binary_messages: broadcast::Sender<PluginBinaryMessage>,
+}
+
+impl PluginHost {
+ pub fn new(registry: PluginRegistry) -> Self {
+ let (events, _) = broadcast::channel(512);
+ let (binary_messages, _) = broadcast::channel(128);
+ Self {
+ inner: Arc::new(PluginHostInner {
+ registry,
+ sessions: RwLock::new(HashMap::new()),
+ activation_lock: Mutex::new(()),
+ events,
+ binary_messages,
+ }),
+ }
+ }
+
+ pub fn subscribe_events(&self) -> broadcast::Receiver<PluginEvent> {
+ self.inner.events.subscribe()
+ }
+
+ pub fn subscribe_binary(&self) -> broadcast::Receiver<PluginBinaryMessage> {
+ self.inner.binary_messages.subscribe()
+ }
+
+ pub(super) fn registry(&self) -> &PluginRegistry {
+ &self.inner.registry
+ }
+
+ pub async fn activate(&self, plugin_id: &str) -> Result<Arc<PluginSidecarSession>, String> {
+ self.activate_with_env(plugin_id, PluginRuntimeEnv::default()).await
+ }
+
+ pub async fn activate_with_env(
+ &self,
+ plugin_id: &str,
+ env: PluginRuntimeEnv,
+ ) -> Result<Arc<PluginSidecarSession>, String> {
+ if let Some(session) = self.running_session(plugin_id).await {
+ return Ok(session);
+ }
+
+ let _activation = self.inner.activation_lock.lock().await;
+ if let Some(session) = self.running_session(plugin_id).await {
+ return Ok(session);
+ }
+ self.inner.sessions.write().await.remove(plugin_id);
+
+ let plugin = self
+ .inner
+ .registry
+ .find_plugin(plugin_id)?
+ .ok_or_else(|| format!("Plugin '{plugin_id}' is not installed"))?;
+ if !plugin.compatibility.compatible {
+ return Err(format!("Plugin '{plugin_id}' is incompatible: {}", plugin.compatibility.errors.join("; ")));
+ }
+ let session = PluginSidecarSession::start(plugin, self.inner.registry.app_version().to_string(), env).await?;
+ self.forward_session_events(&session);
+ self.inner.sessions.write().await.insert(plugin_id.to_string(), session.clone());
+ Ok(session)
+ }
+
+ pub async fn invoke<T>(
+ &self,
+ plugin_id: &str,
+ method: &str,
+ params: serde_json::Value,
+ required_permission: Option<&str>,
+ timeout: Option<Duration>,
+ ) -> Result<T, String>
+ where
+ T: DeserializeOwned,
+ {
+ let session = self.activate(plugin_id).await?;
+ ensure_permission(session.plugin(), required_permission)?;
+ session.invoke_with_timeout(method, params, None, timeout).await
+ }
+
+ pub async fn notify(
+ &self,
+ plugin_id: &str,
+ method: &str,
+ params: serde_json::Value,
+ required_permission: Option<&str>,
+ ) -> Result<(), String> {
+ let session = self.activate(plugin_id).await?;
+ ensure_permission(session.plugin(), required_permission)?;
+ session.notify(method, params, None).await
+ }
+
+ pub async fn send_binary(
+ &self,
+ plugin_id: &str,
+ channel: &str,
+ data: &[u8],
+ required_permission: Option<&str>,
+ ) -> Result<(), String> {
+ let session = self.activate(plugin_id).await?;
+ ensure_permission(session.plugin(), required_permission)?;
+ session.send_binary(channel, data).await
+ }
+
+ pub async fn test_connection(
+ &self,
+ config: &ConnectionConfig,
+ runtime_host: &str,
+ runtime_port: u16,
+ ) -> Result<ConnectionTestResult, String> {
+ let (plugin, provider) = self.resolve_connection_provider(config)?;
+ validate_plugin_connection_values(config, &provider)?;
+ let provider_label = provider.label.as_deref().unwrap_or(&plugin.manifest.name);
+ if !provider.has_capability(PluginConnectionCapability::Test) {
+ return Ok(ConnectionTestResult::success(format!("{provider_label} is available")));
+ }
+ let session = self.activate(config.plugin_id.as_deref().unwrap_or_default()).await?;
+ let result: serde_json::Value = session
+ .invoke_with_timeout(
+ PLUGIN_CONNECTION_TEST_METHOD,
+ plugin_connection_params(config, &provider, runtime_host, runtime_port)?,
+ None,
+ Some(Duration::from_secs(config.effective_connect_timeout_secs())),
+ )
+ .await?;
+ plugin_connection_test_result(result, provider_label)
+ }
+
+ pub async fn connect_connection(
+ &self,
+ config: &ConnectionConfig,
+ runtime_host: &str,
+ runtime_port: u16,
+ ) -> Result<PluginConnectionHandle, String> {
+ let (_, provider) = self.resolve_connection_provider(config)?;
+ validate_plugin_connection_values(config, &provider)?;
+ let params = plugin_connection_params(config, &provider, runtime_host, runtime_port)?;
+ let needs_session = provider.has_capability(PluginConnectionCapability::Connect)
+ || provider.has_capability(PluginConnectionCapability::Disconnect);
+ let session = if needs_session {
+ Some(self.activate(config.plugin_id.as_deref().unwrap_or_default()).await?)
+ } else {
+ None
+ };
+ if provider.has_capability(PluginConnectionCapability::Connect) {
+ if let Some(session) = &session {
+ let result: serde_json::Value = session
+ .invoke_with_timeout(
+ PLUGIN_CONNECTION_CONNECT_METHOD,
+ params.clone(),
+ None,
+ Some(Duration::from_secs(config.effective_connect_timeout_secs())),
+ )
+ .await?;
+ ensure_plugin_operation_succeeded(result)?;
+ }
+ }
+ let disconnect = provider.has_capability(PluginConnectionCapability::Disconnect);
+ Ok(PluginConnectionHandle {
+ plugin_id: config.plugin_id.clone().unwrap_or_default(),
+ provider_id: provider.id,
+ connection_id: config.id.clone(),
+ session,
+ disconnect,
+ params,
+ })
+ }
+
+ pub async fn invoke_connection_action(
+ &self,
+ config: &ConnectionConfig,
+ action_id: &str,
+ runtime_host: &str,
+ runtime_port: u16,
+ ) -> Result<PluginConnectionActionResult, String> {
+ let (_, provider) = self.resolve_connection_provider(config)?;
+ let action = plugin_invoke_connection_action(&provider, action_id)?;
+ validate_plugin_connection_values_for_action(config, &provider, action.requires_valid_form)?;
+ let session = self.activate(config.plugin_id.as_deref().unwrap_or_default()).await?;
+ let mut params = plugin_connection_params(config, &provider, runtime_host, runtime_port)?;
+ params
+ .as_object_mut()
+ .ok_or("Plugin connection action params must be an object")?
+ .insert("action".to_string(), serde_json::json!({ "id": action.id }));
+ let result: serde_json::Value = session
+ .invoke_with_timeout(
+ PLUGIN_CONNECTION_ACTION_METHOD,
+ params,
+ None,
+ action.timeout_ms.map(Duration::from_millis).or(Some(super::PLUGIN_REQUEST_TIMEOUT)),
+ )
+ .await?;
+ plugin_connection_action_result(result, &provider)
+ }
+
+ pub async fn list_active(&self) -> Vec<ActivePluginSession> {
+ let sessions = self.inner.sessions.read().await.values().cloned().collect::<Vec<_>>();
+ let mut active = Vec::with_capacity(sessions.len());
+ for session in sessions {
+ active.push(ActivePluginSession {
+ plugin_id: session.plugin().manifest.id.clone(),
+ process_id: session.pid().await,
+ state: session.status().state,
+ });
+ }
+ active.sort_by(|left, right| left.plugin_id.cmp(&right.plugin_id));
+ active
+ }
+
+ pub async fn stop(&self, plugin_id: &str) {
+ if let Some(session) = self.inner.sessions.write().await.remove(plugin_id) {
+ session.shutdown().await;
+ }
+ }
+
+ pub async fn stop_all(&self) {
+ let sessions = std::mem::take(&mut *self.inner.sessions.write().await);
+ for (_, session) in sessions {
+ session.shutdown().await;
+ }
+ }
+
+ async fn running_session(&self, plugin_id: &str) -> Option<Arc<PluginSidecarSession>> {
+ let session = self.inner.sessions.read().await.get(plugin_id).cloned()?;
+ (session.status().state == PluginSessionState::Running).then_some(session)
+ }
+
+ fn resolve_connection_provider(
+ &self,
+ config: &ConnectionConfig,
+ ) -> Result<(InstalledPlugin, PluginConnectionProviderContribution), String> {
+ if config.db_type != DatabaseType::Plugin {
+ return Err("Connection is not a plugin-owned connection".to_string());
+ }
+ let plugin_id = required_plugin_binding(&config.plugin_id, "plugin_id")?;
+ let provider_id = required_plugin_binding(&config.plugin_connection_provider, "plugin_connection_provider")?;
+ let connection_type = required_plugin_binding(&config.plugin_connection_type, "plugin_connection_type")?;
+ let plugin = self
+ .inner
+ .registry
+ .find_plugin(plugin_id)?
+ .ok_or_else(|| format!("Plugin '{plugin_id}' is not installed"))?;
+ if !plugin.compatibility.compatible {
+ return Err(format!("Plugin '{plugin_id}' is incompatible: {}", plugin.compatibility.errors.join("; ")));
+ }
+ let provider = plugin
+ .manifest
+ .connection_provider(provider_id)?
+ .ok_or_else(|| format!("Plugin '{plugin_id}' does not provide connection provider '{provider_id}'"))?;
+ if provider.database_type != connection_type {
+ return Err(format!(
+ "Connection type '{}' does not match provider '{}' type '{}'",
+ connection_type, provider.id, provider.database_type
+ ));
+ }
+ Ok((plugin, provider))
+ }
+
+ fn forward_session_events(&self, session: &Arc<PluginSidecarSession>) {
+ let mut events = session.subscribe_events();
+ let host_events = self.inner.events.clone();
+ tokio::spawn(async move {
+ loop {
+ match events.recv().await {
+ Ok(event) => {
+ let _ = host_events.send(event);
+ }
+ Err(broadcast::error::RecvError::Lagged(skipped)) => {
+ log::warn!("Plugin host event relay skipped {skipped} events");
+ }
+ Err(broadcast::error::RecvError::Closed) => break,
+ }
+ }
+ });
+
+ let mut binary = session.subscribe_binary();
+ let host_binary = self.inner.binary_messages.clone();
+ tokio::spawn(async move {
+ loop {
+ match binary.recv().await {
+ Ok(message) => {
+ let _ = host_binary.send(message);
+ }
+ Err(broadcast::error::RecvError::Lagged(skipped)) => {
+ log::warn!("Plugin host binary relay skipped {skipped} messages");
+ }
+ Err(broadcast::error::RecvError::Closed) => break,
+ }
+ }
+ });
+ }
+}
+
+fn required_plugin_binding<'a>(value: &'a Option<String>, field: &str) -> Result<&'a str, String> {
+ value
+ .as_deref()
+ .filter(|value| !value.trim().is_empty())
+ .ok_or_else(|| format!("Plugin connection is missing {field}"))
+}
+
+fn plugin_connection_params(
+ config: &ConnectionConfig,
+ provider: &PluginConnectionProviderContribution,
+ runtime_host: &str,
+ runtime_port: u16,
+) -> Result<serde_json::Value, String> {
+ Ok(serde_json::json!({
+ "provider": {
+ "id": provider.id,
+ "databaseType": provider.database_type,
+ },
+ "connection": serde_json::to_value(config).map_err(|error| error.to_string())?,
+ "runtime": {
+ "host": runtime_host,
+ "port": runtime_port,
+ }
+ }))
+}
+
+fn validate_plugin_connection_values(
+ config: &ConnectionConfig,
+ provider: &PluginConnectionProviderContribution,
+) -> Result<(), String> {
+ validate_plugin_connection_values_for_action(config, provider, true)
+}
+
+fn plugin_invoke_connection_action<'a>(
+ provider: &'a PluginConnectionProviderContribution,
+ action_id: &str,
+) -> Result<&'a PluginConnectionActionContribution, String> {
+ provider
+ .actions
+ .iter()
+ .find(|action| action.id == action_id)
+ .ok_or_else(|| format!("Connection provider '{}' does not declare action '{action_id}'", provider.id))
+}
+
+fn validate_plugin_connection_values_for_action(
+ config: &ConnectionConfig,
+ provider: &PluginConnectionProviderContribution,
+ require_required_fields: bool,
+) -> Result<(), String> {
+ let allowed_secrets = provider
+ .fields
+ .iter()
+ .filter(|field| field.effective_binding() == PluginFormFieldBinding::Secret)
+ .map(|field| field.key.as_str())
+ .collect::<HashSet<_>>();
+ for key in config.connection_secrets.keys() {
+ if !allowed_secrets.contains(key.as_str()) {
+ return Err(format!("Connection secret '{key}' is not declared by provider '{}'", provider.id));
+ }
+ }
+ for field in &provider.fields {
+ let value = plugin_connection_field_value(config, field);
+ if require_required_fields && field.required && plugin_field_value_is_empty(value.as_ref()) {
+ return Err(format!("Plugin connection field '{}' is required", field.label));
+ }
+ if let Some(value) = value {
+ validate_plugin_field_type(field, &value)?;
+ if field.effective_binding() == PluginFormFieldBinding::Port
+ && value.as_u64().is_none_or(|port| port == 0 || port > u16::MAX as u64)
+ {
+ return Err(format!("Plugin connection field '{}' must be a port between 1 and 65535", field.label));
+ }
+ }
+ }
+ Ok(())
+}
+
+fn plugin_connection_action_result(
+ result: serde_json::Value,
+ provider: &PluginConnectionProviderContribution,
+) -> Result<PluginConnectionActionResult, String> {
+ if let Some(message) = result.as_str() {
+ return Ok(PluginConnectionActionResult { message: Some(message.to_string()), field_values: BTreeMap::new() });
+ }
+ if result.is_null() {
+ return Ok(PluginConnectionActionResult::default());
+ }
+ let object = result
+ .as_object()
+ .ok_or_else(|| "Plugin connection action must return null, a message string, or an object".to_string())?;
+ if object.get("success").and_then(serde_json::Value::as_bool) == Some(false) {
+ return Err(object
+ .get("message")
+ .and_then(serde_json::Value::as_str)
+ .unwrap_or("Plugin connection action failed")
+ .to_string());
+ }
+ let message = match object.get("message") {
+ None | Some(serde_json::Value::Null) => None,
+ Some(serde_json::Value::String(message)) => Some(message.clone()),
+ Some(_) => return Err("Plugin connection action message must be a string".to_string()),
+ };
+ let mut field_values = BTreeMap::new();
+ if let Some(values) = object.get("fieldValues") {
+ let values =
+ values.as_object().ok_or_else(|| "Plugin connection action fieldValues must be an object".to_string())?;
+ for (key, value) in values {
+ let field = provider
+ .fields
+ .iter()
+ .find(|field| field.key == *key)
+ .ok_or_else(|| format!("Plugin connection action returned undeclared field '{key}'"))?;
+ if !value.is_null() {
+ validate_plugin_field_type(field, value)?;
+ if field.effective_binding() == PluginFormFieldBinding::Port
+ && value.as_u64().is_none_or(|port| port == 0 || port > u16::MAX as u64)
+ {
+ return Err(format!(
+ "Plugin connection field '{}' must be a port between 1 and 65535",
+ field.label
+ ));
+ }
+ }
+ field_values.insert(key.clone(), value.clone());
+ }
+ }
+ Ok(PluginConnectionActionResult { message, field_values })
+}
+
+fn plugin_connection_field_value(
+ config: &ConnectionConfig,
+ field: &PluginFormFieldDefinition,
+) -> Option<serde_json::Value> {
+ match field.effective_binding() {
+ PluginFormFieldBinding::Name => Some(serde_json::Value::String(config.name.clone())),
+ PluginFormFieldBinding::Host => Some(serde_json::Value::String(config.host.clone())),
+ PluginFormFieldBinding::Port => Some(serde_json::Value::Number(config.port.into())),
+ PluginFormFieldBinding::Username => Some(serde_json::Value::String(config.username.clone())),
+ PluginFormFieldBinding::Password => Some(serde_json::Value::String(config.password.clone())),
+ PluginFormFieldBinding::Database => config.database.clone().map(serde_json::Value::String),
+ PluginFormFieldBinding::Secret => {
+ config.connection_secrets.get(&field.key).cloned().map(serde_json::Value::String)
+ }
+ PluginFormFieldBinding::Config => config.external_config.as_ref()?.get(&field.key).cloned(),
+ }
+}
+
+fn plugin_field_value_is_empty(value: Option<&serde_json::Value>) -> bool {
+ match value {
+ None | Some(serde_json::Value::Null) => true,
+ Some(serde_json::Value::String(value)) => value.trim().is_empty(),
+ _ => false,
+ }
+}
+
+fn validate_plugin_field_type(field: &PluginFormFieldDefinition, value: &serde_json::Value) -> Result<(), String> {
+ let valid = match field.field_type {
+ PluginFormFieldType::Text
+ | PluginFormFieldType::Password
+ | PluginFormFieldType::Select
+ | PluginFormFieldType::Radio
+ | PluginFormFieldType::Textarea => value.is_string(),
+ PluginFormFieldType::Number => value.is_number(),
+ PluginFormFieldType::Boolean => value.is_boolean(),
+ };
+ if valid {
+ Ok(())
+ } else {
+ Err(format!("Plugin connection field '{}' has an invalid value type", field.label))
+ }
+}
+
+fn plugin_connection_test_result(
+ result: serde_json::Value,
+ provider_label: &str,
+) -> Result<ConnectionTestResult, String> {
+ if let Some(success) = result.get("success").and_then(serde_json::Value::as_bool) {
+ let message = result.get("message").and_then(serde_json::Value::as_str).unwrap_or(if success {
+ "Connection successful"
+ } else {
+ "Connection failed"
+ });
+ if !success {
+ return Err(message.to_string());
+ }
+ return Ok(ConnectionTestResult::success(message));
+ }
+ if let Some(message) = result.as_str() {
+ return Ok(ConnectionTestResult::success(message));
+ }
+ if result.is_null() {
+ return Ok(ConnectionTestResult::success(format!("{provider_label} connection successful")));
+ }
+ serde_json::from_value(result)
+ .map_err(|error| format!("Plugin connection test returned an invalid result: {error}"))
+}
+
+fn ensure_plugin_operation_succeeded(result: serde_json::Value) -> Result<(), String> {
+ if result.get("success").and_then(serde_json::Value::as_bool) == Some(false) {
+ return Err(result
+ .get("message")
+ .and_then(serde_json::Value::as_str)
+ .unwrap_or("Plugin connection operation failed")
+ .to_string());
+ }
+ Ok(())
+}
+
+fn ensure_permission(plugin: &super::InstalledPlugin, required_permission: Option<&str>) -> Result<(), String> {
+ let Some(permission) = required_permission else {
+ return Ok(());
+ };
+ if plugin.manifest.permissions.iter().any(|declared| declared == permission) {
+ return Ok(());
+ }
+ Err(format!("Plugin '{}' has not declared permission '{permission}'", plugin.manifest.id))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{
+ plugin_connection_action_result, plugin_invoke_connection_action, validate_plugin_connection_values,
+ validate_plugin_connection_values_for_action,
+ };
+ use crate::models::connection::ConnectionConfig;
+ use crate::plugins::PluginConnectionProviderContribution;
+
+ #[test]
+ fn rejects_zero_port_for_port_bound_connection_field() {
+ let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
+ "id": "plugin-connection",
+ "name": "Plugin connection",
+ "db_type": "plugin",
+ "host": "localhost",
+ "port": 0,
+ "username": "",
+ "password": "",
+ "database": null,
+ "plugin_id": "sample",
+ "plugin_connection_provider": "sample.connection",
+ "plugin_connection_type": "sample"
+ }))
+ .unwrap();
+ let provider: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
+ "id": "sample.connection",
+ "label": "Sample",
+ "database_type": "sample",
+ "fields": [{ "key": "port", "label": "Port", "type": "number", "binding": "port", "required": true }]
+ }))
+ .unwrap();
+
+ assert!(validate_plugin_connection_values(&config, &provider)
+ .unwrap_err()
+ .contains("port between 1 and 65535"));
+ }
+
+ #[test]
+ fn allows_incomplete_fields_only_for_declared_permissive_actions() {
+ let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
+ "id": "plugin-connection",
+ "name": "Plugin connection",
+ "db_type": "plugin",
+ "host": "",
+ "port": 0,
+ "username": "",
+ "password": "",
+ "database": null,
+ "plugin_id": "sample",
+ "plugin_connection_provider": "sample.connection",
+ "plugin_connection_type": "sample"
+ }))
+ .unwrap();
+ let provider: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
+ "id": "sample.connection",
+ "label": "Sample",
+ "database_type": "sample",
+ "fields": [{ "key": "host", "label": "Host", "type": "text", "binding": "host", "required": true }]
+ }))
+ .unwrap();
+
+ assert!(validate_plugin_connection_values_for_action(&config, &provider, false).is_ok());
+ assert!(validate_plugin_connection_values_for_action(&config, &provider, true)
+ .unwrap_err()
+ .contains("is required"));
+ }
+
+ #[test]
+ fn resolves_only_declared_custom_actions() {
+ let provider: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
+ "id": "sample.connection",
+ "label": "Sample",
+ "database_type": "sample",
+ "fields": [],
+ "actions": [{ "id": "discover", "label": "Discover" }]
+ }))
+ .unwrap();
+
+ assert_eq!(plugin_invoke_connection_action(&provider, "discover").unwrap().id, "discover");
+ assert!(plugin_invoke_connection_action(&provider, "missing").unwrap_err().contains("does not declare action"));
+ }
+
+ #[test]
+ fn validates_connection_action_field_updates() {
+ let provider: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
+ "id": "sample.connection",
+ "label": "Sample",
+ "database_type": "sample",
+ "fields": [
+ { "key": "host", "label": "Host", "type": "text", "binding": "host" },
+ { "key": "port", "label": "Port", "type": "number", "binding": "port" }
+ ]
+ }))
+ .unwrap();
+
+ let result = plugin_connection_action_result(
+ serde_json::json!({ "message": "Updated", "fieldValues": { "host": "db.internal", "port": 5432 } }),
+ &provider,
+ )
+ .unwrap();
+ assert_eq!(result.message.as_deref(), Some("Updated"));
+ assert_eq!(result.field_values.get("port").and_then(serde_json::Value::as_u64), Some(5432));
+ assert!(plugin_connection_action_result(
+ serde_json::json!({ "fieldValues": { "unknown": "value" } }),
+ &provider,
+ )
+ .unwrap_err()
+ .contains("undeclared field"));
+ assert!(plugin_connection_action_result(serde_json::json!({ "fieldValues": { "port": "5432" } }), &provider,)
+ .unwrap_err()
+ .contains("invalid value type"));
+ }
+}
diff --git a/crates/dbx-core/src/plugins/installer.rs b/crates/dbx-core/src/plugins/installer.rs
new file mode 100644
index 0000000000..47c73d89ab
--- /dev/null
+++ b/crates/dbx-core/src/plugins/installer.rs
@@ -0,0 +1,1255 @@
+use std::collections::{BTreeMap, BTreeSet, HashSet};
+use std::fs::{File, OpenOptions};
+use std::io::{Cursor, Read, Write};
+use std::path::{Component, Path, PathBuf};
+use std::sync::Arc;
+
+use base64::Engine;
+use chrono::Utc;
+use ed25519_dalek::{Signature, Verifier, VerifyingKey};
+use fs2::FileExt;
+use semver::Version;
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+
+use super::{InstalledPlugin, InstalledPluginInfo, PluginManifest};
+
+pub const DBXP_EXTENSION: &str = "dbxp";
+pub const PLUGIN_CHECKSUMS_FILE: &str = "checksums.json";
+pub const PLUGIN_SIGNATURE_FILE: &str = "signature.json";
+
+pub const MAX_PLUGIN_PACKAGE_BYTES: usize = 512 * 1024 * 1024;
+const MAX_UNCOMPRESSED_BYTES: u64 = 1024 * 1024 * 1024;
+const MAX_FILE_BYTES: u64 = 256 * 1024 * 1024;
+const MAX_ARCHIVE_ENTRIES: usize = 10_000;
+const INSTALL_LOCK_FILE: &str = ".install.lock";
+const VERSIONS_DIR: &str = "versions";
+const ACTIVATIONS_DIR: &str = "activations";
+const TRUST_DIR: &str = ".trust";
+const TRUST_KEYS_FILE: &str = "keys.json";
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum PluginInstallPolicy {
+ LocalSigned,
+ LocalDevelopment,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(tag = "status", rename_all = "snake_case")]
+pub enum PluginSignatureStatus {
+ Trusted { key_id: String },
+ Unsigned,
+}
+
+#[derive(Debug, Clone)]
+pub struct PluginInstallResult {
+ pub plugin: InstalledPlugin,
+ pub previous_version: Option<String>,
+ pub package_sha256: String,
+ pub signature: PluginSignatureStatus,
+}
+
+#[derive(Debug, Clone)]
+pub struct PluginRollbackResult {
+ pub plugin: InstalledPlugin,
+ pub previous_version: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginInstallResponse {
+ pub plugin: InstalledPluginInfo,
+ pub previous_version: Option<String>,
+ pub package_sha256: String,
+ pub signature: PluginSignatureStatus,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginRollbackResponse {
+ pub plugin: InstalledPluginInfo,
+ pub previous_version: String,
+}
+
+impl PluginInstallResult {
+ pub fn response(&self) -> PluginInstallResponse {
+ PluginInstallResponse {
+ plugin: self.plugin.info(),
+ previous_version: self.previous_version.clone(),
+ package_sha256: self.package_sha256.clone(),
+ signature: self.signature.clone(),
+ }
+ }
+}
+
+impl PluginRollbackResult {
+ pub fn response(&self) -> PluginRollbackResponse {
+ PluginRollbackResponse { plugin: self.plugin.info(), previous_version: self.previous_version.clone() }
+ }
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct PluginTrustStore {
+ keys: BTreeMap<String, VerifyingKey>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginTrustedKey {
+ pub key_id: String,
+ pub public_key: String,
+}
+
+#[derive(Debug, Deserialize, Serialize, Default)]
+struct PluginTrustDocument {
+ #[serde(default)]
+ keys: BTreeMap<String, String>,
+}
+
+#[derive(Debug, Deserialize)]
+struct PluginPackageChecksums {
+ algorithm: String,
+ files: BTreeMap<String, String>,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+struct PluginPackageSignature {
+ algorithm: String,
+ key_id: String,
+ signature: String,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PluginActivationRecord {
+ sequence: u64,
+ version: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ previous_version: Option<String>,
+ package_sha256: String,
+ activated_at: String,
+}
+
+pub struct PluginPackageInstaller {
+ root_dir: PathBuf,
+ app_version: String,
+ trust_store: Arc<PluginTrustStore>,
+}
+
+#[derive(Debug, Clone)]
+pub(super) struct PluginPackageExpectation {
+ pub id: String,
+ pub version: String,
+ pub publisher: String,
+ pub permissions: BTreeSet<String>,
+ pub signing_key_id: String,
+}
+
+impl PluginTrustStore {
+ pub fn load(root_dir: &Path) -> Result<Self, String> {
+ let document = read_trust_document(root_dir)?;
+ Self::from_base64_keys(document.keys)
+ }
+
+ pub fn list_base64_keys(root_dir: &Path) -> Result<Vec<PluginTrustedKey>, String> {
+ let document = read_trust_document(root_dir)?;
+ Self::from_base64_keys(document.keys.clone())?;
+ Ok(document
+ .keys
+ .into_iter()
+ .map(|(key_id, public_key)| PluginTrustedKey { key_id, public_key: public_key.trim().to_string() })
+ .collect())
+ }
+
+ pub fn from_base64_keys(keys: BTreeMap<String, String>) -> Result<Self, String> {
+ let mut parsed = BTreeMap::new();
+ for (key_id, encoded) in keys {
+ validate_key_id(&key_id)?;
+ let bytes = base64::engine::general_purpose::STANDARD
+ .decode(encoded.trim())
+ .map_err(|error| format!("Invalid trusted plugin key '{key_id}': {error}"))?;
+ let bytes: [u8; 32] =
+ bytes.try_into().map_err(|_| format!("Trusted plugin key '{key_id}' must contain 32 bytes"))?;
+ let key = VerifyingKey::from_bytes(&bytes)
+ .map_err(|error| format!("Invalid trusted plugin key '{key_id}': {error}"))?;
+ parsed.insert(key_id, key);
+ }
+ Ok(Self { keys: parsed })
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.keys.is_empty()
+ }
+
+ pub fn save_base64_key(root_dir: &Path, key_id: &str, public_key: &str) -> Result<(), String> {
+ validate_key_id(key_id)?;
+ let lock = open_install_lock(root_dir)?;
+ lock.lock_exclusive().map_err(|error| format!("Failed to lock plugin store: {error}"))?;
+ let result = (|| {
+ let path = plugin_trust_keys_path(root_dir);
+ let mut document = read_trust_document(root_dir)?;
+ let public_key = public_key.trim();
+ if document.keys.get(key_id).is_some_and(|existing| existing.trim() != public_key) {
+ return Err(format!(
+ "Trusted plugin key '{key_id}' already exists with a different public key; remove it before rotating"
+ ));
+ }
+ let mut candidate = document.keys.clone();
+ candidate.insert(key_id.to_string(), public_key.to_string());
+ Self::from_base64_keys(candidate)?;
+ document.keys.insert(key_id.to_string(), public_key.to_string());
+ write_json_atomically(&path, &document)
+ })();
+ let _ = FileExt::unlock(&lock);
+ result
+ }
+
+ pub fn remove_key(root_dir: &Path, key_id: &str) -> Result<(), String> {
+ validate_key_id(key_id)?;
+ let lock = open_install_lock(root_dir)?;
+ lock.lock_exclusive().map_err(|error| format!("Failed to lock plugin store: {error}"))?;
+ let result = (|| {
+ let path = plugin_trust_keys_path(root_dir);
+ let mut document = read_trust_document(root_dir)?;
+ document.keys.remove(key_id);
+ write_json_atomically(&path, &document)
+ })();
+ let _ = FileExt::unlock(&lock);
+ result
+ }
+
+ fn verify(&self, signature: &PluginPackageSignature, payload: &[u8]) -> Result<PluginSignatureStatus, String> {
+ if signature.algorithm != "ed25519" {
+ return Err(format!("Unsupported plugin signature algorithm '{}'", signature.algorithm));
+ }
+ let key = self
+ .keys
+ .get(&signature.key_id)
+ .ok_or_else(|| format!("Plugin package is signed by untrusted key '{}'", signature.key_id))?;
+ let key_id = signature.key_id.clone();
+ let signature_bytes = base64::engine::general_purpose::STANDARD
+ .decode(signature.signature.trim())
+ .map_err(|error| format!("Invalid plugin package signature: {error}"))?;
+ let signature = Signature::from_slice(&signature_bytes)
+ .map_err(|error| format!("Invalid plugin package signature: {error}"))?;
+ key.verify(payload, &signature).map_err(|_| "Plugin package signature verification failed".to_string())?;
+ Ok(PluginSignatureStatus::Trusted { key_id })
+ }
+}
+
+fn plugin_trust_keys_path(root_dir: &Path) -> PathBuf {
+ root_dir.join(TRUST_DIR).join(TRUST_KEYS_FILE)
+}
+
+fn read_trust_document(root_dir: &Path) -> Result<PluginTrustDocument, String> {
+ let path = plugin_trust_keys_path(root_dir);
+ let raw = match std::fs::read(&path) {
+ Ok(raw) => raw,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(PluginTrustDocument::default()),
+ Err(error) => return Err(format!("Failed to read plugin trust store {}: {error}", path.display())),
+ };
+ serde_json::from_slice(&raw)
+ .map_err(|error| format!("Failed to parse plugin trust store {}: {error}", path.display()))
+}
+
+impl PluginPackageInstaller {
+ pub fn new(root_dir: PathBuf, app_version: impl Into<String>) -> Result<Self, String> {
+ let trust_store = PluginTrustStore::load(&root_dir)?;
+ Ok(Self { root_dir, app_version: app_version.into(), trust_store: Arc::new(trust_store) })
+ }
+
+ pub fn with_trust_store(root_dir: PathBuf, app_version: impl Into<String>, trust_store: PluginTrustStore) -> Self {
+ Self { root_dir, app_version: app_version.into(), trust_store: Arc::new(trust_store) }
+ }
+
+ pub fn install_file(
+ &self,
+ package_path: &Path,
+ policy: PluginInstallPolicy,
+ ) -> Result<PluginInstallResult, String> {
+ if package_path.extension().and_then(|extension| extension.to_str()) != Some(DBXP_EXTENSION) {
+ return Err(format!("Plugin package must use the .{DBXP_EXTENSION} extension"));
+ }
+ let metadata = std::fs::metadata(package_path)
+ .map_err(|error| format!("Failed to inspect plugin package {}: {error}", package_path.display()))?;
+ if metadata.len() > MAX_PLUGIN_PACKAGE_BYTES as u64 {
+ return Err(format!("Plugin package exceeds {MAX_PLUGIN_PACKAGE_BYTES} bytes"));
+ }
+ let bytes = std::fs::read(package_path)
+ .map_err(|error| format!("Failed to read plugin package {}: {error}", package_path.display()))?;
+ self.install_bytes(&bytes, policy)
+ }
+
+ pub fn install_bytes(&self, package: &[u8], policy: PluginInstallPolicy) -> Result<PluginInstallResult, String> {
+ self.install_bytes_with_expectation(package, policy, None)
+ }
+
+ pub(super) fn install_marketplace_bytes(
+ &self,
+ package: &[u8],
+ expectation: &PluginPackageExpectation,
+ ) -> Result<PluginInstallResult, String> {
+ self.install_bytes_with_expectation(package, PluginInstallPolicy::LocalSigned, Some(expectation))
+ }
+
+ fn install_bytes_with_expectation(
+ &self,
+ package: &[u8],
+ policy: PluginInstallPolicy,
+ expectation: Option<&PluginPackageExpectation>,
+ ) -> Result<PluginInstallResult, String> {
+ if package.len() > MAX_PLUGIN_PACKAGE_BYTES {
+ return Err(format!("Plugin package exceeds {MAX_PLUGIN_PACKAGE_BYTES} bytes"));
+ }
+ std::fs::create_dir_all(&self.root_dir).map_err(|error| error.to_string())?;
+ let lock = open_install_lock(&self.root_dir)?;
+ lock.lock_exclusive().map_err(|error| format!("Failed to lock plugin store: {error}"))?;
+ let result = self.install_bytes_locked(package, policy, expectation);
+ let _ = FileExt::unlock(&lock);
+ result
+ }
+
+ pub fn rollback(&self, plugin_id: &str) -> Result<PluginRollbackResult, String> {
+ validate_plugin_id(plugin_id)?;
+ std::fs::create_dir_all(&self.root_dir).map_err(|error| error.to_string())?;
+ let lock = open_install_lock(&self.root_dir)?;
+ lock.lock_exclusive().map_err(|error| format!("Failed to lock plugin store: {error}"))?;
+ let result = self.rollback_locked(plugin_id);
+ let _ = FileExt::unlock(&lock);
+ result
+ }
+
+ pub fn uninstall(&self, plugin_id: &str) -> Result<(), String> {
+ validate_plugin_id(plugin_id)?;
+ let lock = open_install_lock(&self.root_dir)?;
+ lock.lock_exclusive().map_err(|error| format!("Failed to lock plugin store: {error}"))?;
+ let plugin_dir = self.root_dir.join(plugin_id);
+ let result = match std::fs::remove_dir_all(&plugin_dir) {
+ Ok(()) => Ok(()),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(format!("Failed to uninstall plugin '{plugin_id}': {error}")),
+ };
+ let _ = FileExt::unlock(&lock);
+ result
+ }
+
+ fn install_bytes_locked(
+ &self,
+ package: &[u8],
+ policy: PluginInstallPolicy,
+ expectation: Option<&PluginPackageExpectation>,
+ ) -> Result<PluginInstallResult, String> {
+ let package_sha256 = sha256_hex(package);
+ let staging = tempfile::Builder::new()
+ .prefix(".dbxp-staging-")
+ .tempdir_in(&self.root_dir)
+ .map_err(|error| format!("Failed to create plugin staging directory: {error}"))?;
+ let package_dir = staging.path().join("package");
+ std::fs::create_dir(&package_dir).map_err(|error| error.to_string())?;
+ let extracted = extract_package(package, &package_dir)?;
+ let checksums_path = package_dir.join(PLUGIN_CHECKSUMS_FILE);
+ let checksums_raw = std::fs::read(&checksums_path)
+ .map_err(|error| format!("Plugin package is missing {PLUGIN_CHECKSUMS_FILE}: {error}"))?;
+ verify_package_checksums(&package_dir, &extracted, &checksums_raw)?;
+ let signature = verify_package_signature(&package_dir, &checksums_raw, policy, &self.trust_store)?;
+
+ let manifest_path = package_dir.join("manifest.json");
+ let manifest_raw = std::fs::read(&manifest_path)
+ .map_err(|error| format!("Plugin package is missing manifest.json: {error}"))?;
+ let manifest: PluginManifest = serde_json::from_slice(&manifest_raw)
+ .map_err(|error| format!("Failed to parse plugin manifest: {error}"))?;
+ if manifest.manifest_version == 0 {
+ return Err(".dbxp packages must use plugin manifest version 1 or newer".to_string());
+ }
+ validate_plugin_id(&manifest.id)?;
+ let version = Version::parse(&manifest.version)
+ .map_err(|error| format!("Plugin version '{}' is invalid: {error}", manifest.version))?;
+ let compatibility = manifest.compatibility(&package_dir, &self.app_version);
+ if !compatibility.compatible {
+ return Err(format!("Plugin '{}' is incompatible: {}", manifest.id, compatibility.errors.join("; ")));
+ }
+ if let Some(expectation) = expectation {
+ validate_package_expectation(&manifest, &signature, expectation)?;
+ }
+ make_backend_executable(&compatibility.backend_executable)?;
+
+ let container_dir = self.root_dir.join(&manifest.id);
+ migrate_legacy_container(&container_dir)?;
+ let versions_dir = container_dir.join(VERSIONS_DIR);
+ let activations_dir = container_dir.join(ACTIVATIONS_DIR);
+ std::fs::create_dir_all(&versions_dir).map_err(|error| error.to_string())?;
+ std::fs::create_dir_all(&activations_dir).map_err(|error| error.to_string())?;
+ let version_dir = versions_dir.join(version.to_string());
+ if version_dir.exists() && !matches!(policy, PluginInstallPolicy::LocalDevelopment) {
+ return Err(format!("Plugin '{}' version {} is already installed", manifest.id, version));
+ }
+ let current = read_latest_activation(&container_dir)?;
+ let version_string = version.to_string();
+ let previous_version = current.as_ref().and_then(|record| {
+ if record.version == version_string {
+ record.previous_version.clone()
+ } else {
+ Some(record.version.clone())
+ }
+ });
+ let replaced_version_dir = if version_dir.exists() {
+ let mut backup = versions_dir.join(format!(".{version_string}.replaced"));
+ let mut suffix = 0u32;
+ while backup.exists() {
+ suffix = suffix.saturating_add(1);
+ backup = versions_dir.join(format!(".{version_string}.replaced-{suffix}"));
+ }
+ std::fs::rename(&version_dir, &backup).map_err(|error| {
+ format!("Failed to prepare plugin '{}' version {} replacement: {error}", manifest.id, version)
+ })?;
+ Some(backup)
+ } else {
+ None
+ };
+ if let Err(error) = std::fs::rename(&package_dir, &version_dir) {
+ if let Some(backup) = &replaced_version_dir {
+ let _ = std::fs::rename(backup, &version_dir);
+ }
+ return Err(format!("Failed to store plugin '{}' version {}: {error}", manifest.id, version));
+ }
+
+ let activation = PluginActivationRecord {
+ sequence: current.as_ref().map_or(1, |record| record.sequence.saturating_add(1)),
+ version: version_string,
+ previous_version: previous_version.clone(),
+ package_sha256: package_sha256.clone(),
+ activated_at: Utc::now().to_rfc3339(),
+ };
+ if let Err(error) = write_activation_record(&container_dir, &activation) {
+ let _ = std::fs::remove_dir_all(&version_dir);
+ if let Some(backup) = &replaced_version_dir {
+ let _ = std::fs::rename(backup, &version_dir);
+ }
+ return Err(error);
+ }
+ if let Some(backup) = replaced_version_dir {
+ if let Err(error) = std::fs::remove_dir_all(backup) {
+ log::warn!("Failed to remove replaced plugin version backup: {error}");
+ }
+ }
+ if let Err(error) = prune_plugin_history(&container_dir, &activation) {
+ log::warn!("Failed to prune plugin '{}' install history: {error}", manifest.id);
+ }
+ let plugin = InstalledPlugin::new(manifest, version_dir, &self.app_version);
+ Ok(PluginInstallResult { plugin, previous_version, package_sha256, signature })
+ }
+
+ fn rollback_locked(&self, plugin_id: &str) -> Result<PluginRollbackResult, String> {
+ let container_dir = self.root_dir.join(plugin_id);
+ let current = read_latest_activation(&container_dir)?
+ .ok_or_else(|| format!("Plugin '{plugin_id}' does not have an active version"))?;
+ let previous_version = current
+ .previous_version
+ .clone()
+ .ok_or_else(|| format!("Plugin '{plugin_id}' does not have a rollback version"))?;
+ let version_dir = container_dir.join(VERSIONS_DIR).join(&previous_version);
+ let manifest_path = version_dir.join("manifest.json");
+ let manifest: PluginManifest = serde_json::from_slice(
+ &std::fs::read(&manifest_path)
+ .map_err(|error| format!("Rollback version {previous_version} is incomplete: {error}"))?,
+ )
+ .map_err(|error| format!("Rollback manifest is invalid: {error}"))?;
+ if manifest.id != plugin_id || manifest.version != previous_version {
+ return Err(format!("Rollback version {previous_version} does not match plugin '{plugin_id}'"));
+ }
+ let plugin = InstalledPlugin::new(manifest, version_dir, &self.app_version);
+ if !plugin.compatibility.compatible {
+ return Err(format!(
+ "Rollback version {previous_version} is incompatible: {}",
+ plugin.compatibility.errors.join("; ")
+ ));
+ }
+ let target_record = read_latest_activation_for_version(&container_dir, &previous_version)?;
+ let activation = PluginActivationRecord {
+ sequence: current.sequence.saturating_add(1),
+ version: previous_version.clone(),
+ previous_version: Some(current.version),
+ package_sha256: target_record
+ .map_or_else(|| "legacy-unmanaged".to_string(), |record| record.package_sha256),
+ activated_at: Utc::now().to_rfc3339(),
+ };
+ write_activation_record(&container_dir, &activation)?;
+ if let Err(error) = prune_plugin_history(&container_dir, &activation) {
+ log::warn!("Failed to prune plugin '{plugin_id}' rollback history: {error}");
+ }
+ Ok(PluginRollbackResult { plugin, previous_version })
+ }
+}
+
+pub(super) fn resolve_active_plugin_dir(container_dir: &Path) -> Result<Option<PathBuf>, String> {
+ if container_dir.join("manifest.json").is_file() {
+ return Ok(Some(container_dir.to_path_buf()));
+ }
+ let Some(activation) = read_latest_activation(container_dir)? else {
+ return Ok(None);
+ };
+ Version::parse(&activation.version)
+ .map_err(|error| format!("Plugin activation has invalid version '{}': {error}", activation.version))?;
+ let path = container_dir.join(VERSIONS_DIR).join(&activation.version);
+ if !path.join("manifest.json").is_file() {
+ return Err(format!("Active plugin version is incomplete: {}", path.display()));
+ }
+ Ok(Some(path))
+}
+
+fn extract_package(package: &[u8], destination: &Path) -> Result<HashSet<String>, String> {
+ let mut archive =
+ zip::ZipArchive::new(Cursor::new(package)).map_err(|error| format!("Invalid .dbxp archive: {error}"))?;
+ if archive.len() > MAX_ARCHIVE_ENTRIES {
+ return Err(format!("Plugin package contains more than {MAX_ARCHIVE_ENTRIES} entries"));
+ }
+ let mut extracted = HashSet::new();
+ let mut normalized_names = HashSet::new();
+ let mut total_size = 0u64;
+ for index in 0..archive.len() {
+ let mut entry = archive.by_index(index).map_err(|error| error.to_string())?;
+ let enclosed =
+ entry.enclosed_name().ok_or_else(|| format!("Plugin package contains unsafe path '{}'", entry.name()))?;
+ validate_package_path(&enclosed)?;
+ let path_key = path_key(&enclosed)?;
+ let normalized = path_key.to_ascii_lowercase();
+ if !normalized_names.insert(normalized) {
+ return Err(format!("Plugin package contains duplicate path '{path_key}'"));
+ }
+ if entry.is_dir() {
+ std::fs::create_dir_all(destination.join(&enclosed)).map_err(|error| error.to_string())?;
+ continue;
+ }
+ if entry.unix_mode().is_some_and(|mode| mode & 0o170000 == 0o120000) {
+ return Err(format!("Plugin package cannot contain symbolic link '{path_key}'"));
+ }
+ if entry.size() > MAX_FILE_BYTES {
+ return Err(format!("Plugin package file '{path_key}' exceeds {MAX_FILE_BYTES} bytes"));
+ }
+ total_size = total_size.checked_add(entry.size()).ok_or("Plugin package uncompressed size overflow")?;
+ if total_size > MAX_UNCOMPRESSED_BYTES {
+ return Err(format!("Plugin package expands beyond {MAX_UNCOMPRESSED_BYTES} bytes"));
+ }
+ let output = destination.join(&enclosed);
+ if let Some(parent) = output.parent() {
+ std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
+ }
+ let mut target = OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&output)
+ .map_err(|error| format!("Failed to extract '{path_key}': {error}"))?;
+ let copied = std::io::copy(&mut entry.by_ref().take(MAX_FILE_BYTES + 1), &mut target)
+ .map_err(|error| format!("Failed to extract '{path_key}': {error}"))?;
+ if copied > MAX_FILE_BYTES {
+ return Err(format!("Plugin package file '{path_key}' exceeds {MAX_FILE_BYTES} bytes"));
+ }
+ #[cfg(unix)]
+ if let Some(mode) = entry.unix_mode() {
+ use std::os::unix::fs::PermissionsExt;
+
+ std::fs::set_permissions(&output, std::fs::Permissions::from_mode(mode & 0o777))
+ .map_err(|error| error.to_string())?;
+ }
+ extracted.insert(path_key);
+ }
+ Ok(extracted)
+}
+
+fn verify_package_checksums(destination: &Path, extracted: &HashSet<String>, raw: &[u8]) -> Result<(), String> {
+ let checksums: PluginPackageChecksums =
+ serde_json::from_slice(raw).map_err(|error| format!("Failed to parse {PLUGIN_CHECKSUMS_FILE}: {error}"))?;
+ if checksums.algorithm != "sha256" {
+ return Err(format!("Unsupported plugin checksum algorithm '{}'", checksums.algorithm));
+ }
+ let expected_files = extracted
+ .iter()
+ .filter(|path| path.as_str() != PLUGIN_CHECKSUMS_FILE && path.as_str() != PLUGIN_SIGNATURE_FILE)
+ .cloned()
+ .collect::<HashSet<_>>();
+ let declared_files = checksums.files.keys().cloned().collect::<HashSet<_>>();
+ if expected_files != declared_files {
+ let missing = expected_files.difference(&declared_files).cloned().collect::<Vec<_>>();
+ let extra = declared_files.difference(&expected_files).cloned().collect::<Vec<_>>();
+ return Err(format!("Plugin checksums do not cover the package exactly; missing={missing:?}, extra={extra:?}"));
+ }
+ for (relative, expected) in checksums.files {
+ let path = safe_checksum_path(destination, &relative)?;
+ let actual = sha256_file(&path)?;
+ if !expected.eq_ignore_ascii_case(&actual) {
+ return Err(format!("Plugin checksum mismatch for '{relative}'"));
+ }
+ }
+ Ok(())
+}
+
+fn verify_package_signature(
+ destination: &Path,
+ checksums: &[u8],
+ policy: PluginInstallPolicy,
+ trust_store: &PluginTrustStore,
+) -> Result<PluginSignatureStatus, String> {
+ let signature_path = destination.join(PLUGIN_SIGNATURE_FILE);
+ match std::fs::read(&signature_path) {
+ Ok(raw) => {
+ let signature: PluginPackageSignature = serde_json::from_slice(&raw)
+ .map_err(|error| format!("Failed to parse {PLUGIN_SIGNATURE_FILE}: {error}"))?;
+ trust_store.verify(&signature, checksums)
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => match policy {
+ PluginInstallPolicy::LocalDevelopment => Ok(PluginSignatureStatus::Unsigned),
+ PluginInstallPolicy::LocalSigned => Err("Plugin package must have a trusted Ed25519 signature".to_string()),
+ },
+ Err(error) => Err(error.to_string()),
+ }
+}
+
+fn validate_package_expectation(
+ manifest: &PluginManifest,
+ signature: &PluginSignatureStatus,
+ expectation: &PluginPackageExpectation,
+) -> Result<(), String> {
+ if manifest.id != expectation.id {
+ return Err(format!("Marketplace package id '{}' does not match catalog id '{}'", manifest.id, expectation.id));
+ }
+ if manifest.version != expectation.version {
+ return Err(format!(
+ "Marketplace package version '{}' does not match catalog version '{}'",
+ manifest.version, expectation.version
+ ));
+ }
+ if manifest.publisher != expectation.publisher {
+ return Err(format!(
+ "Marketplace package publisher '{}' does not match catalog publisher '{}'",
+ manifest.publisher, expectation.publisher
+ ));
+ }
+ let permissions = manifest.permissions.iter().cloned().collect::<BTreeSet<_>>();
+ if permissions != expectation.permissions {
+ return Err(format!(
+ "Marketplace package permissions {:?} do not match catalog permissions {:?}",
+ permissions, expectation.permissions
+ ));
+ }
+ let PluginSignatureStatus::Trusted { key_id } = signature else {
+ return Err("Marketplace package must have a trusted signature".to_string());
+ };
+ if key_id != &expectation.signing_key_id {
+ return Err(format!(
+ "Marketplace package repository signing key '{}' does not match repository key '{}' declared by the catalog",
+ key_id, expectation.signing_key_id
+ ));
+ }
+ Ok(())
+}
+
+fn read_latest_activation(container_dir: &Path) -> Result<Option<PluginActivationRecord>, String> {
+ let activations_dir = container_dir.join(ACTIVATIONS_DIR);
+ let entries = match std::fs::read_dir(&activations_dir) {
+ Ok(entries) => entries,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => return Err(error.to_string()),
+ };
+ let mut latest: Option<PluginActivationRecord> = None;
+ for entry in entries {
+ let entry = entry.map_err(|error| error.to_string())?;
+ if !entry.file_type().map_err(|error| error.to_string())?.is_file() || !is_activation_record_file(&entry.path())
+ {
+ continue;
+ }
+ let raw = std::fs::read(entry.path()).map_err(|error| error.to_string())?;
+ let record: PluginActivationRecord = serde_json::from_slice(&raw)
+ .map_err(|error| format!("Invalid plugin activation {}: {error}", entry.path().display()))?;
+ if latest.as_ref().is_none_or(|current| record.sequence > current.sequence) {
+ latest = Some(record);
+ }
+ }
+ Ok(latest)
+}
+
+fn read_latest_activation_for_version(
+ container_dir: &Path,
+ version: &str,
+) -> Result<Option<PluginActivationRecord>, String> {
+ let activations_dir = container_dir.join(ACTIVATIONS_DIR);
+ let entries = match std::fs::read_dir(&activations_dir) {
+ Ok(entries) => entries,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => return Err(error.to_string()),
+ };
+ let mut latest: Option<PluginActivationRecord> = None;
+ for entry in entries {
+ let entry = entry.map_err(|error| error.to_string())?;
+ if !entry.file_type().map_err(|error| error.to_string())?.is_file() || !is_activation_record_file(&entry.path())
+ {
+ continue;
+ }
+ let record: PluginActivationRecord =
+ serde_json::from_slice(&std::fs::read(entry.path()).map_err(|error| error.to_string())?)
+ .map_err(|error| format!("Invalid plugin activation {}: {error}", entry.path().display()))?;
+ if record.version == version && latest.as_ref().is_none_or(|current| record.sequence > current.sequence) {
+ latest = Some(record);
+ }
+ }
+ Ok(latest)
+}
+
+fn prune_plugin_history(container_dir: &Path, current: &PluginActivationRecord) -> Result<(), String> {
+ let retained_versions =
+ std::iter::once(current.version.as_str()).chain(current.previous_version.as_deref()).collect::<HashSet<_>>();
+ let versions_dir = container_dir.join(VERSIONS_DIR);
+ if let Ok(entries) = std::fs::read_dir(&versions_dir) {
+ for entry in entries {
+ let entry = entry.map_err(|error| error.to_string())?;
+ if !entry.file_type().map_err(|error| error.to_string())?.is_dir() {
+ continue;
+ }
+ let version = entry.file_name();
+ let version = version.to_string_lossy();
+ if !retained_versions.contains(version.as_ref()) {
+ std::fs::remove_dir_all(entry.path()).map_err(|error| error.to_string())?;
+ }
+ }
+ sync_directory(&versions_dir)?;
+ }
+
+ let activations_dir = container_dir.join(ACTIVATIONS_DIR);
+ let entries = match std::fs::read_dir(&activations_dir) {
+ Ok(entries) => entries,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
+ Err(error) => return Err(error.to_string()),
+ };
+ let mut records = Vec::new();
+ let mut latest_sequences = BTreeMap::<String, u64>::new();
+ for entry in entries {
+ let entry = entry.map_err(|error| error.to_string())?;
+ if !entry.file_type().map_err(|error| error.to_string())?.is_file() || !is_activation_record_file(&entry.path())
+ {
+ continue;
+ }
+ let record: PluginActivationRecord =
+ serde_json::from_slice(&std::fs::read(entry.path()).map_err(|error| error.to_string())?)
+ .map_err(|error| format!("Invalid plugin activation {}: {error}", entry.path().display()))?;
+ if retained_versions.contains(record.version.as_str()) {
+ latest_sequences
+ .entry(record.version.clone())
+ .and_modify(|sequence| *sequence = (*sequence).max(record.sequence))
+ .or_insert(record.sequence);
+ }
+ records.push((entry.path(), record));
+ }
+ for (path, record) in records {
+ let keep = retained_versions.contains(record.version.as_str())
+ && latest_sequences.get(&record.version).is_some_and(|sequence| *sequence == record.sequence);
+ if !keep {
+ std::fs::remove_file(path).map_err(|error| error.to_string())?;
+ }
+ }
+ sync_directory(&activations_dir)
+}
+
+fn is_activation_record_file(path: &Path) -> bool {
+ let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
+ return false;
+ };
+ let Some(stem) = name.strip_suffix(".json") else {
+ return false;
+ };
+ let Some((sequence, unique)) = stem.split_once('-') else {
+ return false;
+ };
+ sequence.len() == 20 && sequence.bytes().all(|byte| byte.is_ascii_digit()) && !unique.is_empty()
+}
+
+fn migrate_legacy_container(container_dir: &Path) -> Result<(), String> {
+ let manifest_path = container_dir.join("manifest.json");
+ if !manifest_path.is_file() {
+ return Ok(());
+ }
+ let manifest: PluginManifest = serde_json::from_slice(
+ &std::fs::read(&manifest_path)
+ .map_err(|error| format!("Failed to read legacy plugin {}: {error}", manifest_path.display()))?,
+ )
+ .map_err(|error| format!("Failed to parse legacy plugin {}: {error}", manifest_path.display()))?;
+ let storage_version = Version::parse(&manifest.version)
+ .map(|version| version.to_string())
+ .unwrap_or_else(|_| format!("0.0.0-legacy.{}", &sha256_hex(manifest.version.as_bytes())[..12]));
+ let parent = container_dir.parent().ok_or("Plugin container has no parent")?;
+ let temporary = parent.join(format!(".legacy-{}-{}", manifest.id, uuid::Uuid::new_v4()));
+ std::fs::rename(container_dir, &temporary)
+ .map_err(|error| format!("Failed to stage legacy plugin '{}': {error}", manifest.id))?;
+ let versions_dir = container_dir.join(VERSIONS_DIR);
+ let activations_dir = container_dir.join(ACTIVATIONS_DIR);
+ let version_dir = versions_dir.join(&storage_version);
+ let migration = (|| {
+ std::fs::create_dir_all(&versions_dir).map_err(|error| error.to_string())?;
+ std::fs::create_dir_all(&activations_dir).map_err(|error| error.to_string())?;
+ std::fs::rename(&temporary, &version_dir).map_err(|error| error.to_string())?;
+ write_activation_record(
+ container_dir,
+ &PluginActivationRecord {
+ sequence: 1,
+ version: storage_version,
+ previous_version: None,
+ package_sha256: "legacy-unmanaged".to_string(),
+ activated_at: Utc::now().to_rfc3339(),
+ },
+ )
+ })();
+ if let Err(error) = migration {
+ let _ = std::fs::remove_dir_all(container_dir);
+ let _ = std::fs::rename(&temporary, container_dir);
+ return Err(format!("Failed to migrate legacy plugin '{}': {error}", manifest.id));
+ }
+ Ok(())
+}
+
+fn write_activation_record(container_dir: &Path, activation: &PluginActivationRecord) -> Result<(), String> {
+ let activations_dir = container_dir.join(ACTIVATIONS_DIR);
+ std::fs::create_dir_all(&activations_dir).map_err(|error| error.to_string())?;
+ let filename = format!("{:020}-{}.json", activation.sequence, uuid::Uuid::new_v4());
+ let final_path = activations_dir.join(filename);
+ let temporary_path = activations_dir.join(format!(".{}.tmp", uuid::Uuid::new_v4()));
+ let bytes = serde_json::to_vec_pretty(activation).map_err(|error| error.to_string())?;
+ let mut file =
+ OpenOptions::new().write(true).create_new(true).open(&temporary_path).map_err(|error| error.to_string())?;
+ file.write_all(&bytes).map_err(|error| error.to_string())?;
+ file.sync_all().map_err(|error| error.to_string())?;
+ std::fs::rename(&temporary_path, &final_path).map_err(|error| error.to_string())?;
+ sync_directory(&activations_dir)?;
+ Ok(())
+}
+
+fn write_json_atomically<T: Serialize>(path: &Path, value: &T) -> Result<(), String> {
+ let parent = path.parent().ok_or("Plugin trust store path has no parent")?;
+ std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
+ let temporary = parent.join(format!(".{}.tmp", uuid::Uuid::new_v4()));
+ let mut file =
+ OpenOptions::new().write(true).create_new(true).open(&temporary).map_err(|error| error.to_string())?;
+ file.write_all(&serde_json::to_vec_pretty(value).map_err(|error| error.to_string())?)
+ .map_err(|error| error.to_string())?;
+ file.sync_all().map_err(|error| error.to_string())?;
+ if path.exists() {
+ std::fs::remove_file(path).map_err(|error| error.to_string())?;
+ }
+ std::fs::rename(&temporary, path).map_err(|error| error.to_string())?;
+ sync_directory(parent)
+}
+
+fn open_install_lock(root_dir: &Path) -> Result<File, String> {
+ std::fs::create_dir_all(root_dir).map_err(|error| error.to_string())?;
+ OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(root_dir.join(INSTALL_LOCK_FILE))
+ .map_err(|error| error.to_string())
+}
+
+fn make_backend_executable(path: &Option<PathBuf>) -> Result<(), String> {
+ #[cfg(unix)]
+ if let Some(path) = path {
+ use std::os::unix::fs::PermissionsExt;
+
+ let mut permissions = std::fs::metadata(path).map_err(|error| error.to_string())?.permissions();
+ permissions.set_mode(permissions.mode() | 0o700);
+ std::fs::set_permissions(path, permissions).map_err(|error| error.to_string())?;
+ }
+ Ok(())
+}
+
+fn safe_checksum_path(root: &Path, relative: &str) -> Result<PathBuf, String> {
+ let path = Path::new(relative);
+ validate_package_path(path)?;
+ Ok(root.join(path))
+}
+
+fn validate_package_path(path: &Path) -> Result<(), String> {
+ if path.as_os_str().is_empty() || path.is_absolute() {
+ return Err("Plugin package paths must be non-empty and relative".to_string());
+ }
+ if path.components().any(|component| !matches!(component, Component::Normal(_))) {
+ return Err(format!("Plugin package contains unsafe path '{}'", path.display()));
+ }
+ Ok(())
+}
+
+fn path_key(path: &Path) -> Result<String, String> {
+ validate_package_path(path)?;
+ path.components()
+ .map(|component| match component {
+ Component::Normal(value) => value
+ .to_str()
+ .map(str::to_string)
+ .ok_or_else(|| format!("Plugin package path is not UTF-8: {}", path.display())),
+ _ => unreachable!(),
+ })
+ .collect::<Result<Vec<_>, _>>()
+ .map(|parts| parts.join("/"))
+}
+
+fn validate_plugin_id(plugin_id: &str) -> Result<(), String> {
+ if plugin_id.is_empty() || plugin_id.len() > 128 {
+ return Err("Plugin id must be between 1 and 128 bytes".to_string());
+ }
+ let mut chars = plugin_id.chars();
+ if !matches!(chars.next(), Some(first) if first.is_ascii_lowercase() || first.is_ascii_digit())
+ || !chars.all(|character| {
+ character.is_ascii_lowercase() || character.is_ascii_digit() || matches!(character, '.' | '-' | '_')
+ })
+ {
+ return Err("Plugin id must contain only lowercase letters, digits, '.', '-' or '_'".to_string());
+ }
+ Ok(())
+}
+
+pub(super) fn validate_key_id(key_id: &str) -> Result<(), String> {
+ if key_id.is_empty()
+ || key_id.len() > 128
+ || !key_id
+ .chars()
+ .all(|character| character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_' | ':'))
+ {
+ return Err("Plugin signing key id contains unsupported characters".to_string());
+ }
+ Ok(())
+}
+
+fn sha256_file(path: &Path) -> Result<String, String> {
+ let mut file = File::open(path).map_err(|error| error.to_string())?;
+ let mut digest = Sha256::new();
+ let mut buffer = [0u8; 64 * 1024];
+ loop {
+ let read = file.read(&mut buffer).map_err(|error| error.to_string())?;
+ if read == 0 {
+ break;
+ }
+ digest.update(&buffer[..read]);
+ }
+ Ok(hex_digest(digest.finalize()))
+}
+
+fn sha256_hex(bytes: &[u8]) -> String {
+ hex_digest(Sha256::digest(bytes))
+}
+
+fn hex_digest(bytes: impl AsRef<[u8]>) -> String {
+ use std::fmt::Write as _;
+
+ bytes.as_ref().iter().fold(String::with_capacity(64), |mut output, byte| {
+ let _ = write!(output, "{byte:02x}");
+ output
+ })
+}
+
+#[cfg(unix)]
+fn sync_directory(path: &Path) -> Result<(), String> {
+ File::open(path).and_then(|directory| directory.sync_all()).map_err(|error| error.to_string())
+}
+
+#[cfg(not(unix))]
+fn sync_directory(_path: &Path) -> Result<(), String> {
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::{BTreeMap, BTreeSet};
+ use std::io::{Cursor, Write};
+
+ use base64::Engine;
+ use ed25519_dalek::{Signer, SigningKey};
+ use zip::write::SimpleFileOptions;
+
+ use super::{
+ is_activation_record_file, sha256_hex, validate_package_expectation, PluginInstallPolicy,
+ PluginPackageExpectation, PluginPackageInstaller, PluginSignatureStatus, PluginTrustStore, ACTIVATIONS_DIR,
+ PLUGIN_CHECKSUMS_FILE, PLUGIN_SIGNATURE_FILE, VERSIONS_DIR,
+ };
+ use crate::plugins::{PluginManifest, PluginRegistry};
+
+ #[test]
+ fn installs_versioned_package_and_rolls_back_atomically() {
+ let root = tempfile::tempdir().unwrap();
+ let installer =
+ PluginPackageInstaller::with_trust_store(root.path().to_path_buf(), "0.5.67", PluginTrustStore::default());
+ let first = package("1.0.0", None, false);
+ let second = package("1.1.0", None, false);
+ installer.install_bytes(&first, PluginInstallPolicy::LocalDevelopment).unwrap();
+ let installed = installer.install_bytes(&second, PluginInstallPolicy::LocalDevelopment).unwrap();
+ assert_eq!(installed.previous_version.as_deref(), Some("1.0.0"));
+
+ let registry = PluginRegistry::new_with_app_version(root.path().to_path_buf(), "0.5.67");
+ assert_eq!(registry.find_plugin("sample.hello").unwrap().unwrap().manifest.version, "1.1.0");
+
+ let rollback = installer.rollback("sample.hello").unwrap();
+ assert_eq!(rollback.previous_version, "1.0.0");
+ assert_eq!(registry.find_plugin("sample.hello").unwrap().unwrap().manifest.version, "1.0.0");
+ }
+
+ #[test]
+ fn local_development_reinstalls_same_version_without_creating_a_self_rollback() {
+ let root = tempfile::tempdir().unwrap();
+ let installer =
+ PluginPackageInstaller::with_trust_store(root.path().to_path_buf(), "0.5.67", PluginTrustStore::default());
+ let package = package("1.0.0", None, false);
+
+ installer.install_bytes(&package, PluginInstallPolicy::LocalDevelopment).unwrap();
+ let reinstalled = installer.install_bytes(&package, PluginInstallPolicy::LocalDevelopment).unwrap();
+
+ assert_eq!(reinstalled.previous_version, None);
+ let registry = PluginRegistry::new_with_app_version(root.path().to_path_buf(), "0.5.67");
+ assert_eq!(registry.find_plugin("sample.hello").unwrap().unwrap().manifest.version, "1.0.0");
+ assert_eq!(std::fs::read_dir(root.path().join("sample.hello").join(VERSIONS_DIR)).unwrap().count(), 1);
+ }
+
+ #[test]
+ fn retains_only_active_and_rollback_versions() {
+ let root = tempfile::tempdir().unwrap();
+ let installer =
+ PluginPackageInstaller::with_trust_store(root.path().to_path_buf(), "0.5.67", PluginTrustStore::default());
+ for version in ["1.0.0", "1.1.0", "1.2.0"] {
+ installer.install_bytes(&package(version, None, false), PluginInstallPolicy::LocalDevelopment).unwrap();
+ }
+
+ let container = root.path().join("sample.hello");
+ let mut versions = std::fs::read_dir(container.join(VERSIONS_DIR))
+ .unwrap()
+ .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
+ .collect::<Vec<_>>();
+ versions.sort();
+ assert_eq!(versions, ["1.1.0", "1.2.0"]);
+ assert_eq!(
+ std::fs::read_dir(container.join(ACTIVATIONS_DIR))
+ .unwrap()
+ .filter(|entry| entry.as_ref().is_ok_and(|entry| is_activation_record_file(&entry.path())))
+ .count(),
+ 2
+ );
+
+ let rollback = installer.rollback("sample.hello").unwrap();
+ assert_eq!(rollback.plugin.manifest.version, "1.1.0");
+ assert_eq!(rollback.previous_version, "1.1.0");
+ }
+
+ #[test]
+ fn ignores_interrupted_activation_temp_files() {
+ let root = tempfile::tempdir().unwrap();
+ let installer =
+ PluginPackageInstaller::with_trust_store(root.path().to_path_buf(), "0.5.67", PluginTrustStore::default());
+ installer.install_bytes(&package("1.0.0", None, false), PluginInstallPolicy::LocalDevelopment).unwrap();
+ let activations = root.path().join("sample.hello").join("activations");
+ std::fs::write(activations.join(".interrupted.tmp"), b"{").unwrap();
+ std::fs::write(activations.join("README.txt"), b"not an activation").unwrap();
+
+ let registry = PluginRegistry::new_with_app_version(root.path().to_path_buf(), "0.5.67");
+
+ assert_eq!(registry.find_plugin("sample.hello").unwrap().unwrap().manifest.version, "1.0.0");
+ }
+
+ #[test]
+ fn installing_v1_migrates_legacy_flat_plugin_and_preserves_rollback() {
+ let root = tempfile::tempdir().unwrap();
+ let legacy = root.path().join("sample.hello");
+ std::fs::create_dir_all(legacy.join("bin")).unwrap();
+ std::fs::write(legacy.join("bin/plugin"), b"legacy").unwrap();
+ std::fs::write(
+ legacy.join("manifest.json"),
+ serde_json::to_vec_pretty(&serde_json::json!({
+ "id": "sample.hello",
+ "name": "Hello legacy",
+ "version": "0.9.0",
+ "protocol_version": 1,
+ "executable": "bin/plugin",
+ "drivers": []
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+
+ let installer =
+ PluginPackageInstaller::with_trust_store(root.path().to_path_buf(), "0.5.67", PluginTrustStore::default());
+ let installed =
+ installer.install_bytes(&package("1.0.0", None, false), PluginInstallPolicy::LocalDevelopment).unwrap();
+
+ assert_eq!(installed.previous_version.as_deref(), Some("0.9.0"));
+ let registry = PluginRegistry::new_with_app_version(root.path().to_path_buf(), "0.5.67");
+ assert_eq!(registry.find_plugin("sample.hello").unwrap().unwrap().manifest.version, "1.0.0");
+
+ let rollback = installer.rollback("sample.hello").unwrap();
+ assert_eq!(rollback.previous_version, "0.9.0");
+ let legacy_plugin = registry.find_plugin("sample.hello").unwrap().unwrap();
+ assert_eq!(legacy_plugin.manifest.version, "0.9.0");
+ assert_eq!(std::fs::read(legacy_plugin.path.join("bin/plugin")).unwrap(), b"legacy");
+ }
+
+ #[test]
+ fn strict_policy_requires_and_verifies_trusted_signature() {
+ let root = tempfile::tempdir().unwrap();
+ let signing_key = SigningKey::from_bytes(&[7u8; 32]);
+ let mut keys = BTreeMap::new();
+ keys.insert(
+ "sample-key".to_string(),
+ base64::engine::general_purpose::STANDARD.encode(signing_key.verifying_key().as_bytes()),
+ );
+ let trust = PluginTrustStore::from_base64_keys(keys).unwrap();
+ let installer = PluginPackageInstaller::with_trust_store(root.path().to_path_buf(), "0.5.67", trust);
+ let expectation = PluginPackageExpectation {
+ id: "sample.hello".to_string(),
+ version: "1.0.0".to_string(),
+ publisher: "sample".to_string(),
+ permissions: BTreeSet::from(["host.events".to_string()]),
+ signing_key_id: "sample-key".to_string(),
+ };
+ let unsigned = package("1.0.0", None, false);
+ assert!(installer.install_marketplace_bytes(&unsigned, &expectation).is_err());
+
+ let signed = package("1.0.0", Some((&signing_key, "sample-key")), false);
+ let result = installer.install_marketplace_bytes(&signed, &expectation).unwrap();
+ assert_eq!(result.signature, PluginSignatureStatus::Trusted { key_id: "sample-key".to_string() });
+ }
+
+ #[test]
+ fn marketplace_expectation_binds_manifest_and_signing_identity() {
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "sample.hello",
+ "name": "Hello",
+ "version": "1.0.0",
+ "publisher": "sample",
+ "permissions": ["host.events"]
+ }))
+ .unwrap();
+ let signature = PluginSignatureStatus::Trusted { key_id: "sample-key".to_string() };
+ let expectation = PluginPackageExpectation {
+ id: "sample.hello".to_string(),
+ version: "1.0.0".to_string(),
+ publisher: "sample".to_string(),
+ permissions: BTreeSet::from(["host.events".to_string()]),
+ signing_key_id: "sample-key".to_string(),
+ };
+
+ validate_package_expectation(&manifest, &signature, &expectation).unwrap();
+ let mut mismatch = expectation.clone();
+ mismatch.id = "sample.replaced".to_string();
+ assert!(validate_package_expectation(&manifest, &signature, &mismatch).unwrap_err().contains("catalog id"));
+ let mut mismatch = expectation.clone();
+ mismatch.publisher = "attacker".to_string();
+ assert!(validate_package_expectation(&manifest, &signature, &mismatch)
+ .unwrap_err()
+ .contains("catalog publisher"));
+ let mut mismatch = expectation;
+ mismatch.signing_key_id = "attacker-key".to_string();
+ assert!(validate_package_expectation(&manifest, &signature, &mismatch).unwrap_err().contains("repository key"));
+ }
+
+ #[test]
+ fn trusted_repository_keys_roundtrip_and_can_be_removed() {
+ let root = tempfile::tempdir().unwrap();
+ let signing_key = SigningKey::from_bytes(&[9u8; 32]);
+ let public_key = base64::engine::general_purpose::STANDARD.encode(signing_key.verifying_key().as_bytes());
+
+ PluginTrustStore::save_base64_key(root.path(), "sample-repository", &public_key).unwrap();
+
+ assert_eq!(
+ PluginTrustStore::list_base64_keys(root.path()).unwrap(),
+ vec![super::PluginTrustedKey { key_id: "sample-repository".to_string(), public_key: public_key.clone() }]
+ );
+ assert!(PluginTrustStore::load(root.path()).unwrap().keys.contains_key("sample-repository"));
+
+ let replacement = base64::engine::general_purpose::STANDARD
+ .encode(SigningKey::from_bytes(&[10u8; 32]).verifying_key().as_bytes());
+ assert!(PluginTrustStore::save_base64_key(root.path(), "sample-repository", &replacement)
+ .unwrap_err()
+ .contains("remove it before rotating"));
+
+ PluginTrustStore::remove_key(root.path(), "sample-repository").unwrap();
+
+ assert!(PluginTrustStore::list_base64_keys(root.path()).unwrap().is_empty());
+ assert!(!PluginTrustStore::load(root.path()).unwrap().keys.contains_key("sample-repository"));
+ }
+
+ #[test]
+ fn rejects_checksum_mismatch_and_path_traversal() {
+ let root = tempfile::tempdir().unwrap();
+ let installer =
+ PluginPackageInstaller::with_trust_store(root.path().to_path_buf(), "0.5.67", PluginTrustStore::default());
+ let tampered = package("1.0.0", None, true);
+ assert!(installer.install_bytes(&tampered, PluginInstallPolicy::LocalDevelopment).is_err());
+
+ let mut output = Cursor::new(Vec::new());
+ {
+ let mut zip = zip::ZipWriter::new(&mut output);
+ zip.start_file("../escape", SimpleFileOptions::default()).unwrap();
+ zip.write_all(b"bad").unwrap();
+ zip.finish().unwrap();
+ }
+ assert!(installer.install_bytes(output.get_ref(), PluginInstallPolicy::LocalDevelopment).is_err());
+ }
+
+ fn package(version: &str, signer: Option<(&SigningKey, &str)>, tamper: bool) -> Vec<u8> {
+ let manifest = serde_json::json!({
+ "manifest_version": 1,
+ "id": "sample.hello",
+ "name": "Hello",
+ "version": version,
+ "publisher": "sample",
+ "engines": { "dbx": ">=0.5.0", "host_api": "^1.0" },
+ "permissions": ["host.events"],
+ "entrypoints": {
+ "backend": {
+ "protocol_versions": [1],
+ "transport": "stdio-jsonl",
+ "executable": "bin/plugin"
+ }
+ }
+ });
+ let manifest = serde_json::to_vec_pretty(&manifest).unwrap();
+ let backend = b"#!/bin/sh\nexit 0\n".to_vec();
+ let mut files = BTreeMap::new();
+ files.insert("manifest.json".to_string(), manifest.clone());
+ files.insert("bin/plugin".to_string(), backend.clone());
+ let checksum_files =
+ files.iter().map(|(path, bytes)| (path.clone(), sha256_hex(bytes))).collect::<BTreeMap<_, _>>();
+ let checksums = serde_json::to_vec_pretty(&serde_json::json!({
+ "algorithm": "sha256",
+ "files": checksum_files
+ }))
+ .unwrap();
+ let signature = signer.map(|(key, key_id)| {
+ serde_json::to_vec_pretty(&serde_json::json!({
+ "algorithm": "ed25519",
+ "key_id": key_id,
+ "signature": base64::engine::general_purpose::STANDARD.encode(key.sign(&checksums).to_bytes())
+ }))
+ .unwrap()
+ });
+
+ let mut output = Cursor::new(Vec::new());
+ {
+ let mut zip = zip::ZipWriter::new(&mut output);
+ for (path, mut bytes) in files {
+ if tamper && path == "manifest.json" {
+ bytes.push(b' ');
+ }
+ let options = if path == "bin/plugin" {
+ SimpleFileOptions::default().unix_permissions(0o755)
+ } else {
+ SimpleFileOptions::default().unix_permissions(0o644)
+ };
+ zip.start_file(path, options).unwrap();
+ zip.write_all(&bytes).unwrap();
+ }
+ zip.start_file(PLUGIN_CHECKSUMS_FILE, SimpleFileOptions::default()).unwrap();
+ zip.write_all(&checksums).unwrap();
+ if let Some(signature) = signature {
+ zip.start_file(PLUGIN_SIGNATURE_FILE, SimpleFileOptions::default()).unwrap();
+ zip.write_all(&signature).unwrap();
+ }
+ zip.finish().unwrap();
+ }
+ output.into_inner()
+ }
+}
diff --git a/crates/dbx-core/src/plugins/manifest.rs b/crates/dbx-core/src/plugins/manifest.rs
new file mode 100644
index 0000000000..84d28eba04
--- /dev/null
+++ b/crates/dbx-core/src/plugins/manifest.rs
@@ -0,0 +1,1667 @@
+use std::collections::{BTreeMap, HashSet};
+use std::path::{Component, Path, PathBuf};
+
+use semver::{Version, VersionReq};
+use serde::{Deserialize, Serialize};
+
+pub const SUPPORTED_PLUGIN_MANIFEST_VERSION: u32 = 1;
+pub const SUPPORTED_PLUGIN_HOST_API_VERSION: &str = "1.0.0";
+pub const SUPPORTED_PLUGIN_PROTOCOL_VERSION: u32 = 1;
+pub const PLUGIN_CONNECTION_TEST_METHOD: &str = "connection/test";
+pub const PLUGIN_CONNECTION_CONNECT_METHOD: &str = "connection/connect";
+pub const PLUGIN_CONNECTION_DISCONNECT_METHOD: &str = "connection/disconnect";
+pub const PLUGIN_CONNECTION_ACTION_METHOD: &str = "connection/action";
+pub const SUPPORTED_PLUGIN_PERMISSIONS: &[&str] = &["host.events", "host.binary", "host.workbench", "host.filesystem"];
+
+/// Cap the number of `host.network:<origin>` entries so a manifest cannot bloat
+/// the sandbox CSP or enumerate large origin lists.
+pub const MAX_PLUGIN_NETWORK_ORIGINS: usize = 8;
+const HOST_NETWORK_PERMISSION_PREFIX: &str = "host.network:";
+
+/// Parse a `host.network:https://host[:port]` permission into the origin that
+/// may appear in the sandbox `connect-src`. Only https origins without path,
+/// query, or fragment parts are accepted.
+pub fn parse_host_network_permission(permission: &str) -> Option<&str> {
+ let origin = permission.strip_prefix(HOST_NETWORK_PERMISSION_PREFIX)?;
+ let rest = origin.strip_prefix("https://")?;
+ if rest.is_empty() || rest.contains('/') || rest.contains('?') || rest.contains('#') {
+ return None;
+ }
+ let host = rest.split(':').next().unwrap_or_default();
+ if host.is_empty()
+ || !host.chars().all(|character| character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_'))
+ {
+ return None;
+ }
+ if let Some(port) = rest.rsplit(':').next() {
+ if rest.contains(':') && (port.is_empty() || !port.chars().all(|character| character.is_ascii_digit())) {
+ return None;
+ }
+ }
+ Some(origin)
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct PluginManifest {
+ #[serde(rename = "$schema", default, skip_serializing)]
+ pub schema: Option<String>,
+ #[serde(default)]
+ pub manifest_version: u32,
+ pub id: String,
+ pub name: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub icon: Option<String>,
+ #[serde(default)]
+ pub version: String,
+ #[serde(default)]
+ pub publisher: String,
+ #[serde(default)]
+ pub description: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub source: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub homepage: Option<String>,
+ #[serde(default)]
+ pub engines: PluginEngines,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub permissions: Vec<String>,
+ #[serde(default)]
+ pub entrypoints: PluginEntrypoints,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub contributions: Vec<PluginContribution>,
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub localizations: BTreeMap<String, PluginManifestLocalization>,
+ #[serde(default, flatten, skip_serializing)]
+ pub unknown_fields: BTreeMap<String, serde_json::Value>,
+
+ // Legacy manifest v0 fields. They remain readable so the existing JDBC
+ // plugin can migrate independently from the host runtime.
+ #[serde(default = "default_plugin_protocol_version", skip_serializing_if = "is_default_plugin_protocol_version")]
+ pub protocol_version: u32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub executable: Option<String>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub drivers: Vec<PluginDriverManifest>,
+}
+
+fn default_plugin_protocol_version() -> u32 {
+ SUPPORTED_PLUGIN_PROTOCOL_VERSION
+}
+
+fn is_default_plugin_protocol_version(version: &u32) -> bool {
+ *version == SUPPORTED_PLUGIN_PROTOCOL_VERSION
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginEngines {
+ #[serde(default)]
+ pub dbx: String,
+ #[serde(default)]
+ pub host_api: String,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginEntrypoints {
+ #[serde(default)]
+ pub backend: Option<PluginBackendEntrypoint>,
+ #[serde(default)]
+ pub ui: Option<PluginUiEntrypoint>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginBackendEntrypoint {
+ #[serde(
+ default = "default_backend_protocol_versions",
+ skip_serializing_if = "is_default_backend_protocol_versions"
+ )]
+ pub protocol_versions: Vec<u32>,
+ #[serde(default, skip_serializing_if = "is_default_backend_transport")]
+ pub transport: PluginBackendTransport,
+ pub executable: String,
+}
+
+fn default_backend_protocol_versions() -> Vec<u32> {
+ vec![SUPPORTED_PLUGIN_PROTOCOL_VERSION]
+}
+
+fn is_default_backend_protocol_versions(versions: &Vec<u32>) -> bool {
+ versions.as_slice() == [SUPPORTED_PLUGIN_PROTOCOL_VERSION]
+}
+
+fn is_default_backend_transport(transport: &PluginBackendTransport) -> bool {
+ *transport == PluginBackendTransport::StdioJsonLines
+}
+
+#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
+pub enum PluginBackendTransport {
+ #[default]
+ #[serde(rename = "stdio-jsonl")]
+ StdioJsonLines,
+ #[serde(rename = "stdio-framed")]
+ StdioFramed,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginUiEntrypoint {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub root: Option<String>,
+ pub entry: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct PluginDriverManifest {
+ pub id: String,
+ pub label: String,
+ pub kind: String,
+ #[serde(default)]
+ pub database_type: Option<String>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginManifestLocalization {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub description: Option<String>,
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub contributions: BTreeMap<String, PluginContributionLocalization>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginContributionLocalization {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub label: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub description: Option<String>,
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub fields: BTreeMap<String, PluginFormFieldLocalization>,
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub actions: BTreeMap<String, PluginConnectionActionLocalization>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginConnectionActionLocalization {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub label: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub description: Option<String>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginFormFieldLocalization {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub label: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub description: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub placeholder: Option<String>,
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub options: BTreeMap<String, String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "kebab-case")]
+pub enum PluginContribution {
+ ConnectionProvider(PluginConnectionProviderContribution),
+ Workbench(PluginWorkbenchContribution),
+ FilesystemProvider(PluginFilesystemProviderContribution),
+ ContextMenu(PluginContextMenuContribution),
+ ResultView(PluginResultViewContribution),
+}
+
+impl PluginContribution {
+ pub fn id(&self) -> &str {
+ match self {
+ Self::ConnectionProvider(contribution) => &contribution.id,
+ Self::Workbench(contribution) => &contribution.id,
+ Self::FilesystemProvider(contribution) => &contribution.id,
+ Self::ContextMenu(contribution) => &contribution.id,
+ Self::ResultView(contribution) => &contribution.id,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginFormFieldDefinition {
+ pub key: String,
+ pub label: String,
+ #[serde(rename = "type")]
+ pub field_type: PluginFormFieldType,
+ #[serde(default)]
+ pub description: Option<String>,
+ #[serde(default)]
+ pub placeholder: Option<String>,
+ #[serde(default)]
+ pub required: bool,
+ #[serde(default)]
+ pub default: Option<serde_json::Value>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub options: Vec<PluginFormFieldOption>,
+ #[serde(default)]
+ pub binding: Option<PluginFormFieldBinding>,
+}
+
+impl PluginFormFieldDefinition {
+ pub fn effective_binding(&self) -> PluginFormFieldBinding {
+ self.binding.unwrap_or(if self.field_type == PluginFormFieldType::Password {
+ PluginFormFieldBinding::Secret
+ } else {
+ PluginFormFieldBinding::Config
+ })
+ }
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "kebab-case")]
+pub enum PluginFormFieldType {
+ Text,
+ Password,
+ Number,
+ Boolean,
+ Select,
+ Radio,
+ Textarea,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "kebab-case")]
+pub enum PluginFormFieldBinding {
+ Config,
+ Secret,
+ Name,
+ Host,
+ Port,
+ Username,
+ Password,
+ Database,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginFormFieldOption {
+ pub label: String,
+ pub value: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginConnectionProviderContribution {
+ pub id: String,
+ #[serde(default)]
+ pub label: Option<String>,
+ #[serde(default)]
+ pub icon: Option<String>,
+ pub database_type: String,
+ #[serde(default)]
+ pub description: Option<String>,
+ #[serde(default)]
+ pub fields: Vec<PluginFormFieldDefinition>,
+ #[serde(default)]
+ pub workbench: Option<String>,
+ #[serde(default)]
+ pub filesystem_provider: Option<String>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub capabilities: Vec<PluginConnectionCapability>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub actions: Vec<PluginConnectionActionContribution>,
+}
+
+impl PluginConnectionProviderContribution {
+ pub fn has_capability(&self, capability: PluginConnectionCapability) -> bool {
+ self.capabilities.contains(&capability)
+ }
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
+#[serde(rename_all = "kebab-case")]
+pub enum PluginConnectionCapability {
+ Test,
+ Connect,
+ Disconnect,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginConnectionActionContribution {
+ pub id: String,
+ pub label: String,
+ #[serde(default)]
+ pub description: Option<String>,
+ #[serde(default)]
+ pub variant: Option<PluginConnectionActionVariant>,
+ #[serde(default)]
+ pub when: Option<PluginConnectionActionWhen>,
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub close_on_success: bool,
+ #[serde(default = "default_action_requires_valid_form", skip_serializing_if = "is_true")]
+ pub requires_valid_form: bool,
+ #[serde(default)]
+ pub timeout_ms: Option<u64>,
+}
+
+fn default_action_requires_valid_form() -> bool {
+ true
+}
+
+fn is_true(value: &bool) -> bool {
+ *value
+}
+
+fn is_false(value: &bool) -> bool {
+ !*value
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "kebab-case")]
+pub enum PluginConnectionActionVariant {
+ Default,
+ Outline,
+ Secondary,
+ Destructive,
+ Ghost,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "kebab-case")]
+pub enum PluginConnectionActionWhen {
+ Always,
+ Create,
+ Edit,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginWorkbenchContribution {
+ pub id: String,
+ pub label: String,
+ #[serde(default)]
+ pub description: Option<String>,
+ #[serde(default)]
+ pub icon: Option<String>,
+}
+
+/// Native context-menu entry contributed to DBX surfaces. v1 targets the
+/// saved-connection sidebar menu; clicks are dispatched to the plugin backend
+/// as `contextMenu/<id>` requests.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginContextMenuContribution {
+ pub id: String,
+ pub label: String,
+ #[serde(default)]
+ pub description: Option<String>,
+ #[serde(default)]
+ pub icon: Option<String>,
+ /// Menu surface the item belongs to; currently only `connection`.
+ #[serde(default)]
+ pub menu: String,
+}
+
+/// Plugin-rendered visualization surface for query results. Selecting the view
+/// opens the plugin workbench with the current result set as its context.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginResultViewContribution {
+ pub id: String,
+ pub label: String,
+ #[serde(default)]
+ pub description: Option<String>,
+ #[serde(default)]
+ pub icon: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginFilesystemProviderContribution {
+ pub id: String,
+ pub label: String,
+ pub schemes: Vec<String>,
+ #[serde(default)]
+ pub description: Option<String>,
+ #[serde(default)]
+ pub capabilities: Vec<PluginFilesystemCapability>,
+ #[serde(default)]
+ pub root_uri: Option<String>,
+}
+
+impl PluginFilesystemProviderContribution {
+ pub fn has_capability(&self, capability: PluginFilesystemCapability) -> bool {
+ self.capabilities.contains(&capability)
+ }
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
+#[serde(rename_all = "kebab-case")]
+pub enum PluginFilesystemCapability {
+ Read,
+ Write,
+ Delete,
+ Rename,
+ Mkdir,
+}
+
+impl PluginFilesystemCapability {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Read => "read",
+ Self::Write => "write",
+ Self::Delete => "delete",
+ Self::Rename => "rename",
+ Self::Mkdir => "mkdir",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct PluginCompatibility {
+ pub compatible: bool,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub errors: Vec<String>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub warnings: Vec<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub target: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub backend_executable: Option<PathBuf>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ui_entry: Option<PathBuf>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ui_root: Option<PathBuf>,
+}
+
+impl PluginManifest {
+ pub fn is_legacy(&self) -> bool {
+ self.manifest_version == 0
+ }
+
+ pub fn backend_entrypoint(&self) -> Option<PluginBackendEntrypoint> {
+ if let Some(backend) = &self.entrypoints.backend {
+ return Some(backend.clone());
+ }
+ self.executable.as_ref().map(|executable| PluginBackendEntrypoint {
+ protocol_versions: vec![self.protocol_version],
+ transport: PluginBackendTransport::StdioJsonLines,
+ executable: executable.clone(),
+ })
+ }
+
+ pub fn connection_provider(
+ &self,
+ provider_id: &str,
+ ) -> Result<Option<PluginConnectionProviderContribution>, String> {
+ Ok(self.contributions.iter().find_map(|contribution| match contribution {
+ PluginContribution::ConnectionProvider(provider) if provider.id == provider_id => Some(provider.clone()),
+ _ => None,
+ }))
+ }
+
+ pub fn filesystem_provider(
+ &self,
+ provider_id: &str,
+ ) -> Result<Option<PluginFilesystemProviderContribution>, String> {
+ Ok(self.contributions.iter().find_map(|contribution| match contribution {
+ PluginContribution::FilesystemProvider(provider) if provider.id == provider_id => Some(provider.clone()),
+ _ => None,
+ }))
+ }
+
+ pub fn compatibility(&self, plugin_dir: &Path, dbx_version: &str) -> PluginCompatibility {
+ let mut errors = Vec::new();
+ let mut warnings = Vec::new();
+
+ if self.manifest_version > SUPPORTED_PLUGIN_MANIFEST_VERSION {
+ errors.push(format!(
+ "Plugin manifest version {} is newer than the supported version {}",
+ self.manifest_version, SUPPORTED_PLUGIN_MANIFEST_VERSION
+ ));
+ }
+ if self.manifest_version == 0 {
+ warnings.push("Legacy plugin manifest v0 is supported for migration only".to_string());
+ } else if !self.unknown_fields.is_empty() {
+ errors.push(format!(
+ "Plugin manifest contains unknown top-level field(s): {}",
+ self.unknown_fields.keys().cloned().collect::<Vec<_>>().join(", ")
+ ));
+ }
+ if !valid_identifier(&self.id) {
+ errors.push("Plugin id must contain only lowercase letters, digits, '.', '-' or '_'".to_string());
+ }
+ if self.name.trim().is_empty() {
+ errors.push("Plugin name cannot be empty".to_string());
+ }
+ if self.manifest_version > 0 {
+ if self.executable.is_some() || !self.drivers.is_empty() {
+ errors.push(
+ "Manifest v1 cannot use legacy executable or drivers fields; use entrypoints and contributions"
+ .to_string(),
+ );
+ }
+ if self.protocol_version != SUPPORTED_PLUGIN_PROTOCOL_VERSION {
+ errors.push("Manifest v1 cannot override the legacy protocol_version field".to_string());
+ }
+ if Version::parse(self.version.trim()).is_err() {
+ errors.push("Plugin version must be valid semantic versioning".to_string());
+ }
+ if self.publisher.trim().is_empty() {
+ errors.push("Manifest v1 plugins must declare a publisher".to_string());
+ }
+ validate_engine_requirement("DBX", &self.engines.dbx, dbx_version, &mut errors);
+ if self.engines.host_api.trim().is_empty() {
+ errors.push("Manifest v1 plugins must declare engines.host_api".to_string());
+ } else {
+ validate_engine_requirement(
+ "DBX Host API",
+ &self.engines.host_api,
+ SUPPORTED_PLUGIN_HOST_API_VERSION,
+ &mut errors,
+ );
+ }
+ }
+
+ let mut seen_permissions = HashSet::new();
+ let mut network_origins: HashSet<&str> = HashSet::new();
+ for permission in &self.permissions {
+ let valid = SUPPORTED_PLUGIN_PERMISSIONS.contains(&permission.as_str())
+ || (permission.starts_with("host.network:") && parse_host_network_permission(permission).is_some());
+ if !valid {
+ errors.push(format!(
+ "Unsupported plugin Host API permission '{permission}' (network permissions must look like host.network:https://example.com)"
+ ));
+ } else if !seen_permissions.insert(permission) {
+ errors.push(format!("Duplicate plugin permission '{permission}'"));
+ }
+ if let Some(origin) = parse_host_network_permission(permission) {
+ if !network_origins.insert(origin) {
+ errors.push(format!("Duplicate plugin network origin '{origin}'"));
+ }
+ }
+ }
+ if network_origins.len() > MAX_PLUGIN_NETWORK_ORIGINS {
+ errors.push(format!(
+ "Plugin declares {} network origins; at most {MAX_PLUGIN_NETWORK_ORIGINS} are allowed",
+ network_origins.len()
+ ));
+ }
+ validate_localizations(&self.localizations, &mut errors);
+ validate_declared_icon(plugin_dir, "Plugin icon", self.icon.as_deref(), &mut errors);
+ validate_contributions(
+ &self.contributions,
+ self.backend_entrypoint().is_some(),
+ self.entrypoints.ui.is_some(),
+ plugin_dir,
+ &mut errors,
+ );
+
+ let target = current_plugin_target();
+ let backend_executable = self.backend_entrypoint().and_then(|backend| {
+ if !backend.protocol_versions.contains(&SUPPORTED_PLUGIN_PROTOCOL_VERSION) {
+ errors.push(format!(
+ "Plugin backend does not support protocol version {}",
+ SUPPORTED_PLUGIN_PROTOCOL_VERSION
+ ));
+ }
+ match resolve_safe_plugin_path(plugin_dir, &backend.executable) {
+ Ok(path) => {
+ let path = resolve_existing_backend_path(path);
+ if !path.is_file() {
+ errors.push(format!("Plugin backend executable does not exist: {}", path.display()));
+ }
+ Some(path)
+ }
+ Err(error) => {
+ errors.push(error);
+ None
+ }
+ }
+ });
+
+ let mut ui_root = None;
+ let ui_entry = self.entrypoints.ui.as_ref().and_then(|ui| {
+ let root_relative = ui.root.clone().unwrap_or_else(|| {
+ Path::new(&ui.entry)
+ .parent()
+ .filter(|parent| !parent.as_os_str().is_empty())
+ .map(|parent| parent.to_string_lossy().into_owned())
+ .unwrap_or_else(|| ".".to_string())
+ });
+ match resolve_safe_plugin_path(plugin_dir, &root_relative) {
+ Ok(path) if path.is_dir() => ui_root = Some(path),
+ Ok(path) => errors.push(format!("Plugin UI root does not exist: {}", path.display())),
+ Err(error) => errors.push(error),
+ }
+ match resolve_safe_plugin_path(plugin_dir, &ui.entry) {
+ Ok(path) => {
+ if !path.is_file() {
+ errors.push(format!("Plugin UI entry does not exist: {}", path.display()));
+ }
+ if ui_root.as_ref().is_some_and(|root| !path.starts_with(root)) {
+ errors.push("Plugin UI entry must be contained by its UI root".to_string());
+ }
+ Some(path)
+ }
+ Err(error) => {
+ errors.push(error);
+ None
+ }
+ }
+ });
+
+ PluginCompatibility {
+ compatible: errors.is_empty(),
+ errors,
+ warnings,
+ target: Some(target),
+ backend_executable,
+ ui_entry,
+ ui_root,
+ }
+ }
+}
+
+fn validate_localizations(localizations: &BTreeMap<String, PluginManifestLocalization>, errors: &mut Vec<String>) {
+ for (locale, localization) in localizations {
+ if !valid_locale_tag(locale) {
+ errors.push(format!("Invalid plugin localization locale '{locale}'"));
+ }
+ if localization.name.as_ref().is_some_and(|value| value.trim().is_empty()) {
+ errors.push(format!("Plugin localization '{locale}' has an empty name"));
+ }
+ for (contribution_id, contribution) in &localization.contributions {
+ if !valid_identifier(contribution_id)
+ || contribution.label.as_ref().is_some_and(|value| value.trim().is_empty())
+ {
+ errors.push(format!(
+ "Plugin localization '{locale}' has an invalid contribution entry '{contribution_id}'"
+ ));
+ }
+ for (field_key, field) in &contribution.fields {
+ if !valid_identifier(field_key)
+ || field.label.as_ref().is_some_and(|value| value.trim().is_empty())
+ || field.options.values().any(|value| value.trim().is_empty())
+ {
+ errors.push(format!(
+ "Plugin localization '{locale}' has an invalid field entry '{contribution_id}/{field_key}'"
+ ));
+ }
+ }
+ for (action_id, action) in &contribution.actions {
+ if !valid_identifier(action_id) || action.label.as_ref().is_some_and(|value| value.trim().is_empty()) {
+ errors.push(format!(
+ "Plugin localization '{locale}' has an invalid action entry '{contribution_id}/{action_id}'"
+ ));
+ }
+ }
+ }
+ }
+}
+
+fn resolve_existing_backend_path(path: PathBuf) -> PathBuf {
+ // Windows cannot execute the Unix shell script shipped beside the launcher;
+ // when both exist the .bat launcher always wins (see the May 2026 JDBC
+ // plugin "os error 193" and ".bat over shell script" fixes).
+ #[cfg(windows)]
+ {
+ let batch_path = path.with_extension("bat");
+ if batch_path.is_file() {
+ return batch_path;
+ }
+ }
+ if path.is_file() {
+ return path;
+ }
+ path
+}
+
+pub fn current_plugin_target() -> String {
+ let os = match std::env::consts::OS {
+ "macos" => "darwin",
+ other => other,
+ };
+ let arch = match std::env::consts::ARCH {
+ "x86_64" => "x64",
+ "aarch64" => "arm64",
+ other => other,
+ };
+ format!("{os}-{arch}")
+}
+
+pub fn resolve_safe_plugin_path(plugin_dir: &Path, relative_path: &str) -> Result<PathBuf, String> {
+ let relative_path = Path::new(relative_path);
+ if relative_path.as_os_str().is_empty() || relative_path.is_absolute() {
+ return Err("Plugin entrypoint path must be a non-empty relative path".to_string());
+ }
+ if relative_path
+ .components()
+ .any(|component| matches!(component, Component::ParentDir | Component::RootDir | Component::Prefix(_)))
+ {
+ return Err(format!("Plugin entrypoint escapes its package: {}", relative_path.display()));
+ }
+ Ok(plugin_dir.join(relative_path))
+}
+
+fn validate_engine_requirement(label: &str, requirement: &str, actual: &str, errors: &mut Vec<String>) {
+ if requirement.trim().is_empty() {
+ return;
+ }
+ let requirement = match VersionReq::parse(requirement.trim()) {
+ Ok(requirement) => requirement,
+ Err(error) => {
+ errors.push(format!("Invalid {label} version requirement '{requirement}': {error}"));
+ return;
+ }
+ };
+ let actual = match Version::parse(actual.trim()) {
+ Ok(actual) => actual,
+ Err(error) => {
+ errors.push(format!("Invalid installed {label} version '{actual}': {error}"));
+ return;
+ }
+ };
+ if !requirement.matches(&actual) {
+ errors.push(format!("Plugin requires {label} {requirement}, but {actual} is installed"));
+ }
+}
+
+fn validate_contributions(
+ contributions: &[PluginContribution],
+ has_backend: bool,
+ has_ui: bool,
+ plugin_dir: &Path,
+ errors: &mut Vec<String>,
+) {
+ let mut seen_ids = HashSet::new();
+ let mut provider_ids = HashSet::new();
+ let mut workbench_ids = HashSet::new();
+ let mut filesystem_provider_ids = HashSet::new();
+ let mut workbench_references = Vec::new();
+ let mut filesystem_references = Vec::new();
+
+ for (index, contribution) in contributions.iter().enumerate() {
+ let id = contribution.id();
+ if !valid_identifier(id) {
+ errors.push(format!("Contribution at index {index} has an invalid id"));
+ } else if !seen_ids.insert(id) {
+ errors.push(format!("Duplicate plugin contribution id '{id}'"));
+ }
+
+ match contribution {
+ PluginContribution::ConnectionProvider(provider) => {
+ validate_optional_text(provider.label.as_deref(), &format!("Connection provider '{id}' label"), errors);
+ validate_declared_icon(
+ plugin_dir,
+ &format!("Connection provider '{id}' icon"),
+ provider.icon.as_deref(),
+ errors,
+ );
+ if !valid_identifier(&provider.database_type) {
+ errors.push(format!("Connection provider '{id}' has an invalid database_type"));
+ }
+ if valid_identifier(id) {
+ provider_ids.insert(id.to_string());
+ }
+ validate_form_fields(&provider.fields, index, errors);
+ validate_optional_reference(provider.workbench.as_deref(), "workbench", id, errors);
+ validate_optional_reference(provider.filesystem_provider.as_deref(), "filesystem provider", id, errors);
+ if let Some(workbench) = &provider.workbench {
+ workbench_references.push((id.to_string(), workbench.clone()));
+ }
+ if let Some(filesystem_provider) = &provider.filesystem_provider {
+ filesystem_references.push((id.to_string(), filesystem_provider.clone()));
+ }
+ let mut seen_capabilities = HashSet::new();
+ for capability in &provider.capabilities {
+ if !seen_capabilities.insert(*capability) {
+ errors.push(format!("Connection provider '{id}' has duplicate capabilities"));
+ }
+ }
+ if provider.has_capability(PluginConnectionCapability::Disconnect)
+ && !provider.has_capability(PluginConnectionCapability::Connect)
+ {
+ errors.push(format!("Connection provider '{id}' cannot declare disconnect without connect"));
+ }
+ if (!provider.capabilities.is_empty() || !provider.actions.is_empty()) && !has_backend {
+ errors.push(format!("Connection provider '{id}' declares backend operations without a backend"));
+ }
+ validate_connection_actions(&provider.actions, id, errors);
+ }
+ PluginContribution::Workbench(workbench) => {
+ validate_required_text(&workbench.label, &format!("Workbench '{id}' label"), errors);
+ validate_declared_icon(
+ plugin_dir,
+ &format!("Workbench '{id}' icon"),
+ workbench.icon.as_deref(),
+ errors,
+ );
+ if valid_identifier(id) {
+ workbench_ids.insert(id.to_string());
+ }
+ if !has_ui {
+ errors.push(format!("Workbench contribution '{id}' requires a UI entrypoint"));
+ }
+ }
+ PluginContribution::ResultView(result_view) => {
+ validate_required_text(&result_view.label, &format!("Result view '{id}' label"), errors);
+ validate_declared_icon(
+ plugin_dir,
+ &format!("Result view '{id}' icon"),
+ result_view.icon.as_deref(),
+ errors,
+ );
+ if !has_ui {
+ errors.push(format!("Result view contribution '{id}' requires a UI entrypoint"));
+ }
+ }
+ PluginContribution::ContextMenu(menu) => {
+ validate_required_text(&menu.label, &format!("Context menu '{id}' label"), errors);
+ validate_declared_icon(plugin_dir, &format!("Context menu '{id}' icon"), menu.icon.as_deref(), errors);
+ if menu.menu != "connection" {
+ errors.push(format!(
+ "Context menu '{id}' declares unsupported menu '{}'; only 'connection' is available",
+ menu.menu
+ ));
+ }
+ if !has_backend {
+ errors.push(format!("Context menu contribution '{id}' requires a backend entrypoint"));
+ }
+ }
+ PluginContribution::FilesystemProvider(provider) => {
+ validate_required_text(&provider.label, &format!("Filesystem provider '{id}' label"), errors);
+ if valid_identifier(id) {
+ filesystem_provider_ids.insert(id.to_string());
+ }
+ if provider.schemes.is_empty() {
+ errors.push(format!("Filesystem provider '{id}' must declare at least one scheme"));
+ }
+ let mut seen_schemes = HashSet::new();
+ for scheme in &provider.schemes {
+ if !valid_capability_name(scheme) {
+ errors.push(format!("Filesystem provider '{id}' has an invalid scheme '{scheme}'"));
+ } else if !seen_schemes.insert(scheme) {
+ errors.push(format!("Filesystem provider '{id}' has duplicate scheme '{scheme}'"));
+ }
+ }
+ let mut seen_capabilities = HashSet::new();
+ for capability in &provider.capabilities {
+ if !seen_capabilities.insert(*capability) {
+ errors.push(format!("Filesystem provider '{id}' has duplicate capabilities"));
+ }
+ }
+ if let Some(root_uri) = &provider.root_uri {
+ let root_uri = root_uri.trim();
+ let scheme = root_uri.split_once(':').map(|(scheme, _)| scheme).unwrap_or_default();
+ if root_uri.is_empty()
+ || root_uri.len() > 4_096
+ || root_uri.chars().any(char::is_whitespace)
+ || !provider.schemes.iter().any(|declared| declared == scheme)
+ {
+ errors.push(format!("Filesystem provider '{id}' has an invalid root_uri"));
+ }
+ }
+ if !has_backend {
+ errors.push(format!("Filesystem provider '{id}' requires a backend entrypoint"));
+ }
+ }
+ }
+ }
+
+ for (provider, workbench) in workbench_references {
+ if !workbench_ids.contains(&workbench) {
+ errors.push(format!("Connection provider '{provider}' references missing workbench '{workbench}'"));
+ }
+ }
+ for (provider, filesystem_provider) in filesystem_references {
+ if !filesystem_provider_ids.contains(&filesystem_provider) {
+ errors.push(format!(
+ "Connection provider '{provider}' references missing filesystem provider '{filesystem_provider}'"
+ ));
+ }
+ }
+}
+
+fn validate_connection_actions(
+ actions: &[PluginConnectionActionContribution],
+ provider_id: &str,
+ errors: &mut Vec<String>,
+) {
+ let mut seen_ids = HashSet::new();
+ for action in actions {
+ if !valid_identifier(&action.id) || !seen_ids.insert(&action.id) {
+ errors.push(format!(
+ "Connection provider '{provider_id}' action '{}' has an invalid or duplicate id",
+ action.id
+ ));
+ }
+ validate_required_text(
+ &action.label,
+ &format!("Connection provider '{provider_id}' action '{}' label", action.id),
+ errors,
+ );
+ if action.timeout_ms.is_some_and(|timeout| !(1..=120_000).contains(&timeout)) {
+ errors.push(format!(
+ "Connection provider '{provider_id}' action '{}' timeout_ms must be between 1 and 120000",
+ action.id
+ ));
+ }
+ }
+}
+
+fn validate_form_fields(fields: &[PluginFormFieldDefinition], contribution_index: usize, errors: &mut Vec<String>) {
+ let mut seen_keys = HashSet::new();
+ for (field_index, field) in fields.iter().enumerate() {
+ if !valid_identifier(&field.key) || !seen_keys.insert(&field.key) {
+ errors.push(format!(
+ "Contribution at index {contribution_index} field {field_index} has an invalid or duplicate key"
+ ));
+ }
+ validate_required_text(
+ &field.label,
+ &format!("Contribution at index {contribution_index} field {field_index} label"),
+ errors,
+ );
+
+ if matches!(field.field_type, PluginFormFieldType::Select | PluginFormFieldType::Radio) {
+ if field.options.is_empty() {
+ errors.push(format!(
+ "Contribution at index {contribution_index} field {field_index} choice options cannot be empty"
+ ));
+ }
+ let mut seen_values = HashSet::new();
+ for option in &field.options {
+ if option.label.trim().is_empty() || !seen_values.insert(&option.value) {
+ errors.push(format!(
+ "Contribution at index {contribution_index} field {field_index} has invalid or duplicate choice options"
+ ));
+ }
+ }
+ } else if !field.options.is_empty() {
+ errors.push(format!(
+ "Contribution at index {contribution_index} field {field_index} only supports options for select or radio fields"
+ ));
+ }
+
+ if field.binding == Some(PluginFormFieldBinding::Port) && field.field_type != PluginFormFieldType::Number {
+ errors.push(format!(
+ "Contribution at index {contribution_index} field {field_index} port binding requires number type"
+ ));
+ }
+ if matches!(
+ field.binding,
+ Some(
+ PluginFormFieldBinding::Secret
+ | PluginFormFieldBinding::Name
+ | PluginFormFieldBinding::Host
+ | PluginFormFieldBinding::Username
+ | PluginFormFieldBinding::Password
+ | PluginFormFieldBinding::Database
+ )
+ ) && !matches!(
+ field.field_type,
+ PluginFormFieldType::Text
+ | PluginFormFieldType::Password
+ | PluginFormFieldType::Select
+ | PluginFormFieldType::Radio
+ | PluginFormFieldType::Textarea
+ ) {
+ errors.push(format!(
+ "Contribution at index {contribution_index} field {field_index} string binding requires a string field type"
+ ));
+ }
+
+ if let Some(default) = &field.default {
+ let valid = match field.field_type {
+ PluginFormFieldType::Text
+ | PluginFormFieldType::Password
+ | PluginFormFieldType::Select
+ | PluginFormFieldType::Radio
+ | PluginFormFieldType::Textarea => default.is_string(),
+ PluginFormFieldType::Number => default.is_number(),
+ PluginFormFieldType::Boolean => default.is_boolean(),
+ };
+ if !valid {
+ errors.push(format!(
+ "Contribution at index {contribution_index} field {field_index} has an invalid default value"
+ ));
+ }
+ if matches!(field.field_type, PluginFormFieldType::Select | PluginFormFieldType::Radio)
+ && default.as_str().is_some_and(|default| !field.options.iter().any(|option| option.value == default))
+ {
+ errors.push(format!(
+ "Contribution at index {contribution_index} field {field_index} choice default is not declared in options"
+ ));
+ }
+ }
+ }
+}
+
+fn validate_optional_reference(value: Option<&str>, label: &str, contribution_id: &str, errors: &mut Vec<String>) {
+ if value.is_some_and(|value| !valid_identifier(value)) {
+ errors.push(format!("Connection provider '{contribution_id}' has an invalid {label} reference"));
+ }
+}
+
+fn validate_required_text(value: &str, label: &str, errors: &mut Vec<String>) {
+ if value.trim().is_empty() {
+ errors.push(format!("{label} cannot be empty"));
+ }
+}
+
+fn validate_optional_text(value: Option<&str>, label: &str, errors: &mut Vec<String>) {
+ if value.is_some_and(|value| value.trim().is_empty()) {
+ errors.push(format!("{label} cannot be empty when present"));
+ }
+}
+
+fn validate_declared_icon(plugin_dir: &Path, label: &str, icon: Option<&str>, errors: &mut Vec<String>) {
+ let Some(icon) = icon else {
+ return;
+ };
+ if icon.trim().is_empty() {
+ errors.push(format!("{label} must be a non-empty relative path"));
+ return;
+ }
+ match resolve_safe_plugin_path(plugin_dir, icon) {
+ Ok(path) if !path.is_file() => errors.push(format!("{label} does not exist: {}", path.display())),
+ Ok(path) if !supported_icon_path(&path) => {
+ errors.push(format!("{label} must use svg, png, jpg, jpeg, gif, webp, or ico: {}", path.display()))
+ }
+ Ok(_) => {}
+ Err(error) => errors.push(format!("{label} is invalid: {error}")),
+ }
+}
+
+fn supported_icon_path(path: &Path) -> bool {
+ path.extension().and_then(|extension| extension.to_str()).is_some_and(|extension| {
+ matches!(extension.to_ascii_lowercase().as_str(), "svg" | "png" | "jpg" | "jpeg" | "gif" | "webp" | "ico")
+ })
+}
+
+fn valid_identifier(value: &str) -> bool {
+ if value.is_empty() || value.len() > 128 {
+ return false;
+ }
+ let mut chars = value.chars();
+ matches!(chars.next(), Some(first) if first.is_ascii_lowercase() || first.is_ascii_digit())
+ && chars.all(|character| {
+ character.is_ascii_lowercase() || character.is_ascii_digit() || matches!(character, '.' | '-' | '_')
+ })
+}
+
+fn valid_capability_name(value: &str) -> bool {
+ !value.is_empty()
+ && value.len() <= 256
+ && value.chars().all(|character| {
+ character.is_ascii_lowercase() || character.is_ascii_digit() || matches!(character, '.' | '-' | ':' | '_')
+ })
+}
+
+fn valid_locale_tag(value: &str) -> bool {
+ let mut parts = value.split('-');
+ let Some(language) = parts.next() else {
+ return false;
+ };
+ (2..=3).contains(&language.len())
+ && language.chars().all(|character| character.is_ascii_alphabetic())
+ && parts.all(|part| {
+ (2..=8).contains(&part.len()) && part.chars().all(|character| character.is_ascii_alphanumeric())
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{
+ parse_host_network_permission, resolve_safe_plugin_path, validate_connection_actions,
+ PluginConnectionActionContribution, PluginConnectionProviderContribution, PluginFormFieldBinding,
+ PluginManifest,
+ };
+
+ #[test]
+ fn parses_only_strict_https_network_permissions() {
+ assert_eq!(
+ parse_host_network_permission("host.network:https://api.vendor.com"),
+ Some("https://api.vendor.com")
+ );
+ assert_eq!(
+ parse_host_network_permission("host.network:https://metrics.vendor.com:8443"),
+ Some("https://metrics.vendor.com:8443")
+ );
+ assert_eq!(parse_host_network_permission("host.events"), None);
+ assert_eq!(parse_host_network_permission("host.network:"), None);
+ assert_eq!(parse_host_network_permission("host.network:http://api.vendor.com"), None);
+ assert_eq!(parse_host_network_permission("host.network:https://api.vendor.com/path"), None);
+ assert_eq!(parse_host_network_permission("host.network:https://api.vendor.com?q=1"), None);
+ assert_eq!(parse_host_network_permission("host.network:https://api.vendor.com:notaport"), None);
+ assert_eq!(parse_host_network_permission("host.network:https://"), None);
+ }
+
+ #[test]
+ fn manifest_rejects_malformed_network_permissions() {
+ let dir = tempfile::tempdir().unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.example",
+ "name": "Example",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "entrypoints": { "ui": { "root": "ui", "entry": "ui/index.html" } },
+ "permissions": ["host.network:http://api.vendor.com", "host.network:https://api.vendor.com"]
+ }))
+ .unwrap();
+ std::fs::create_dir_all(dir.path().join("ui")).unwrap();
+ std::fs::write(dir.path().join("ui").join("index.html"), "<!doctype html>").unwrap();
+ let compatibility = manifest.compatibility(dir.path(), "0.1.0");
+ assert!(compatibility.errors.iter().any(|error| error.contains("host.network:http://api.vendor.com")));
+ }
+
+ #[test]
+ fn validates_manifest_v1_and_resolves_package_executable() {
+ let dir = tempfile::tempdir().unwrap();
+ let executable = dir.path().join("bin").join("example");
+ std::fs::create_dir_all(executable.parent().unwrap()).unwrap();
+ std::fs::write(&executable, b"example").unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.example",
+ "name": "Example",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "entrypoints": {
+ "backend": { "executable": "bin/example" }
+ },
+ "contributions": [{
+ "type": "connection-provider",
+ "id": "io.dbx.example.connection",
+ "database_type": "example",
+ "fields": [{
+ "key": "protocol",
+ "label": "Protocol",
+ "type": "radio",
+ "default": "https",
+ "options": [
+ { "label": "HTTPS", "value": "https" },
+ { "label": "HTTP", "value": "http" }
+ ]
+ }]
+ }],
+ "permissions": ["host.events"]
+ }))
+ .unwrap();
+
+ let compatibility = manifest.compatibility(dir.path(), "0.5.67");
+
+ assert!(compatibility.compatible, "{:?}", compatibility.errors);
+ assert_eq!(compatibility.backend_executable.as_deref(), Some(executable.as_path()));
+ }
+
+ #[test]
+ fn validates_localized_plugin_metadata() {
+ let dir = tempfile::tempdir().unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.localized",
+ "name": "Localized",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "localizations": {
+ "zh-CN": {
+ "name": "本地化插件",
+ "contributions": {
+ "localized.connection": {
+ "label": "本地化连接",
+ "fields": { "host": { "label": "主机" } }
+ }
+ }
+ }
+ }
+ }))
+ .unwrap();
+
+ let compatibility = manifest.compatibility(dir.path(), "0.5.68");
+
+ assert!(compatibility.compatible, "{:?}", compatibility.errors);
+ assert_eq!(manifest.localizations["zh-CN"].name.as_deref(), Some("本地化插件"));
+ }
+
+ #[test]
+ fn rejects_invalid_localization_metadata() {
+ let dir = tempfile::tempdir().unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.localized",
+ "name": "Localized",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "localizations": { "invalid_locale": { "name": "" } }
+ }))
+ .unwrap();
+
+ let compatibility = manifest.compatibility(dir.path(), "0.5.68");
+
+ assert!(compatibility.errors.iter().any(|error| error.contains("Invalid plugin localization locale")));
+ assert!(compatibility.errors.iter().any(|error| error.contains("empty name")));
+ }
+
+ #[test]
+ fn rejects_entrypoint_path_traversal() {
+ let error = resolve_safe_plugin_path(std::path::Path::new("/plugins/example"), "../other/bin").unwrap_err();
+ assert!(error.contains("escapes"));
+ }
+
+ #[test]
+ fn accepts_declared_plugin_and_provider_icons_with_optional_provider_label() {
+ let dir = tempfile::tempdir().unwrap();
+ std::fs::create_dir_all(dir.path().join("assets")).unwrap();
+ std::fs::write(dir.path().join("assets/plugin.svg"), "<svg/>").unwrap();
+ std::fs::write(dir.path().join("assets/provider.png"), b"png").unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.icons",
+ "name": "Icons",
+ "icon": "assets/plugin.svg",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "contributions": [{
+ "type": "connection-provider",
+ "id": "icons.connection",
+ "icon": "assets/provider.png",
+ "database_type": "icons",
+ "fields": []
+ }]
+ }))
+ .unwrap();
+
+ let compatibility = manifest.compatibility(dir.path(), "0.5.68");
+ let provider = manifest.connection_provider("icons.connection").unwrap().unwrap();
+
+ assert!(compatibility.compatible, "{:?}", compatibility.errors);
+ assert_eq!(provider.label, None);
+ assert_eq!(provider.icon.as_deref(), Some("assets/provider.png"));
+ }
+
+ #[test]
+ fn rejects_unsafe_or_missing_declared_icons() {
+ let dir = tempfile::tempdir().unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.icons",
+ "name": "Icons",
+ "icon": "../outside.svg",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "contributions": [{
+ "type": "connection-provider",
+ "id": "icons.connection",
+ "icon": "assets/missing.svg",
+ "database_type": "icons",
+ "fields": []
+ }]
+ }))
+ .unwrap();
+
+ let compatibility = manifest.compatibility(dir.path(), "0.5.68");
+
+ assert!(compatibility.errors.iter().any(|error| error.contains("Plugin icon is invalid")));
+ assert!(compatibility
+ .errors
+ .iter()
+ .any(|error| error.contains("Connection provider 'icons.connection' icon does not exist")));
+ }
+
+ #[test]
+ fn rejects_obsolete_ui_kind_declaration() {
+ let ui_error = serde_json::from_value::<PluginManifest>(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.host-ui",
+ "name": "Host UI",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "entrypoints": { "ui": { "kind": "sandbox-webview", "root": "ui", "entry": "ui/index.html" } }
+ }))
+ .unwrap_err();
+ let backend_error = serde_json::from_value::<PluginManifest>(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.backend-protocol",
+ "name": "Backend protocol",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "entrypoints": { "backend": { "protocol": "dbx-jsonrpc", "executable": "bin/plugin" } }
+ }))
+ .unwrap_err();
+
+ assert!(ui_error.to_string().contains("unknown field `kind`"));
+ assert!(backend_error.to_string().contains("unknown field `protocol`"));
+ }
+
+ #[test]
+ fn rejects_unknown_v1_top_level_fields_without_breaking_legacy_manifests() {
+ let dir = tempfile::tempdir().unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.unknown-field",
+ "name": "Unknown field",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "activation_events": ["onStartup"]
+ }))
+ .unwrap();
+ let compatibility = manifest.compatibility(dir.path(), "0.5.68");
+
+ assert!(compatibility
+ .errors
+ .iter()
+ .any(|error| error.contains("unknown top-level field(s): activation_events")));
+
+ let legacy: PluginManifest = serde_json::from_value(serde_json::json!({
+ "id": "jdbc",
+ "name": "JDBC",
+ "protocol_version": 1,
+ "legacy_metadata": true
+ }))
+ .unwrap();
+ assert!(legacy.compatibility(dir.path(), "0.5.68").errors.iter().all(|error| !error.contains("unknown")));
+ }
+
+ #[test]
+ fn rejects_legacy_runtime_declarations_in_manifest_v1() {
+ let dir = tempfile::tempdir().unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.mixed-contract",
+ "name": "Mixed contract",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "protocol_version": 2,
+ "executable": "bin/legacy",
+ "drivers": [{ "id": "legacy", "label": "Legacy", "kind": "external" }]
+ }))
+ .unwrap();
+ let compatibility = manifest.compatibility(dir.path(), "0.5.68");
+
+ assert!(compatibility
+ .errors
+ .iter()
+ .any(|error| error.contains("cannot use legacy executable or drivers fields")));
+ assert!(compatibility
+ .errors
+ .iter()
+ .any(|error| error.contains("cannot override the legacy protocol_version field")));
+ }
+
+ #[test]
+ fn legacy_manifest_remains_readable() {
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "id": "jdbc",
+ "name": "JDBC",
+ "protocol_version": 1,
+ "executable": "bin/dbx-jdbc-plugin",
+ "drivers": []
+ }))
+ .unwrap();
+
+ assert!(manifest.is_legacy());
+ assert_eq!(manifest.backend_entrypoint().unwrap().executable, "bin/dbx-jdbc-plugin");
+ }
+
+ #[test]
+ fn accepts_supported_connection_field_bindings() {
+ let dir = tempfile::tempdir().unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.connection-bindings",
+ "name": "Connection bindings",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "contributions": [{
+ "type": "connection-provider",
+ "id": "bindings.connection",
+ "label": "Bindings",
+ "database_type": "bindings",
+ "fields": [
+ { "key": "display_name", "label": "Name", "type": "text", "binding": "name" },
+ { "key": "host", "label": "Host", "type": "text", "binding": "host" },
+ { "key": "port", "label": "Port", "type": "number", "binding": "port" },
+ { "key": "username", "label": "Username", "type": "text", "binding": "username" },
+ { "key": "password", "label": "Password", "type": "password", "binding": "password" },
+ { "key": "database", "label": "Database", "type": "text", "binding": "database" },
+ { "key": "mode", "label": "Mode", "type": "text", "binding": "config" },
+ { "key": "token", "label": "Token", "type": "password", "binding": "secret" }
+ ]
+ }]
+ }))
+ .unwrap();
+
+ let compatibility = manifest.compatibility(dir.path(), "0.5.67");
+
+ assert!(compatibility.compatible, "{:?}", compatibility.errors);
+ let provider = manifest.connection_provider("bindings.connection").unwrap().unwrap();
+ assert_eq!(provider.fields.last().unwrap().effective_binding(), PluginFormFieldBinding::Secret);
+ }
+
+ #[test]
+ fn rejects_unknown_connection_field_binding() {
+ let error = serde_json::from_value::<PluginManifest>(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.invalid-binding",
+ "name": "Invalid binding",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "contributions": [{
+ "type": "connection-provider",
+ "id": "invalid.connection",
+ "label": "Invalid",
+ "database_type": "invalid",
+ "fields": [{ "key": "token", "label": "Token", "type": "password", "binding": "environment" }]
+ }]
+ }))
+ .unwrap_err();
+
+ assert!(error.to_string().contains("unknown variant `environment`"));
+ }
+
+ #[test]
+ fn rejects_incompatible_field_defaults_and_missing_provider_references() {
+ let dir = tempfile::tempdir().unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.invalid-contract",
+ "name": "Invalid contract",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "contributions": [
+ {
+ "type": "connection-provider",
+ "id": "invalid.connection",
+ "label": "Invalid",
+ "database_type": "invalid type",
+ "fields": [{ "key": "port", "label": "Port", "type": "text", "binding": "port", "default": true }],
+ "workbench": "missing.main"
+ }
+ ]
+ }))
+ .unwrap();
+
+ let compatibility = manifest.compatibility(dir.path(), "0.5.67");
+
+ assert!(compatibility.errors.iter().any(|error| error.contains("invalid database_type")));
+ assert!(compatibility.errors.iter().any(|error| error.contains("port binding requires number type")));
+ assert!(compatibility.errors.iter().any(|error| error.contains("invalid default value")));
+ assert!(compatibility.errors.iter().any(|error| error.contains("missing workbench")));
+ }
+
+ #[test]
+ fn validates_connection_bound_filesystem_provider_contract() {
+ let dir = tempfile::tempdir().unwrap();
+ let executable = dir.path().join("plugin");
+ std::fs::write(&executable, "binary").unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.files",
+ "name": "Files",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "entrypoints": { "backend": { "executable": "plugin" } },
+ "contributions": [
+ {
+ "type": "connection-provider",
+ "id": "files.connection",
+ "label": "Files",
+ "database_type": "files",
+ "fields": [],
+ "filesystem_provider": "files.provider"
+ },
+ {
+ "type": "filesystem-provider",
+ "id": "files.provider",
+ "label": "Files",
+ "schemes": ["files"],
+ "root_uri": "files:/",
+ "capabilities": ["read"]
+ }
+ ]
+ }))
+ .unwrap();
+
+ let compatibility = manifest.compatibility(dir.path(), "0.5.68");
+
+ assert!(compatibility.compatible, "{:?}", compatibility.errors);
+ assert_eq!(
+ manifest.filesystem_provider("files.provider").unwrap().unwrap().root_uri.as_deref(),
+ Some("files:/")
+ );
+ assert_eq!(
+ manifest.connection_provider("files.connection").unwrap().unwrap().filesystem_provider.as_deref(),
+ Some("files.provider")
+ );
+ }
+
+ #[test]
+ fn rejects_invalid_filesystem_root_and_missing_reference() {
+ let dir = tempfile::tempdir().unwrap();
+ let executable = dir.path().join("plugin");
+ std::fs::write(&executable, "binary").unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.invalid-files",
+ "name": "Invalid files",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "entrypoints": { "backend": { "executable": "plugin" } },
+ "contributions": [
+ {
+ "type": "connection-provider",
+ "id": "files.connection",
+ "label": "Files",
+ "database_type": "files",
+ "fields": [],
+ "filesystem_provider": "missing.provider"
+ },
+ {
+ "type": "filesystem-provider",
+ "id": "files.provider",
+ "label": "Files",
+ "schemes": ["files"],
+ "root_uri": "other:/",
+ "capabilities": ["read", "read"]
+ }
+ ]
+ }))
+ .unwrap();
+
+ let compatibility = manifest.compatibility(dir.path(), "0.5.68");
+
+ assert!(compatibility.errors.iter().any(|error| error.contains("invalid root_uri")));
+ assert!(compatibility.errors.iter().any(|error| error.contains("duplicate capabilities")));
+ assert!(compatibility.errors.iter().any(|error| error.contains("missing filesystem provider")));
+ }
+
+ #[test]
+ fn omits_empty_connection_actions_from_serialized_manifest() {
+ let omitted: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
+ "id": "sample.connection",
+ "label": "Sample",
+ "database_type": "sample",
+ "fields": []
+ }))
+ .unwrap();
+ let empty: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
+ "id": "sample.connection",
+ "label": "Sample",
+ "database_type": "sample",
+ "fields": [],
+ "actions": []
+ }))
+ .unwrap();
+
+ assert!(omitted.actions.is_empty());
+ assert!(empty.actions.is_empty());
+ assert!(serde_json::to_value(omitted).unwrap().get("actions").is_none());
+ assert!(serde_json::to_value(empty).unwrap().get("actions").is_none());
+ }
+
+ #[test]
+ fn validates_connection_action_contract() {
+ let actions: Vec<PluginConnectionActionContribution> = serde_json::from_value(serde_json::json!([
+ {
+ "id": "discover",
+ "label": "Discover",
+ "variant": "outline",
+ "when": "create",
+ "requires_valid_form": false,
+ "timeout_ms": 5000
+ }
+ ]))
+ .unwrap();
+ let mut errors = Vec::new();
+
+ validate_connection_actions(&actions, "sample.connection", &mut errors);
+
+ assert!(errors.is_empty(), "{errors:?}");
+ }
+
+ #[test]
+ fn rejects_invalid_connection_action_contracts() {
+ let malformed = serde_json::from_value::<PluginConnectionActionContribution>(serde_json::json!({
+ "id": "legacy",
+ "kind": "invoke",
+ "label": "Legacy",
+ "method": "sample/legacy"
+ }))
+ .unwrap_err();
+ let actions: Vec<PluginConnectionActionContribution> = serde_json::from_value(serde_json::json!([
+ { "id": "duplicate", "label": "" },
+ { "id": "duplicate", "label": "Duplicate", "timeout_ms": 0 }
+ ]))
+ .unwrap();
+ let mut errors = Vec::new();
+
+ validate_connection_actions(&actions, "sample.connection", &mut errors);
+
+ assert!(malformed.to_string().contains("unknown field `kind`"));
+ assert!(errors.iter().any(|error| error.contains("label cannot be empty")));
+ assert!(errors.iter().any(|error| error.contains("invalid or duplicate id")));
+ assert!(errors.iter().any(|error| error.contains("timeout_ms must be between")));
+ }
+}
diff --git a/crates/dbx-core/src/plugins/marketplace.rs b/crates/dbx-core/src/plugins/marketplace.rs
new file mode 100644
index 0000000000..2e4a4e5c53
--- /dev/null
+++ b/crates/dbx-core/src/plugins/marketplace.rs
@@ -0,0 +1,1109 @@
+use std::collections::{BTreeMap, BTreeSet};
+use std::fs::{File, OpenOptions};
+use std::io::Write;
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use fs2::FileExt;
+use futures::StreamExt;
+use reqwest::redirect::Policy;
+use reqwest::{Client, Url};
+use semver::Version;
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+
+use super::installer::{validate_key_id, PluginPackageExpectation};
+use super::manifest::{parse_host_network_permission, MAX_PLUGIN_NETWORK_ORIGINS};
+use super::{
+ current_plugin_target, PluginInstallResult, PluginPackageInstaller, PluginTrustStore, MAX_PLUGIN_PACKAGE_BYTES,
+ SUPPORTED_PLUGIN_PERMISSIONS,
+};
+
+pub const SUPPORTED_PLUGIN_CATALOG_VERSION: u32 = 1;
+pub const OFFICIAL_PLUGIN_REPOSITORY_ID: &str = "dbx-official";
+pub const UNIVERSAL_PLUGIN_TARGET: &str = "universal";
+pub const MAX_PLUGIN_CATALOG_BYTES: usize = 4 * 1024 * 1024;
+
+const REPOSITORIES_FILE: &str = ".repositories.json";
+const REPOSITORIES_LOCK_FILE: &str = ".repositories.lock";
+const OFFICIAL_CATALOG_URL: &str = "https://raw.githubusercontent.com/t8y2/dbx-store/main/catalog/index.json";
+const ADDITIONAL_OFFICIAL_TRUSTED_KEYS_JSON: Option<&str> = option_env!("DBX_PLUGIN_MARKETPLACE_TRUSTED_KEYS_JSON");
+const BUILTIN_OFFICIAL_TRUSTED_KEYS: &[(&str, &str)] = &[
+ ("dbx-store-preview-2026", "VRb0VscZfWwuFa7LYfeD/wEOJeyNP8wPGND9br8Icmk="),
+ ("dbx-store-release-2026", "6WbMG2UDx+EZ/oauMtHjdinvSD5MuFWSgXbI0n7eL+k="),
+];
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum PluginRepositoryKind {
+ Official,
+ Custom,
+ Enterprise,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginRepository {
+ pub id: String,
+ pub name: String,
+ pub kind: PluginRepositoryKind,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub catalog_url: Option<String>,
+ #[serde(default = "default_true")]
+ pub enabled: bool,
+ #[serde(default)]
+ pub managed: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct PluginMarketplaceRepositoryMetadata {
+ pub id: String,
+ pub name: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub homepage: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct PluginMarketplaceLocalization {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub description: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct PluginMarketplaceArtifact {
+ pub target: String,
+ pub url: String,
+ pub sha256: String,
+ pub signing_key_id: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub size: Option<u64>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct PluginMarketplaceVersion {
+ pub version: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub released_at: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub release_notes: Option<String>,
+ #[serde(default)]
+ pub artifacts: Vec<PluginMarketplaceArtifact>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct PluginMarketplacePlugin {
+ pub id: String,
+ pub name: String,
+ #[serde(default)]
+ pub description: String,
+ pub publisher: String,
+ #[serde(default)]
+ pub verified: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub icon: Option<String>,
+ #[serde(default)]
+ pub tags: Vec<String>,
+ #[serde(default)]
+ pub permissions: Vec<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub source: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub homepage: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub license: Option<String>,
+ pub latest_version: String,
+ #[serde(default)]
+ pub versions: Vec<PluginMarketplaceVersion>,
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub localizations: BTreeMap<String, PluginMarketplaceLocalization>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginMarketplaceCatalog {
+ pub catalog_version: u32,
+ pub repository: PluginMarketplaceRepositoryMetadata,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub generated_at: Option<String>,
+ #[serde(default)]
+ pub plugins: Vec<PluginMarketplacePlugin>,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginRepositoryCatalogResult {
+ pub repository: PluginRepository,
+ pub target: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub catalog: Option<PluginMarketplaceCatalog>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginMarketplaceInstallRequest {
+ pub repository_id: String,
+ pub plugin_id: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub version: Option<String>,
+}
+
+#[derive(Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct PluginRepositoryDocument {
+ #[serde(default = "supported_repository_document_version")]
+ version: u32,
+ #[serde(default)]
+ repositories: Vec<PluginRepository>,
+}
+
+#[derive(Debug, Clone)]
+pub struct PluginRepositoryStore {
+ root_dir: PathBuf,
+}
+
+impl PluginRepositoryStore {
+ pub fn new(root_dir: PathBuf) -> Self {
+ Self { root_dir }
+ }
+
+ pub fn list(&self) -> Result<Vec<PluginRepository>, String> {
+ let document = self.read_document()?;
+ let mut repositories = vec![official_repository()];
+ repositories.extend(document.repositories);
+ Ok(repositories)
+ }
+
+ pub fn find(&self, repository_id: &str) -> Result<PluginRepository, String> {
+ self.list()?
+ .into_iter()
+ .find(|repository| repository.id == repository_id)
+ .ok_or_else(|| format!("Plugin repository '{repository_id}' does not exist"))
+ }
+
+ pub fn save(&self, mut repository: PluginRepository) -> Result<Vec<PluginRepository>, String> {
+ validate_repository(&repository)?;
+ if repository.id == OFFICIAL_PLUGIN_REPOSITORY_ID
+ || repository.kind == PluginRepositoryKind::Official
+ || repository.managed
+ {
+ return Err("Managed plugin repositories cannot be modified".to_string());
+ }
+ repository.managed = false;
+ let lock = self.open_lock()?;
+ lock.lock_exclusive().map_err(|error| format!("Failed to lock plugin repositories: {error}"))?;
+ let result = (|| {
+ let mut document = self.read_document()?;
+ if let Some(existing) = document.repositories.iter_mut().find(|existing| existing.id == repository.id) {
+ *existing = repository;
+ } else {
+ document.repositories.push(repository);
+ }
+ document.repositories.sort_by(|left, right| left.id.cmp(&right.id));
+ write_json_atomically(&self.document_path(), &document)
+ })();
+ let _ = FileExt::unlock(&lock);
+ result?;
+ self.list()
+ }
+
+ pub fn remove(&self, repository_id: &str) -> Result<Vec<PluginRepository>, String> {
+ validate_repository_id(repository_id)?;
+ if repository_id == OFFICIAL_PLUGIN_REPOSITORY_ID {
+ return Err("Managed plugin repositories cannot be removed".to_string());
+ }
+ let lock = self.open_lock()?;
+ lock.lock_exclusive().map_err(|error| format!("Failed to lock plugin repositories: {error}"))?;
+ let result = (|| {
+ let mut document = self.read_document()?;
+ document.repositories.retain(|repository| repository.id != repository_id);
+ write_json_atomically(&self.document_path(), &document)
+ })();
+ let _ = FileExt::unlock(&lock);
+ result?;
+ self.list()
+ }
+
+ fn document_path(&self) -> PathBuf {
+ self.root_dir.join(REPOSITORIES_FILE)
+ }
+
+ fn open_lock(&self) -> Result<File, String> {
+ std::fs::create_dir_all(&self.root_dir).map_err(|error| error.to_string())?;
+ OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(self.root_dir.join(REPOSITORIES_LOCK_FILE))
+ .map_err(|error| error.to_string())
+ }
+
+ fn read_document(&self) -> Result<PluginRepositoryDocument, String> {
+ let path = self.document_path();
+ let raw = match std::fs::read(&path) {
+ Ok(raw) => raw,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
+ return Ok(PluginRepositoryDocument {
+ version: supported_repository_document_version(),
+ repositories: vec![],
+ });
+ }
+ Err(error) => return Err(format!("Failed to read plugin repositories {}: {error}", path.display())),
+ };
+ let document: PluginRepositoryDocument = serde_json::from_slice(&raw)
+ .map_err(|error| format!("Failed to parse plugin repositories {}: {error}", path.display()))?;
+ if document.version != supported_repository_document_version() {
+ return Err(format!("Unsupported plugin repository document version {}", document.version));
+ }
+ for repository in &document.repositories {
+ validate_repository(repository)?;
+ if repository.id == OFFICIAL_PLUGIN_REPOSITORY_ID
+ || repository.kind == PluginRepositoryKind::Official
+ || repository.managed
+ {
+ return Err(format!("Plugin repository '{}' attempts to override a managed repository", repository.id));
+ }
+ }
+ Ok(document)
+ }
+}
+
+#[derive(Clone)]
+pub struct PluginMarketplace {
+ root_dir: PathBuf,
+ app_version: String,
+ repositories: PluginRepositoryStore,
+ client: Client,
+}
+
+impl PluginMarketplace {
+ pub fn new(root_dir: PathBuf, app_version: impl Into<String>) -> Result<Self, String> {
+ let client = Client::builder()
+ .redirect(Policy::limited(5))
+ .connect_timeout(Duration::from_secs(10))
+ .timeout(Duration::from_secs(300))
+ .user_agent(format!("DBX/{}/plugin-marketplace", env!("CARGO_PKG_VERSION")))
+ .build()
+ .map_err(|error| format!("Failed to create plugin marketplace HTTP client: {error}"))?;
+ Ok(Self {
+ repositories: PluginRepositoryStore::new(root_dir.clone()),
+ root_dir,
+ app_version: app_version.into(),
+ client,
+ })
+ }
+
+ pub fn repositories(&self) -> &PluginRepositoryStore {
+ &self.repositories
+ }
+
+ pub async fn fetch_catalogs(&self) -> Vec<PluginRepositoryCatalogResult> {
+ let repositories = match self.repositories.list() {
+ Ok(repositories) => repositories,
+ Err(error) => {
+ return vec![PluginRepositoryCatalogResult {
+ repository: official_repository(),
+ target: current_plugin_target(),
+ catalog: None,
+ error: Some(error),
+ }];
+ }
+ };
+ self.fetch_catalog_results(repositories).await
+ }
+
+ async fn fetch_catalog_results(&self, repositories: Vec<PluginRepository>) -> Vec<PluginRepositoryCatalogResult> {
+ let futures = repositories.into_iter().filter(|repository| repository.enabled).map(|repository| async move {
+ match self.fetch_catalog(&repository).await {
+ Ok(catalog) => PluginRepositoryCatalogResult {
+ repository,
+ target: current_plugin_target(),
+ catalog: Some(catalog),
+ error: None,
+ },
+ Err(error) => PluginRepositoryCatalogResult {
+ repository,
+ target: current_plugin_target(),
+ catalog: None,
+ error: Some(error),
+ },
+ }
+ });
+ futures::future::join_all(futures).await
+ }
+
+ pub async fn fetch_catalog(&self, repository: &PluginRepository) -> Result<PluginMarketplaceCatalog, String> {
+ validate_repository(repository)?;
+ let catalog_url = repository_catalog_url(repository)?;
+ let raw = self.download_limited(catalog_url.clone(), MAX_PLUGIN_CATALOG_BYTES, "Plugin catalog").await?;
+ let mut catalog: PluginMarketplaceCatalog = serde_json::from_slice(&raw)
+ .map_err(|error| format!("Failed to parse plugin catalog from {catalog_url}: {error}"))?;
+ validate_and_resolve_catalog(&mut catalog, repository, &catalog_url)?;
+ Ok(catalog)
+ }
+
+ pub async fn install(&self, request: PluginMarketplaceInstallRequest) -> Result<PluginInstallResult, String> {
+ let repository = self.repositories.find(&request.repository_id)?;
+ if !repository.enabled {
+ return Err(format!("Plugin repository '{}' is disabled", repository.id));
+ }
+ let catalog = self.fetch_catalog(&repository).await?;
+ let plugin =
+ catalog.plugins.iter().find(|plugin| plugin.id == request.plugin_id).ok_or_else(|| {
+ format!("Plugin '{}' is not listed by repository '{}'", request.plugin_id, repository.id)
+ })?;
+ let requested_version = request.version.as_deref().unwrap_or(&plugin.latest_version);
+ let version = plugin
+ .versions
+ .iter()
+ .find(|version| version.version == requested_version)
+ .ok_or_else(|| format!("Plugin '{}' version '{}' is not listed", plugin.id, requested_version))?;
+ let target = current_plugin_target();
+ let artifact = select_marketplace_artifact(version, &target).ok_or_else(|| {
+ format!("Plugin '{}' version '{}' does not support target '{}'", plugin.id, version.version, target)
+ })?;
+ let artifact_url =
+ Url::parse(&artifact.url).map_err(|error| format!("Invalid plugin artifact URL: {error}"))?;
+ let package = self.download_limited(artifact_url, MAX_PLUGIN_PACKAGE_BYTES, "Plugin package").await?;
+ verify_artifact_bytes(artifact, &package)?;
+ let trust_store = marketplace_trust_store(&self.root_dir, repository.kind)?;
+ let expectation = PluginPackageExpectation {
+ id: plugin.id.clone(),
+ version: version.version.clone(),
+ publisher: plugin.publisher.clone(),
+ permissions: plugin.permissions.iter().cloned().collect(),
+ signing_key_id: artifact.signing_key_id.clone(),
+ };
+ PluginPackageInstaller::with_trust_store(self.root_dir.clone(), self.app_version.clone(), trust_store)
+ .install_marketplace_bytes(&package, &expectation)
+ }
+
+ async fn download_limited(&self, url: Url, max_bytes: usize, label: &str) -> Result<Vec<u8>, String> {
+ let response = self
+ .client
+ .get(url.clone())
+ .send()
+ .await
+ .map_err(|error| format!("Failed to download {label} from {url}: {error}"))?;
+ if !response.status().is_success() {
+ return Err(format!("Failed to download {label} from {url}: HTTP {}", response.status()));
+ }
+ if response.content_length().is_some_and(|length| length > max_bytes as u64) {
+ return Err(format!("{label} exceeds {max_bytes} bytes"));
+ }
+ let mut bytes = Vec::new();
+ let mut stream = response.bytes_stream();
+ while let Some(chunk) = stream.next().await {
+ let chunk = chunk.map_err(|error| format!("Failed to read {label} from {url}: {error}"))?;
+ if bytes.len().saturating_add(chunk.len()) > max_bytes {
+ return Err(format!("{label} exceeds {max_bytes} bytes"));
+ }
+ bytes.extend_from_slice(&chunk);
+ }
+ Ok(bytes)
+ }
+}
+
+fn select_marketplace_artifact<'a>(
+ version: &'a PluginMarketplaceVersion,
+ target: &str,
+) -> Option<&'a PluginMarketplaceArtifact> {
+ version
+ .artifacts
+ .iter()
+ .find(|artifact| artifact.target == target)
+ .or_else(|| version.artifacts.iter().find(|artifact| artifact.target == UNIVERSAL_PLUGIN_TARGET))
+}
+
+fn default_true() -> bool {
+ true
+}
+
+fn supported_repository_document_version() -> u32 {
+ 1
+}
+
+fn official_repository() -> PluginRepository {
+ PluginRepository {
+ id: OFFICIAL_PLUGIN_REPOSITORY_ID.to_string(),
+ name: "DBX Marketplace".to_string(),
+ kind: PluginRepositoryKind::Official,
+ catalog_url: Some(OFFICIAL_CATALOG_URL.to_string()),
+ enabled: true,
+ managed: true,
+ }
+}
+
+fn repository_catalog_url(repository: &PluginRepository) -> Result<Url, String> {
+ let raw = repository.catalog_url.as_deref().and_then(trimmed_nonempty).ok_or_else(|| {
+ if repository.kind == PluginRepositoryKind::Official {
+ "Official DBX Marketplace catalog is not configured in this build".to_string()
+ } else {
+ format!("Plugin repository '{}' has no catalog URL", repository.id)
+ }
+ })?;
+ parse_http_url(raw, "Plugin repository catalog URL")
+}
+
+fn validate_repository(repository: &PluginRepository) -> Result<(), String> {
+ validate_repository_id(&repository.id)?;
+ if repository.name.trim().is_empty() || repository.name.len() > 128 {
+ return Err("Plugin repository name must be between 1 and 128 bytes".to_string());
+ }
+ if let Some(catalog_url) = repository.catalog_url.as_deref().and_then(trimmed_nonempty) {
+ parse_http_url(catalog_url, "Plugin repository catalog URL")?;
+ } else if repository.kind != PluginRepositoryKind::Official {
+ return Err("Custom plugin repositories require a catalog URL".to_string());
+ }
+ Ok(())
+}
+
+fn validate_repository_id(id: &str) -> Result<(), String> {
+ if id.is_empty() || id.len() > 128 {
+ return Err("Plugin repository id must be between 1 and 128 bytes".to_string());
+ }
+ let mut characters = id.chars();
+ if !matches!(characters.next(), Some(character) if character.is_ascii_lowercase() || character.is_ascii_digit())
+ || !characters.all(|character| {
+ character.is_ascii_lowercase() || character.is_ascii_digit() || matches!(character, '.' | '-' | '_')
+ })
+ {
+ return Err(format!("Invalid plugin repository id '{id}'"));
+ }
+ Ok(())
+}
+
+fn validate_and_resolve_catalog(
+ catalog: &mut PluginMarketplaceCatalog,
+ repository: &PluginRepository,
+ catalog_url: &Url,
+) -> Result<(), String> {
+ if catalog.catalog_version != SUPPORTED_PLUGIN_CATALOG_VERSION {
+ return Err(format!(
+ "Unsupported plugin catalog version {}; this DBX build supports version {}",
+ catalog.catalog_version, SUPPORTED_PLUGIN_CATALOG_VERSION
+ ));
+ }
+ if catalog.repository.id != repository.id {
+ return Err(format!(
+ "Plugin catalog repository id '{}' does not match configured repository '{}'",
+ catalog.repository.id, repository.id
+ ));
+ }
+ if catalog.repository.name.trim().is_empty() {
+ return Err("Plugin catalog repository name cannot be empty".to_string());
+ }
+ let mut plugin_ids = BTreeSet::new();
+ for plugin in &mut catalog.plugins {
+ validate_plugin_id(&plugin.id)?;
+ if !plugin_ids.insert(plugin.id.clone()) {
+ return Err(format!("Plugin catalog contains duplicate plugin '{}'", plugin.id));
+ }
+ if plugin.name.trim().is_empty() || plugin.publisher.trim().is_empty() {
+ return Err(format!("Plugin '{}' must declare a name and publisher", plugin.id));
+ }
+ let permissions = plugin.permissions.iter().collect::<BTreeSet<_>>();
+ if permissions.len() != plugin.permissions.len() {
+ return Err(format!("Plugin '{}' contains duplicate permissions", plugin.id));
+ }
+ if let Some(permission) = plugin.permissions.iter().find(|permission| {
+ !SUPPORTED_PLUGIN_PERMISSIONS.contains(&permission.as_str())
+ && parse_host_network_permission(permission).is_none()
+ }) {
+ return Err(format!("Plugin '{}' declares unsupported permission '{}'", plugin.id, permission));
+ }
+ let network_origins = plugin
+ .permissions
+ .iter()
+ .filter_map(|permission| parse_host_network_permission(permission))
+ .collect::<BTreeSet<_>>();
+ if network_origins.len() > MAX_PLUGIN_NETWORK_ORIGINS {
+ return Err(format!(
+ "Plugin '{}' declares {} network origins; at most {} are allowed",
+ plugin.id,
+ network_origins.len(),
+ MAX_PLUGIN_NETWORK_ORIGINS
+ ));
+ }
+ let latest = Version::parse(&plugin.latest_version)
+ .map_err(|error| format!("Plugin '{}' has invalid latestVersion: {error}", plugin.id))?;
+ let mut versions = BTreeSet::new();
+ let mut contains_latest = false;
+ for version in &mut plugin.versions {
+ let parsed = Version::parse(&version.version).map_err(|error| {
+ format!("Plugin '{}' has invalid version '{}': {error}", plugin.id, version.version)
+ })?;
+ if !versions.insert(parsed.clone()) {
+ return Err(format!("Plugin '{}' contains duplicate version '{}'", plugin.id, version.version));
+ }
+ contains_latest |= parsed == latest;
+ let mut targets = BTreeSet::new();
+ for artifact in &mut version.artifacts {
+ validate_target(&artifact.target)?;
+ if !targets.insert(artifact.target.clone()) {
+ return Err(format!(
+ "Plugin '{}' version '{}' contains duplicate target '{}'",
+ plugin.id, version.version, artifact.target
+ ));
+ }
+ validate_sha256(&artifact.sha256)?;
+ validate_key_id(&artifact.signing_key_id)?;
+ if artifact.size.is_some_and(|size| size > MAX_PLUGIN_PACKAGE_BYTES as u64) {
+ return Err(format!(
+ "Plugin '{}' version '{}' target '{}' exceeds the package size limit",
+ plugin.id, version.version, artifact.target
+ ));
+ }
+ artifact.url = resolve_http_url(catalog_url, &artifact.url, "Plugin artifact URL")?.to_string();
+ }
+ }
+ if !contains_latest {
+ return Err(format!(
+ "Plugin '{}' latestVersion '{}' is not present in versions",
+ plugin.id, plugin.latest_version
+ ));
+ }
+ if let Some(icon) = plugin.icon.as_deref().and_then(trimmed_nonempty) {
+ plugin.icon = Some(resolve_http_url(catalog_url, icon, "Plugin icon URL")?.to_string());
+ }
+ }
+ Ok(())
+}
+
+fn validate_plugin_id(id: &str) -> Result<(), String> {
+ if id.is_empty() || id.len() > 128 {
+ return Err("Marketplace plugin id must be between 1 and 128 bytes".to_string());
+ }
+ let mut characters = id.chars();
+ if !matches!(characters.next(), Some(character) if character.is_ascii_lowercase() || character.is_ascii_digit())
+ || !characters.all(|character| {
+ character.is_ascii_lowercase() || character.is_ascii_digit() || matches!(character, '.' | '-' | '_')
+ })
+ {
+ return Err(format!("Invalid marketplace plugin id '{id}'"));
+ }
+ Ok(())
+}
+
+fn validate_target(target: &str) -> Result<(), String> {
+ if target.is_empty()
+ || target.len() > 64
+ || !target
+ .chars()
+ .all(|character| character.is_ascii_lowercase() || character.is_ascii_digit() || character == '-')
+ {
+ return Err(format!("Invalid plugin artifact target '{target}'"));
+ }
+ Ok(())
+}
+
+fn validate_sha256(sha256: &str) -> Result<(), String> {
+ if sha256.len() != 64 || !sha256.bytes().all(|byte| byte.is_ascii_hexdigit()) {
+ return Err("Plugin artifact SHA-256 must contain 64 hexadecimal characters".to_string());
+ }
+ Ok(())
+}
+
+fn verify_artifact_bytes(artifact: &PluginMarketplaceArtifact, bytes: &[u8]) -> Result<(), String> {
+ if artifact.size.is_some_and(|expected| expected != bytes.len() as u64) {
+ return Err(format!(
+ "Plugin artifact size mismatch: expected {}, received {}",
+ artifact.size.unwrap_or_default(),
+ bytes.len()
+ ));
+ }
+ let actual = format!("{:x}", Sha256::digest(bytes));
+ if !actual.eq_ignore_ascii_case(&artifact.sha256) {
+ return Err(format!("Plugin artifact SHA-256 mismatch: expected {}, received {actual}", artifact.sha256));
+ }
+ Ok(())
+}
+
+fn marketplace_trust_store(root_dir: &Path, kind: PluginRepositoryKind) -> Result<PluginTrustStore, String> {
+ if kind != PluginRepositoryKind::Official {
+ return PluginTrustStore::load(root_dir);
+ }
+ let mut keys = BUILTIN_OFFICIAL_TRUSTED_KEYS
+ .iter()
+ .map(|(key_id, public_key)| ((*key_id).to_string(), (*public_key).to_string()))
+ .collect::<BTreeMap<_, _>>();
+ if let Some(raw) = ADDITIONAL_OFFICIAL_TRUSTED_KEYS_JSON.and_then(trimmed_nonempty) {
+ let additional: BTreeMap<String, String> = serde_json::from_str(raw)
+ .map_err(|error| format!("Failed to parse additional official DBX Marketplace signing keys: {error}"))?;
+ for (key_id, public_key) in additional {
+ if keys.insert(key_id.clone(), public_key).is_some() {
+ return Err(format!("Duplicate official DBX Marketplace signing key '{key_id}'"));
+ }
+ }
+ }
+ let store = PluginTrustStore::from_base64_keys(keys)?;
+ if store.is_empty() {
+ return Err("Official DBX Marketplace signing keys are empty".to_string());
+ }
+ Ok(store)
+}
+
+fn parse_http_url(raw: &str, label: &str) -> Result<Url, String> {
+ let url = Url::parse(raw).map_err(|error| format!("Invalid {label}: {error}"))?;
+ ensure_http_url(url, label)
+}
+
+fn resolve_http_url(base: &Url, raw: &str, label: &str) -> Result<Url, String> {
+ let url = base.join(raw).map_err(|error| format!("Invalid {label}: {error}"))?;
+ ensure_http_url(url, label)
+}
+
+fn ensure_http_url(url: Url, label: &str) -> Result<Url, String> {
+ if !matches!(url.scheme(), "http" | "https") {
+ return Err(format!("{label} must use HTTP or HTTPS"));
+ }
+ if url.host_str().is_none() {
+ return Err(format!("{label} must include a host"));
+ }
+ Ok(url)
+}
+
+fn trimmed_nonempty(value: &str) -> Option<&str> {
+ let value = value.trim();
+ (!value.is_empty()).then_some(value)
+}
+
+fn write_json_atomically<T: Serialize>(path: &Path, value: &T) -> Result<(), String> {
+ let parent = path.parent().ok_or("Plugin repository path has no parent")?;
+ std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
+ let temporary = parent.join(format!(".{}.tmp", uuid::Uuid::new_v4()));
+ let mut file =
+ OpenOptions::new().write(true).create_new(true).open(&temporary).map_err(|error| error.to_string())?;
+ file.write_all(&serde_json::to_vec_pretty(value).map_err(|error| error.to_string())?)
+ .map_err(|error| error.to_string())?;
+ file.sync_all().map_err(|error| error.to_string())?;
+ if path.exists() {
+ std::fs::remove_file(path).map_err(|error| error.to_string())?;
+ }
+ std::fs::rename(&temporary, path).map_err(|error| error.to_string())?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use base64::Engine;
+ use ed25519_dalek::{Signer, SigningKey};
+ use std::io::Cursor;
+ use zip::write::SimpleFileOptions;
+
+ use crate::plugins::{PLUGIN_CHECKSUMS_FILE, PLUGIN_SIGNATURE_FILE};
+
+ fn custom_repository(id: &str) -> PluginRepository {
+ PluginRepository {
+ id: id.to_string(),
+ name: format!("Repository {id}"),
+ kind: PluginRepositoryKind::Custom,
+ catalog_url: Some(format!("https://plugins.example.com/{id}/catalog/index.json")),
+ enabled: true,
+ managed: false,
+ }
+ }
+
+ fn catalog(repository_id: &str) -> PluginMarketplaceCatalog {
+ PluginMarketplaceCatalog {
+ catalog_version: 1,
+ repository: PluginMarketplaceRepositoryMetadata {
+ id: repository_id.to_string(),
+ name: "Example Marketplace".to_string(),
+ homepage: None,
+ },
+ generated_at: None,
+ plugins: vec![PluginMarketplacePlugin {
+ id: "example.hello".to_string(),
+ name: "Hello".to_string(),
+ description: "Example".to_string(),
+ publisher: "example".to_string(),
+ verified: true,
+ icon: Some("../assets/icon.svg".to_string()),
+ tags: vec!["hello".to_string()],
+ permissions: vec!["host.events".to_string()],
+ source: None,
+ homepage: None,
+ license: Some("Apache-2.0".to_string()),
+ latest_version: "1.0.0".to_string(),
+ versions: vec![PluginMarketplaceVersion {
+ version: "1.0.0".to_string(),
+ released_at: None,
+ release_notes: Some("Initial release".to_string()),
+ artifacts: vec![PluginMarketplaceArtifact {
+ target: current_plugin_target(),
+ url: "../dist/plugin.dbxp".to_string(),
+ sha256: "a".repeat(64),
+ signing_key_id: "example.release".to_string(),
+ size: Some(100),
+ }],
+ }],
+ localizations: BTreeMap::new(),
+ }],
+ }
+ }
+
+ #[test]
+ fn persists_custom_repositories_without_overriding_official() {
+ let root = tempfile::tempdir().unwrap();
+ let store = PluginRepositoryStore::new(root.path().to_path_buf());
+ let repositories = store.save(custom_repository("team-marketplace")).unwrap();
+ assert_eq!(repositories.len(), 2);
+ assert!(repositories[0].managed);
+ assert_eq!(repositories[1].id, "team-marketplace");
+
+ let reloaded = PluginRepositoryStore::new(root.path().to_path_buf()).list().unwrap();
+ assert_eq!(reloaded, repositories);
+ assert!(store.remove(OFFICIAL_PLUGIN_REPOSITORY_ID).unwrap_err().contains("Managed"));
+
+ let mut override_repository = custom_repository(OFFICIAL_PLUGIN_REPOSITORY_ID);
+ override_repository.kind = PluginRepositoryKind::Official;
+ override_repository.managed = true;
+ assert!(store.save(override_repository).unwrap_err().contains("Managed"));
+ }
+
+ #[test]
+ fn validates_catalog_and_resolves_relative_urls() {
+ let repository = custom_repository("team-marketplace");
+ let catalog_url = Url::parse(repository.catalog_url.as_deref().unwrap()).unwrap();
+ let mut catalog = catalog(&repository.id);
+ validate_and_resolve_catalog(&mut catalog, &repository, &catalog_url).unwrap();
+
+ let plugin = &catalog.plugins[0];
+ assert_eq!(plugin.icon.as_deref(), Some("https://plugins.example.com/team-marketplace/assets/icon.svg"));
+ assert_eq!(
+ plugin.versions[0].artifacts[0].url,
+ "https://plugins.example.com/team-marketplace/dist/plugin.dbxp"
+ );
+ }
+
+ #[test]
+ fn validates_declared_network_permissions_in_catalogs() {
+ let repository = custom_repository("team-marketplace");
+ let catalog_url = Url::parse(repository.catalog_url.as_deref().unwrap()).unwrap();
+
+ let mut valid_catalog = catalog(&repository.id);
+ valid_catalog.plugins[0].permissions.push("host.network:https://api.example.com".to_string());
+ validate_and_resolve_catalog(&mut valid_catalog, &repository, &catalog_url).unwrap();
+
+ valid_catalog.plugins[0].permissions.push("host.network:http://api.example.com".to_string());
+ assert!(validate_and_resolve_catalog(&mut valid_catalog, &repository, &catalog_url)
+ .unwrap_err()
+ .contains("unsupported permission"));
+
+ let mut too_many_origins_catalog = catalog(&repository.id);
+ too_many_origins_catalog.plugins[0].permissions = (0..=MAX_PLUGIN_NETWORK_ORIGINS)
+ .map(|index| format!("host.network:https://api{index}.example.com"))
+ .collect();
+ assert!(validate_and_resolve_catalog(&mut too_many_origins_catalog, &repository, &catalog_url)
+ .unwrap_err()
+ .contains("network origins"));
+ }
+
+ #[test]
+ fn selects_exact_marketplace_artifact_before_universal_fallback() {
+ let version = PluginMarketplaceVersion {
+ version: "1.0.0".to_string(),
+ released_at: None,
+ release_notes: None,
+ artifacts: vec![
+ PluginMarketplaceArtifact {
+ target: UNIVERSAL_PLUGIN_TARGET.to_string(),
+ url: "https://plugins.example.com/universal.dbxp".to_string(),
+ sha256: "a".repeat(64),
+ signing_key_id: "example.release".to_string(),
+ size: None,
+ },
+ PluginMarketplaceArtifact {
+ target: "darwin-arm64".to_string(),
+ url: "https://plugins.example.com/darwin-arm64.dbxp".to_string(),
+ sha256: "b".repeat(64),
+ signing_key_id: "example.release".to_string(),
+ size: None,
+ },
+ ],
+ };
+
+ assert_eq!(
+ select_marketplace_artifact(&version, "darwin-arm64").map(|artifact| artifact.target.as_str()),
+ Some("darwin-arm64")
+ );
+ }
+
+ #[test]
+ fn falls_back_to_universal_marketplace_artifact() {
+ let version = PluginMarketplaceVersion {
+ version: "1.0.0".to_string(),
+ released_at: None,
+ release_notes: None,
+ artifacts: vec![PluginMarketplaceArtifact {
+ target: UNIVERSAL_PLUGIN_TARGET.to_string(),
+ url: "https://plugins.example.com/universal.dbxp".to_string(),
+ sha256: "a".repeat(64),
+ signing_key_id: "example.release".to_string(),
+ size: None,
+ }],
+ };
+
+ assert_eq!(
+ select_marketplace_artifact(&version, "linux-x64").map(|artifact| artifact.target.as_str()),
+ Some(UNIVERSAL_PLUGIN_TARGET)
+ );
+ }
+
+ #[test]
+ fn rejects_duplicate_versions_invalid_sha_and_repository_mismatch() {
+ let repository = custom_repository("team-marketplace");
+ let catalog_url = Url::parse(repository.catalog_url.as_deref().unwrap()).unwrap();
+
+ let mut duplicate = catalog(&repository.id);
+ let duplicate_version = duplicate.plugins[0].versions[0].clone();
+ duplicate.plugins[0].versions.push(duplicate_version);
+ assert!(validate_and_resolve_catalog(&mut duplicate, &repository, &catalog_url)
+ .unwrap_err()
+ .contains("duplicate version"));
+
+ let mut invalid_sha = catalog(&repository.id);
+ invalid_sha.plugins[0].versions[0].artifacts[0].sha256 = "invalid".to_string();
+ assert!(validate_and_resolve_catalog(&mut invalid_sha, &repository, &catalog_url)
+ .unwrap_err()
+ .contains("SHA-256"));
+
+ let mut mismatch = catalog("another-repository");
+ assert!(validate_and_resolve_catalog(&mut mismatch, &repository, &catalog_url)
+ .unwrap_err()
+ .contains("does not match"));
+ }
+
+ #[test]
+ fn verifies_artifact_size_and_sha256() {
+ let bytes = b"plugin-package";
+ let artifact = PluginMarketplaceArtifact {
+ target: current_plugin_target(),
+ url: "https://plugins.example.com/plugin.dbxp".to_string(),
+ sha256: format!("{:x}", Sha256::digest(bytes)),
+ signing_key_id: "example.release".to_string(),
+ size: Some(bytes.len() as u64),
+ };
+ verify_artifact_bytes(&artifact, bytes).unwrap();
+
+ let mut wrong_sha = artifact.clone();
+ wrong_sha.sha256 = "0".repeat(64);
+ assert!(verify_artifact_bytes(&wrong_sha, bytes).unwrap_err().contains("SHA-256 mismatch"));
+
+ let mut wrong_size = artifact;
+ wrong_size.size = Some(1);
+ assert!(verify_artifact_bytes(&wrong_size, bytes).unwrap_err().contains("size mismatch"));
+ }
+
+ #[test]
+ fn exposes_managed_official_repository() {
+ let repository = official_repository();
+ assert_eq!(repository.id, OFFICIAL_PLUGIN_REPOSITORY_ID);
+ assert_eq!(repository.kind, PluginRepositoryKind::Official);
+ assert_eq!(repository.catalog_url.as_deref(), Some(OFFICIAL_CATALOG_URL));
+ assert!(repository.enabled);
+ assert!(repository.managed);
+ }
+
+ #[test]
+ fn loads_builtin_official_trusted_keys() {
+ let root = tempfile::tempdir().unwrap();
+ assert!(!marketplace_trust_store(root.path(), PluginRepositoryKind::Official).unwrap().is_empty());
+ }
+
+ #[tokio::test]
+ async fn isolates_repository_fetch_failures() {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+ let root = tempfile::tempdir().unwrap();
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let working = PluginRepository {
+ catalog_url: Some(format!("http://{address}/catalog.json")),
+ ..custom_repository("working-marketplace")
+ };
+ let broken = PluginRepository {
+ catalog_url: Some("http://127.0.0.1:9/catalog.json".to_string()),
+ ..custom_repository("broken-marketplace")
+ };
+ let store = PluginRepositoryStore::new(root.path().to_path_buf());
+ store.save(working.clone()).unwrap();
+ store.save(broken.clone()).unwrap();
+ let body = serde_json::to_vec(&catalog(&working.id)).unwrap();
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut request = [0u8; 2048];
+ let _ = socket.read(&mut request).await.unwrap();
+ socket
+ .write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).as_bytes())
+ .await
+ .unwrap();
+ socket.write_all(&body).await.unwrap();
+ });
+
+ let marketplace = PluginMarketplace::new(root.path().to_path_buf(), "0.5.68").unwrap();
+ let results = marketplace.fetch_catalog_results(vec![working.clone(), broken.clone()]).await;
+ server.await.unwrap();
+
+ assert!(results.iter().any(|result| result.repository.id == working.id && result.catalog.is_some()));
+ assert!(results.iter().any(|result| result.repository.id == broken.id && result.error.is_some()));
+ }
+
+ #[tokio::test]
+ async fn downloads_and_installs_a_signed_universal_marketplace_package() {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+ let root = tempfile::tempdir().unwrap();
+ let signing_key = SigningKey::from_bytes(&[42u8; 32]);
+ let key_id = "example-marketplace-release";
+ PluginTrustStore::save_base64_key(
+ root.path(),
+ key_id,
+ &base64::engine::general_purpose::STANDARD.encode(signing_key.verifying_key().as_bytes()),
+ )
+ .unwrap();
+ let package = signed_package(&signing_key, key_id);
+ let package_sha256 = format!("{:x}", Sha256::digest(&package));
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let repository = PluginRepository {
+ catalog_url: Some(format!("http://{address}/catalog.json")),
+ ..custom_repository("install-marketplace")
+ };
+ PluginRepositoryStore::new(root.path().to_path_buf()).save(repository.clone()).unwrap();
+ let catalog = PluginMarketplaceCatalog {
+ catalog_version: 1,
+ repository: PluginMarketplaceRepositoryMetadata {
+ id: repository.id.clone(),
+ name: repository.name.clone(),
+ homepage: None,
+ },
+ generated_at: None,
+ plugins: vec![PluginMarketplacePlugin {
+ id: "marketplace.install".to_string(),
+ name: "Marketplace Install".to_string(),
+ description: String::new(),
+ publisher: "example".to_string(),
+ verified: false,
+ icon: None,
+ tags: vec![],
+ permissions: vec![],
+ source: None,
+ homepage: None,
+ license: None,
+ latest_version: "1.0.0".to_string(),
+ versions: vec![PluginMarketplaceVersion {
+ version: "1.0.0".to_string(),
+ released_at: None,
+ release_notes: None,
+ artifacts: vec![PluginMarketplaceArtifact {
+ target: UNIVERSAL_PLUGIN_TARGET.to_string(),
+ url: "package.dbxp".to_string(),
+ sha256: package_sha256,
+ signing_key_id: key_id.to_string(),
+ size: Some(package.len() as u64),
+ }],
+ }],
+ localizations: BTreeMap::new(),
+ }],
+ };
+ let catalog = serde_json::to_vec(&catalog).unwrap();
+ let server = tokio::spawn(async move {
+ for _ in 0..2 {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut request = [0u8; 2048];
+ let read = socket.read(&mut request).await.unwrap();
+ let request = String::from_utf8_lossy(&request[..read]);
+ let body = if request.starts_with("GET /catalog.json ") { &catalog } else { &package };
+ socket
+ .write_all(
+ format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len())
+ .as_bytes(),
+ )
+ .await
+ .unwrap();
+ socket.write_all(body).await.unwrap();
+ }
+ });
+
+ let marketplace = PluginMarketplace::new(root.path().to_path_buf(), "0.5.68").unwrap();
+ let result = marketplace
+ .install(PluginMarketplaceInstallRequest {
+ repository_id: repository.id,
+ plugin_id: "marketplace.install".to_string(),
+ version: None,
+ })
+ .await
+ .unwrap();
+ server.await.unwrap();
+
+ assert_eq!(result.plugin.manifest.id, "marketplace.install");
+ assert_eq!(result.plugin.manifest.version, "1.0.0");
+ assert_eq!(result.signature, crate::plugins::PluginSignatureStatus::Trusted { key_id: key_id.to_string() });
+ }
+
+ fn signed_package(signing_key: &SigningKey, key_id: &str) -> Vec<u8> {
+ let manifest = serde_json::to_vec_pretty(&serde_json::json!({
+ "manifest_version": 1,
+ "id": "marketplace.install",
+ "name": "Marketplace Install",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.5.0", "host_api": "^1.0" },
+ "entrypoints": {
+ "backend": {
+ "protocol_versions": [1],
+ "transport": "stdio-jsonl",
+ "executable": "bin/plugin"
+ }
+ }
+ }))
+ .unwrap();
+ let backend = b"#!/bin/sh\nexit 0\n".to_vec();
+ let files = BTreeMap::from([("bin/plugin".to_string(), backend), ("manifest.json".to_string(), manifest)]);
+ let checksums = serde_json::to_vec_pretty(&serde_json::json!({
+ "algorithm": "sha256",
+ "files": files
+ .iter()
+ .map(|(path, bytes)| (path.clone(), format!("{:x}", Sha256::digest(bytes))))
+ .collect::<BTreeMap<_, _>>()
+ }))
+ .unwrap();
+ let signature = serde_json::to_vec_pretty(&serde_json::json!({
+ "algorithm": "ed25519",
+ "key_id": key_id,
+ "signature": base64::engine::general_purpose::STANDARD.encode(signing_key.sign(&checksums).to_bytes())
+ }))
+ .unwrap();
+ let mut output = Cursor::new(Vec::new());
+ {
+ let mut archive = zip::ZipWriter::new(&mut output);
+ for (path, bytes) in files {
+ let options = if path == "bin/plugin" {
+ SimpleFileOptions::default().unix_permissions(0o755)
+ } else {
+ SimpleFileOptions::default().unix_permissions(0o644)
+ };
+ archive.start_file(path, options).unwrap();
+ archive.write_all(&bytes).unwrap();
+ }
+ archive.start_file(PLUGIN_CHECKSUMS_FILE, SimpleFileOptions::default()).unwrap();
+ archive.write_all(&checksums).unwrap();
+ archive.start_file(PLUGIN_SIGNATURE_FILE, SimpleFileOptions::default()).unwrap();
+ archive.write_all(&signature).unwrap();
+ archive.finish().unwrap();
+ }
+ output.into_inner()
+ }
+}
diff --git a/crates/dbx-core/src/plugins/runtime.rs b/crates/dbx-core/src/plugins/runtime.rs
new file mode 100644
index 0000000000..5074cffa56
--- /dev/null
+++ b/crates/dbx-core/src/plugins/runtime.rs
@@ -0,0 +1,912 @@
+use std::collections::HashMap;
+use std::path::Path;
+use std::process::Stdio;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+
+use bytes::Bytes;
+use serde::de::DeserializeOwned;
+use serde::{Deserialize, Serialize};
+use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
+use tokio::process::{Child, ChildStdin, ChildStdout};
+use tokio::sync::{broadcast, oneshot, watch, Mutex, RwLock};
+use tokio::time::timeout;
+
+use super::{
+ InstalledPlugin, PluginBackendTransport, PluginRuntimeEnv, SUPPORTED_PLUGIN_HOST_API_VERSION,
+ SUPPORTED_PLUGIN_PROTOCOL_VERSION,
+};
+
+pub const PLUGIN_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
+const MAX_JSON_MESSAGE_BYTES: usize = 8 * 1024 * 1024;
+const MAX_BINARY_MESSAGE_BYTES: usize = 64 * 1024 * 1024;
+const FRAME_KIND_JSON: u8 = 0;
+const FRAME_KIND_BINARY: u8 = 1;
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginEvent {
+ pub plugin_id: String,
+ pub method: String,
+ #[serde(default)]
+ pub params: serde_json::Value,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PluginBinaryMessage {
+ pub plugin_id: String,
+ pub channel: String,
+ pub data: Bytes,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum PluginSessionState {
+ Starting,
+ Running,
+ Stopping,
+ Stopped,
+ Exited,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginSessionStatus {
+ pub state: PluginSessionState,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub message: Option<String>,
+}
+
+impl PluginSessionStatus {
+ fn new(state: PluginSessionState, message: Option<String>) -> Self {
+ Self { state, message }
+ }
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginHandshake {
+ pub protocol_version: u32,
+ #[serde(default)]
+ pub capabilities: Vec<String>,
+ pub plugin: PluginHandshakeIdentity,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+pub struct PluginHandshakeIdentity {
+ pub id: String,
+ pub version: String,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PluginInitializeParams<'a> {
+ host: PluginHostDescription<'a>,
+ plugin: PluginDescription<'a>,
+ permissions: &'a [String],
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PluginHostDescription<'a> {
+ dbx_version: &'a str,
+ host_api_version: &'static str,
+ protocol_versions: [u32; 1],
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PluginDescription<'a> {
+ id: &'a str,
+ version: &'a str,
+}
+
+#[derive(Debug, Serialize)]
+struct PluginRequest<'a> {
+ jsonrpc: &'static str,
+ id: u64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ driver: Option<&'a str>,
+ method: &'a str,
+ params: serde_json::Value,
+}
+
+#[derive(Debug, Serialize)]
+struct PluginNotification<'a> {
+ jsonrpc: &'static str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ driver: Option<&'a str>,
+ method: &'a str,
+ params: serde_json::Value,
+}
+
+type PendingResponse = oneshot::Sender<Result<serde_json::Value, String>>;
+
+pub struct PluginSidecarSession {
+ plugin: InstalledPlugin,
+ app_version: String,
+ transport: PluginBackendTransport,
+ child: Arc<Mutex<Child>>,
+ stdin: Mutex<ChildStdin>,
+ pending: Arc<Mutex<HashMap<u64, PendingResponse>>>,
+ next_request_id: AtomicU64,
+ events: broadcast::Sender<PluginEvent>,
+ binary_messages: broadcast::Sender<PluginBinaryMessage>,
+ status: watch::Sender<PluginSessionStatus>,
+ handshake: RwLock<Option<PluginHandshake>>,
+}
+
+impl PluginSidecarSession {
+ pub async fn start(
+ plugin: InstalledPlugin,
+ app_version: impl Into<String>,
+ env: PluginRuntimeEnv,
+ ) -> Result<Arc<Self>, String> {
+ ensure_plugin_backend(&plugin)?;
+ let transport = plugin.manifest.backend_entrypoint().map(|backend| backend.transport).unwrap_or_default();
+ let app_version = app_version.into();
+ let mut child = spawn_plugin_child(&plugin, &app_version, &env)?;
+ let stdin = child.stdin.take().ok_or("Plugin stdin unavailable")?;
+ let stdout = child.stdout.take().ok_or("Plugin stdout unavailable")?;
+ let stderr = child.stderr.take();
+ let child = Arc::new(Mutex::new(child));
+ let pending = Arc::new(Mutex::new(HashMap::new()));
+ let (events, _) = broadcast::channel(256);
+ let (binary_messages, _) = broadcast::channel(64);
+ let (status, _) = watch::channel(PluginSessionStatus::new(PluginSessionState::Starting, None));
+ let session = Arc::new(Self {
+ plugin,
+ app_version,
+ transport,
+ child,
+ stdin: Mutex::new(stdin),
+ pending,
+ next_request_id: AtomicU64::new(1),
+ events,
+ binary_messages,
+ status,
+ handshake: RwLock::new(None),
+ });
+
+ session.spawn_stdout_reader(stdout);
+ if let Some(stderr) = stderr {
+ session.spawn_stderr_reader(stderr);
+ }
+
+ if !session.plugin.manifest.is_legacy() {
+ let handshake = match session.initialize().await {
+ Ok(handshake) => handshake,
+ Err(error) => {
+ session.shutdown().await;
+ return Err(format!("Plugin '{}' initialization failed: {error}", session.plugin.manifest.id));
+ }
+ };
+ *session.handshake.write().await = Some(handshake);
+ }
+ let transitioned = session.status.send_if_modified(|status| {
+ if status.state != PluginSessionState::Starting {
+ return false;
+ }
+ *status = PluginSessionStatus::new(PluginSessionState::Running, None);
+ true
+ });
+ if !transitioned {
+ let status = session.status();
+ session.shutdown().await;
+ return Err(format!(
+ "Plugin '{}' stopped during initialization{}",
+ session.plugin.manifest.id,
+ status.message.map_or_else(String::new, |message| format!(": {message}"))
+ ));
+ }
+ Ok(session)
+ }
+
+ pub fn plugin(&self) -> &InstalledPlugin {
+ &self.plugin
+ }
+
+ pub fn subscribe_events(&self) -> broadcast::Receiver<PluginEvent> {
+ self.events.subscribe()
+ }
+
+ pub fn subscribe_binary(&self) -> broadcast::Receiver<PluginBinaryMessage> {
+ self.binary_messages.subscribe()
+ }
+
+ pub fn subscribe_status(&self) -> watch::Receiver<PluginSessionStatus> {
+ self.status.subscribe()
+ }
+
+ pub fn status(&self) -> PluginSessionStatus {
+ self.status.borrow().clone()
+ }
+
+ pub async fn handshake(&self) -> Option<PluginHandshake> {
+ self.handshake.read().await.clone()
+ }
+
+ pub async fn invoke<T>(&self, method: &str, params: serde_json::Value) -> Result<T, String>
+ where
+ T: DeserializeOwned,
+ {
+ self.invoke_with_timeout(method, params, None, Some(PLUGIN_REQUEST_TIMEOUT)).await
+ }
+
+ pub async fn invoke_with_timeout<T>(
+ &self,
+ method: &str,
+ params: serde_json::Value,
+ driver: Option<&str>,
+ timeout_duration: Option<Duration>,
+ ) -> Result<T, String>
+ where
+ T: DeserializeOwned,
+ {
+ let value = self.invoke_value(method, params, driver, timeout_duration).await?;
+ serde_json::from_value(value)
+ .map_err(|error| format!("Failed to decode plugin '{}' result: {error}", self.plugin.manifest.id))
+ }
+
+ pub async fn notify(&self, method: &str, params: serde_json::Value, driver: Option<&str>) -> Result<(), String> {
+ self.ensure_running()?;
+ validate_protocol_name(method)?;
+ let notification = PluginNotification { jsonrpc: "2.0", driver, method, params };
+ let payload = serde_json::to_vec(&notification).map_err(|error| error.to_string())?;
+ self.write_json(&payload).await
+ }
+
+ pub async fn send_binary(&self, channel: &str, data: &[u8]) -> Result<(), String> {
+ self.ensure_running()?;
+ if self.transport != PluginBackendTransport::StdioFramed {
+ return Err(format!(
+ "Plugin '{}' does not use the framed transport required for binary messages",
+ self.plugin.manifest.id
+ ));
+ }
+ validate_binary_channel(channel)?;
+ if data.len() > MAX_BINARY_MESSAGE_BYTES {
+ return Err(format!("Plugin binary message exceeds {MAX_BINARY_MESSAGE_BYTES} bytes"));
+ }
+ let channel_bytes = channel.as_bytes();
+ let payload_len = 2usize
+ .checked_add(channel_bytes.len())
+ .and_then(|length| length.checked_add(data.len()))
+ .ok_or("Plugin binary frame is too large")?;
+ let mut stdin = self.stdin.lock().await;
+ stdin.write_u8(FRAME_KIND_BINARY).await.map_err(|error| self.write_error(error))?;
+ stdin.write_u32(payload_len as u32).await.map_err(|error| self.write_error(error))?;
+ stdin.write_u16(channel_bytes.len() as u16).await.map_err(|error| self.write_error(error))?;
+ stdin.write_all(channel_bytes).await.map_err(|error| self.write_error(error))?;
+ stdin.write_all(data).await.map_err(|error| self.write_error(error))?;
+ stdin.flush().await.map_err(|error| self.write_error(error))
+ }
+
+ pub async fn shutdown(&self) {
+ self.status.send_replace(PluginSessionStatus::new(PluginSessionState::Stopping, None));
+ let kill_result = self.child.lock().await.kill().await;
+ let message = kill_result.err().map(|error| error.to_string());
+ fail_pending(&self.pending, "Plugin session stopped").await;
+ self.status.send_replace(PluginSessionStatus::new(PluginSessionState::Stopped, message));
+ }
+
+ pub async fn pid(&self) -> Option<u32> {
+ self.child.lock().await.id()
+ }
+
+ async fn initialize(&self) -> Result<PluginHandshake, String> {
+ let params = PluginInitializeParams {
+ host: PluginHostDescription {
+ dbx_version: &self.app_version,
+ host_api_version: SUPPORTED_PLUGIN_HOST_API_VERSION,
+ protocol_versions: [SUPPORTED_PLUGIN_PROTOCOL_VERSION],
+ },
+ plugin: PluginDescription { id: &self.plugin.manifest.id, version: &self.plugin.manifest.version },
+ permissions: &self.plugin.manifest.permissions,
+ };
+ let params = serde_json::to_value(params).map_err(|error| error.to_string())?;
+ let handshake: PluginHandshake =
+ self.invoke_with_timeout("plugin/initialize", params, None, Some(PLUGIN_REQUEST_TIMEOUT)).await?;
+ if handshake.protocol_version != SUPPORTED_PLUGIN_PROTOCOL_VERSION {
+ return Err(format!(
+ "Plugin selected protocol version {}, expected {}",
+ handshake.protocol_version, SUPPORTED_PLUGIN_PROTOCOL_VERSION
+ ));
+ }
+ if handshake.plugin.id != self.plugin.manifest.id || handshake.plugin.version != self.plugin.manifest.version {
+ return Err(format!(
+ "Plugin backend identity '{}/{}' does not match manifest '{}/{}'",
+ handshake.plugin.id, handshake.plugin.version, self.plugin.manifest.id, self.plugin.manifest.version
+ ));
+ }
+ Ok(handshake)
+ }
+
+ async fn invoke_value(
+ &self,
+ method: &str,
+ params: serde_json::Value,
+ driver: Option<&str>,
+ timeout_duration: Option<Duration>,
+ ) -> Result<serde_json::Value, String> {
+ self.ensure_running_or_starting()?;
+ validate_protocol_name(method)?;
+ let request_id = self.next_request_id.fetch_add(1, Ordering::Relaxed);
+ let request = PluginRequest { jsonrpc: "2.0", id: request_id, driver, method, params };
+ let payload = serde_json::to_vec(&request).map_err(|error| error.to_string())?;
+ let (sender, receiver) = oneshot::channel();
+ self.pending.lock().await.insert(request_id, sender);
+ if let Err(error) = self.write_json(&payload).await {
+ self.pending.lock().await.remove(&request_id);
+ return Err(error);
+ }
+
+ let receive = async {
+ receiver.await.map_err(|_| format!("Plugin '{}' response channel closed", self.plugin.manifest.id))?
+ };
+ match timeout_duration {
+ Some(duration) => match timeout(duration, receive).await {
+ Ok(result) => result,
+ Err(_) => {
+ self.pending.lock().await.remove(&request_id);
+ Err(format!(
+ "Plugin '{}' request '{}' timed out after {} seconds",
+ self.plugin.manifest.id,
+ method,
+ duration.as_secs()
+ ))
+ }
+ },
+ None => receive.await,
+ }
+ }
+
+ async fn write_json(&self, payload: &[u8]) -> Result<(), String> {
+ if payload.len() > MAX_JSON_MESSAGE_BYTES {
+ return Err(format!("Plugin JSON message exceeds {MAX_JSON_MESSAGE_BYTES} bytes"));
+ }
+ let mut stdin = self.stdin.lock().await;
+ match self.transport {
+ PluginBackendTransport::StdioJsonLines => {
+ stdin.write_all(payload).await.map_err(|error| self.write_error(error))?;
+ stdin.write_u8(b'\n').await.map_err(|error| self.write_error(error))?;
+ }
+ PluginBackendTransport::StdioFramed => {
+ stdin.write_u8(FRAME_KIND_JSON).await.map_err(|error| self.write_error(error))?;
+ stdin.write_u32(payload.len() as u32).await.map_err(|error| self.write_error(error))?;
+ stdin.write_all(payload).await.map_err(|error| self.write_error(error))?;
+ }
+ }
+ stdin.flush().await.map_err(|error| self.write_error(error))
+ }
+
+ fn write_error(&self, error: std::io::Error) -> String {
+ format!("Failed to write to plugin '{}': {error}", self.plugin.manifest.id)
+ }
+
+ fn ensure_running(&self) -> Result<(), String> {
+ let status = self.status();
+ if status.state == PluginSessionState::Running {
+ Ok(())
+ } else {
+ Err(format!("Plugin '{}' is not running ({:?})", self.plugin.manifest.id, status.state))
+ }
+ }
+
+ fn ensure_running_or_starting(&self) -> Result<(), String> {
+ let status = self.status();
+ if matches!(status.state, PluginSessionState::Starting | PluginSessionState::Running) {
+ Ok(())
+ } else {
+ Err(format!("Plugin '{}' is not available ({:?})", self.plugin.manifest.id, status.state))
+ }
+ }
+
+ fn spawn_stdout_reader(self: &Arc<Self>, stdout: ChildStdout) {
+ let session = self.clone();
+ tokio::spawn(async move {
+ let result = match session.transport {
+ PluginBackendTransport::StdioJsonLines => read_json_lines(&session, BufReader::new(stdout)).await,
+ PluginBackendTransport::StdioFramed => read_framed(&session, stdout).await,
+ };
+ let message = match result {
+ Ok(()) => session.exit_message().await,
+ Err(error) => error,
+ };
+ fail_pending(&session.pending, &message).await;
+ if matches!(session.status().state, PluginSessionState::Stopping | PluginSessionState::Stopped) {
+ return;
+ }
+ let message = session.terminate_after_output_end(message).await;
+ session.status.send_if_modified(|status| {
+ if matches!(status.state, PluginSessionState::Stopping | PluginSessionState::Stopped) {
+ return false;
+ }
+ *status = PluginSessionStatus::new(PluginSessionState::Exited, Some(message.clone()));
+ true
+ });
+ });
+ }
+
+ fn spawn_stderr_reader(self: &Arc<Self>, stderr: tokio::process::ChildStderr) {
+ let plugin_id = self.plugin.manifest.id.clone();
+ tokio::spawn(async move {
+ let mut reader = BufReader::new(stderr);
+ loop {
+ match read_limited_line(&mut reader, MAX_JSON_MESSAGE_BYTES).await {
+ Ok(Some(line)) => log::warn!("[plugin:{plugin_id}] {}", String::from_utf8_lossy(&line).trim_end()),
+ Ok(None) => break,
+ Err(error) => {
+ log::warn!("[plugin:{plugin_id}] failed to read stderr: {error}");
+ break;
+ }
+ }
+ }
+ });
+ }
+
+ async fn exit_message(&self) -> String {
+ match self.child.lock().await.try_wait() {
+ Ok(Some(status)) => format!("Plugin '{}' exited with status {status}", self.plugin.manifest.id),
+ Ok(None) => format!("Plugin '{}' closed its output stream", self.plugin.manifest.id),
+ Err(error) => format!("Plugin '{}' output closed: {error}", self.plugin.manifest.id),
+ }
+ }
+
+ async fn terminate_after_output_end(&self, message: String) -> String {
+ let mut child = self.child.lock().await;
+ match child.try_wait() {
+ Ok(Some(_)) => message,
+ Ok(None) => match child.kill().await {
+ Ok(()) => format!("{message}; process terminated by host"),
+ Err(error) => format!("{message}; failed to terminate process: {error}"),
+ },
+ Err(error) => format!("{message}; failed to inspect process: {error}"),
+ }
+ }
+
+ async fn dispatch_json(&self, payload: &[u8]) -> Result<(), String> {
+ let value: serde_json::Value = serde_json::from_slice(payload).map_err(|error| {
+ format!("Failed to parse plugin '{}' protocol message: {error}", self.plugin.manifest.id)
+ })?;
+ if !self.plugin.manifest.is_legacy() && value.get("jsonrpc").and_then(serde_json::Value::as_str) != Some("2.0")
+ {
+ return Err(format!("Plugin '{}' sent a message without jsonrpc 2.0", self.plugin.manifest.id));
+ }
+ if let Some(request_id) = value.get("id").and_then(serde_json::Value::as_u64) {
+ let result = decode_response_value(&self.plugin.manifest.id, value);
+ if let Some(sender) = self.pending.lock().await.remove(&request_id) {
+ let _ = sender.send(result);
+ } else {
+ log::warn!("[plugin:{}] ignored response for unknown request {request_id}", self.plugin.manifest.id);
+ }
+ return Ok(());
+ }
+ if let Some(method) = value.get("method").and_then(serde_json::Value::as_str) {
+ if !self.plugin.manifest.is_legacy() {
+ validate_protocol_name(method)?;
+ }
+ let event = PluginEvent {
+ plugin_id: self.plugin.manifest.id.clone(),
+ method: method.to_string(),
+ params: value.get("params").cloned().unwrap_or(serde_json::Value::Null),
+ };
+ let _ = self.events.send(event);
+ return Ok(());
+ }
+ Err(format!("Plugin '{}' sent a protocol message without id or method", self.plugin.manifest.id))
+ }
+
+ fn dispatch_binary(&self, payload: Bytes) -> Result<(), String> {
+ if payload.len() < 2 {
+ return Err(format!("Plugin '{}' sent an invalid binary frame", self.plugin.manifest.id));
+ }
+ let channel_len = u16::from_be_bytes([payload[0], payload[1]]) as usize;
+ if channel_len == 0 || payload.len() < 2 + channel_len {
+ return Err(format!("Plugin '{}' sent an invalid binary channel", self.plugin.manifest.id));
+ }
+ let channel = std::str::from_utf8(&payload[2..2 + channel_len]).map_err(|error| {
+ format!("Plugin '{}' sent a non-UTF-8 binary channel: {error}", self.plugin.manifest.id)
+ })?;
+ validate_binary_channel(channel)?;
+ let message = PluginBinaryMessage {
+ plugin_id: self.plugin.manifest.id.clone(),
+ channel: channel.to_string(),
+ data: payload.slice(2 + channel_len..),
+ };
+ let _ = self.binary_messages.send(message);
+ Ok(())
+ }
+}
+
+async fn read_json_lines(session: &PluginSidecarSession, mut reader: BufReader<ChildStdout>) -> Result<(), String> {
+ loop {
+ let Some(line) = read_limited_line(&mut reader, MAX_JSON_MESSAGE_BYTES)
+ .await
+ .map_err(|error| format!("Failed to read plugin '{}' output: {error}", session.plugin.manifest.id))?
+ else {
+ return Ok(());
+ };
+ let trimmed = trim_ascii_whitespace(&line);
+ if trimmed.is_empty() {
+ continue;
+ }
+ if let Err(error) = session.dispatch_json(trimmed).await {
+ if !session.plugin.manifest.is_legacy() {
+ return Err(error);
+ }
+ log::warn!(
+ "[plugin:{}] ignored non-protocol stdout: {} ({error})",
+ session.plugin.manifest.id,
+ String::from_utf8_lossy(trimmed)
+ );
+ }
+ }
+}
+
+async fn read_framed(session: &PluginSidecarSession, mut stdout: ChildStdout) -> Result<(), String> {
+ loop {
+ let kind = match stdout.read_u8().await {
+ Ok(kind) => kind,
+ Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(()),
+ Err(error) => {
+ return Err(format!("Failed to read plugin '{}' frame kind: {error}", session.plugin.manifest.id))
+ }
+ };
+ let length =
+ stdout.read_u32().await.map_err(|error| {
+ format!("Failed to read plugin '{}' frame length: {error}", session.plugin.manifest.id)
+ })? as usize;
+ let maximum = if kind == FRAME_KIND_JSON { MAX_JSON_MESSAGE_BYTES } else { MAX_BINARY_MESSAGE_BYTES + 1024 };
+ if length > maximum {
+ return Err(format!("Plugin '{}' frame exceeds {maximum} bytes", session.plugin.manifest.id));
+ }
+ let mut payload = vec![0; length];
+ stdout.read_exact(&mut payload).await.map_err(|error| {
+ format!("Failed to read plugin '{}' frame payload: {error}", session.plugin.manifest.id)
+ })?;
+ match kind {
+ FRAME_KIND_JSON => session.dispatch_json(&payload).await?,
+ FRAME_KIND_BINARY => session.dispatch_binary(Bytes::from(payload))?,
+ _ => return Err(format!("Plugin '{}' sent unknown frame kind {kind}", session.plugin.manifest.id)),
+ }
+ }
+}
+
+async fn read_limited_line<R>(reader: &mut R, maximum: usize) -> std::io::Result<Option<Vec<u8>>>
+where
+ R: AsyncBufRead + Unpin,
+{
+ let mut output = Vec::new();
+ loop {
+ let available = reader.fill_buf().await?;
+ if available.is_empty() {
+ return if output.is_empty() { Ok(None) } else { Ok(Some(output)) };
+ }
+ let take = available.iter().position(|byte| *byte == b'\n').map(|index| index + 1).unwrap_or(available.len());
+ if output.len().saturating_add(take) > maximum {
+ return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "plugin output line is too large"));
+ }
+ output.extend_from_slice(&available[..take]);
+ reader.consume(take);
+ if output.last() == Some(&b'\n') {
+ return Ok(Some(output));
+ }
+ }
+}
+
+fn trim_ascii_whitespace(mut bytes: &[u8]) -> &[u8] {
+ while bytes.first().is_some_and(u8::is_ascii_whitespace) {
+ bytes = &bytes[1..];
+ }
+ while bytes.last().is_some_and(u8::is_ascii_whitespace) {
+ bytes = &bytes[..bytes.len() - 1];
+ }
+ bytes
+}
+
+fn decode_response_value(plugin_id: &str, value: serde_json::Value) -> Result<serde_json::Value, String> {
+ if let Some(error) = value.get("error") {
+ let message = error
+ .get("message")
+ .and_then(serde_json::Value::as_str)
+ .map(str::to_string)
+ .unwrap_or_else(|| error.to_string());
+ return Err(message);
+ }
+ if value.get("result").is_none() && value.get("error").is_none() {
+ return Err(format!("Plugin '{plugin_id}' response has neither result nor error"));
+ }
+ Ok(value.get("result").cloned().unwrap_or(serde_json::Value::Null))
+}
+
+async fn fail_pending(pending: &Mutex<HashMap<u64, PendingResponse>>, message: &str) {
+ let responses = std::mem::take(&mut *pending.lock().await);
+ for (_, sender) in responses {
+ let _ = sender.send(Err(message.to_string()));
+ }
+}
+
+fn validate_binary_channel(channel: &str) -> Result<(), String> {
+ if channel.is_empty() || channel.len() > u16::MAX as usize {
+ return Err("Plugin binary channel must contain 1-65535 bytes".to_string());
+ }
+ if channel.chars().any(char::is_whitespace) {
+ return Err("Plugin binary channel cannot contain whitespace".to_string());
+ }
+ Ok(())
+}
+
+fn validate_protocol_name(value: &str) -> Result<(), String> {
+ if value.is_empty()
+ || value.len() > 256
+ || !value
+ .chars()
+ .all(|character| character.is_ascii_alphanumeric() || matches!(character, '.' | '_' | ':' | '/' | '-'))
+ {
+ return Err("Plugin protocol name is invalid".to_string());
+ }
+ Ok(())
+}
+
+fn ensure_plugin_backend(plugin: &InstalledPlugin) -> Result<(), String> {
+ if !plugin.compatibility.compatible {
+ return Err(format!(
+ "Plugin '{}' is incompatible: {}",
+ plugin.manifest.id,
+ plugin.compatibility.errors.join("; ")
+ ));
+ }
+ if plugin.compatibility.backend_executable.is_none() {
+ return Err(format!("Plugin '{}' does not provide a backend entrypoint", plugin.manifest.id));
+ }
+ Ok(())
+}
+
+fn spawn_plugin_child(plugin: &InstalledPlugin, app_version: &str, env: &PluginRuntimeEnv) -> Result<Child, String> {
+ let executable_path =
+ plugin.compatibility.backend_executable.as_ref().ok_or_else(|| {
+ format!("Plugin '{}' does not provide a compatible backend executable", plugin.manifest.id)
+ })?;
+ ensure_executable_permission(executable_path)?;
+ let mut command = crate::process::new_tokio_command(executable_path);
+ command
+ .current_dir(&plugin.path)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .kill_on_drop(true)
+ .env("DBX_PLUGIN_ID", &plugin.manifest.id)
+ .env("DBX_PLUGIN_VERSION", &plugin.manifest.version)
+ .env("DBX_APP_VERSION", app_version)
+ .env("DBX_HOST_API_VERSION", SUPPORTED_PLUGIN_HOST_API_VERSION)
+ .env("DBX_PLUGIN_PROTOCOL_VERSION", SUPPORTED_PLUGIN_PROTOCOL_VERSION.to_string());
+ env.apply_to(&mut command);
+ command.spawn().map_err(|error| format!("Failed to start plugin '{}': {error}", plugin.manifest.id))
+}
+
+fn ensure_executable_permission(path: &Path) -> Result<(), String> {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+
+ let mode = std::fs::metadata(path).map_err(|error| error.to_string())?.permissions().mode();
+ if mode & 0o111 == 0 {
+ return Err(format!("Plugin backend is not executable: {}", path.display()));
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use std::time::Duration;
+
+ use super::{
+ decode_response_value, read_limited_line, trim_ascii_whitespace, PluginSessionState, PluginSidecarSession,
+ };
+ use crate::plugins::{InstalledPlugin, PluginManifest, PluginRuntimeEnv};
+ use tokio::io::BufReader;
+
+ #[tokio::test]
+ async fn rejects_oversized_json_lines_before_unbounded_growth() {
+ let mut reader = BufReader::new(std::io::Cursor::new(b"123456\n"));
+ let error = read_limited_line(&mut reader, 4).await.expect_err("line should be rejected");
+ assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
+ }
+
+ #[test]
+ fn decodes_json_rpc_result_and_error() {
+ assert_eq!(
+ decode_response_value("sample", serde_json::json!({ "id": 1, "result": { "ok": true } })).unwrap(),
+ serde_json::json!({ "ok": true })
+ );
+ assert_eq!(
+ decode_response_value("sample", serde_json::json!({ "id": 1, "error": { "message": "boom" } }))
+ .unwrap_err(),
+ "boom"
+ );
+ }
+
+ #[test]
+ fn trims_protocol_whitespace() {
+ assert_eq!(trim_ascii_whitespace(b" \n{}\r\n"), b"{}");
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn negotiates_routes_concurrent_responses_and_forwards_events() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let dir = tempfile::tempdir().unwrap();
+ let executable = dir.path().join("plugin.sh");
+ std::fs::write(
+ &executable,
+ r#"#!/bin/sh
+IFS= read -r initialize
+initialize_id=$(printf '%s' "$initialize" | sed -E 's/.*"id":([0-9]+).*/\1/')
+printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"capabilities":["events"],"plugin":{"id":"sample.sidecar","version":"1.0.0"}}}\n' "$initialize_id"
+IFS= read -r first
+IFS= read -r second
+first_id=$(printf '%s' "$first" | sed -E 's/.*"id":([0-9]+).*/\1/')
+second_id=$(printf '%s' "$second" | sed -E 's/.*"id":([0-9]+).*/\1/')
+first_method=$(printf '%s' "$first" | sed -E 's/.*"method":"([^"]+)".*/\1/')
+second_method=$(printf '%s' "$second" | sed -E 's/.*"method":"([^"]+)".*/\1/')
+printf '{"jsonrpc":"2.0","method":"sample/progress","params":{"value":50}}\n'
+printf '{"jsonrpc":"2.0","id":%s,"result":"%s"}\n' "$second_id" "$second_method"
+printf '{"jsonrpc":"2.0","id":%s,"result":"%s"}\n' "$first_id" "$first_method"
+sleep 30
+"#,
+ )
+ .unwrap();
+ let mut permissions = std::fs::metadata(&executable).unwrap().permissions();
+ permissions.set_mode(0o755);
+ std::fs::set_permissions(&executable, permissions).unwrap();
+
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "sample.sidecar",
+ "name": "Sample Sidecar",
+ "version": "1.0.0",
+ "publisher": "dbx",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "permissions": ["host.events"],
+ "entrypoints": {
+ "backend": {
+ "protocol_versions": [1],
+ "transport": "stdio-jsonl",
+ "executable": "plugin.sh"
+ }
+ }
+ }))
+ .unwrap();
+ let plugin = InstalledPlugin::new(manifest, dir.path().to_path_buf(), "0.5.67");
+ let session = PluginSidecarSession::start(plugin, "0.5.67", PluginRuntimeEnv::default())
+ .await
+ .expect("v1 sidecar should initialize");
+ assert_eq!(session.status().state, PluginSessionState::Running);
+ assert_eq!(session.handshake().await.unwrap().capabilities, vec!["events"]);
+ let mut events = session.subscribe_events();
+
+ let first = session.invoke::<String>("sample/first", serde_json::Value::Null);
+ let second = session.invoke::<String>("sample/second", serde_json::Value::Null);
+ let (first, second) = tokio::join!(first, second);
+
+ assert_eq!(first.unwrap(), "sample/first");
+ assert_eq!(second.unwrap(), "sample/second");
+ let event = events.recv().await.unwrap();
+ assert_eq!(event.method, "sample/progress");
+ assert_eq!(event.params["value"], 50);
+ session.shutdown().await;
+ assert_eq!(session.status().state, PluginSessionState::Stopped);
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn failed_initialize_terminates_plugin_process() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let dir = tempfile::tempdir().unwrap();
+ let executable = dir.path().join("plugin.sh");
+ let pid_file = dir.path().join("plugin.pid");
+ std::fs::write(
+ &executable,
+ format!(
+ r#"#!/bin/sh
+printf '%s' "$$" > '{}'
+IFS= read -r initialize
+initialize_id=$(printf '%s' "$initialize" | sed -E 's/.*"id":([0-9]+).*/\1/')
+printf '{{"jsonrpc":"2.0","id":%s,"result":{{"protocolVersion":1,"capabilities":[],"plugin":{{"id":"wrong.sidecar","version":"1.0.0"}}}}}}\n' "$initialize_id"
+sleep 30
+"#,
+ pid_file.display()
+ ),
+ )
+ .unwrap();
+ let mut permissions = std::fs::metadata(&executable).unwrap().permissions();
+ permissions.set_mode(0o755);
+ std::fs::set_permissions(&executable, permissions).unwrap();
+
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "sample.sidecar",
+ "name": "Sample Sidecar",
+ "version": "1.0.0",
+ "publisher": "dbx",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "entrypoints": {
+ "backend": {
+ "protocol_versions": [1],
+ "transport": "stdio-jsonl",
+ "executable": "plugin.sh"
+ }
+ }
+ }))
+ .unwrap();
+ let plugin = InstalledPlugin::new(manifest, dir.path().to_path_buf(), "0.5.67");
+ let error = match PluginSidecarSession::start(plugin, "0.5.67", PluginRuntimeEnv::default()).await {
+ Ok(session) => {
+ session.shutdown().await;
+ panic!("mismatched backend identity should fail initialization")
+ }
+ Err(error) => error,
+ };
+ assert!(error.contains("does not match manifest"));
+
+ let pid = std::fs::read_to_string(&pid_file).unwrap().parse::<u32>().unwrap();
+ for _ in 0..20 {
+ if !process_exists(pid) {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ assert!(!process_exists(pid), "plugin process {pid} survived failed initialization");
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn legacy_jsonl_runtime_ignores_banner_output() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let dir = tempfile::tempdir().unwrap();
+ let executable = dir.path().join("plugin.sh");
+ std::fs::write(
+ &executable,
+ r#"#!/bin/sh
+IFS= read -r request
+request_id=$(printf '%s' "$request" | sed -E 's/.*"id":([0-9]+).*/\1/')
+printf 'legacy banner\n'
+printf '{"id":%s,"result":{"ok":true}}\n' "$request_id"
+sleep 30
+"#,
+ )
+ .unwrap();
+ let mut permissions = std::fs::metadata(&executable).unwrap().permissions();
+ permissions.set_mode(0o755);
+ std::fs::set_permissions(&executable, permissions).unwrap();
+
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "id": "legacy",
+ "name": "Legacy",
+ "executable": "plugin.sh"
+ }))
+ .unwrap();
+ let plugin = InstalledPlugin::new(manifest, dir.path().to_path_buf(), "0.5.67");
+ let session = PluginSidecarSession::start(plugin, "0.5.67", PluginRuntimeEnv::default()).await.unwrap();
+ let result: serde_json::Value = session.invoke("ping", serde_json::Value::Null).await.unwrap();
+ assert_eq!(result["ok"], true);
+ session.shutdown().await;
+ }
+
+ #[cfg(unix)]
+ fn process_exists(pid: u32) -> bool {
+ std::process::Command::new("kill")
+ .arg("-0")
+ .arg(pid.to_string())
+ .stderr(std::process::Stdio::null())
+ .status()
+ .map(|status| status.success())
+ .unwrap_or(false)
+ }
+}
diff --git a/crates/dbx-core/src/production_safety.rs b/crates/dbx-core/src/production_safety.rs
index ffbbd49bb8..66d38c76f2 100644
--- a/crates/dbx-core/src/production_safety.rs
+++ b/crates/dbx-core/src/production_safety.rs
@@ -810,6 +810,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
one_time: false,
save_password: true,
read_only: false,
diff --git a/crates/dbx-core/src/query.rs b/crates/dbx-core/src/query.rs
index 54cc8fe48f..7039f170a6 100644
--- a/crates/dbx-core/src/query.rs
+++ b/crates/dbx-core/src/query.rs
@@ -2318,6 +2318,7 @@ async fn do_execute_typed(
.await
.map(|result| truncate_result_with_max_rows(result, max_rows))
}
+ PoolKind::PluginConnection(_) => Err("SQL execution is not supported for plugin connections".to_string()),
PoolKind::HBase(_) => Err("SQL execution is not supported for HBase connections".to_string()),
PoolKind::DynamoDb(client) => {
let client = client.clone();
@@ -4098,7 +4099,8 @@ fn pool_kind_has_transactional_path(pool: &PoolKind) -> bool {
| PoolKind::InfluxDb(_)
| PoolKind::InfluxDb3(_)
| PoolKind::VictoriaMetrics(_)
- | PoolKind::ExternalDriver { .. } => false,
+ | PoolKind::ExternalDriver { .. }
+ | PoolKind::PluginConnection(_) => false,
#[cfg(feature = "mq-admin")]
PoolKind::Mqtt(_) => false,
}
@@ -4468,7 +4470,8 @@ fn batch_transaction_path(pool: &PoolKind) -> BatchTransactionPath {
| PoolKind::InfluxDb(_)
| PoolKind::InfluxDb3(_)
| PoolKind::VictoriaMetrics(_)
- | PoolKind::ExternalDriver { .. } => BatchTransactionPath::Unsupported,
+ | PoolKind::ExternalDriver { .. }
+ | PoolKind::PluginConnection(_) => BatchTransactionPath::Unsupported,
}
}
@@ -6553,7 +6556,8 @@ mod tests {
use crate::models::connection::{default_redis_key_separator, ConnectionConfig, DatabaseType};
#[cfg(unix)]
use crate::plugins::{
- InstalledPlugin, PluginDriverManifest, PluginDriverSession, PluginManifest, PluginRuntimeEnv,
+ InstalledPlugin, PluginCompatibility, PluginDriverManifest, PluginDriverSession, PluginManifest,
+ PluginRuntimeEnv,
};
use crate::storage::Storage;
@@ -6880,6 +6884,10 @@ for line in sys.stdin:
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
@@ -8671,8 +8679,14 @@ for line in sys.stdin:
kind: "external".to_string(),
database_type: Some("jdbc".to_string()),
}],
+ ..Default::default()
},
path: dir.clone(),
+ compatibility: PluginCompatibility {
+ compatible: true,
+ backend_executable: Some(dir.join("plugin.sh")),
+ ..Default::default()
+ },
};
let session = PluginDriverSession::start_for_test(plugin, "jdbc".to_string(), PluginRuntimeEnv::default())
.await
@@ -8771,8 +8785,14 @@ for line in sys.stdin:
kind: "external".to_string(),
database_type: Some("jdbc".to_string()),
}],
+ ..Default::default()
},
path: dir.clone(),
+ compatibility: PluginCompatibility {
+ compatible: true,
+ backend_executable: Some(dir.join("plugin.sh")),
+ ..Default::default()
+ },
};
let session = Arc::new(
PluginDriverSession::start_for_test(plugin, "jdbc".to_string(), PluginRuntimeEnv::default())
@@ -8881,8 +8901,14 @@ for line in sys.stdin:
kind: "external".to_string(),
database_type: Some("jdbc".to_string()),
}],
+ ..Default::default()
},
path: dir.clone(),
+ compatibility: PluginCompatibility {
+ compatible: true,
+ backend_executable: Some(dir.join("plugin.sh")),
+ ..Default::default()
+ },
};
let session = PluginDriverSession::start_for_test(plugin, "jdbc".to_string(), PluginRuntimeEnv::default())
.await
@@ -8939,8 +8965,14 @@ for line in sys.stdin:
kind: "external".to_string(),
database_type: Some("jdbc".to_string()),
}],
+ ..Default::default()
},
path: dir.clone(),
+ compatibility: PluginCompatibility {
+ compatible: true,
+ backend_executable: Some(dir.join("plugin.sh")),
+ ..Default::default()
+ },
};
let session = PluginDriverSession::start_for_test(plugin, "jdbc".to_string(), PluginRuntimeEnv::default())
.await
@@ -9400,6 +9432,10 @@ for line in sys.stdin:
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/src/schema.rs b/crates/dbx-core/src/schema.rs
index 7309a9dfc7..796b4182a6 100644
--- a/crates/dbx-core/src/schema.rs
+++ b/crates/dbx-core/src/schema.rs
@@ -3409,6 +3409,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: HashMap::new(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
@@ -3636,8 +3640,14 @@ done
kind: "external".to_string(),
database_type: Some("jdbc".to_string()),
}],
+ ..PluginManifest::default()
},
path: dir.clone(),
+ compatibility: crate::plugins::PluginCompatibility {
+ compatible: true,
+ backend_executable: Some(dir.join("plugin.sh")),
+ ..Default::default()
+ },
};
let session = std::sync::Arc::new(
PluginDriverSession::start_for_test(plugin, "jdbc".to_string(), PluginRuntimeEnv::default()).await.unwrap(),
diff --git a/crates/dbx-core/src/schema/normalization.rs b/crates/dbx-core/src/schema/normalization.rs
index 9c1a4dcb37..4bbc5fd102 100644
--- a/crates/dbx-core/src/schema/normalization.rs
+++ b/crates/dbx-core/src/schema/normalization.rs
@@ -187,7 +187,12 @@ mod tests {
redis_key_separator: default_redis_key_separator(),
etcd_endpoints: String::new(),
gbase_server: String::new(),
- informix_server: String::new(), external_config: None,
+ informix_server: String::new(),
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
+ external_config: None,
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
@@ -211,7 +216,7 @@ mod tests {
numeric_precision: None,
numeric_scale: None,
character_maximum_length: None,
- ..Default::default()
+ ..Default::default()
}
}
diff --git a/crates/dbx-core/src/sql_dialect/ddl_profile.rs b/crates/dbx-core/src/sql_dialect/ddl_profile.rs
index 96831eeeec..e7e57652b8 100644
--- a/crates/dbx-core/src/sql_dialect/ddl_profile.rs
+++ b/crates/dbx-core/src/sql_dialect/ddl_profile.rs
@@ -818,6 +818,8 @@ pub fn profile_for(db_type: DatabaseType) -> DdlDialectProfile {
InfluxDb => influxdb_profile(),
+ Plugin => conservative_ansi(db_type),
+
// Non-tabular / not applicable for relational CREATE TABLE
Redis | MongoDb | DynamoDb | Elasticsearch | Easysearch | Meilisearch | Qdrant | Milvus | Weaviate
| ChromaDb | Neo4j | Cassandra | Etcd | ZooKeeper | Nacos | Consul | InfluxDb3 | VictoriaMetrics
diff --git a/crates/dbx-core/src/storage.rs b/crates/dbx-core/src/storage.rs
index 20be2754b0..e8aac1a85e 100644
--- a/crates/dbx-core/src/storage.rs
+++ b/crates/dbx-core/src/storage.rs
@@ -18,7 +18,7 @@ use crate::connection_secrets::{
CASSANDRA_KEYSTORE_PASSWORD_KEY, CASSANDRA_TLS_SECRET_PREFIX, CASSANDRA_TRUSTSTORE_PASSWORD_KEY,
MQ_AUTH_API_KEY_VALUE_KEY, MQ_AUTH_CLIENT_SECRET_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_SECRET_PREFIX,
MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY, MQ_TOKEN_SIGNING_SECRET_PREFIX, NACOS_AUTH_PASSWORD_KEY,
- NACOS_AUTH_SECRET_PREFIX, NACOS_RNACOS_CONSOLE_PASSWORD_KEY,
+ NACOS_AUTH_SECRET_PREFIX, NACOS_RNACOS_CONSOLE_PASSWORD_KEY, PLUGIN_CONNECTION_SECRET_PREFIX,
};
use crate::db::sqlite::{connect_path_create_if_missing, SqliteHandle};
use crate::history::{
@@ -3203,6 +3203,7 @@ fn sanitized_connection_config(config: &ConnectionConfig) -> ConnectionConfig {
scrub_mq_token_signing_secret(&mut sanitized);
scrub_nacos_auth_secrets(&mut sanitized);
scrub_cassandra_tls_secrets(&mut sanitized);
+ sanitized.connection_secrets.clear();
sanitized
}
@@ -3279,7 +3280,40 @@ fn persist_connection_in_tx(tx: &rusqlite::Transaction<'_>, config: &ConnectionC
persist_mq_auth_secrets_in_tx(tx, &config)?;
persist_mq_token_signing_secret_in_tx(tx, &config)?;
persist_nacos_auth_secrets_in_tx(tx, &config)?;
- persist_cassandra_tls_secrets_in_tx(tx, &config)
+ persist_cassandra_tls_secrets_in_tx(tx, &config)?;
+ delete_secret_prefix_in_tx(tx, &config.id, PLUGIN_CONNECTION_SECRET_PREFIX)?;
+ for (key, secret) in &config.connection_secrets {
+ if !key.is_empty() {
+ persist_secret_in_tx(tx, &config.id, &format!("{PLUGIN_CONNECTION_SECRET_PREFIX}{key}"), secret)?;
+ }
+ }
+ Ok(())
+}
+
+async fn load_plugin_connection_secrets(
+ storage: &Storage,
+ connection_id: &str,
+) -> Result<HashMap<String, String>, String> {
+ let connection_id = connection_id.to_string();
+ storage
+ .with_conn(move |conn| {
+ let like = format!("{PLUGIN_CONNECTION_SECRET_PREFIX}%");
+ let mut statement = conn
+ .prepare("SELECT key, secret FROM connection_secrets WHERE connection_id = ?1 AND key LIKE ?2")
+ .map_err(|error| error.to_string())?;
+ let rows = statement
+ .query_map(params![connection_id, like], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))
+ .map_err(|error| error.to_string())?;
+ let mut secrets = HashMap::new();
+ for row in rows {
+ let (key, secret) = row.map_err(|error| error.to_string())?;
+ if let Some(key) = key.strip_prefix(PLUGIN_CONNECTION_SECRET_PREFIX) {
+ secrets.insert(key.to_string(), secret);
+ }
+ }
+ Ok(secrets)
+ })
+ .await
}
fn insert_connection_copy_next_to_source(entries: &mut Vec<serde_json::Value>, source_id: &str, copy_id: &str) -> bool {
@@ -3415,6 +3449,7 @@ impl Storage {
scrub_mq_token_signing_secret(&mut sanitized);
scrub_nacos_auth_secrets(&mut sanitized);
scrub_cassandra_tls_secrets(&mut sanitized);
+ sanitized.connection_secrets.clear();
let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
tx.execute("INSERT INTO connections (id, config_json) VALUES (?1, ?2)", params![config_id, json])
@@ -3733,6 +3768,10 @@ impl Storage {
config.redis_sentinel_password = self.get_secret(&id, "redis_sentinel_password").await?.unwrap_or_default();
config.connection_string = self.get_secret(&id, "connection_string").await?;
config.init_script = self.get_secret(&id, "init_script").await?;
+ let stored_plugin_secrets = load_plugin_connection_secrets(self, &id).await?;
+ if !stored_plugin_secrets.is_empty() {
+ config.connection_secrets = stored_plugin_secrets;
+ }
let needs_mq_auth_rewrite = self.hydrate_mq_auth_secrets(&id, &mut config).await?;
let needs_mq_token_signing_rewrite = self.hydrate_mq_token_signing_secret(&id, &mut config).await?;
let needs_nacos_auth_rewrite = self.hydrate_nacos_auth_secret(&id, &mut config).await?;
@@ -4276,6 +4315,21 @@ impl Storage {
})
.await
}
+
+ pub async fn delete_secret_prefix(&self, connection_id: &str, key_prefix: &str) -> Result<(), String> {
+ let connection_id = connection_id.to_string();
+ let key_prefix = key_prefix.to_string();
+ self.with_conn(move |conn| {
+ let like = format!("{key_prefix}%");
+ conn.execute(
+ "DELETE FROM connection_secrets WHERE connection_id = ?1 AND key LIKE ?2",
+ params![connection_id, like],
+ )
+ .map(|_| ())
+ .map_err(|error| error.to_string())
+ })
+ .await
+ }
}
// MQ token records
@@ -5300,7 +5354,7 @@ mod tests {
use crate::connection_secrets::NACOS_RNACOS_CONSOLE_PASSWORD_KEY;
use crate::connection_secrets::{
CASSANDRA_KEYSTORE_PASSWORD_KEY, CASSANDRA_TRUSTSTORE_PASSWORD_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_TOKEN_KEY,
- MQ_TOKEN_SIGNING_KEY, NACOS_AUTH_PASSWORD_KEY,
+ MQ_TOKEN_SIGNING_KEY, NACOS_AUTH_PASSWORD_KEY, PLUGIN_CONNECTION_SECRET_PREFIX,
};
use crate::history::{HistoryConnectionFilter, HistoryDatabaseFilter, HistoryEntry, HistorySearchRequest};
use crate::models::connection::{
@@ -6029,6 +6083,41 @@ mod tests {
let _ = std::fs::remove_file(path);
}
+ #[tokio::test]
+ async fn save_connections_moves_plugin_secrets_to_secret_table_and_restores_them() {
+ let path = temp_db_path("plugin-secrets");
+ let storage = Storage::open(&path).await.unwrap();
+ let mut config = plain_connection("plugin", "");
+ config.db_type = DatabaseType::Plugin;
+ config.plugin_id = Some("example.plugin".to_string());
+ config.plugin_connection_provider = Some("example.connection".to_string());
+ config.connection_secrets.insert("api_token".to_string(), "plugin-secret".to_string());
+
+ storage.save_connections(std::slice::from_ref(&config)).await.unwrap();
+
+ let raw_json = raw_connection_json(&storage, &config.id).await;
+ assert!(!raw_json.contains("plugin-secret"));
+ assert_eq!(
+ storage
+ .get_secret(&config.id, &format!("{PLUGIN_CONNECTION_SECRET_PREFIX}api_token"))
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("plugin-secret")
+ );
+ assert_eq!(storage.load_connections().await.unwrap()[0].connection_secrets, config.connection_secrets);
+
+ let mut cleared = config;
+ cleared.connection_secrets.clear();
+ storage.save_connections(std::slice::from_ref(&cleared)).await.unwrap();
+ assert_eq!(
+ storage.get_secret(&cleared.id, &format!("{PLUGIN_CONNECTION_SECRET_PREFIX}api_token")).await.unwrap(),
+ None
+ );
+
+ let _ = std::fs::remove_file(path);
+ }
+
#[tokio::test]
async fn switching_save_password_off_removes_stored_password() {
let path = temp_db_path("save-password-switch-off");
@@ -6107,6 +6196,10 @@ mod tests {
"token": token
}
})),
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
@@ -6178,6 +6271,10 @@ mod tests {
"password": password
}
})),
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/src/table_export.rs b/crates/dbx-core/src/table_export.rs
index 4cf5a9181e..2269a4e7a6 100644
--- a/crates/dbx-core/src/table_export.rs
+++ b/crates/dbx-core/src/table_export.rs
@@ -2287,8 +2287,8 @@ mod tests {
permissions.set_mode(0o755);
std::fs::set_permissions(&executable, permissions).unwrap();
- let plugin = InstalledPlugin {
- manifest: PluginManifest {
+ let plugin = InstalledPlugin::new(
+ PluginManifest {
id: "jdbc".to_string(),
name: "JDBC".to_string(),
version: "test".to_string(),
@@ -2301,9 +2301,12 @@ mod tests {
kind: "external".to_string(),
database_type: Some("jdbc".to_string()),
}],
+ contributions: Vec::new(),
+ ..PluginManifest::default()
},
- path: dir.clone(),
- };
+ dir.clone(),
+ env!("CARGO_PKG_VERSION"),
+ );
let session = Arc::new(
PluginDriverSession::start_for_test(plugin, "jdbc".to_string(), PluginRuntimeEnv::default())
.await
diff --git a/crates/dbx-core/src/transfer.rs b/crates/dbx-core/src/transfer.rs
index 82f734066c..80b87d1278 100644
--- a/crates/dbx-core/src/transfer.rs
+++ b/crates/dbx-core/src/transfer.rs
@@ -10063,6 +10063,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: if driver_class.is_empty() { None } else { Some(driver_class.to_string()) },
jdbc_driver_paths: Vec::new(),
one_time: false,
@@ -15184,6 +15188,10 @@ SELECT 1 FROM dual"#
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/tests/dump_docs_fixture.rs b/crates/dbx-core/tests/dump_docs_fixture.rs
index 563271fea2..bdbb874788 100644
--- a/crates/dbx-core/tests/dump_docs_fixture.rs
+++ b/crates/dbx-core/tests/dump_docs_fixture.rs
@@ -70,6 +70,10 @@ fn live_postgres_config(
etcd_endpoints: String::new(),
gbase_server: String::new(),
informix_server: String::new(),
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
external_config: None,
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
diff --git a/crates/dbx-core/tests/live_postgres_docs_annotations.rs b/crates/dbx-core/tests/live_postgres_docs_annotations.rs
index 50b24c2efc..bcda63c8ad 100644
--- a/crates/dbx-core/tests/live_postgres_docs_annotations.rs
+++ b/crates/dbx-core/tests/live_postgres_docs_annotations.rs
@@ -66,6 +66,10 @@ fn live_postgres_config(
etcd_endpoints: String::new(),
gbase_server: String::new(),
informix_server: String::new(),
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
external_config: None,
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
diff --git a/crates/dbx-core/tests/live_postgres_docs_snapshot.rs b/crates/dbx-core/tests/live_postgres_docs_snapshot.rs
index a217073cda..229708c673 100644
--- a/crates/dbx-core/tests/live_postgres_docs_snapshot.rs
+++ b/crates/dbx-core/tests/live_postgres_docs_snapshot.rs
@@ -61,6 +61,10 @@ fn live_postgres_config(
etcd_endpoints: String::new(),
gbase_server: String::new(),
informix_server: String::new(),
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
external_config: None,
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
diff --git a/crates/dbx-core/tests/live_postgres_query_result_export.rs b/crates/dbx-core/tests/live_postgres_query_result_export.rs
index b2ed9a5afb..68bc292e61 100644
--- a/crates/dbx-core/tests/live_postgres_query_result_export.rs
+++ b/crates/dbx-core/tests/live_postgres_query_result_export.rs
@@ -67,6 +67,10 @@ fn live_postgres_config(
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/tests/live_postgres_transfer.rs b/crates/dbx-core/tests/live_postgres_transfer.rs
index e230bbc257..5f60b87088 100644
--- a/crates/dbx-core/tests/live_postgres_transfer.rs
+++ b/crates/dbx-core/tests/live_postgres_transfer.rs
@@ -61,6 +61,10 @@ fn postgres_test_config(id: &str, database: &str) -> ConnectionConfig {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/tests/live_sqlserver_completion.rs b/crates/dbx-core/tests/live_sqlserver_completion.rs
index e594bbcbc7..6715ee35c9 100644
--- a/crates/dbx-core/tests/live_sqlserver_completion.rs
+++ b/crates/dbx-core/tests/live_sqlserver_completion.rs
@@ -68,6 +68,10 @@ fn live_sqlserver_config(id: &str, database: &str) -> dbx_core::models::connecti
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/tests/live_sqlserver_query_result_export.rs b/crates/dbx-core/tests/live_sqlserver_query_result_export.rs
index a24dd1b77e..e19d40a81c 100644
--- a/crates/dbx-core/tests/live_sqlserver_query_result_export.rs
+++ b/crates/dbx-core/tests/live_sqlserver_query_result_export.rs
@@ -57,6 +57,10 @@ fn live_sqlserver_config(id: &str, database: &str) -> dbx_core::models::connecti
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/tests/live_sqlserver_transfer.rs b/crates/dbx-core/tests/live_sqlserver_transfer.rs
index c64a236c26..c1e776af0a 100644
--- a/crates/dbx-core/tests/live_sqlserver_transfer.rs
+++ b/crates/dbx-core/tests/live_sqlserver_transfer.rs
@@ -60,6 +60,10 @@ fn live_sqlserver_config(id: &str, database: &str) -> ConnectionConfig {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-core/tests/support/mod.rs b/crates/dbx-core/tests/support/mod.rs
index 36b90858ee..8e576f3786 100644
--- a/crates/dbx-core/tests/support/mod.rs
+++ b/crates/dbx-core/tests/support/mod.rs
@@ -181,6 +181,10 @@ pub fn postgres_test_config(id: &str, port: u16) -> ConnectionConfig {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rs
index 3d5ade5aa0..7083a4c014 100644
--- a/crates/dbx-web/src/main.rs
+++ b/crates/dbx-web/src/main.rs
@@ -403,6 +403,37 @@ async fn main() {
.route("/connection/mcp/duplicate", post(routes::connection::mcp_duplicate_connection))
.route("/connection/mcp/remove", post(routes::connection::mcp_remove_connection))
.route("/plugins", get(routes::plugins::list_plugins))
+ .route("/plugins/trusted-keys", get(routes::plugins::list_plugin_trusted_keys))
+ .route("/plugins/trusted-keys/save", post(routes::plugins::save_plugin_trusted_key))
+ .route("/plugins/trusted-keys/remove", post(routes::plugins::remove_plugin_trusted_key))
+ .route("/plugins/repositories", get(routes::plugins::list_plugin_repositories))
+ .route("/plugins/repositories/save", post(routes::plugins::save_plugin_repository))
+ .route("/plugins/repositories/remove", post(routes::plugins::remove_plugin_repository))
+ .route("/plugins/marketplace/catalogs", get(routes::plugins::fetch_plugin_marketplace_catalogs))
+ .route("/plugins/marketplace/install", post(routes::plugins::install_marketplace_plugin))
+ .route(
+ "/plugins/install",
+ post(routes::plugins::install_plugin).layer(axum::extract::DefaultBodyLimit::max(512 * 1024 * 1024)),
+ )
+ .route("/plugins/rollback", post(routes::plugins::rollback_plugin))
+ .route("/plugins/uninstall", post(routes::plugins::uninstall_plugin))
+ .route("/plugins/activate", post(routes::plugins::activate_plugin))
+ .route("/plugins/active", get(routes::plugins::list_active_plugins))
+ .route("/plugins/stop", post(routes::plugins::stop_plugin))
+ .route("/plugins/invoke", post(routes::plugins::invoke_plugin))
+ .route("/plugins/connection-action", post(routes::plugins::invoke_plugin_connection_action))
+ .route("/plugins/notify", post(routes::plugins::notify_plugin))
+ .route("/plugins/binary", post(routes::plugins::send_plugin_binary))
+ .route("/plugins/filesystem/list", post(routes::plugins::list_plugin_filesystem_entries))
+ .route("/plugins/filesystem/read", post(routes::plugins::read_plugin_filesystem_file))
+ .route("/plugins/filesystem/write", post(routes::plugins::write_plugin_filesystem_file))
+ .route("/plugins/filesystem/create-directory", post(routes::plugins::create_plugin_filesystem_directory))
+ .route("/plugins/filesystem/delete", post(routes::plugins::delete_plugin_filesystem_entry))
+ .route("/plugins/filesystem/rename", post(routes::plugins::rename_plugin_filesystem_entry))
+ .route("/plugins/events", get(routes::plugins::plugin_events))
+ .route("/plugins/{pluginId}/assets/{*path}", get(routes::plugins::plugin_asset))
+ .route("/plugins/{pluginId}/ui", get(routes::plugins::plugin_ui_entry))
+ .route("/plugins/{pluginId}/ui/{*path}", get(routes::plugins::plugin_ui_asset))
// JDBC
.route("/jdbc/drivers", get(routes::jdbc::list_jdbc_drivers).post(routes::jdbc::import_jdbc_drivers))
.route(
diff --git a/crates/dbx-web/src/routes/connection.rs b/crates/dbx-web/src/routes/connection.rs
index f14be71e14..72c0b37610 100644
--- a/crates/dbx-web/src/routes/connection.rs
+++ b/crates/dbx-web/src/routes/connection.rs
@@ -869,6 +869,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/crates/dbx-web/src/routes/plugins.rs b/crates/dbx-web/src/routes/plugins.rs
index ed1c9a3329..52c1543a5f 100644
--- a/crates/dbx-web/src/routes/plugins.rs
+++ b/crates/dbx-web/src/routes/plugins.rs
@@ -1,12 +1,633 @@
+use std::convert::Infallible;
use std::sync::Arc;
+use std::time::Duration;
-use axum::extract::State;
+use async_stream::stream;
+use axum::body::Body;
+use axum::extract::{Multipart, Path, Query, State};
+use axum::http::header::{CACHE_CONTROL, CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG};
+use axum::http::{HeaderName, HeaderValue, Response};
+use axum::response::sse::{Event, KeepAlive, Sse};
use axum::Json;
-use dbx_core::plugins::InstalledPlugin;
+use base64::Engine;
+use dbx_core::models::connection::ConnectionConfig;
+use dbx_core::plugins::{
+ ActivePluginSession, InstalledPlugin, InstalledPluginInfo, PluginConnectionActionResult,
+ PluginFilesystemListResult, PluginFilesystemMutationResult, PluginFilesystemReadResult, PluginInstallPolicy,
+ PluginInstallResponse, PluginMarketplace, PluginMarketplaceInstallRequest, PluginPackageInstaller,
+ PluginRepository, PluginRepositoryCatalogResult, PluginRollbackResponse, PluginTrustStore, PluginTrustedKey,
+ PluginUiAsset,
+};
+use serde::{Deserialize, Serialize};
use crate::error::AppError;
use crate::state::WebState;
-pub async fn list_plugins(State(state): State<Arc<WebState>>) -> Result<Json<Vec<InstalledPlugin>>, AppError> {
- state.app.plugins.list_installed().map(Json).map_err(AppError::from)
+const MAX_PLUGIN_UPLOAD_BYTES: usize = 512 * 1024 * 1024;
+
+#[derive(Debug, Deserialize, Default)]
+pub struct PluginInstallQuery {
+ #[serde(default)]
+ allow_unsigned: bool,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct PluginIdRequest {
+ plugin_id: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginTrustedKeyRequest {
+ key_id: String,
+ public_key: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginTrustedKeyIdRequest {
+ key_id: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginRepositoryIdRequest {
+ repository_id: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginInvokeRequest {
+ plugin_id: String,
+ method: String,
+ #[serde(default)]
+ params: serde_json::Value,
+ timeout_ms: Option<u64>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginConnectionActionRequest {
+ config: ConnectionConfig,
+ action_id: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginNotifyRequest {
+ plugin_id: String,
+ method: String,
+ #[serde(default)]
+ params: serde_json::Value,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginBinaryRequest {
+ plugin_id: String,
+ channel: String,
+ data_base64: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginFilesystemListRequest {
+ plugin_id: String,
+ provider_id: String,
+ connection_id: Option<String>,
+ uri: Option<String>,
+ cursor: Option<String>,
+ limit: Option<u32>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginFilesystemReadRequest {
+ plugin_id: String,
+ provider_id: String,
+ connection_id: Option<String>,
+ uri: String,
+ max_bytes: Option<u64>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginFilesystemWriteRequest {
+ plugin_id: String,
+ provider_id: String,
+ connection_id: Option<String>,
+ uri: String,
+ data_base64: String,
+ #[serde(default)]
+ create: bool,
+ #[serde(default)]
+ overwrite: bool,
+ etag: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginFilesystemDirectoryRequest {
+ plugin_id: String,
+ provider_id: String,
+ connection_id: Option<String>,
+ uri: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginFilesystemDeleteRequest {
+ plugin_id: String,
+ provider_id: String,
+ connection_id: Option<String>,
+ uri: String,
+ #[serde(default)]
+ recursive: bool,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginFilesystemRenameRequest {
+ plugin_id: String,
+ provider_id: String,
+ connection_id: Option<String>,
+ source_uri: String,
+ target_uri: String,
+ #[serde(default)]
+ overwrite: bool,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(tag = "kind", rename_all = "snake_case", rename_all_fields = "camelCase")]
+enum PluginStreamMessage {
+ Event { plugin_id: String, method: String, params: serde_json::Value },
+ Binary { plugin_id: String, channel: String, data_base64: String },
+ Lagged { skipped: u64 },
+}
+
+pub async fn list_plugins(State(state): State<Arc<WebState>>) -> Result<Json<Vec<InstalledPluginInfo>>, AppError> {
+ state
+ .app
+ .plugins
+ .list_installed()
+ .map(|plugins| Json(plugins.into_iter().map(|plugin| plugin.info()).collect()))
+ .map_err(AppError::from)
+}
+
+pub async fn list_plugin_trusted_keys(
+ State(state): State<Arc<WebState>>,
+) -> Result<Json<Vec<PluginTrustedKey>>, AppError> {
+ PluginTrustStore::list_base64_keys(state.app.plugins.root_dir()).map(Json).map_err(AppError::from)
+}
+
+pub async fn list_plugin_repositories(
+ State(state): State<Arc<WebState>>,
+) -> Result<Json<Vec<PluginRepository>>, AppError> {
+ let marketplace =
+ PluginMarketplace::new(state.app.plugins.root_dir().to_path_buf(), state.app.plugins.app_version().to_string())
+ .map_err(AppError::from)?;
+ marketplace.repositories().list().map(Json).map_err(AppError::from)
+}
+
+pub async fn save_plugin_repository(
+ State(state): State<Arc<WebState>>,
+ Json(repository): Json<PluginRepository>,
+) -> Result<Json<Vec<PluginRepository>>, AppError> {
+ let marketplace =
+ PluginMarketplace::new(state.app.plugins.root_dir().to_path_buf(), state.app.plugins.app_version().to_string())
+ .map_err(AppError::from)?;
+ marketplace.repositories().save(repository).map(Json).map_err(AppError::bad_request)
+}
+
+pub async fn remove_plugin_repository(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginRepositoryIdRequest>,
+) -> Result<Json<Vec<PluginRepository>>, AppError> {
+ let marketplace =
+ PluginMarketplace::new(state.app.plugins.root_dir().to_path_buf(), state.app.plugins.app_version().to_string())
+ .map_err(AppError::from)?;
+ marketplace.repositories().remove(&request.repository_id).map(Json).map_err(AppError::bad_request)
+}
+
+pub async fn fetch_plugin_marketplace_catalogs(
+ State(state): State<Arc<WebState>>,
+) -> Result<Json<Vec<PluginRepositoryCatalogResult>>, AppError> {
+ let marketplace =
+ PluginMarketplace::new(state.app.plugins.root_dir().to_path_buf(), state.app.plugins.app_version().to_string())
+ .map_err(AppError::from)?;
+ Ok(Json(marketplace.fetch_catalogs().await))
+}
+
+pub async fn install_marketplace_plugin(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginMarketplaceInstallRequest>,
+) -> Result<Json<PluginInstallResponse>, AppError> {
+ let marketplace =
+ PluginMarketplace::new(state.app.plugins.root_dir().to_path_buf(), state.app.plugins.app_version().to_string())
+ .map_err(AppError::from)?;
+ let result = marketplace.install(request).await.map_err(AppError::bad_request)?;
+ state.app.remove_plugin_connection_pools(&result.plugin.manifest.id).await;
+ stop_external_driver_pools(&state, &result.plugin).await;
+ state.app.plugin_host.stop(&result.plugin.manifest.id).await;
+ Ok(Json(result.response()))
+}
+
+pub async fn save_plugin_trusted_key(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginTrustedKeyRequest>,
+) -> Result<Json<Vec<PluginTrustedKey>>, AppError> {
+ let root_dir = state.app.plugins.root_dir().to_path_buf();
+ tokio::task::spawn_blocking(move || {
+ PluginTrustStore::save_base64_key(&root_dir, &request.key_id, &request.public_key)?;
+ PluginTrustStore::list_base64_keys(&root_dir)
+ })
+ .await
+ .map_err(|error| AppError::internal(error.to_string()))?
+ .map(Json)
+ .map_err(AppError::bad_request)
+}
+
+pub async fn remove_plugin_trusted_key(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginTrustedKeyIdRequest>,
+) -> Result<Json<Vec<PluginTrustedKey>>, AppError> {
+ let root_dir = state.app.plugins.root_dir().to_path_buf();
+ tokio::task::spawn_blocking(move || {
+ PluginTrustStore::remove_key(&root_dir, &request.key_id)?;
+ PluginTrustStore::list_base64_keys(&root_dir)
+ })
+ .await
+ .map_err(|error| AppError::internal(error.to_string()))?
+ .map(Json)
+ .map_err(AppError::bad_request)
+}
+
+pub async fn install_plugin(
+ State(state): State<Arc<WebState>>,
+ Query(query): Query<PluginInstallQuery>,
+ mut multipart: Multipart,
+) -> Result<Json<PluginInstallResponse>, AppError> {
+ let mut package = None;
+ while let Some(field) = multipart.next_field().await.map_err(|error| AppError::bad_request(error.to_string()))? {
+ if field.name() != Some("file") {
+ continue;
+ }
+ let bytes = field.bytes().await.map_err(|error| AppError::bad_request(error.to_string()))?;
+ if bytes.len() > MAX_PLUGIN_UPLOAD_BYTES {
+ return Err(AppError::bad_request("Plugin package is too large"));
+ }
+ package = Some(bytes.to_vec());
+ break;
+ }
+ let package = package.ok_or_else(|| AppError::bad_request("Missing plugin package field 'file'"))?;
+ let policy =
+ if query.allow_unsigned { PluginInstallPolicy::LocalDevelopment } else { PluginInstallPolicy::LocalSigned };
+ let root_dir = state.app.plugins.root_dir().to_path_buf();
+ let app_version = state.app.plugins.app_version().to_string();
+ let result = tokio::task::spawn_blocking(move || {
+ PluginPackageInstaller::new(root_dir, app_version)?.install_bytes(&package, policy)
+ })
+ .await
+ .map_err(|error| AppError::internal(error.to_string()))?
+ .map_err(AppError::bad_request)?;
+ state.app.remove_plugin_connection_pools(&result.plugin.manifest.id).await;
+ stop_external_driver_pools(&state, &result.plugin).await;
+ state.app.plugin_host.stop(&result.plugin.manifest.id).await;
+ Ok(Json(result.response()))
+}
+
+pub async fn rollback_plugin(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginIdRequest>,
+) -> Result<Json<PluginRollbackResponse>, AppError> {
+ state.app.remove_plugin_connection_pools(&request.plugin_id).await;
+ state.app.plugin_host.stop(&request.plugin_id).await;
+ let root_dir = state.app.plugins.root_dir().to_path_buf();
+ let app_version = state.app.plugins.app_version().to_string();
+ let result = tokio::task::spawn_blocking(move || {
+ PluginPackageInstaller::new(root_dir, app_version)?.rollback(&request.plugin_id)
+ })
+ .await
+ .map_err(|error| AppError::internal(error.to_string()))?
+ .map_err(AppError::bad_request)?;
+ stop_external_driver_pools(&state, &result.plugin).await;
+ Ok(Json(result.response()))
+}
+
+pub async fn uninstall_plugin(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginIdRequest>,
+) -> Result<Json<Vec<InstalledPluginInfo>>, AppError> {
+ let dependent_connections = state
+ .app
+ .storage
+ .load_connections()
+ .await
+ .map_err(AppError::from)?
+ .into_iter()
+ .filter(|connection| {
+ connection.db_type == dbx_core::models::connection::DatabaseType::Plugin
+ && connection.plugin_id.as_deref() == Some(request.plugin_id.as_str())
+ })
+ .map(|connection| connection.name)
+ .collect::<Vec<_>>();
+ if !dependent_connections.is_empty() {
+ return Err(AppError::bad_request(format!(
+ "Cannot uninstall plugin '{}' while these connections still use it: {}",
+ request.plugin_id,
+ dependent_connections.join(", ")
+ )));
+ }
+ let plugin = state.app.plugins.find_plugin(&request.plugin_id).map_err(AppError::from)?;
+ state.app.remove_plugin_connection_pools(&request.plugin_id).await;
+ state.app.plugin_host.stop(&request.plugin_id).await;
+ if let Some(plugin) = &plugin {
+ stop_external_driver_pools(&state, plugin).await;
+ }
+ let root_dir = state.app.plugins.root_dir().to_path_buf();
+ let app_version = state.app.plugins.app_version().to_string();
+ tokio::task::spawn_blocking(move || {
+ PluginPackageInstaller::new(root_dir, app_version)?.uninstall(&request.plugin_id)
+ })
+ .await
+ .map_err(|error| AppError::internal(error.to_string()))?
+ .map_err(AppError::bad_request)?;
+ list_plugins(State(state)).await
+}
+
+pub async fn activate_plugin(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginIdRequest>,
+) -> Result<Json<Vec<ActivePluginSession>>, AppError> {
+ state.app.plugin_host.activate(&request.plugin_id).await.map_err(AppError::bad_request)?;
+ Ok(Json(state.app.plugin_host.list_active().await))
+}
+
+pub async fn list_active_plugins(
+ State(state): State<Arc<WebState>>,
+) -> Result<Json<Vec<ActivePluginSession>>, AppError> {
+ Ok(Json(state.app.plugin_host.list_active().await))
+}
+
+pub async fn stop_plugin(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginIdRequest>,
+) -> Result<Json<serde_json::Value>, AppError> {
+ state.app.plugin_host.stop(&request.plugin_id).await;
+ Ok(Json(serde_json::json!({ "ok": true })))
+}
+
+pub async fn invoke_plugin(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginInvokeRequest>,
+) -> Result<Json<serde_json::Value>, AppError> {
+ let timeout = request.timeout_ms.map(|milliseconds| Duration::from_millis(milliseconds.clamp(1, 120_000)));
+ state
+ .app
+ .plugin_host
+ .invoke(&request.plugin_id, &request.method, request.params, None, timeout)
+ .await
+ .map(Json)
+ .map_err(AppError::bad_request)
+}
+
+pub async fn invoke_plugin_connection_action(
+ State(state): State<Arc<WebState>>,
+ Json(body): Json<PluginConnectionActionRequest>,
+) -> Result<Json<PluginConnectionActionResult>, AppError> {
+ state.app.invoke_plugin_connection_action(body.config, &body.action_id).await.map(Json).map_err(AppError::from)
+}
+
+pub async fn notify_plugin(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginNotifyRequest>,
+) -> Result<Json<serde_json::Value>, AppError> {
+ state
+ .app
+ .plugin_host
+ .notify(&request.plugin_id, &request.method, request.params, None)
+ .await
+ .map_err(AppError::bad_request)?;
+ Ok(Json(serde_json::json!({ "ok": true })))
+}
+
+pub async fn send_plugin_binary(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginBinaryRequest>,
+) -> Result<Json<serde_json::Value>, AppError> {
+ let data = base64::engine::general_purpose::STANDARD
+ .decode(request.data_base64)
+ .map_err(|error| AppError::bad_request(format!("Invalid plugin binary payload: {error}")))?;
+ state
+ .app
+ .plugin_host
+ .send_binary(&request.plugin_id, &request.channel, &data, None)
+ .await
+ .map_err(AppError::bad_request)?;
+ Ok(Json(serde_json::json!({ "ok": true })))
+}
+
+pub async fn list_plugin_filesystem_entries(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginFilesystemListRequest>,
+) -> Result<Json<PluginFilesystemListResult>, AppError> {
+ state
+ .app
+ .plugin_host
+ .list_filesystem_entries(
+ &request.plugin_id,
+ &request.provider_id,
+ request.connection_id.as_deref(),
+ request.uri.as_deref(),
+ request.cursor.as_deref(),
+ request.limit,
+ )
+ .await
+ .map(Json)
+ .map_err(AppError::bad_request)
+}
+
+pub async fn read_plugin_filesystem_file(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginFilesystemReadRequest>,
+) -> Result<Json<PluginFilesystemReadResult>, AppError> {
+ state
+ .app
+ .plugin_host
+ .read_filesystem_file(
+ &request.plugin_id,
+ &request.provider_id,
+ request.connection_id.as_deref(),
+ &request.uri,
+ request.max_bytes,
+ )
+ .await
+ .map(Json)
+ .map_err(AppError::bad_request)
+}
+
+pub async fn write_plugin_filesystem_file(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginFilesystemWriteRequest>,
+) -> Result<Json<PluginFilesystemMutationResult>, AppError> {
+ state
+ .app
+ .plugin_host
+ .write_filesystem_file(
+ &request.plugin_id,
+ &request.provider_id,
+ request.connection_id.as_deref(),
+ &request.uri,
+ &request.data_base64,
+ request.create,
+ request.overwrite,
+ request.etag.as_deref(),
+ )
+ .await
+ .map(Json)
+ .map_err(AppError::bad_request)
+}
+
+pub async fn create_plugin_filesystem_directory(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginFilesystemDirectoryRequest>,
+) -> Result<Json<PluginFilesystemMutationResult>, AppError> {
+ state
+ .app
+ .plugin_host
+ .create_filesystem_directory(
+ &request.plugin_id,
+ &request.provider_id,
+ request.connection_id.as_deref(),
+ &request.uri,
+ )
+ .await
+ .map(Json)
+ .map_err(AppError::bad_request)
+}
+
+pub async fn delete_plugin_filesystem_entry(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginFilesystemDeleteRequest>,
+) -> Result<Json<PluginFilesystemMutationResult>, AppError> {
+ state
+ .app
+ .plugin_host
+ .delete_filesystem_entry(
+ &request.plugin_id,
+ &request.provider_id,
+ request.connection_id.as_deref(),
+ &request.uri,
+ request.recursive,
+ )
+ .await
+ .map(Json)
+ .map_err(AppError::bad_request)
+}
+
+pub async fn rename_plugin_filesystem_entry(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<PluginFilesystemRenameRequest>,
+) -> Result<Json<PluginFilesystemMutationResult>, AppError> {
+ state
+ .app
+ .plugin_host
+ .rename_filesystem_entry(
+ &request.plugin_id,
+ &request.provider_id,
+ request.connection_id.as_deref(),
+ &request.source_uri,
+ &request.target_uri,
+ request.overwrite,
+ )
+ .await
+ .map(Json)
+ .map_err(AppError::bad_request)
+}
+
+pub async fn plugin_events(
+ State(state): State<Arc<WebState>>,
+) -> Sse<impl futures::Stream<Item = Result<Event, Infallible>>> {
+ let mut events = state.app.plugin_host.subscribe_events();
+ let mut binary = state.app.plugin_host.subscribe_binary();
+ let stream = stream! {
+ loop {
+ let message = tokio::select! {
+ event = events.recv() => match event {
+ Ok(event) => PluginStreamMessage::Event { plugin_id: event.plugin_id, method: event.method, params: event.params },
+ Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => PluginStreamMessage::Lagged { skipped },
+ Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
+ },
+ message = binary.recv() => match message {
+ Ok(message) => PluginStreamMessage::Binary {
+ plugin_id: message.plugin_id,
+ channel: message.channel,
+ data_base64: base64::engine::general_purpose::STANDARD.encode(message.data),
+ },
+ Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => PluginStreamMessage::Lagged { skipped },
+ Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
+ },
+ };
+ if let Ok(data) = serde_json::to_string(&message) {
+ yield Ok(Event::default().data(data));
+ }
+ }
+ };
+ Sse::new(stream).keep_alive(KeepAlive::default())
+}
+
+pub async fn plugin_ui_entry(
+ State(state): State<Arc<WebState>>,
+ Path(plugin_id): Path<String>,
+) -> Result<Response<Body>, AppError> {
+ let asset = state.app.plugins.read_ui_entry(&plugin_id).map_err(AppError::bad_request)?;
+ asset_response(asset)
+}
+
+pub async fn plugin_asset(
+ State(state): State<Arc<WebState>>,
+ Path((plugin_id, path)): Path<(String, String)>,
+) -> Result<Response<Body>, AppError> {
+ let asset = state.app.plugins.read_asset(&plugin_id, &path).map_err(AppError::bad_request)?;
+ asset_response(asset)
+}
+
+pub async fn plugin_ui_asset(
+ State(state): State<Arc<WebState>>,
+ Path((plugin_id, path)): Path<(String, String)>,
+) -> Result<Response<Body>, AppError> {
+ let asset = state.app.plugins.read_ui_asset(&plugin_id, &path).map_err(AppError::bad_request)?;
+ asset_response(asset)
+}
+
+fn asset_response(asset: PluginUiAsset) -> Result<Response<Body>, AppError> {
+ let is_html = asset.content_type.starts_with("text/html");
+ let mut response = Response::new(Body::from(asset.bytes));
+ response.headers_mut().insert(
+ CONTENT_TYPE,
+ HeaderValue::from_str(&asset.content_type).map_err(|error| AppError::internal(error.to_string()))?,
+ );
+ response
+ .headers_mut()
+ .insert(ETAG, HeaderValue::from_str(&asset.etag).map_err(|error| AppError::internal(error.to_string()))?);
+ response.headers_mut().insert(CACHE_CONTROL, HeaderValue::from_static("no-cache"));
+ response
+ .headers_mut()
+ .insert(HeaderName::from_static("x-content-type-options"), HeaderValue::from_static("nosniff"));
+ if is_html {
+ response.headers_mut().insert(
+ CONTENT_SECURITY_POLICY,
+ HeaderValue::from_static(
+ "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'none'; frame-ancestors 'self'",
+ ),
+ );
+ }
+ Ok(response)
+}
+
+async fn stop_external_driver_pools(state: &Arc<WebState>, plugin: &InstalledPlugin) {
+ for driver in &plugin.manifest.drivers {
+ let driver_id = driver.database_type.as_deref().unwrap_or(&driver.id);
+ state.app.remove_external_driver_pools(driver_id).await;
+ }
}
diff --git a/crates/dbx-web/src/routes/transfer.rs b/crates/dbx-web/src/routes/transfer.rs
index 4ae1e3283b..7e307db251 100644
--- a/crates/dbx-web/src/routes/transfer.rs
+++ b/crates/dbx-web/src/routes/transfer.rs
@@ -724,6 +724,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
diff --git a/docs/content/docs/contributing.cn.mdx b/docs/content/docs/contributing.cn.mdx
index b8cb4e58d3..ed41261dc5 100644
--- a/docs/content/docs/contributing.cn.mdx
+++ b/docs/content/docs/contributing.cn.mdx
@@ -15,6 +15,10 @@ description: 从零搭建 DBX 开发环境,运行桌面版,完成第一次
第一次贡献推荐从文档、翻译、小型 UI 问题或你熟悉的数据库问题开始。一个 PR 只解决一个明确问题,会更容易验证和合并。
</Callout>
+<Callout type="warn">
+ 本页的 PR 目标仓库是 `t8y2/dbx`,适用于 DBX 主应用、插件框架、SDK、CLI、文档和 Agent。普通插件源码保留在插件自己的仓库;插件上架 PR 应提交到 `t8y2/dbx-store`。完整流程见[开发和提交 DBX 插件](/cn/docs/plugin-development)。
+</Callout>
+
## 1. 选择并认领任务
打开 [DBX Issues](https://github.com/t8y2/dbx/issues),选择一个尚未分配、评论中也没有人正在处理的 Issue。第一次贡献优先考虑:
diff --git a/docs/content/docs/contributing.mdx b/docs/content/docs/contributing.mdx
index 470f816a9a..0927a961a1 100644
--- a/docs/content/docs/contributing.mdx
+++ b/docs/content/docs/contributing.mdx
@@ -15,6 +15,10 @@ This tutorial is for first-time DBX contributors. By the end, you will have:
Documentation, translations, small UI fixes, and issues for a database you can test are good first contributions. Keep each pull request focused on one verifiable problem.
</Callout>
+<Callout type="warn">
+ Pull requests described on this page target `t8y2/dbx` and cover the DBX application, plugin platform, SDK, CLI, documentation, and Agents. Ordinary plugin source remains in the plugin's own repository, while Marketplace listing PRs target `t8y2/dbx-store`. See [Develop and Submit DBX Plugins](/en/docs/plugin-development) for the complete flow.
+</Callout>
+
## 1. Choose and Claim an Issue
Open [DBX Issues](https://github.com/t8y2/dbx/issues) and choose an issue that has no assignee and no active contributor in its comments. Good first contributions have one of these properties:
diff --git a/docs/content/docs/meta.cn.json b/docs/content/docs/meta.cn.json
index 5c05ca420b..44895e6b9f 100644
--- a/docs/content/docs/meta.cn.json
+++ b/docs/content/docs/meta.cn.json
@@ -46,6 +46,7 @@
"keyboard-shortcuts",
"---开发与社区---",
"database-lab",
+ "plugin-development",
"contributing"
]
}
diff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.json
index f5aeb52e15..5d9f1070bf 100644
--- a/docs/content/docs/meta.json
+++ b/docs/content/docs/meta.json
@@ -46,6 +46,7 @@
"keyboard-shortcuts",
"---Development and Community---",
"database-lab",
+ "plugin-development",
"contributing"
]
}
diff --git a/docs/content/docs/plugin-development.cn.mdx b/docs/content/docs/plugin-development.cn.mdx
new file mode 100644
index 0000000000..20c6953868
--- /dev/null
+++ b/docs/content/docs/plugin-development.cn.mdx
@@ -0,0 +1,204 @@
+---
+title: 开发和提交 DBX 插件
+description: 创建 DBX 插件、构建未签名候选包,并明确源码、框架和官方商店分别向哪个仓库提交 Issue 或 Pull Request。
+---
+
+DBX 插件是独立安装的 `.dbxp` 包,可以提供连接类型、工作台、文件系统和原生 Sidecar。插件源码、DBX 插件框架和官方商店目录由不同仓库负责。
+
+<Callout type="warn">
+ **插件上架 Pull Request 提交到 [`t8y2/dbx-store`](https://github.com/t8y2/dbx-store),不是 `t8y2/dbx`。** 插件自己的功能代码通常保留在开发者自己的源码仓库;只有修改 DBX Host、SDK、CLI、协议、Schema、文档或官方示例时,才向 [`t8y2/dbx`](https://github.com/t8y2/dbx) 提交 PR。
+</Callout>
+
+## 应该提交到哪个仓库
+
+| 你要修改的内容 | 提交位置 | 是否向 DBX 官方提 PR |
+| --- | --- | --- |
+| 你的插件前端、Rust/Go 后端、测试和发布脚本 | 插件自己的源码仓库 | 不向 `dbx` 提交;在自己的仓库开发和发布 |
+| 新插件上架、版本更新、商店图标和介绍 | [`t8y2/dbx-store`](https://github.com/t8y2/dbx-store) | 是,目标分支为 `main` |
+| DBX 插件 Host、Manifest/Marketplace Schema、SDK、CLI、Packager | [`t8y2/dbx`](https://github.com/t8y2/dbx) | 是,目标分支为 `main` |
+| DBX 官方示例或插件开发文档 | [`t8y2/dbx`](https://github.com/t8y2/dbx) | 是 |
+| 某个第三方插件自身的 Bug | 该插件的源码仓库 | 不要提交到 `dbx-store` |
+| 自定义或企业私有仓库 | 你的私有仓库 | 不需要向官方商店提交 |
+| 数据库厂商 JDBC Driver JAR | 不提交到 Git 仓库 | 用户在本机或服务器中导入 |
+
+DBX 官方维护但需要独立发布节奏的插件,通常也应使用独立源码仓库。只有与 Host 强耦合的最小示例、SDK 验证项目或维护者明确同意的组件才放进 `t8y2/dbx`。
+
+## 插件由哪些部分组成
+
+```text
+my-plugin/
+├── manifest.json
+├── dbx-plugin.toml
+├── assets/
+├── ui/
+├── backend/ # frontend 模板没有此目录
+├── .github/workflows/
+│ └── plugin-release.yml
+└── dist/ # 构建输出,不提交到 Git
+```
+
+- `manifest.json` 声明插件身份、版本、权限、入口和 Contributions。
+- `ui/` 在沙箱工作台中运行,通过 Host API 与 DBX 交互。
+- `backend/` 是可选的原生 Sidecar,可以使用 Rust、Go 或其他能够实现 DBX JSON-RPC 协议的语言。
+- `.dbxp` 是安装包,不是源码仓库。
+- 前端插件可以发布一个 `universal` 包;包含原生 Sidecar 的插件需要按操作系统和 CPU 架构分别构建。
+
+## Workbench 上下文契约
+
+Workbench 上下文跨越 DBX 与插件边界时是 JSON 数据快照。宿主会递归移除 Vue 响应式包装并发送独立副本,因此插件不能依赖 Vue ref、Proxy、DOM 节点、函数、组件实例或凭据。
+
+上下文可以包含 `null`、布尔值、有限数字、字符串、数组和普通对象。对象中的 `undefined` 字段会省略,数组中的 `undefined` 会转换为 `null`。Date、Map、Set、Symbol、BigInt、非有限数字、循环引用和自定义 class 实例会被拒绝并返回错误。上下文 UTF-8 编码后的大小上限为 2 MiB。
+
+连接 Provider 使用 `binding: "config"` 的字段会保存到 `external_config`;使用 `binding: "secret"` 的字段会保存到 Secret Store。插件连接的 `external_config` 会在新建、编辑、保存和重新连接流程中保留。
+
+## 创建插件
+
+直接安装预编译 CLI,不需要 Rust,也不需要克隆 DBX 源码:
+
+```bash
+npm install --global @dbx-app/plugin-cli
+dbx-plugin --help
+```
+
+也可以直接使用 `npx`:
+
+```bash
+npx @dbx-app/plugin-cli create my-ui-plugin --template frontend
+```
+
+npm 包会自动选择当前平台的预编译二进制,并携带匹配版本的 Rust/Go 插件 SDK。纯前端插件不需要 Rust 或 Go;原生编译环境只用于构建插件自己的 Sidecar。
+
+创建项目:
+
+```bash
+# 纯前端、跨平台
+dbx-plugin create my-ui-plugin --template frontend
+
+# Rust Sidecar + 前端
+dbx-plugin create my-rust-plugin --template rust
+
+# Go Sidecar + 前端
+dbx-plugin create my-go-plugin --template go
+```
+
+生成项目后,先在自己的插件源码仓库开发、测试和维护版本记录。不要为了发布一个普通插件而把整个源码目录复制进 `t8y2/dbx`。
+
+## 构建候选包
+
+在插件项目根目录执行:
+
+```bash
+dbx-plugin package .
+```
+
+该命令只生成**未签名审核候选包**:
+
+```text
+dist/<plugin-id>-<version>-<target>.dbxp
+dist/<plugin-id>-<version>-<target>.artifact.json
+```
+
+官方插件作者不创建或持有 DBX Store 私钥。生成的 GitHub Release 工作流会按目标平台构建候选包,并合并产生 `release-candidates.json`。
+
+本地测试未签名包时,需要在插件中心显式开启“允许安装未签名开发包”。该选项不会放宽官方商店安装校验。
+
+## 提交官方商店的完整流程
+
+### 第一步:发布源码和候选 Release
+
+在插件自己的源码仓库创建版本 Tag 和 GitHub Release。Release 中应包含:
+
+- 每个平台的未签名 `.dbxp` 候选包;
+- 每个候选包对应的 `.artifact.json`;
+- 汇总后的 `release-candidates.json`;
+- Release Notes 和对应源码 Tag。
+
+候选包可以放在插件源码仓库的 GitHub Releases、CDN 或对象存储中,但不要把 `.dbxp` 提交到 Git 历史。
+
+### 第二步:在 dbx-store 发起审核 Issue
+
+前往 [`t8y2/dbx-store` Issues](https://github.com/t8y2/dbx-store/issues/new/choose),选择 **Plugin submission**,填写:
+
+- 插件 ID、版本和发布者;
+- 源码仓库和对应 Tag;
+- `release-candidates.json` 的 HTTPS 地址;
+- 权限、数据访问、网络访问和原生 Sidecar 行为;
+- 许可证、隐私政策和支持地址。
+
+审核 Issue 属于签名前的审核入口。此时不要向 `t8y2/dbx` 提交插件源码 PR,也不要自行添加官方 `signingKeyId`。
+
+### 第三步:DBX Store 审核并签名
+
+维护者会检查源码、Manifest、权限、候选 SHA-256、大小和原生行为。审核通过后,受保护的 DBX Store 工作流会:
+
+1. 按已审核 SHA-256 和大小下载候选包;
+2. 确认候选包没有已有签名,并核对插件 ID 和版本;
+3. 使用 DBX Store 仓库密钥添加 Ed25519 签名;
+4. 发布最终 `.dbxp`、最终 artifact metadata 和 signing receipt。
+
+开发者不会接触官方仓库私钥。
+
+### 第四步:向 dbx-store 提交上架 PR
+
+获得最终签名 artifact metadata 后,Fork [`t8y2/dbx-store`](https://github.com/t8y2/dbx-store),添加或更新:
+
+```text
+publishers/<publisher-id>.json # 仅发布者首次提交时需要
+plugins/<plugin-id>.json
+catalog/index.json # 由验证脚本生成
+```
+
+运行:
+
+```bash
+node scripts/validate.mjs
+```
+
+然后创建 Pull Request:
+
+```text
+目标仓库:t8y2/dbx-store
+目标分支:main
+```
+
+<Callout type="info">
+ 一个新插件的正式上架 PR **只提交到 `t8y2/dbx-store`**。`t8y2/dbx` PR 只用于修改插件平台本身,不用于登记普通第三方插件版本。
+</Callout>
+
+上架 PR 中不要包含:
+
+- `.dbxp` 二进制;
+- 插件完整源码副本;
+- Ed25519 私钥、Token 或下载凭据;
+- 未经 DBX Store 签名的候选包 URL;
+- 自行伪造的 `verified: true`。
+
+## 更新已有插件
+
+每次更新都发布新语义版本,不允许覆盖旧版本的 Release 资产:
+
+1. 在插件源码仓库发布新的源码 Tag 和候选 Release。
+2. 在 `t8y2/dbx-store` 创建新的 Plugin submission Issue,并引用旧插件和新版本。
+3. 等待新候选包完成审核和仓库签名。
+4. 向 `t8y2/dbx-store` 提交更新 `plugins/<plugin-id>.json` 的 PR。
+
+插件代码问题继续在插件源码仓库修复;只有目录、审核状态、最终下载地址、哈希、大小或商店文案变更才进入 `dbx-store`。
+
+## 签名和发布者身份
+
+DBX 当前使用单一仓库签名:
+
+- `publisher` 表示作者归属和商店记录;
+- `signingKeyId` 表示发布最终安装包的仓库密钥;
+- 官方插件由 DBX Store 审核后统一签名;
+- 自定义或私有仓库由仓库运营方维护自己的密钥;
+- 开发者签名或双签名不是当前上架要求。
+
+人工审核决定插件能否展示,Ed25519 仓库签名保证审核后的安装包没有被替换。签名不能替代源码审查,也不是原生 Sidecar 的操作系统沙箱。
+
+## 相关资料
+
+- [JDBC 插件与数据库驱动](/cn/docs/plugins)
+- [参与 DBX 主仓库贡献](/cn/docs/contributing)
+- [`t8y2/dbx` 插件平台源码](https://github.com/t8y2/dbx/tree/main/plugins)
+- [`t8y2/dbx-store` 官方商店仓库](https://github.com/t8y2/dbx-store)
diff --git a/docs/content/docs/plugin-development.mdx b/docs/content/docs/plugin-development.mdx
new file mode 100644
index 0000000000..1056d42243
--- /dev/null
+++ b/docs/content/docs/plugin-development.mdx
@@ -0,0 +1,204 @@
+---
+title: Develop and Submit DBX Plugins
+description: Create DBX plugins, build unsigned candidates, and identify the correct repository for source, framework, and official Marketplace pull requests.
+---
+
+DBX plugins are independently installed `.dbxp` packages that can contribute connection types, workbenches, filesystems, and native sidecars. Plugin source, the DBX plugin platform, and the official Marketplace catalog are owned by different repositories.
+
+<Callout type="warn">
+ **Marketplace listing pull requests go to [`t8y2/dbx-store`](https://github.com/t8y2/dbx-store), not `t8y2/dbx`.** A plugin's feature code normally remains in its author's source repository. Open a PR against [`t8y2/dbx`](https://github.com/t8y2/dbx) only when changing the DBX host, SDK, CLI, protocol, schemas, documentation, or official examples.
+</Callout>
+
+## Which Repository Receives the Change
+
+| Change | Destination | Official DBX PR? |
+| --- | --- | --- |
+| Your plugin frontend, Rust/Go backend, tests, and release scripts | The plugin's source repository | Do not submit it to `dbx`; develop and release it in its own repository |
+| A new Marketplace listing, version update, icon, or description | [`t8y2/dbx-store`](https://github.com/t8y2/dbx-store) | Yes, target `main` |
+| DBX plugin host, Manifest/Marketplace schemas, SDK, CLI, or packager | [`t8y2/dbx`](https://github.com/t8y2/dbx) | Yes, target `main` |
+| Official examples or plugin-development documentation | [`t8y2/dbx`](https://github.com/t8y2/dbx) | Yes |
+| A bug in a specific third-party plugin | That plugin's source repository | Do not submit it to `dbx-store` |
+| A custom or enterprise private repository | Your private repository | No official Marketplace submission is required |
+| A vendor JDBC driver JAR | Do not commit it to either repository | Users import it locally or on the server |
+
+DBX-maintained plugins that need an independent release cadence should normally use separate source repositories as well. Only tightly coupled host examples, SDK verification projects, or components explicitly accepted by maintainers belong in `t8y2/dbx`.
+
+## Plugin Project Layout
+
+```text
+my-plugin/
+├── manifest.json
+├── dbx-plugin.toml
+├── assets/
+├── ui/
+├── backend/ # absent from the frontend template
+├── .github/workflows/
+│ └── plugin-release.yml
+└── dist/ # generated; do not commit
+```
+
+- `manifest.json` declares identity, version, permissions, entrypoints, and contributions.
+- `ui/` runs in a sandboxed workbench and talks to DBX through Host APIs.
+- `backend/` is an optional native sidecar. Rust and Go SDKs are provided, while other languages may implement the DBX JSON-RPC protocol directly.
+- `.dbxp` is an installable artifact, not the source repository.
+- Frontend-only plugins can publish one `universal` package. Native sidecars require packages for each operating-system and CPU target.
+
+## Workbench Context Contract
+
+Workbench context is a JSON data snapshot across the DBX/plugin boundary. The host recursively removes Vue reactivity and sends an independent copy, so plugins must not expect Vue refs, proxies, DOM nodes, functions, component instances, or credentials.
+
+Context may contain `null`, booleans, finite numbers, strings, arrays, and plain objects. Undefined object properties are omitted and undefined array entries become `null`. Dates, Maps, Sets, symbols, bigints, non-finite numbers, circular references, and custom class instances are rejected with an error. The UTF-8 encoded context is limited to 2 MiB.
+
+Connection provider fields using `binding: "config"` are persisted in `external_config`; fields using `binding: "secret"` are persisted in the Secret Store. Plugin connection configuration keeps `external_config` through create, edit, save, and reconnect flows.
+
+## Create a Plugin
+
+Install the precompiled CLI without Rust or a DBX source checkout:
+
+```bash
+npm install --global @dbx-app/plugin-cli
+dbx-plugin --help
+```
+
+Or run it directly through `npx`:
+
+```bash
+npx @dbx-app/plugin-cli create my-ui-plugin --template frontend
+```
+
+The npm package selects the precompiled binary for the current platform and bundles the matching Rust and Go plugin SDK sources. Frontend-only plugins do not need Rust or Go; native toolchains are required only to compile the plugin's own sidecar.
+
+Create a project:
+
+```bash
+# Frontend only and cross-platform
+dbx-plugin create my-ui-plugin --template frontend
+
+# Rust sidecar plus frontend
+dbx-plugin create my-rust-plugin --template rust
+
+# Go sidecar plus frontend
+dbx-plugin create my-go-plugin --template go
+```
+
+Develop, test, and version the generated project in the plugin's own source repository. Do not copy an ordinary plugin source tree into `t8y2/dbx` merely to publish it.
+
+## Build Review Candidates
+
+From the plugin project root, run:
+
+```bash
+dbx-plugin package .
+```
+
+The command produces **unsigned review candidates** only:
+
+```text
+dist/<plugin-id>-<version>-<target>.dbxp
+dist/<plugin-id>-<version>-<target>.artifact.json
+```
+
+Official plugin authors do not create or possess the DBX Store private key. The generated GitHub Release workflow builds candidates for each target and merges their metadata into `release-candidates.json`.
+
+To install an unsigned package during local development, explicitly enable **Allow unsigned development packages** in Plugin Center. This option never relaxes official Marketplace verification.
+
+## Complete Official Marketplace Flow
+
+### Step 1: Publish Source and a Candidate Release
+
+Create a version tag and GitHub Release in the plugin's source repository. The Release should contain:
+
+- one unsigned `.dbxp` candidate for each supported target;
+- the corresponding `.artifact.json` files;
+- merged `release-candidates.json`;
+- release notes and the matching source tag.
+
+Candidate packages may live in GitHub Releases, a CDN, or object storage. Do not commit `.dbxp` binaries to Git history.
+
+### Step 2: Open a Review Issue in dbx-store
+
+Open [`t8y2/dbx-store` Issues](https://github.com/t8y2/dbx-store/issues/new/choose), choose **Plugin submission**, and provide:
+
+- plugin ID, version, and publisher;
+- source repository and exact tag;
+- the HTTPS URL of `release-candidates.json`;
+- permissions, data access, network access, and native-sidecar behavior;
+- license, privacy policy, and support links.
+
+The Issue is the pre-signing review entrypoint. Do not submit the plugin source to `t8y2/dbx`, and do not invent an official `signingKeyId` yourself.
+
+### Step 3: DBX Store Reviews and Signs
+
+Maintainers review the source, Manifest, permissions, candidate SHA-256 values, sizes, and native behavior. After approval, the protected DBX Store workflow:
+
+1. downloads the candidate using its reviewed SHA-256 and size;
+2. confirms that it is unsigned and matches the expected plugin ID and version;
+3. adds an Ed25519 signature using the DBX Store repository key;
+4. publishes the final `.dbxp`, final artifact metadata, and signing receipt.
+
+Plugin authors never receive the official repository private key.
+
+### Step 4: Open the Listing PR Against dbx-store
+
+After receiving final signed artifact metadata, fork [`t8y2/dbx-store`](https://github.com/t8y2/dbx-store) and add or update:
+
+```text
+publishers/<publisher-id>.json # only for a publisher's first submission
+plugins/<plugin-id>.json
+catalog/index.json # generated by validation
+```
+
+Run:
+
+```bash
+node scripts/validate.mjs
+```
+
+Then open the pull request with:
+
+```text
+Base repository: t8y2/dbx-store
+Base branch: main
+```
+
+<Callout type="info">
+ A new plugin's final listing PR goes **only to `t8y2/dbx-store`**. A `t8y2/dbx` PR is for changes to the plugin platform itself, not for registering ordinary third-party plugin versions.
+</Callout>
+
+Do not include the following in a listing PR:
+
+- `.dbxp` binaries;
+- a copied plugin source tree;
+- Ed25519 private keys, tokens, or download credentials;
+- unsigned candidate URLs as final install artifacts;
+- a self-assigned `verified: true` value.
+
+## Update an Existing Plugin
+
+Every update uses a new semantic version. Existing Release assets cannot be replaced:
+
+1. Publish a new source tag and candidate Release in the plugin source repository.
+2. Open a new Plugin submission Issue in `t8y2/dbx-store` and reference the existing plugin and new version.
+3. Wait for the new candidates to complete review and repository signing.
+4. Open a PR against `t8y2/dbx-store` that updates `plugins/<plugin-id>.json`.
+
+Fix plugin-code problems in the plugin source repository. Only catalog metadata, review status, final URLs, hashes, sizes, and Marketplace copy belong in `dbx-store`.
+
+## Signatures and Publisher Identity
+
+DBX currently uses one repository signature:
+
+- `publisher` records authorship and Marketplace ownership;
+- `signingKeyId` identifies the repository key that published the final installable package;
+- DBX Store reviews and signs official plugins centrally;
+- custom and private repository operators manage their own repository keys;
+- developer signatures and dual signatures are not current listing requirements.
+
+Human review determines whether a plugin may appear in the Marketplace. Ed25519 repository signing ensures that the reviewed package was not replaced afterward. A signature does not replace source review and is not an operating-system sandbox for native sidecars.
+
+## Related Documentation
+
+- [JDBC Plugin and Database Drivers](/en/docs/plugins)
+- [Contribute to the DBX Core Repository](/en/docs/contributing)
+- [`t8y2/dbx` plugin platform source](https://github.com/t8y2/dbx/tree/main/plugins)
+- [`t8y2/dbx-store` official Marketplace repository](https://github.com/t8y2/dbx-store)
diff --git a/docs/content/docs/plugins.cn.mdx b/docs/content/docs/plugins.cn.mdx
index ec030740fc..90762db3ef 100644
--- a/docs/content/docs/plugins.cn.mdx
+++ b/docs/content/docs/plugins.cn.mdx
@@ -5,6 +5,8 @@ description: 安装 DBX JDBC 插件、导入数据库厂商驱动 JAR,并创
DBX 默认使用 Rust 原生数据库驱动。JDBC 是可选能力:当你需要连接 DBX 暂未内置支持的数据库,或希望使用数据库厂商提供的 JDBC 驱动时,可以安装 JDBC 插件。
+<Callout type="info">本页介绍的是 JDBC 插件和厂商 Driver JAR。若你要开发 SSH、SFTP、文件管理器或其他 DBX 扩展,并提交官方插件商店,请阅读[开发和提交 DBX 插件](/cn/docs/plugin-development)。</Callout>
+
<Callout type="info">JDBC 插件不会打包进 DBX 主应用,也不包含任何数据库厂商的 JDBC 驱动。你需要先安装 DBX JDBC 插件,再导入对应数据库的 JDBC driver JAR。</Callout>
<Callout type="warn">“JDBC 能连接”不等于拥有原生 DBX profile 的全部能力。表树、对象源码、结构编辑、导入、传输和管理视图取决于 JDBC 元数据、识别出的实际数据库类型和驱动能力清单;未知数据库会按通用 JDBC 能力运行。</Callout>
diff --git a/docs/content/docs/plugins.mdx b/docs/content/docs/plugins.mdx
index 56d54a9f72..175501de03 100644
--- a/docs/content/docs/plugins.mdx
+++ b/docs/content/docs/plugins.mdx
@@ -5,6 +5,8 @@ description: Install the DBX JDBC plugin, import vendor JDBC driver JARs, and cr
DBX uses native Rust database drivers by default. JDBC is optional: install the JDBC plugin when you need to connect to a database that DBX does not support natively, or when you specifically need a vendor JDBC driver.
+<Callout type="info">This page covers the JDBC plugin and vendor driver JARs. To build SSH, SFTP, file-manager, or other DBX extensions and submit them to the official Marketplace, read [Develop and Submit DBX Plugins](/en/docs/plugin-development).</Callout>
+
<Callout type="info">The JDBC plugin is not bundled with the main DBX app, and it does not include vendor JDBC drivers. Install the DBX JDBC plugin first, then import the database vendor's JDBC driver JAR.</Callout>
<Callout type="warn">A successful JDBC connection does not imply every capability of a native DBX profile. Object trees, source definitions, structure editing, import, transfer, and admin views depend on JDBC metadata, the detected effective database type, and the driver capability manifest. Unknown engines run with generic JDBC capabilities.</Callout>
diff --git a/package.json b/package.json
index 839a91a6ac..713bad847c 100644
--- a/package.json
+++ b/package.json
@@ -10,10 +10,11 @@
"dev:web": "vite --config apps/desktop/vite.config.ts --port 5173 --mode web",
"dev:backend": "node scripts/dev-backend.mjs",
"dev:full:win": ".\\scripts\\dev-full.bat",
- "build:packages": "pnpm --filter @dbx-app/cli build && pnpm --filter @dbx-app/mcp-server build",
- "test:packages": "pnpm --filter @dbx-app/cli test && pnpm --filter @dbx-app/mcp-server test",
- "pack:packages": "rm -rf /tmp/dbx-pack-check && mkdir -p /tmp/dbx-pack-check && pnpm --filter @dbx-app/cli pack --pack-destination /tmp/dbx-pack-check && pnpm --filter @dbx-app/mcp-server pack --pack-destination /tmp/dbx-pack-check",
+ "build:packages": "pnpm --filter @dbx-app/cli build && pnpm --filter @dbx-app/mcp-server build && pnpm --filter @dbx-app/plugin-cli build",
+ "test:packages": "pnpm --filter @dbx-app/cli test && pnpm --filter @dbx-app/mcp-server test && pnpm --filter @dbx-app/plugin-cli test",
+ "pack:packages": "rm -rf /tmp/dbx-pack-check && mkdir -p /tmp/dbx-pack-check && pnpm --filter @dbx-app/cli pack --pack-destination /tmp/dbx-pack-check && pnpm --filter @dbx-app/mcp-server pack --pack-destination /tmp/dbx-pack-check && pnpm --filter @dbx-app/plugin-cli pack --pack-destination /tmp/dbx-pack-check",
"verify:package-install": "node scripts/verify-package-install.mjs /tmp/dbx-pack-check",
+ "verify:plugin-cli-package": "node scripts/verify-plugin-cli-package.mjs",
"test:cli:migration": "node scripts/verify-cli-migration.mjs",
"benchmark:cli": "node scripts/benchmark-cli.mjs",
"publish:dry-run": "pnpm build:packages && pnpm pack:packages && pnpm verify:package-install",
diff --git a/packages/app-tests/queryResultToolbar.test.ts b/packages/app-tests/queryResultToolbar.test.ts
index 9959a485cf..027b431625 100644
--- a/packages/app-tests/queryResultToolbar.test.ts
+++ b/packages/app-tests/queryResultToolbar.test.ts
@@ -52,7 +52,7 @@ test("query result toolbar reuses the production icon contract", () => {
assert.match(contentArea, /<Wrench class="h-4 w-4"/);
assert.match(contentArea, /<ChevronDown class="h-3\.5 w-3\.5"/);
assert.match(viewSwitcher, /import \{ BarChart3, ListChecks, MessageSquareText \} from "@lucide\/vue"/);
- assert.match(toolbarActions, /import \{ GitBranch, Gauge, Loader2, Upload \} from "@lucide\/vue"/);
+ assert.match(toolbarActions, /import \{ GitBranch, Gauge, Loader2, PlugZap, Upload \} from "@lucide\/vue"/);
assert.match(editorToolbar, /@click="emit\('importResultArchive'\)"[\s\S]{0,100}<Download/);
assert.match(toolbarActions, /@click="emit\('exportArchive'\)"[\s\S]{0,200}<Upload v-else/);
assert.match(dataGrid, /return \{ label: t\("grid\.export"\), icon: Upload, children: items \};/);
@@ -112,12 +112,12 @@ test("appending a result run preserves the tab-strip scroll position", () => {
test("the close-tab shortcut clears query results before closing the tab", () => {
const app = source(appPath);
- const closeShortcutStart = app.indexOf("if (isCloseTabShortcut(e, shortcuts))");
- const closeShortcutEnd = app.indexOf("if (isSaveShortcut", closeShortcutStart);
- const closeShortcut = app.slice(closeShortcutStart, closeShortcutEnd);
+ const closeSurfaceStart = app.indexOf("async function closeActiveSurface()");
+ const closeSurfaceEnd = app.indexOf("function activateMainContentSurface", closeSurfaceStart);
+ const closeSurface = app.slice(closeSurfaceStart, closeSurfaceEnd);
- assert.ok(closeShortcutStart >= 0);
- assert.ok(closeShortcut.indexOf("await queryStore.clearQueryResults(queryStore.activeTabId)") < closeShortcut.indexOf("queryStore.closeTab(queryStore.activeTabId)"));
+ assert.ok(closeSurfaceStart >= 0);
+ assert.ok(closeSurface.indexOf("await queryStore.clearQueryResults(queryStore.activeTabId)") < closeSurface.indexOf("queryStore.closeTab(queryStore.activeTabId)"));
});
test("the configurable results pane shortcut only toggles existing output", () => {
diff --git a/packages/plugin-cli-darwin-arm64/package.json b/packages/plugin-cli-darwin-arm64/package.json
new file mode 100644
index 0000000000..34a3ff5cc0
--- /dev/null
+++ b/packages/plugin-cli-darwin-arm64/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "@dbx-app/plugin-cli-darwin-arm64",
+ "version": "0.1.1",
+ "description": "Precompiled DBX Plugin CLI binary for darwin arm64",
+ "license": "Apache-2.0",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/t8y2/dbx",
+ "directory": "packages/plugin-cli-darwin-arm64"
+ },
+ "os": ["darwin"],
+ "cpu": ["arm64"],
+ "bin": {
+ "dbx-plugin-native": "bin/dbx-plugin"
+ },
+ "files": ["bin"]
+}
diff --git a/packages/plugin-cli-darwin-x64/package.json b/packages/plugin-cli-darwin-x64/package.json
new file mode 100644
index 0000000000..7daf28262b
--- /dev/null
+++ b/packages/plugin-cli-darwin-x64/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "@dbx-app/plugin-cli-darwin-x64",
+ "version": "0.1.1",
+ "description": "Precompiled DBX Plugin CLI binary for darwin x64",
+ "license": "Apache-2.0",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/t8y2/dbx",
+ "directory": "packages/plugin-cli-darwin-x64"
+ },
+ "os": ["darwin"],
+ "cpu": ["x64"],
+ "bin": {
+ "dbx-plugin-native": "bin/dbx-plugin"
+ },
+ "files": ["bin"]
+}
diff --git a/packages/plugin-cli-linux-arm64-gnu/package.json b/packages/plugin-cli-linux-arm64-gnu/package.json
new file mode 100644
index 0000000000..be6220c699
--- /dev/null
+++ b/packages/plugin-cli-linux-arm64-gnu/package.json
@@ -0,0 +1,18 @@
+{
+ "name": "@dbx-app/plugin-cli-linux-arm64-gnu",
+ "version": "0.1.1",
+ "description": "Precompiled DBX Plugin CLI binary for linux arm64",
+ "license": "Apache-2.0",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/t8y2/dbx",
+ "directory": "packages/plugin-cli-linux-arm64-gnu"
+ },
+ "os": ["linux"],
+ "cpu": ["arm64"],
+ "libc": ["glibc"],
+ "bin": {
+ "dbx-plugin-native": "bin/dbx-plugin"
+ },
+ "files": ["bin"]
+}
diff --git a/packages/plugin-cli-linux-x64-gnu/package.json b/packages/plugin-cli-linux-x64-gnu/package.json
new file mode 100644
index 0000000000..3fe4702f34
--- /dev/null
+++ b/packages/plugin-cli-linux-x64-gnu/package.json
@@ -0,0 +1,18 @@
+{
+ "name": "@dbx-app/plugin-cli-linux-x64-gnu",
+ "version": "0.1.1",
+ "description": "Precompiled DBX Plugin CLI binary for linux x64",
+ "license": "Apache-2.0",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/t8y2/dbx",
+ "directory": "packages/plugin-cli-linux-x64-gnu"
+ },
+ "os": ["linux"],
+ "cpu": ["x64"],
+ "libc": ["glibc"],
+ "bin": {
+ "dbx-plugin-native": "bin/dbx-plugin"
+ },
+ "files": ["bin"]
+}
diff --git a/packages/plugin-cli-win32-arm64/package.json b/packages/plugin-cli-win32-arm64/package.json
new file mode 100644
index 0000000000..96c686bdb4
--- /dev/null
+++ b/packages/plugin-cli-win32-arm64/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "@dbx-app/plugin-cli-win32-arm64",
+ "version": "0.1.1",
+ "description": "Precompiled DBX Plugin CLI binary for win32 arm64",
+ "license": "Apache-2.0",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/t8y2/dbx",
+ "directory": "packages/plugin-cli-win32-arm64"
+ },
+ "os": ["win32"],
+ "cpu": ["arm64"],
+ "bin": {
+ "dbx-plugin-native": "bin/dbx-plugin.exe"
+ },
+ "files": ["bin"]
+}
diff --git a/packages/plugin-cli-win32-x64/package.json b/packages/plugin-cli-win32-x64/package.json
new file mode 100644
index 0000000000..8e31f66309
--- /dev/null
+++ b/packages/plugin-cli-win32-x64/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "@dbx-app/plugin-cli-win32-x64",
+ "version": "0.1.1",
+ "description": "Precompiled DBX Plugin CLI binary for win32 x64",
+ "license": "Apache-2.0",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/t8y2/dbx",
+ "directory": "packages/plugin-cli-win32-x64"
+ },
+ "os": ["win32"],
+ "cpu": ["x64"],
+ "bin": {
+ "dbx-plugin-native": "bin/dbx-plugin.exe"
+ },
+ "files": ["bin"]
+}
diff --git a/packages/plugin-cli/.gitignore b/packages/plugin-cli/.gitignore
new file mode 100644
index 0000000000..c7f2419540
--- /dev/null
+++ b/packages/plugin-cli/.gitignore
@@ -0,0 +1,2 @@
+/dev-runtime/
+/sdk-root/
diff --git a/packages/plugin-cli/README.md b/packages/plugin-cli/README.md
new file mode 100644
index 0000000000..72ac0399a0
--- /dev/null
+++ b/packages/plugin-cli/README.md
@@ -0,0 +1,46 @@
+# @dbx-app/plugin-cli
+
+Precompiled `dbx-plugin` CLI for creating and packaging DBX plugins. Installing this package does not compile the CLI and does not require a DBX source checkout.
+
+```bash
+npm install --global @dbx-app/plugin-cli
+dbx-plugin create my-plugin
+```
+
+Or run it without a global installation:
+
+```bash
+npx @dbx-app/plugin-cli create my-plugin
+```
+
+The package selects a precompiled binary for macOS, Linux, or Windows and bundles the matching Rust and Go DBX plugin SDK sources. Frontend-only plugins, including the Svelte template, require only Node.js. Rust and Go are needed only when the plugin itself has a Rust or Go backend.
+
+```bash
+dbx-plugin create my-plugin --template frontend
+dbx-plugin create my-svelte-plugin --template svelte
+dbx-plugin create my-rust-plugin --template rust
+dbx-plugin create my-go-plugin --template go
+dbx-plugin package my-plugin
+dbx-plugin dev --path my-plugin --port 5190
+```
+
+The `dev` subcommand requires Node.js 22+ and runs the bundled browser development runtime, without DBX or source-tree dependencies. It supports frontend-only workbenches and Rust/Go backends, with JSONL or framed transport. Optional `[dev]` `ui_build` and `ui_watch` command arrays configure project builds. Development credentials are stored locally as plaintext under `.dbx-dev/` (or `--data-dir`). Other commands retain their existing Node requirements.
+
+## 中文说明
+
+`@dbx-app/plugin-cli` 提供预编译的 `dbx-plugin` 命令。安装时不会编译 CLI,也不需要克隆 DBX 源码仓库。
+
+```bash
+npm install -g @dbx-app/plugin-cli
+dbx-plugin create my-plugin
+```
+
+也可以直接使用:
+
+```bash
+npx @dbx-app/plugin-cli create my-plugin
+```
+
+npm 主包会自动选择当前操作系统对应的预编译二进制,并携带匹配版本的 Rust 和 Go 插件 SDK。纯前端插件只需要 Node.js;只有插件自身包含 Rust 或 Go 后端时才需要对应语言的编译环境。
+
+使用 `dbx-plugin dev --path my-plugin --port 5190` 可在浏览器运行通用插件开发环境,无需启动 DBX。仅 `dev` 要求 Node.js 22+;运行时及外壳已包含在 npm 包中。开发配置和凭据以明文保存在 `.dbx-dev/`,不要提交或打包该目录。
diff --git a/packages/plugin-cli/bin/dbx-plugin.js b/packages/plugin-cli/bin/dbx-plugin.js
new file mode 100644
index 0000000000..09ea2101b5
--- /dev/null
+++ b/packages/plugin-cli/bin/dbx-plugin.js
@@ -0,0 +1,91 @@
+#!/usr/bin/env node
+
+import { spawnSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import { createRequire } from "node:module";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const require = createRequire(import.meta.url);
+const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+const platformPackages = {
+ "darwin-arm64": ["@dbx-app/plugin-cli-darwin-arm64", "dbx-plugin"],
+ "darwin-x64": ["@dbx-app/plugin-cli-darwin-x64", "dbx-plugin"],
+ "linux-arm64": ["@dbx-app/plugin-cli-linux-arm64-gnu", "dbx-plugin"],
+ "linux-x64": ["@dbx-app/plugin-cli-linux-x64-gnu", "dbx-plugin"],
+ "win32-arm64": ["@dbx-app/plugin-cli-win32-arm64", "dbx-plugin.exe"],
+ "win32-x64": ["@dbx-app/plugin-cli-win32-x64", "dbx-plugin.exe"],
+};
+
+function platformTarget() {
+ const platform = `${process.platform}-${process.arch}`;
+ const target = platformPackages[platform];
+ if (!target) {
+ throw new Error(`DBX Plugin CLI does not provide a binary for ${platform}.`);
+ }
+ return target;
+}
+
+function resolveBinary() {
+ if (process.env.DBX_PLUGIN_CLI_BINARY) {
+ if (!existsSync(process.env.DBX_PLUGIN_CLI_BINARY)) {
+ throw new Error(`DBX_PLUGIN_CLI_BINARY does not exist: ${process.env.DBX_PLUGIN_CLI_BINARY}`);
+ }
+ return process.env.DBX_PLUGIN_CLI_BINARY;
+ }
+
+ const [packageName, binaryName] = platformTarget();
+ let manifest;
+ try {
+ manifest = require.resolve(`${packageName}/package.json`);
+ } catch {
+ throw new Error(
+ `The optional package ${packageName} was not installed. Reinstall @dbx-app/plugin-cli without --no-optional.`,
+ );
+ }
+
+ const binary = join(dirname(manifest), "bin", binaryName);
+ if (!existsSync(binary)) {
+ throw new Error(`The DBX Plugin CLI binary is missing from ${packageName}.`);
+ }
+ return binary;
+}
+
+function bundledSdkRoot() {
+ const sdkRoot = join(packageRoot, "sdk-root");
+ const rustManifest = join(sdkRoot, "plugins", "sdk", "rust", "dbx-plugin-sdk", "Cargo.toml");
+ const goManifest = join(sdkRoot, "plugins", "sdk", "go", "dbx-plugin-sdk", "go.mod");
+ return existsSync(rustManifest) && existsSync(goManifest) ? sdkRoot : undefined;
+}
+
+try {
+ if (process.argv[2] === "--verify-platform") {
+ platformTarget();
+ process.exit(0);
+ }
+
+ const binary = resolveBinary();
+ const env = { ...process.env };
+ delete env.DBX_PLUGIN_CLI_BINARY;
+ if (process.argv[2] === "dev") {
+ if (Number(process.versions.node.split(".")[0]) < 22) throw new Error("dbx-plugin dev requires Node.js 22+.");
+ env.DBX_PLUGIN_NODE = env.DBX_PLUGIN_NODE || process.execPath;
+ env.DBX_PLUGIN_DEV_RUNTIME = env.DBX_PLUGIN_DEV_RUNTIME || join(packageRoot, "dev-runtime", "runtime.mjs");
+ }
+ if (!env.DBX_PLUGIN_SDK_ROOT) {
+ const sdkRoot = bundledSdkRoot();
+ if (sdkRoot) env.DBX_PLUGIN_SDK_ROOT = sdkRoot;
+ }
+
+ const result = spawnSync(binary, process.argv.slice(2), { stdio: "inherit", env });
+ if (result.error) {
+ throw result.error;
+ }
+ if (result.signal) {
+ process.kill(process.pid, result.signal);
+ }
+ process.exit(result.status ?? 1);
+} catch (error) {
+ console.error(error instanceof Error ? error.message : String(error));
+ process.exit(1);
+}
diff --git a/packages/plugin-cli/package.json b/packages/plugin-cli/package.json
new file mode 100644
index 0000000000..5ee5ca107b
--- /dev/null
+++ b/packages/plugin-cli/package.json
@@ -0,0 +1,47 @@
+{
+ "name": "@dbx-app/plugin-cli",
+ "version": "0.1.1",
+ "description": "Create and package DBX plugins without compiling the DBX plugin CLI",
+ "keywords": [
+ "cli",
+ "database",
+ "dbx",
+ "plugin",
+ "plugin-development"
+ ],
+ "homepage": "https://github.com/t8y2/dbx/tree/main/plugins",
+ "license": "Apache-2.0",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/t8y2/dbx",
+ "directory": "packages/plugin-cli"
+ },
+ "bin": {
+ "dbx-plugin": "bin/dbx-plugin.js"
+ },
+ "files": [
+ "bin",
+ "README.md",
+ "sdk-root",
+ "dev-runtime"
+ ],
+ "type": "module",
+ "scripts": {
+ "build": "node --check bin/dbx-plugin.js && node --check scripts/stage-sdk.mjs",
+ "test": "node --test tests/*.test.mjs",
+ "prepack": "node scripts/stage-sdk.mjs && node scripts/stage-dev.mjs",
+ "postpack": "node scripts/stage-sdk.mjs --clean && node scripts/stage-dev.mjs --clean",
+ "prepublishOnly": "npm run build && npm test"
+ },
+ "optionalDependencies": {
+ "@dbx-app/plugin-cli-darwin-arm64": "0.1.1",
+ "@dbx-app/plugin-cli-darwin-x64": "0.1.1",
+ "@dbx-app/plugin-cli-linux-arm64-gnu": "0.1.1",
+ "@dbx-app/plugin-cli-linux-x64-gnu": "0.1.1",
+ "@dbx-app/plugin-cli-win32-arm64": "0.1.1",
+ "@dbx-app/plugin-cli-win32-x64": "0.1.1"
+ },
+ "engines": {
+ "node": ">=18.18.0"
+ }
+}
diff --git a/packages/plugin-cli/scripts/stage-dev.mjs b/packages/plugin-cli/scripts/stage-dev.mjs
new file mode 100644
index 0000000000..120936d84e
--- /dev/null
+++ b/packages/plugin-cli/scripts/stage-dev.mjs
@@ -0,0 +1,17 @@
+import { cpSync, existsSync, rmSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { spawnSync } from 'node:child_process';
+const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const root = resolve(packageRoot, '../../plugins/sdk/dev-host');
+const destination = resolve(packageRoot, 'dev-runtime');
+if (process.argv.includes('--clean')) {
+ rmSync(destination, { recursive: true, force: true });
+} else {
+ if (Number(process.versions.node.split('.')[0]) < 22) throw new Error('Building dev runtime requires Node.js 22+');
+ if (!existsSync(resolve(root, 'node_modules/vite'))) throw new Error('Run npm ci --prefix plugins/sdk/dev-host before packing the CLI');
+ const result = spawnSync(process.execPath, [resolve(root, 'build.mjs')], { stdio: 'inherit' });
+ if (result.status !== 0) throw new Error('Development runtime build failed');
+ rmSync(destination, { recursive: true, force: true });
+ cpSync(resolve(root, 'dist'), destination, { recursive: true });
+}
diff --git a/packages/plugin-cli/scripts/stage-sdk.mjs b/packages/plugin-cli/scripts/stage-sdk.mjs
new file mode 100644
index 0000000000..a0c7c2dfe4
--- /dev/null
+++ b/packages/plugin-cli/scripts/stage-sdk.mjs
@@ -0,0 +1,49 @@
+import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { dirname, join, relative, resolve, sep } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+const repositoryRoot = resolve(packageRoot, "../..");
+const destinationRoot = join(packageRoot, "sdk-root");
+
+if (process.argv.includes("--clean")) {
+ rmSync(destinationRoot, { recursive: true, force: true });
+ process.exit(0);
+}
+
+const packageManifest = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
+const cliManifest = readFileSync(join(repositoryRoot, "plugins/sdk/cli/Cargo.toml"), "utf8");
+const cliVersion = cliManifest.match(/^version\s*=\s*"([^"]+)"/m)?.[1];
+if (cliVersion !== packageManifest.version) {
+ throw new Error(
+ `@dbx-app/plugin-cli version ${packageManifest.version} does not match dbx-plugin-cli ${cliVersion ?? "unknown"}.`,
+ );
+}
+
+const sources = [
+ ["plugins/sdk/rust/dbx-plugin-sdk", "plugins/sdk/rust/dbx-plugin-sdk"],
+ ["plugins/sdk/go/dbx-plugin-sdk", "plugins/sdk/go/dbx-plugin-sdk"],
+];
+const excludedNames = new Set([".DS_Store", ".gitignore", "Cargo.lock", "target"]);
+
+rmSync(destinationRoot, { recursive: true, force: true });
+for (const [sourceRelative, destinationRelative] of sources) {
+ const source = join(repositoryRoot, sourceRelative);
+ if (!existsSync(source)) {
+ throw new Error(`Plugin SDK source is missing: ${source}`);
+ }
+ const destination = join(destinationRoot, destinationRelative);
+ mkdirSync(dirname(destination), { recursive: true });
+ cpSync(source, destination, {
+ recursive: true,
+ filter(path) {
+ const relativePath = relative(source, path);
+ return !relativePath.split(sep).some((part) => excludedNames.has(part));
+ },
+ });
+}
+
+writeFileSync(
+ join(destinationRoot, "README.md"),
+ "# Bundled DBX Plugin SDK\n\nThis directory is bundled for `dbx-plugin package` and is managed by `@dbx-app/plugin-cli`.\n",
+);
diff --git a/packages/plugin-cli/tests/dev-launcher.test.mjs b/packages/plugin-cli/tests/dev-launcher.test.mjs
new file mode 100644
index 0000000000..0b082bc2a4
--- /dev/null
+++ b/packages/plugin-cli/tests/dev-launcher.test.mjs
@@ -0,0 +1,21 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, resolve, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+test('dev selects the bundled runtime and current Node without changing ordinary launcher behavior', () => {
+ const cwd = mkdtempSync(join(tmpdir(), 'dbx-dev-launcher-'));
+ try {
+ writeFileSync(join(cwd, 'dev'), 'console.log(JSON.stringify({runtime:process.env.DBX_PLUGIN_DEV_RUNTIME,node:process.env.DBX_PLUGIN_NODE,args:process.argv.slice(2)}))');
+ const invoke = extra => spawnSync(process.execPath, [join(root, 'bin/dbx-plugin.js'), 'dev', '--port', '5190'], {
+ cwd, encoding: 'utf8', env: { ...process.env, DBX_PLUGIN_CLI_BINARY: process.execPath, DBX_PLUGIN_NODE: '', DBX_PLUGIN_DEV_RUNTIME: '', ...extra },
+ });
+ const result = invoke({}); assert.equal(result.status, 0, result.stderr);
+ const data = JSON.parse(result.stdout); assert.equal(data.runtime, join(root, 'dev-runtime/runtime.mjs')); assert.equal(data.node, process.execPath); assert.deepEqual(data.args, ['--port','5190']);
+ const explicit = invoke({ DBX_PLUGIN_DEV_RUNTIME: '/custom/runtime.mjs', DBX_PLUGIN_NODE: '/custom/node' });
+ assert.equal(JSON.parse(explicit.stdout).runtime, '/custom/runtime.mjs');
+ } finally { rmSync(cwd, { recursive: true, force: true }); }
+});
diff --git a/packages/plugin-cli/tests/launcher.test.mjs b/packages/plugin-cli/tests/launcher.test.mjs
new file mode 100644
index 0000000000..3edf722547
--- /dev/null
+++ b/packages/plugin-cli/tests/launcher.test.mjs
@@ -0,0 +1,63 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { existsSync, rmSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+
+const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+const launcher = join(packageRoot, "bin", "dbx-plugin.js");
+const stageSdk = join(packageRoot, "scripts", "stage-sdk.mjs");
+const sdkRoot = join(packageRoot, "sdk-root");
+
+test("forwards arguments and provides the bundled SDK root", () => {
+ const stage = spawnSync(process.execPath, [stageSdk], { encoding: "utf8" });
+ assert.equal(stage.status, 0, stage.stderr);
+ try {
+ const result = spawnSync(
+ process.execPath,
+ [launcher, "-e", "process.stdout.write(process.env.DBX_PLUGIN_SDK_ROOT || '')"],
+ {
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ DBX_PLUGIN_CLI_BINARY: process.execPath,
+ DBX_PLUGIN_SDK_ROOT: "",
+ },
+ },
+ );
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout, sdkRoot);
+ assert.ok(existsSync(join(sdkRoot, "plugins", "sdk", "rust", "dbx-plugin-sdk", "Cargo.toml")));
+ assert.ok(existsSync(join(sdkRoot, "plugins", "sdk", "go", "dbx-plugin-sdk", "go.mod")));
+ } finally {
+ rmSync(sdkRoot, { recursive: true, force: true });
+ }
+});
+
+test("preserves an explicit SDK root", () => {
+ const result = spawnSync(
+ process.execPath,
+ [launcher, "-e", "process.stdout.write(process.env.DBX_PLUGIN_SDK_ROOT || '')"],
+ {
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ DBX_PLUGIN_CLI_BINARY: process.execPath,
+ DBX_PLUGIN_SDK_ROOT: "/custom/dbx-plugin-sdk",
+ },
+ },
+ );
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout, "/custom/dbx-plugin-sdk");
+});
+
+test("rejects a missing binary override", () => {
+ const missing = join(packageRoot, "missing-dbx-plugin-binary");
+ const result = spawnSync(process.execPath, [launcher, "--version"], {
+ encoding: "utf8",
+ env: { ...process.env, DBX_PLUGIN_CLI_BINARY: missing },
+ });
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /DBX_PLUGIN_CLI_BINARY does not exist/);
+});
diff --git a/plugins/GETTING_STARTED.zh-CN.md b/plugins/GETTING_STARTED.zh-CN.md
new file mode 100644
index 0000000000..f99a6b7e40
--- /dev/null
+++ b/plugins/GETTING_STARTED.zh-CN.md
@@ -0,0 +1,443 @@
+# DBX 插件开发快速开始
+
+本文面向第一次开发 DBX 插件的开发者,覆盖 CLI 安装、项目创建、前后端模板选择、本地打包、签名、DBX 安装测试和发布前准备。
+
+当前插件契约由以下部分组成:
+
+- Manifest v1:描述插件身份、权限、入口和贡献点。
+- Host API 1.x:沙箱前端与 DBX 宿主通信的接口。
+- Sidecar Protocol v1:可选原生后端与 DBX 通信的协议。
+- `.dbxp`:DBX 最终安装的插件包。
+
+插件可以在 `manifest.json` 中声明可选的 `source`(源码仓库)和 `homepage`(项目主页)。这两个字段会随插件包签名并在“已安装”页面本地显示,因此不依赖联网;市场目录可以重复这些字段用于展示未安装插件。
+
+正式文档和仓库提交流程参考 [`docs/content/docs/plugin-development.cn.mdx`](../docs/content/docs/plugin-development.cn.mdx)。完整协议和贡献点参考 [`README.md`](./README.md),底层发布流程参考 [`RELEASING.md`](./RELEASING.md)。
+
+## 先说结论:SDK 不需要“启动”
+
+DBX 插件 SDK 不是一个常驻服务,不需要先启动 SDK Server。
+
+开发时实际使用的是三类工具:
+
+1. `dbx-plugin` CLI:创建项目、构建后端、打包和生成签名密钥。
+2. Rust/Go SDK:仅供需要原生后端的插件链接使用。
+3. DBX Host API:由 DBX 在插件沙箱页面中注入,前端通过 `window.dbxPlugin` 调用。
+
+典型流程如下:
+
+```text
+插件源码
+├── manifest.json
+├── ui/
+└── backend/(可选)
+ │
+ ▼
+dbx-plugin package
+ │
+ ├── *.dbxp
+ └── *.artifact.json
+ │
+ ▼
+DBX 插件中心本地安装,或上传 Release 后进入插件商店
+```
+
+## 1. 安装 CLI
+
+推荐直接安装预编译的 npm 包。安装过程不会编译 CLI,也不需要克隆 DBX 源码:
+
+```bash
+npm install --global @dbx-app/plugin-cli
+dbx-plugin --help
+```
+
+也可以不做全局安装,直接运行:
+
+```bash
+npx @dbx-app/plugin-cli create my-plugin
+```
+
+npm 主包会自动安装 macOS、Linux 或 Windows 当前平台对应的预编译二进制,并携带匹配版本的 Rust/Go 插件 SDK。纯前端插件只需要 Node.js;只有插件自身包含 Rust 或 Go 后端时才需要对应语言的编译环境。
+
+只有开发 CLI 本身或验证尚未发布的 SDK 改动时,才需要从 DBX 源码安装:
+
+```bash
+cd /path/to/dbx
+
+CARGO_TARGET_DIR=/tmp/dbx-plugin-cli-target \
+ cargo install --locked --path plugins/sdk/cli --force
+```
+
+CLI 在交互式终端中默认显示彩色输出。设置 `NO_COLOR=1` 可以关闭颜色。
+
+## 2. 选择插件模板
+
+`dbx-plugin create` 提供四种模板:
+
+| 模板 | 组成 | 产物 | 适用场景 |
+| --- | --- | --- | --- |
+| `frontend` | 沙箱前端,无原生后端 | 一个 `universal.dbxp` | 纯 UI、信息面板、调用 Host API 的轻量工具 |
+| `svelte` | Svelte + Vite 沙箱前端,无原生后端 | 一个 `universal.dbxp` | 使用 Svelte 编写的自定义工作台 |
+| `rust` | 沙箱前端 + Rust Sidecar | 每个平台一个 `.dbxp` | SSH、终端、复杂协议、系统能力、高性能任务 |
+| `go` | 沙箱前端 + Go Sidecar | 每个平台一个 `.dbxp` | 已有 Go 生态、网络服务、协议客户端 |
+
+不需要后端时直接选 `frontend`。不要为了“像完整插件”而强行添加 Sidecar;只有浏览器沙箱无法完成的能力才需要 Rust 或 Go 后端。
+
+## 3. 创建第一个前端插件
+
+运行交互式向导:
+
+```bash
+dbx-plugin create ~/Desktop/dbx-plugin-demo --template frontend
+
+# 使用 Svelte + Vite 工作台模板
+dbx-plugin create ~/Desktop/dbx-plugin-svelte --template svelte
+```
+
+也可以一次性传入全部参数:
+
+```bash
+dbx-plugin create ~/Desktop/dbx-plugin-demo \
+ --template frontend \
+ --id com.example.dbx-plugin-demo \
+ --name "DBX Plugin Demo" \
+ --publisher example \
+ --description "A small DBX frontend plugin." \
+ --version 0.1.0 \
+ --yes
+```
+
+生成的目录结构如下:
+
+```text
+dbx-plugin-demo/
+├── .github/workflows/plugin-release.yml
+├── assets/plugin.svg
+├── ui/index.html
+├── dbx-plugin.toml
+├── manifest.json
+└── README.md
+```
+
+其中:
+
+- `manifest.json` 是 DBX 运行时读取的插件契约,声明名称、图标、权限、入口、国际化和贡献点。
+- `dbx-plugin.toml` 是开发和打包配置,决定要包含哪些目录,以及是否需要构建原生后端。
+- `ui/index.html` 是沙箱前端入口,可以换成构建后的 Vue、React、Svelte 或其他静态资源。
+- `assets/plugin.svg` 是插件提供的图标;未提供可用图标时,DBX 才使用默认图标。
+
+## 4. 修改前端和使用 Host API
+
+生成的前端示例已经可以调用 DBX Host API:
+
+```html
+<script>
+ await window.dbxPlugin.ready;
+
+ const locale = window.dbxPlugin.locale;
+ const context = await window.dbxPlugin.request("host.getContext");
+
+ console.log(locale, context);
+</script>
+```
+
+常用对象:
+
+- `window.dbxPlugin.ready`:等待 DBX 完成宿主桥接初始化。
+- `window.dbxPlugin.locale`:读取当前 DBX 界面语言。
+- `window.dbxPlugin.context`:读取当前工作台允许访问的上下文。
+- `window.dbxPlugin.request(...)`:调用宿主提供的方法。
+- `window.dbxPlugin.invoke(...)`:调用插件自己的原生 Sidecar 方法。
+
+插件前端运行在沙箱中,不能直接导入 DBX 内部 Vue 组件,也不能直接访问 Tauri、Node.js 或任意本地文件。需要的能力必须通过 Manifest 权限和 Host API 明确暴露。
+
+### 国际化
+
+国际化分为两层:
+
+1. `manifest.json` 的 `localizations`:翻译插件名称、说明、连接字段、按钮和贡献点名称。
+2. 插件自己的 UI:根据 `window.dbxPlugin.locale` 选择文案或接入自己的 i18n 库。
+
+生成模板已经包含中文和英文切换示例,可以直接扩展其他语言。
+
+## 5. 打包未签名开发包
+
+### 打包前:使用独立浏览器开发环境
+
+Agent 可通过只读接口获取调试日志,无需浏览器会话:
+
+```bash
+curl -sS 'http://127.0.0.1:5190/api/diagnostics?after=0&limit=100'
+```
+
+端口使用实际启动值。增量查询传入上次返回的 `nextAfter`(作为 `after`)与 `instanceId`,可增加 `level=error` 筛选错误。`hasMore` 表示还有下一页,`reset` 表示实例或游标重置,`truncated` 表示旧日志已被覆盖。日志沿用界面脱敏规则,仅保留内存中最近 500 条。详见 [Agent 调试接口](sdk/dev-host/README.md#agent-diagnostics-api)。
+
+语言按钮支持中文与英文,同时切换调试外壳、日志面板和插件语言;插件名称与字段标签使用 Manifest 本地化。已有插件页面在确认后自动重载,取消则保持原语言。用户保存的连接名称与业务数据不翻译。
+
+顶部“自动重载”默认关闭。启用后,UI 输出更新会自动刷新所有插件页面;Rust/Go 后端源码修改会自动构建并重启。编译型前端仍需配置 `ui_watch`。已保存连接配置不会丢失,但后端重启后需重新连接;页面草稿与进行中的操作可能丢失。构建失败不会启动旧产物,重启调试服务后此开关恢复关闭。
+
+配置 `ui_watch` 后,监听命令必须在每次构建成功且产物全部写入后,向标准输出打印独立一行 `DBX_UI_BUILD_SUCCESS`,调试服务才会通知页面重载。请接入构建工具的成功回调,不要在失败或无条件退出回调中发送;仅修改输出文件不会触发重载。未配置 `ui_watch` 的静态页面仍按文件变化重载。
+
+浏览器刷新或关闭后,旧页面的工作台会保留 30 秒,允许事件流短暂断开后重连;超时后回收工作台,并断开没有其他页面使用的连接。已保存的连接配置不受影响。
+
+使用包含 `dev` 子命令的 CLI,可不启动 DBX 进行前后端联调:
+
+```bash
+dbx-plugin dev --path /path/to/my-plugin --port 5190
+```
+
+`--path` 默认为当前目录,端口占用时自动选择空闲端口。仅此子命令要求 Node.js 22+。纯前端插件直接打开工作台;Rust/Go 插件根据 `[backend]` 配置构建并启动后端,兼容 JSONL 和 framed v1。
+
+可在 `dbx-plugin.toml` 配置前端构建命令:
+
+```toml
+[dev]
+ui_build = ["npm", "run", "build"]
+ui_watch = ["npm", "run", "build:watch"]
+```
+
+命令按参数数组执行,不经过 shell;未配置时使用已有 UI。先自行安装插件依赖,工具不会猜测框架或自动安装。前端重新构建后手动重载页面,后端改动后点击重建并重新连接。
+
+点击“重载页面”右侧的“调试”,底部显示最近 500 条构建、后端状态、RPC 和请求校验日志,包含端口、项目与请求路径、耗时,以及可展开的 JSON 入参和出参。支持级别筛选、清空视图和自动滚动,终端同步输出 `[dbx-dev]` 日志。密码、令牌及 Manifest 声明的敏感字段脱敏,二进制内容省略,长内容截断;普通业务内容仍可见,仅用于本地开发。重启服务后历史清空。
+
+开发环境提供声明式连接表单、工作台 Tab、RPC、事件、资源读取和主题切换。普通配置与凭据以本地明文形式保存在 `.dbx-dev/`,默认忽略提交,可通过 `--data-dir` 更换。它不读取 DBX 用户数据,也不替代真实宿主的安装、Secret Store 或生命周期验收。
+
+源码构建和支持范围见[开发运行时说明](sdk/dev-host/README.md)。
+
+### 构建安装包
+
+进入插件目录并打包:
+
+```bash
+cd ~/Desktop/dbx-plugin-demo
+dbx-plugin package .
+```
+
+前端插件默认生成:
+
+```text
+dist/
+├── com.example.dbx-plugin-demo-0.1.0-universal.dbxp
+└── com.example.dbx-plugin-demo-0.1.0-universal.artifact.json
+```
+
+- `.dbxp` 是交给 DBX 安装的文件。
+- `.artifact.json` 包含目标平台、URL、SHA-256 和文件大小;签名构建还会写入 `signingKeyId`。
+- 本地开发默认不签名。
+
+未签名构建生成的元数据只适合本地检查,不能直接进入插件商店目录。商店条目必须包含 `signingKeyId`,安装前 DBX 会同时比对包内 Manifest 的 ID、版本、发布者、权限和签名 Key ID。
+
+## 6. 在 DBX 中安装测试
+
+未签名包只用于自己构建的本地开发测试:
+
+1. 打开 DBX 顶部工具栏的“插件中心”。
+2. 切换到“设置”。
+3. 展开“第三方与开发者选项”。
+4. 开启“允许安装未签名开发包”。
+5. 点击“安装 `.dbxp`”,选择 `dist/` 中的文件。
+6. 安装完成后切换到“已安装”,打开插件提供的工作台或其他入口。
+
+本地开发包允许用相同版本重新安装,DBX 会替换当前开发版本并重启对应插件运行时;正式签名包仍不允许覆盖同版本。
+
+测试结束后建议关闭“允许安装未签名开发包”。该开关只影响手动本地安装,不会放宽官方插件商店的签名校验。
+
+## 7. 需要原生后端时
+
+### Rust
+
+```bash
+dbx-plugin create ~/Desktop/dbx-rust-plugin \
+ --template rust \
+ --sdk-root /path/to/dbx
+
+cd ~/Desktop/dbx-rust-plugin
+dbx-plugin package .
+```
+
+### Go
+
+```bash
+dbx-plugin create ~/Desktop/dbx-go-plugin \
+ --template go \
+ --sdk-root /path/to/dbx
+
+cd ~/Desktop/dbx-go-plugin
+dbx-plugin package .
+```
+
+`--sdk-root` 让生成项目直接使用当前 DBX 工作区里的 SDK,适合 SDK 尚未发布或正在联调时使用。如果项目已经创建,也可以在打包前设置:
+
+```bash
+export DBX_PLUGIN_SDK_ROOT=/path/to/dbx
+dbx-plugin package .
+```
+
+原生插件包含平台二进制,所以必须在对应平台构建:
+
+- macOS Apple Silicon:`darwin-arm64`
+- macOS Intel:`darwin-x64`
+- Windows x64:`windows-x64`
+- Linux x64:`linux-x64`
+- Linux ARM64:`linux-arm64`
+
+本机打包只产生当前平台的包。正式发布时由 GitHub Actions 矩阵在各个平台分别构建,开发者不需要手工准备所有电脑。
+
+## 8. 候选包、仓库签名和 Key ID
+
+### 本地开发可以不签名
+
+`dbx-plugin package` 始终生成未签名候选包。自己开发测试时,在插件中心显式开启“允许安装未签名开发包”即可。这个开关只影响手动本地安装,不会放宽插件商店校验。
+
+### 官方插件作者不管理签名密钥
+
+官方发布流程只要求开发者提交源码、Release 和未签名候选包:
+
+1. 开发者 CI 构建候选 `.dbxp` 和 `.artifact.json`。
+2. DBX Store 审核源码、Manifest、权限、哈希和版本信息。
+3. 受保护的 DBX Store 工作流使用官方仓库密钥签名审核通过的候选包。
+4. 商店目录只引用最终签名包。
+
+`publisher` 表示作者和商店归属,不表示签名密钥所有者。当前 v1 不要求开发者签名,也不做双签名。以后只有在商业分发或供应链证明确实需要时,才会新增独立的“作者证明”,不会改变现有仓库签名含义。
+
+### Key ID 是什么
+
+Key ID 是仓库签名公钥的稳定公开标识,不是密码,也不是私钥。自定义仓库可以使用:
+
+```text
+company.plugins.release
+company.plugins.release:2026-01
+company.repository-signing-v1
+```
+
+建议使用“仓库 + 用途 + 轮换版本”的命名方式。Key ID 最长 128 个字符,可使用字母、数字、点、横线、下划线和冒号。
+
+同一个 Key ID 必须始终对应同一把 Ed25519 公钥。更换密钥时应创建新的 Key ID,而不是让旧 ID 指向另一把公钥。
+
+### 自定义或私有仓库生成签名密钥
+
+```bash
+dbx-plugin keygen company.plugins.release
+```
+
+命令会:
+
+- 创建 `.dbx-repository-signing-key.env`,Unix 下权限为 `0600`。
+- 在终端打印 Key ID 和 Base64 公钥。
+- 不在终端打印私钥。
+- 如果文件已存在则拒绝覆盖,除非显式使用 `--force`。
+
+仓库运营方在审核候选包后加载密钥并执行独立签名:
+
+```bash
+source .dbx-repository-signing-key.env
+cargo run --release \
+ --manifest-path /path/to/dbx/plugins/sdk/packager/Cargo.toml \
+ -- sign candidate.dbxp signed.dbxp \
+ --key-id "$DBX_PLUGIN_SIGNING_KEY_ID" \
+ --artifact-metadata signed.artifact.json \
+ --target universal
+```
+
+不要提交 `.dbx-repository-signing-key.env`。它包含仓库私钥,只能保存在密码管理器或受保护的仓库签名 CI Secret 中。官方插件开发者不需要执行本节。
+
+### 在 DBX 中信任自定义仓库
+
+使用自定义或私有仓库时,在插件中心“设置”的“自定义仓库信任”中填写:
+
+- 仓库密钥 ID:`dbx-plugin keygen` 使用的 Key ID。
+- Ed25519 公钥:`dbx-plugin keygen` 打印的 Base64 公钥。
+
+官方插件商店的公钥由 DBX 管理,普通用户不需要手工添加。人工审核决定插件能否进入商店,仓库签名保证审核后的安装包没有被替换,两者不能互相替代。
+
+## 9. 发布到 GitHub Release
+
+生成项目已经包含 `.github/workflows/plugin-release.yml`。官方插件作者不需要配置任何签名 Secret 或 Key ID。
+
+发布 GitHub Release 后,工作流会构建并上传:
+
+- 前端插件:一个 `universal.dbxp` 候选包。
+- Rust/Go 插件:各目标平台的 `.dbxp` 候选包。
+- 每个候选包对应的 `.artifact.json`。
+- 合并后的 `release-candidates.json`。
+
+这些 `.dbxp` 不能直接作为官方商店安装地址。审核通过后,DBX Store 的受保护工作流生成最终签名包并发布到仓库控制的 Release/CDN。源码放在插件自己的 Git 仓库;`dbx-store` Git 仓库只保存商店元数据、最终下载地址、哈希、大小、仓库公钥和审核信息。
+
+## 10. 常用命令
+
+```bash
+# 查看帮助
+dbx-plugin --help
+dbx-plugin create --help
+dbx-plugin dev --help
+dbx-plugin package --help
+dbx-plugin keygen --help
+
+# 创建纯前端插件
+dbx-plugin create my-plugin --template frontend
+
+# 创建 Svelte + Vite 插件
+dbx-plugin create my-svelte-plugin --template svelte
+
+# 创建 Rust 插件
+dbx-plugin create my-plugin --template rust
+
+# 创建 Go 插件
+dbx-plugin create my-plugin --template go
+
+# 仅在开发未发布的本地 SDK 时覆盖 SDK 根目录
+dbx-plugin create my-plugin --template rust --sdk-root /path/to/dbx
+
+# 打包当前项目
+dbx-plugin package .
+
+# 自定义/私有仓库运营方生成仓库密钥
+dbx-plugin keygen company.plugins.release
+
+# 关闭彩色输出
+NO_COLOR=1 dbx-plugin --help
+```
+
+### 独立调试插件
+
+无需启动 DBX,使用 Node.js 22+ 在浏览器中调试真实插件前后端:
+
+```bash
+# 在插件目录启动,默认端口 5190
+dbx-plugin dev
+
+# 指定插件目录和端口
+dbx-plugin dev --path /path/to/my-plugin --port 5190
+
+# 指定开发配置存储目录
+dbx-plugin dev --path /path/to/my-plugin --data-dir /path/to/dev-data
+```
+
+启动后打开终端输出的本地地址,按 `Ctrl+C` 停止。端口占用时自动选择空闲端口。纯前端插件无需后端;Rust/Go 插件会根据项目配置构建并启动 Sidecar,需先安装对应工具链及插件依赖。
+
+连接配置与凭据默认以明文保存在插件目录的 `.dbx-dev/` 中。前端构建监听通过 `[dev].ui_watch` 配置,自动重载默认关闭,可在页面中开启。完整配置与调试方式见[独立浏览器开发环境](#打包前使用独立浏览器开发环境)。
+
+## 11. 常见问题
+
+### `dbx-plugin: command not found`
+
+确认 npm 全局命令目录已经加入 `PATH`,或者直接使用 `npx`:
+
+```bash
+npx @dbx-app/plugin-cli --help
+```
+
+### 我只想写前端,为什么还要安装 Rust?
+
+不需要。`@dbx-app/plugin-cli` 安装的是 CI 预编译二进制;生成的 `frontend` 插件不包含 Rust 后端,最终 `.dbxp` 是跨平台的 `universal` 包。只有插件自身选择 Rust 后端,或者开发 CLI 源码时才需要 Rust。
+
+### 为什么原生插件不能只构建一个包?
+
+Rust/Go Sidecar 是操作系统原生二进制,不同系统和 CPU 架构不能混用。插件源码是一份,但 CI 会生成多个目标包;DBX 插件商店自动选择当前平台对应的包。
+
+### `.dbxp` 会增加 DBX 主安装包体积吗?
+
+不会。可选插件不打进 DBX 基础安装包。只有用户安装插件后,该插件才占用本机插件存储空间。
+
+### 开发者提交源码还是 `.dbxp`?
+
+两者都需要,但用途不同:源码保留在开发者仓库供审查和协作;开发者 CI 生成未签名候选 `.dbxp`;审核通过后由 DBX Store 发布最终签名 `.dbxp`;官方商店 Git 仓库只登记元数据和产物地址,不接收私钥,也不把大型二进制提交到 Git 历史。
diff --git a/plugins/README.md b/plugins/README.md
index dbb4f29e07..949d96f26c 100644
--- a/plugins/README.md
+++ b/plugins/README.md
@@ -1,14 +1,533 @@
-# Plugins
+# DBX plugin platform
-DBX declarative extension metadata and runtime plugins live here.
+DBX plugins are optional, versioned `.dbxp` packages. They can add native backend behavior, sandboxed workbench UI, saved connection types, and filesystem providers without increasing the base DBX installation size. Declarative extension metadata consumed at build time lives here as well.
-Plugins are not Node packages, so they intentionally stay separate from `packages/`.
+New plugin developers can read the official [Chinese](../docs/content/docs/plugin-development.cn.mdx) or [English](../docs/content/docs/plugin-development.mdx) documentation. The lower-level Chinese CLI walkthrough remains available in [`GETTING_STARTED.zh-CN.md`](./GETTING_STARTED.zh-CN.md).
-## Directories
+Install the precompiled development CLI without cloning or compiling DBX:
-- `connection-types/` - build-time registry for every DBX connection target, including databases, data services, message queues, and service registries.
-- `dialects/` - SQL dialect descriptors, type catalogs, DDL templates, and metadata rules.
-- `mappings/` - cross-dialect type mapping rules.
-- `jdbc/` - optional Java/JDBC plugin for connecting through vendor JDBC drivers and custom JDBC URLs.
+```bash
+npm install --global @dbx-app/plugin-cli
+```
-Plugin build artifacts, downloaded driver JARs, and local targets are ignored by Git.
+Marketplace listing pull requests go to `t8y2/dbx-store`. Plugin host, SDK, CLI, schema, documentation, and official-example changes go to `t8y2/dbx`. Ordinary plugin source stays in the plugin author's own repository.
+
+The platform contract is manifest v1 + Host API 1.x + sidecar protocol v1. The source code for a plugin may live in this repository or in a separate repository; DBX installs only the built package.
+
+## Repository layout
+
+- `manifest.schema.json` — editor/CI schema for manifest v1.
+- `marketplace.schema.json` — editor/CI schema for marketplace catalog v1.
+- `sdk/rust/dbx-plugin-sdk` — Rust sidecar SDK.
+- `sdk/go/dbx-plugin-sdk` — Go sidecar SDK.
+- `sdk/cli` — Rust source for the `dbx-plugin create/package` CLI published as `@dbx-app/plugin-cli`.
+- `sdk/packager` — deterministic `.dbxp` packager plus repository-side Ed25519 signing.
+- `sdk/templates/github/plugin-release.yml` — caller template for multi-platform unsigned release candidates.
+- `examples/hello-workbench` — complete connection provider + native sidecar + sandboxed workbench example.
+- `RELEASING.md` — source ownership, release assets, official-store submission, and review workflow.
+- `SIGNING.md` — repository-signing trust model, key rotation, and future author-attestation boundary.
+- `connection-types/` — build-time registry for every DBX connection target, including databases, data services, message queues, and service registries.
+- `dialects/` — SQL dialect descriptors, type catalogs, DDL templates, and metadata rules.
+- `mappings/` — cross-dialect type mapping rules.
+- `jdbc/` — legacy JDBC sidecar retained during migration to manifest v1; connects through vendor JDBC drivers and custom JDBC URLs.
+
+Create a frontend-only universal plugin or a complete Rust/Go plugin project:
+
+```bash
+dbx-plugin create my-ui-plugin --template frontend
+dbx-plugin create my-rust-plugin --template rust
+dbx-plugin create my-go-plugin --template go
+```
+
+All generated projects include sandbox workbench UI, localized manifest metadata, `.dbxp` packaging configuration, and a GitHub Release workflow. Rust and Go templates additionally include a native sidecar and multi-platform build matrix; frontend-only projects publish one `universal` package.
+
+## Source, package, and installation
+
+These are separate artifacts:
+
+1. **Source repository** — plugin authors build and test here or in another repository.
+2. **`.dbxp` artifacts** — plugin CI publishes unsigned review candidates; the repository operator signs approved candidates and publishes the installable assets.
+3. **Installed plugin** — DBX verifies and extracts the package under its plugin store.
+
+Optional plugins are not bundled into the DBX base package. Installing SSH, SFTP, OpenDAL, or another future plugin increases only the local plugin store size.
+
+## Marketplace and repository model
+
+The Plugin Center separates three concerns:
+
+- **Marketplace** aggregates enabled repositories, searches and filters catalog metadata, selects the current platform artifact, and installs or updates it.
+- **Installed** manages the local plugin lifecycle and opens connection providers, workbenches, and filesystem providers.
+- **Settings** manages local `.dbxp` installation, custom repositories, development-only unsigned packages, and advanced repository trust.
+
+Repository configuration is persisted under the plugin store in `.repositories.json`. DBX always exposes one managed `dbx-official` repository backed by the official catalog:
+
+```text
+https://raw.githubusercontent.com/t8y2/dbx-store/main/catalog/index.json
+```
+
+The official URL is part of the DBX client contract and cannot be edited in Plugin Center settings. Official repository signing public keys are built into DBX; release builds may append rotation keys with `DBX_PLUGIN_MARKETPLACE_TRUSTED_KEYS_JSON`. Custom repositories use user-managed repository keys. The official repository accepts only DBX-managed keys, so adding a custom key cannot impersonate an official package.
+
+Catalog v1 is defined by `marketplace.schema.json` and includes repository metadata, localized plugin metadata, searchable tags, permissions, versions, release notes, and target artifacts. Each artifact declares `signingKeyId`. DBX first selects the exact current target and then falls back to `universal`. Artifact URLs may be relative to the catalog URL. DBX enforces a 4 MiB catalog limit and a 512 MiB package limit, resolves only HTTP(S) URLs, limits redirects, isolates repository failures, verifies the catalog-declared size and SHA-256, then requires the package Manifest ID, version, publisher, permissions, and Ed25519 key ID to match the reviewed catalog before activation.
+
+Run the live official-store smoke test with:
+
+```bash
+cargo run -p dbx-core --no-default-features --example plugin_marketplace_smoke
+cargo run -p dbx-core --no-default-features --example plugin_marketplace_smoke -- <plugin-id> [version]
+```
+
+Without a plugin ID the smoke test verifies catalog availability and parsing. With a listed plugin ID it additionally downloads, verifies, installs, and reports the trusted signing key.
+
+### Review and signatures have different jobs
+
+- **Human review** decides whether a plugin is allowed into a curated catalog and whether `verified` may be shown.
+- **Catalog SHA-256** proves that the downloaded release asset is the exact artifact selected by the reviewed catalog.
+- **Ed25519 repository signing** proves that the installed package is exactly the artifact approved and published by that repository.
+- **Runtime permissions and host boundaries** limit what the plugin UI can request after installation.
+
+Review alone cannot protect an already approved download URL from later replacement. A signature alone does not mean the plugin is safe or reviewed; it only authenticates the signer and bytes.
+
+### Recommended repository ownership
+
+Keep the host, SDK, schemas, packager, and minimal examples in `t8y2/dbx`. The official catalog and review metadata live in the separate [`t8y2/dbx-store`](https://github.com/t8y2/dbx-store) repository:
+
+```text
+t8y2/dbx-store
+├── plugins/ # reviewed metadata submissions
+├── publishers/ # publisher identity and review records
+├── revoked.json # revoked versions or signing keys
+├── catalog/index.json # generated catalog v1
+└── .github/workflows/ # schema, review, hash, and publish gates
+```
+
+Plugin source code may remain in independent author repositories. Author CI builds one unsigned `.dbxp` candidate per target and publishes it to GitHub Releases, a CDN, or object storage. The reusable release workflow emits `release-candidates.json` with Manifest identity plus verified candidate metadata. After review, the repository signing workflow signs the accepted bytes and publishes final artifacts and metadata; the catalog Git repository should not accumulate binary packages.
+
+The same protocol supports future commercial deployment without changing package format: a public official repository, user-added third-party repositories, managed enterprise repositories with organization policy, and fully offline catalog/package mirrors. Credentials for private repositories must enter a secret-store-backed request layer rather than `.repositories.json`.
+
+## Package layout
+
+```text
+example-1.0.0-darwin-arm64.dbxp
+├── manifest.json
+├── checksums.json
+├── signature.json # required except explicit development installs
+├── bin/
+│ └── darwin-arm64/
+│ └── example-plugin
+├── assets/
+│ ├── plugin.svg
+│ └── connection.svg
+└── ui/
+ ├── index.html
+ └── assets/...
+```
+
+`.dbxp` is a ZIP container with stricter rules:
+
+- every file except `checksums.json` and `signature.json` must be covered exactly once by SHA-256 checksums;
+- absolute paths, parent traversal, duplicate entries, symlinks, oversized entries, and decompression bombs are rejected;
+- installed versions are immutable;
+- activation records select the current version and support rollback;
+- install, rollback, uninstall, and trust-store mutation share a filesystem lock;
+- marketplace and normal local installs require a signature from a trusted Ed25519 repository key;
+- unsigned packages require the explicit development-install toggle.
+
+## Manifest v1
+
+Add the schema to a manifest for editor validation:
+
+```json
+{
+ "$schema": "../../manifest.schema.json",
+ "manifest_version": 1,
+ "id": "vendor.example",
+ "name": "Example",
+ "icon": "assets/plugin.svg",
+ "version": "1.0.0",
+ "source": "https://github.com/example/dbx-plugin",
+ "homepage": "https://example.com/dbx-plugin",
+ "engines": {
+ "dbx": ">=0.5.68",
+ "host_api": "^1.0"
+ }
+}
+```
+
+The runtime also validates semantic versions, engine ranges, IDs, contribution references, field types and bindings, entrypoint containment, current-platform binaries, and required backend/UI entrypoints. The JSON schema improves authoring but is not the security boundary.
+
+### Entrypoints
+
+```json
+{
+ "entrypoints": {
+ "backend": {
+ "executable": "bin/darwin-arm64/example"
+ },
+ "ui": {
+ "root": "ui",
+ "entry": "ui/index.html"
+ }
+ }
+}
+```
+
+Use `stdio-jsonl` for ordinary request/event traffic. Use `stdio-framed` when PTY, SFTP, file transfer, or another feature needs binary channels. The workbench bridge transfers plugin-UI binary payloads as transferable `ArrayBuffer`s in both directions (8 MiB per message; chunk larger transfers), so UI-side binary traffic no longer pays a base64 round trip.
+
+## Contributions
+
+### `connection-provider`
+
+A provider owns validation and connect/disconnect lifecycle for a saved non-SQL connection. DBX stores these as:
+
+```text
+ConnectionConfig
+├── db_type: "plugin"
+├── plugin_id
+├── plugin_connection_provider
+├── plugin_connection_type
+├── common fields: name / host / port / username / password / database
+├── external_config: provider-defined non-secret values
+├── connection_secrets: provider-defined secrets
+└── transport_layers: SSH jump / SOCKS / HTTP proxy
+```
+
+The provider-defined type, such as `ssh`, stays in `plugin_connection_type`; it does not extend DBX's exhaustive database enum.
+
+Plugin authors may declare package-relative display metadata:
+
+```json
+{
+ "name": "Example plugin",
+ "icon": "assets/plugin.svg",
+ "contributions": [
+ {
+ "type": "connection-provider",
+ "id": "vendor.example.connection",
+ "label": "Example connection",
+ "icon": "assets/connection.svg"
+ }
+ ]
+}
+```
+
+DBX resolves connection display metadata in this order: provider `label` / `icon`, plugin `name` / `icon`, then provider ID and the built-in generic plugin icon. Declared icon files must remain inside the plugin package and use SVG, PNG, JPEG, GIF, WebP, or ICO. SVG is rendered through an image URL rather than injected into the DBX document.
+
+Field bindings:
+
+| Binding | Storage |
+| ---------------------------------------------------------- | ---------------------------------------------------------------- |
+| `name`, `host`, `port`, `username`, `password`, `database` | matching common `ConnectionConfig` field |
+| `config` | `external_config[field.key]` |
+| `secret` | `connection_secrets[field.key]`, persisted outside `config_json` |
+
+Password fields default to `secret` when `binding` is omitted. DBX validates required values and value types before calling the plugin. The plugin receives the hydrated connection only in its backend lifecycle request; the workbench UI receives a connection ID and non-secret navigation context.
+
+Lifecycle methods receive:
+
+```json
+{
+ "provider": { "id": "vendor.example.connection", "databaseType": "example" },
+ "connection": { "id": "...", "db_type": "plugin", "...": "..." },
+ "runtime": { "host": "127.0.0.1", "port": 49152 }
+}
+```
+
+`runtime.host` and `runtime.port` are the final endpoint after DBX transport layers. A protocol plugin must connect to this endpoint instead of rebuilding DBX tunnels itself.
+
+#### Connection dialog actions
+
+Connection providers may add ordered custom actions before DBX-owned lifecycle buttons:
+
+```json
+{
+ "actions": [
+ {
+ "id": "discover",
+ "label": "Discover endpoint",
+ "variant": "outline",
+ "requires_valid_form": false
+ }
+ ]
+}
+```
+
+- `actions` declares only custom button metadata. DBX invokes `connection/action` with the action ID; plugins cannot choose arbitrary RPC method names.
+- `test`, `save`, and `save-and-connect` are host-owned actions. DBX adds them from provider capabilities and dialog mode, validates the form, persists secrets through its secret store, and invokes the fixed lifecycle methods.
+- A custom action may run with an incomplete form only when `requires_valid_form` is `false`; DBX still validates declared field types, secret keys, and transport configuration.
+- `when` accepts `always`, `create`, or `edit`. `variant` accepts `default`, `outline`, `secondary`, `destructive`, or `ghost`. `timeout_ms` is limited to 1-120000 ms.
+- `close_on_success` controls whether the connection dialog closes after a successful custom action.
+
+`connection/action` receives the normal provider lifecycle payload plus `action: { id }`. It may return a message and updates for declared fields:
+
+```json
+{
+ "success": true,
+ "message": "Endpoint discovered",
+ "fieldValues": {
+ "host": "db.internal",
+ "port": 5432
+ }
+}
+```
+
+`fieldValues` may contain only fields declared by that provider and must match their declared types. `null` clears a field. The plugin cannot write arbitrary `ConnectionConfig` keys or bypass DBX-owned save, secret persistence, transport, and connection lifecycle logic.
+
+### `workbench`
+
+A workbench opens in a normal persistent DBX tab. The iframe is loaded with `sandbox="allow-scripts"`, a restrictive CSP, no Tauri object, no parent DOM access, and no direct network access. The host injects `window.dbxPlugin`:
+
+- `ready` / `context` / `locale` — `locale` is the current DBX locale such as `en` or `zh-CN`
+- `theme` — `{ appearance: "light" | "dark", tokens }` with the resolved DBX design tokens; theme changes are pushed live through env updates, and the SDK applies them to the plugin document root
+- `onContext(listener)` — context changes are pushed live; the iframe is not reloaded, so plugin UI state survives navigation
+- `invoke(method, params, options)`
+- `notify(method, params)`
+- `sendBinary(channel, data)` — requires `host.binary`
+- `readAsset(path)` / `readAssetUrl(path)`
+- `openWorkbench(contributionId, context)` — requires `host.workbench`
+- `openFilesystem(providerId, context)` — requires `host.filesystem`
+- `onEvent(listener)` — events are forwarded only with `host.events`
+- `onBinary(listener)` — binary frames are forwarded only with `host.binary`; listeners receive `{ channel, data: Uint8Array }`
+
+The sandbox default is no network access at all. A plugin may declare per-origin permissions such as `host.network:https://api.vendor.com` (https only, no path, at most 8 origins, duplicates rejected); declared origins — and only those — are added to the sandbox `connect-src`, so reviewers can see exactly which services the plugin UI may call.
+
+All backend calls are rebound to the owning plugin ID by the host. A plugin UI cannot invoke another plugin.
+
+### Official UI kit and theming
+
+Every sandbox document ships with a small official component kit built on the DBX design tokens, so plugin UI follows light/dark mode and custom palettes automatically:
+
+```html
+<button class="dbx-btn dbx-btn--primary">Connect</button>
+<input class="dbx-input" placeholder="Endpoint" />
+<span class="dbx-badge">Ready</span>
+```
+
+Available classes: `dbx-card`, `dbx-section-title`, `dbx-btn` (`--primary` / `--danger` / `--ghost`), `dbx-label`, `dbx-input`, `dbx-select`, `dbx-textarea`, `dbx-hint`, `dbx-row` (label + field grid), `dbx-table`, `dbx-badge`, `dbx-link`. Custom plugin CSS can use the same `var(--color-*)` tokens; `document.documentElement.dataset.dbxTheme` reflects the current appearance.
+
+Plugin-authored names, descriptions, contribution labels, form-field text, and select-option labels can be localized through `manifest.json > localizations`. DBX selects the exact current locale first, then its base language, and finally falls back to the manifest's default text:
+
+```json
+{
+ "localizations": {
+ "zh-CN": {
+ "name": "示例插件",
+ "contributions": {
+ "vendor.example.connection": {
+ "label": "示例连接",
+ "fields": {
+ "host": { "label": "主机", "placeholder": "请输入主机" },
+ "mode": { "options": { "readonly": "只读" } }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+### `result-view`
+
+A result view contributes a plugin-rendered visualization for query results. DBX shows one toolbar button per installed view next to the result grid; clicking it opens the plugin workbench with the current result as context:
+
+```json
+{
+ "type": "result-view",
+ "id": "vendor.example.graph",
+ "label": "Graph"
+}
+```
+
+The workbench `context.result` is a bounded snapshot — `{ columns, rows (<= 500), truncated }` plus `sql`, `connectionId`, and `database`. Plugins that need the full or streamed result set should re-execute through their backend using the SQL and connection reference. Requires a UI entrypoint.
+
+### `context-menu`
+
+A context-menu entry is rendered **natively** by DBX (no sandbox iframe, native theme and keyboard behavior) in the declared menu surface. v1 supports the saved-connection sidebar menu:
+
+```json
+{
+ "type": "context-menu",
+ "id": "vendor.example.inspect",
+ "label": "Inspect endpoint",
+ "menu": "connection"
+}
+```
+
+Clicking the item dispatches a `contextMenu/<id>` backend request with a non-secret connection summary (`{ id, dbType, name, database }`). The backend entrypoint is required; return `{ "message": "..." }` to surface a toast.
+
+### `filesystem-provider`
+
+A filesystem provider declares URI schemes, an optional `root_uri`, and capabilities (`read`, `write`, `delete`, `rename`, `mkdir`). It is the reusable boundary for OpenDAL-like storage integrations: DBX owns the generic file-browser tab, while the plugin owns authentication, remote API calls, and provider-specific state.
+
+A connection provider can set `filesystem_provider` instead of `workbench`. Opening that saved connection connects the plugin lifecycle and opens the DBX host file manager. A provider may declare both: DBX opens the custom workbench by default, and the sandboxed UI can call `openFilesystem(providerId, context)` with `host.filesystem` permission.
+
+```json
+{
+ "type": "filesystem-provider",
+ "id": "vendor.storage.files",
+ "label": "Object storage",
+ "schemes": ["s3"],
+ "root_uri": "s3://bucket/",
+ "capabilities": ["read"]
+}
+```
+
+Host API 1.x defines these backend methods:
+
+- `filesystem/list` receives `providerId`, optional `connectionId`, `uri`, optional pagination `cursor`, and a bounded `limit`. It returns `{ entries, nextCursor? }`.
+- `filesystem/read` receives `providerId`, optional `connectionId`, `uri`, and bounded `maxBytes`. It returns `{ dataBase64, contentType?, truncated, etag? }` for preview-sized reads.
+- `filesystem/write` receives `providerId`, optional `connectionId`, `uri`, `dataBase64`, `create`, `overwrite`, and optional optimistic-concurrency `etag`.
+- `filesystem/createDirectory` receives `providerId`, optional `connectionId`, and `uri`.
+- `filesystem/delete` receives `providerId`, optional `connectionId`, `uri`, and `recursive`.
+- `filesystem/rename` receives `providerId`, optional `connectionId`, `sourceUri`, `targetUri`, and `overwrite`.
+
+Every entry has `name`, canonical `uri`, `kind` (`file`, `directory`, `symlink`, or `other`), and optional `size`, `modifiedAt`, and `contentType`. DBX validates schemes, response sizes, base64, cursors, and entry metadata before the frontend sees a result.
+
+Mutation methods return `{ success, message?, entry? }` and are rejected unless the provider declares the matching capability. Inline read/write payloads are capped at 4 MiB. The built-in file manager currently owns directory navigation, pagination, and bounded file preview. Large upload/download and PTY/SFTP streams use `stdio-framed` binary channels with plugin-defined transfer methods, chunk acknowledgements, cancellation, and progress events; they must not be encoded as one large JSON value.
+
+## Backend protocol
+
+The backend is a persistent child process with stdin/stdout reserved for the DBX protocol. Diagnostics must go to stderr.
+
+### Initialization
+
+DBX starts every sidecar with `plugin/initialize`:
+
+```json
+{
+ "host": {
+ "dbxVersion": "0.5.68",
+ "hostApiVersion": "1.0.0",
+ "protocolVersions": [1]
+ },
+ "plugin": {
+ "id": "vendor.example",
+ "version": "1.0.0"
+ },
+ "permissions": ["host.events"]
+}
+```
+
+The plugin returns:
+
+```json
+{
+ "protocolVersion": 1,
+ "capabilities": ["connections", "events"],
+ "plugin": {
+ "id": "vendor.example",
+ "version": "1.0.0"
+ }
+}
+```
+
+The host rejects a protocol or backend identity mismatch before exposing the session. This catches a package that points at the wrong executable even when the process otherwise speaks the protocol.
+
+### JSON messages
+
+Requests and responses follow JSON-RPC 2.0. Plugin events are JSON-RPC notifications emitted by the sidecar. The host supports concurrent in-flight requests, per-request timeouts, strict JSON-RPC validation for manifest v1, crash propagation, status reporting, bounded event buffers, and automatic child termination after handshake, protocol, or output failure. The Rust SDK dispatches work through a bounded configurable worker pool.
+
+`stdio-jsonl` writes one JSON value per line. A single JSON message is limited to 8 MiB.
+
+### Framed messages
+
+`stdio-framed` uses a 5-byte header:
+
+```text
+kind: u8 | payload_length: u32 big-endian | payload
+```
+
+- kind `0`: UTF-8 JSON payload;
+- kind `1`: `channel_length: u16 big-endian | channel UTF-8 | binary bytes`.
+
+Binary payloads are limited to 64 MiB per frame. Channel names are validated. Use application-level chunking, offsets, acknowledgements, and cancellation for large transfers.
+
+## Activation and process lifecycle
+
+```mermaid
+sequenceDiagram
+ participant UI as DBX UI
+ participant Host as PluginHost
+ participant Sidecar as Plugin sidecar
+ UI->>Host: invoke / test / connect / open workbench
+ Host->>Host: resolve active compatible version
+ Host->>Sidecar: spawn once on demand
+ Host->>Sidecar: plugin/initialize
+ Sidecar-->>Host: protocol + capabilities
+ Host->>Sidecar: provider or workbench RPC request
+ Sidecar-->>Host: result + events/binary frames
+ Host-->>UI: typed result + plugin-scoped events
+```
+
+Sidecars are shared per plugin process, not spawned per tab. Plugins own their internal session registries. DBX tears down plugin-owned connection pools before replace, rollback, or uninstall. Uninstall is blocked while saved connections still reference the plugin.
+
+## Security model
+
+- **Package authenticity:** checksums + trusted Ed25519 repository keys.
+- **UI isolation:** sandboxed iframe, restrictive CSP, bounded bridge payloads, safe asset paths, plugin identity binding.
+- **Secret persistence:** plugin secrets are removed from connection JSON and stored through DBX's secret-store path. Ordinary cloud-sync snapshots always contain redacted placeholders. Secrets enter sync data only inside the encrypted payload when the user has configured a sync passphrase; without one, plugin secrets remain local and are not synchronized.
+- **Native backend trust:** a native sidecar runs with the current OS user's privileges. A signature identifies the repository that approved and published the package; it is not an OS sandbox or proof that the author is harmless. Install only plugins whose backend code you trust.
+- **Permission declarations:** privileged host bridge operations require declared permissions. Plugin UI network egress is fully blocked except for explicitly declared `host.network:` origins. Native process filesystem/network access cannot currently be completely mediated by DBX.
+
+Custom repository public keys can be added or removed in Plugin Center. Obtain them through a channel independent from the downloaded package.
+
+## Build and release
+
+The complete author and official-store flow is documented in [`RELEASING.md`](RELEASING.md). Plugin authors keep source code in their own repository and publish unsigned candidates. DBX Store reviews and signs approved candidates, publishes installable artifacts, and records only catalog metadata in Git.
+
+For a Rust backend:
+
+```bash
+cargo build --release --manifest-path path/to/backend/Cargo.toml
+```
+
+Stage `manifest.json`, declared assets, the current-target binary, and optional UI assets, then package:
+
+```bash
+cargo run --release \
+ --manifest-path plugins/sdk/packager/Cargo.toml \
+ -- path/to/stage path/to/vendor.example-1.0.0-darwin-arm64.dbxp \
+ --artifact-metadata path/to/vendor.example-1.0.0-darwin-arm64.artifact.json \
+ --target darwin-arm64
+```
+
+Repository operators sign an already-built candidate after review:
+
+```bash
+DBX_PLUGIN_SIGNING_KEY="..." \
+cargo run --release \
+ --manifest-path plugins/sdk/packager/Cargo.toml \
+ -- sign path/to/vendor.example-1.0.0-darwin-arm64.unsigned.dbxp path/to/vendor.example-1.0.0-darwin-arm64.dbxp \
+ --key-id vendor-release \
+ --artifact-metadata path/to/vendor.example-1.0.0-darwin-arm64.artifact.json \
+ --target darwin-arm64
+```
+
+Plugin authors do not receive the official repository private key. Never commit a repository signing seed. Publish the corresponding 32-byte public key separately and rotate it with a new `signingKeyId`.
+
+For native plugins, copy `sdk/templates/github/plugin-release.yml` into the plugin repository and pin the reusable workflow to a released DBX plugin SDK tag or commit. Frontend-only plugins may replace the build matrix with one `universal` build.
+
+## Compatibility policy
+
+- Increment `manifest_version` only for manifest shape changes that an older DBX cannot interpret.
+- Increment the sidecar protocol version only for wire-level incompatibilities.
+- Use `engines.host_api` for host API compatibility and `engines.dbx` for product-version constraints.
+- Additive contribution fields should remain optional within the same host API major version.
+- Saved plugin connections must remain readable across plugin upgrades; migrate provider-owned `external_config` explicitly in the plugin backend when needed.
+
+## Validation
+
+Core checks:
+
+```bash
+cargo test -p dbx-core --no-default-features plugins::
+cargo check -p dbx-web --no-default-features
+```
+
+SDK and example checks:
+
+```bash
+cargo test --manifest-path plugins/sdk/rust/dbx-plugin-sdk/Cargo.toml
+cargo check --manifest-path plugins/sdk/packager/Cargo.toml
+node plugins/examples/hello-workbench/package.mjs
+node plugins/examples/hello-workbench/smoke.mjs
+```
diff --git a/plugins/RELEASING.md b/plugins/RELEASING.md
new file mode 100644
index 0000000000..0b11a3aa50
--- /dev/null
+++ b/plugins/RELEASING.md
@@ -0,0 +1,123 @@
+# Publishing DBX plugins
+
+DBX separates plugin source, unsigned review candidates, repository-signed installable artifacts, and catalog metadata. These artifacts have different owners and should not be copied into one Git repository.
+
+The signing rationale and future author-attestation boundary are documented in [`SIGNING.md`](SIGNING.md).
+
+## What goes where
+
+### Plugin source repository
+
+The plugin author keeps the following in the plugin's own Git repository:
+
+- backend and frontend source code;
+- `manifest.json`, schemas, tests, documentation, screenshots, and license;
+- package scripts and GitHub Actions workflows;
+- public release notes and issue tracker links.
+
+The source may live inside `t8y2/dbx` for a tightly coupled official plugin or in an independent author repository. Official and verified submissions must give DBX reviewers access to the corresponding source. Open-source plugins normally provide a public source URL; a future closed-source commercial flow may use private reviewer access.
+
+Official plugin authors do not receive or maintain the DBX Store signing key.
+
+### Candidate artifact storage
+
+Author-controlled GitHub Releases, a CDN, or object storage contains the unsigned packages submitted for review:
+
+```text
+vendor.example-1.2.0-darwin-arm64.dbxp
+vendor.example-1.2.0-darwin-x64.dbxp
+vendor.example-1.2.0-windows-x64.dbxp
+vendor.example-1.2.0-linux-x64.dbxp
+vendor.example-1.2.0-linux-arm64.dbxp
+release-candidates.json
+```
+
+Frontend-only or otherwise platform-independent plugins may publish one `vendor.example-1.2.0-universal.dbxp` candidate. Use `universal` only when the exact same package is valid on every supported DBX target.
+
+Candidates are not normal Marketplace installation assets. They deliberately contain no `signature.json`, and their `.artifact.json` records contain no `signingKeyId`.
+
+### Repository-signed artifact storage
+
+After review, the repository operator signs the accepted candidate bytes and publishes final installable `.dbxp` assets to repository-controlled release storage. Final artifact metadata contains:
+
+- target and final download URL;
+- SHA-256 and byte size of the signed package;
+- repository `signingKeyId`.
+
+The official implementation publishes these assets from a protected `dbx-store` workflow. A custom or private repository operates the same trust boundary with its own key and storage.
+
+### Official store Git repository
+
+`t8y2/dbx-store` contains reviewed catalog inputs, publisher identities, repository public keys, revocations, and generated catalog JSON. It does not contain plugin source trees, private keys, or `.dbxp` binaries.
+
+A store submission references:
+
+- plugin ID, display metadata, icon, screenshots, tags, permissions, and localization;
+- publisher identity, source, homepage, support, license, and privacy links;
+- release tag and release notes;
+- each final artifact URL, size, SHA-256, target, and repository signing key ID;
+- reviewer status and any revocation information.
+
+Human review decides whether a plugin is allowed in the official catalog. SHA-256 and Ed25519 repository signing ensure the installed bytes are the reviewed bytes. DBX also compares the package Manifest ID, version, publisher, and permissions with the selected catalog entry before activation.
+
+## Author release workflow
+
+Install the precompiled CLI and run `dbx-plugin create <directory> --template frontend|rust|go` for a complete project, or copy `sdk/templates/github/plugin-release.yml`:
+
+```bash
+npm install --global @dbx-app/[email protected]
+```
+
+Pin both the reusable workflow reference and `plugin-cli-version`. The npm package contains the matching CLI binary, packager, and Rust/Go SDK sources. Building the CLI from a DBX checkout is reserved for SDK development and can be enabled with `install-plugin-cli-from-source: true` plus a reviewed `sdk-ref`.
+
+Before publishing a new CLI version, update the CLI and npm manifests together, merge them to `main`, then run the **Plugin CLI Release** workflow. The workflow creates `plugin-cli-v<version>`, builds six platform packages, publishes `@dbx-app/plugin-cli`, and verifies clean npm installation with frontend, Rust, and Go templates.
+
+For local CLI development only:
+
+```bash
+cargo install --locked --path plugins/sdk/cli
+```
+
+When an author publishes a GitHub Release, the reusable workflow:
+
+1. installs the pinned precompiled `dbx-plugin` npm package and builds on the configured target runners;
+2. produces one unsigned `.dbxp` and `.artifact.json` per target;
+3. rejects candidates containing `signature.json` or metadata containing `signingKeyId`;
+4. validates unique targets, SHA-256 values, sizes, package names, and one shared Manifest identity;
+5. uploads all candidates and merged `release-candidates.json` to the author Release.
+
+The default native matrix covers `darwin-arm64`, `darwin-x64`, `windows-x64`, `linux-x64`, and `linux-arm64`. A frontend-only plugin uses one `universal` build.
+
+## Official review and signing
+
+1. The author opens a Plugin submission Issue in `t8y2/dbx-store` with the source tag and `release-candidates.json` URL.
+2. Review the source tag, Manifest, permissions, release notes, and candidate metadata.
+3. Verify every candidate URL is immutable and matches `release-candidates.json`.
+4. Run the protected `dbx-store` signing workflow with the expected plugin ID, version, target, output filename, and reviewed DBX SDK ref.
+5. The workflow downloads the candidate, rejects pre-existing signatures, verifies Manifest identity, appends the DBX Store signature, and publishes the signed asset plus final metadata.
+6. The author opens the final catalog PR against `t8y2/dbx-store:main`, adding the final artifact URL, size, SHA-256, and repository `signingKeyId`.
+7. Run store validation and complete maintainer review before making the version visible.
+
+The protected GitHub Environment must require reviewer approval and provide matching `DBX_STORE_SIGNING_KEY` secret and `DBX_STORE_SIGNING_KEY_ID` variable values. The public key must already exist in `signing-keys.json` and must not be revoked.
+
+## Custom and private repositories
+
+Repository operators may create a repository key with:
+
+```bash
+dbx-plugin keygen company-plugins.release
+source .dbx-repository-signing-key.env
+cargo run --release \
+ --manifest-path /path/to/dbx/plugins/sdk/packager/Cargo.toml \
+ -- sign candidate.dbxp signed.dbxp \
+ --key-id "$DBX_PLUGIN_SIGNING_KEY_ID" \
+ --artifact-metadata signed.artifact.json \
+ --target darwin-arm64 \
+ --artifact-url https://plugins.example.com/releases/signed.dbxp
+```
+
+Distribute the public key through an independent trusted channel. Never commit the private seed or place it in the plugin package, catalog, source repository, workflow logs, or release notes.
+
+## Immutability
+
+Rebuilding an existing version in place is not allowed. If source, metadata, review decisions, or package bytes change, publish a new semantic version and new release assets.
diff --git a/plugins/SIGNING.md b/plugins/SIGNING.md
new file mode 100644
index 0000000000..af0991b375
--- /dev/null
+++ b/plugins/SIGNING.md
@@ -0,0 +1,33 @@
+# DBX plugin signing model
+
+DBX plugin signing v1 uses one signature owned by the repository that distributes the package. It does not require every plugin author to maintain a private signing key.
+
+## Trust boundary
+
+The official flow is:
+
+1. The plugin author publishes source and unsigned `.dbxp` candidates.
+2. DBX Store reviews the source, Manifest, permissions, candidate hashes, and release metadata.
+3. A protected store workflow signs the approved candidate with the DBX Store repository key.
+4. The catalog references the final signed artifact, SHA-256, size, and `signingKeyId`.
+5. DBX verifies the catalog metadata, package checksums, repository signature, Manifest identity, version, publisher, and permissions before activation.
+
+The `publisher` field records authorship and catalog ownership. It is not a signing-key owner. The repository signature proves that the repository approved and published the exact installed bytes; it does not replace code review or sandbox native code.
+
+## Official and custom repositories
+
+- The official repository key is controlled by DBX Store and its public key is shipped with DBX.
+- A custom or private repository controls one or more repository keys and distributes the public keys to its users through an independent trusted channel.
+- Plugin authors do not need `dbx-plugin keygen` for official submissions.
+- `dbx-plugin keygen` exists only for operators of custom or private repositories.
+- Unsigned packages are accepted only through the explicit local-development installation option.
+
+## Key rotation
+
+`signingKeyId` identifies a repository key and supports rotation. A key ID must never be reused for different public-key bytes. Rotation adds a new key ID, ships the new public key to clients, begins signing with the new key, and later revokes the old key after supported clients have updated.
+
+## Why there is no author signature in v1
+
+Author identity is currently established through the source repository, account ownership, submission history, review records, and the catalog publisher record. Adding a second cryptographic author signature would introduce author key recovery, rotation, revocation, organization transfer, and historical verification requirements without improving the repository-to-user integrity path needed for v1.
+
+A future author-attestation layer is optional, not inevitable. If commercial distribution or stronger supply-chain provenance requires it, add a separate author attestation with its own schema and trust policy while retaining the repository signature. Do not overload the existing `signature.json` or reinterpret `signingKeyId` as an author identity.
diff --git a/plugins/connection-types/plugin.yaml b/plugins/connection-types/plugin.yaml
new file mode 100644
index 0000000000..198682a6dd
--- /dev/null
+++ b/plugins/connection-types/plugin.yaml
@@ -0,0 +1,29 @@
+schemaVersion: 1
+order: 790
+dbType: plugin
+rustVariant: Plugin
+label: Plugin
+runtimeMode: external
+mcpMode: unsupported
+singleConnectionPool: false
+metadataConnectionScoped: false
+skipTcpProbe: true
+supportLevel: connect
+specializedSurface: true
+capabilities:
+ queryExecution: false
+ metadataBrowse: false
+ objectBrowser: false
+ objectSource: false
+ schemaSearch: false
+ diagram: false
+ tableDataEdit: false
+ tableStructureEdit: false
+ tableImport: false
+ dataTransfer: false
+ sqlFileExecution: false
+ databaseCreate: false
+ fieldLineage: false
+ sqlExplain: false
+ userAdmin: false
+ driverManagement: false
diff --git a/plugins/examples/hello-workbench/.gitignore b/plugins/examples/hello-workbench/.gitignore
new file mode 100644
index 0000000000..61cb808db5
--- /dev/null
+++ b/plugins/examples/hello-workbench/.gitignore
@@ -0,0 +1,2 @@
+dist/
+backend/target/
diff --git a/plugins/examples/hello-workbench/README.md b/plugins/examples/hello-workbench/README.md
new file mode 100644
index 0000000000..263ee3e63b
--- /dev/null
+++ b/plugins/examples/hello-workbench/README.md
@@ -0,0 +1,171 @@
+# DBX Hello Workbench plugin
+
+This example exercises the complete manifest v1 path instead of mocking a contribution preview:
+
+- native Rust sidecar built with `dbx-plugin-sdk`;
+- protocol handshake and concurrent JSON-RPC requests;
+- saved `connection-provider` with common/config/secret field bindings;
+- test, connect, and disconnect lifecycle;
+- per-connection backend registry;
+- asynchronous connection/progress events;
+- sandboxed workbench UI using `window.dbxPlugin`;
+- workbench-to-sidecar RPC plus a read-only filesystem contribution rendered by DBX's host-owned file manager;
+- unsigned `.dbxp` candidate packaging plus separate repository signing;
+- automated install-to-uninstall smoke runner.
+
+## Files
+
+```text
+hello-workbench/
+├── manifest.json
+├── assets/ # plugin and connection-provider icons
+├── backend/ # native sidecar
+├── ui/index.html # sandboxed workbench
+├── package.mjs # current-platform unsigned candidate build
+├── repository-sign.mjs # custom repository signing example
+├── repository-smoke.mjs # candidate-to-signed-install end-to-end smoke
+└── smoke.mjs # package + lifecycle smoke test
+```
+
+The reusable smoke executable lives at `crates/dbx-core/examples/plugin_package_smoke.rs` so it shares DBX's workspace lockfile and dependency patches.
+
+## Build an unsigned development package
+
+From the DBX repository root:
+
+```bash
+node plugins/examples/hello-workbench/package.mjs
+```
+
+The package is written to:
+
+```text
+plugins/examples/hello-workbench/dist/
+ dbx.example.hello-1.0.0-<target>.dbxp
+ dbx.example.hello-1.0.0-<target>.artifact.json
+```
+
+The `.artifact.json` file contains the target, candidate URL, package SHA-256, and size used by review and multi-platform release aggregation. It intentionally contains no `signingKeyId`.
+
+In DBX, open **Plugin Center**, enable **Allow unsigned development package**, and install the `.dbxp`.
+
+## Use the example
+
+1. Select **DBX Hello Workbench** in the plugin center.
+2. Create a **Hello connection**.
+3. Fill the host, port, greeting, and optional example token.
+4. Click **Test**.
+5. Click **Save & Open**.
+6. Invoke the sidecar from the workbench.
+7. Click **Open host files** to browse and preview the virtual `hello:/` filesystem without plugin-owned file-browser UI.
+
+The example token is persisted through `connection_secrets`; the raw connection `config_json` contains only an empty placeholder. The iframe receives the saved connection ID, never the token.
+
+## Run the real package smoke test
+
+```bash
+node plugins/examples/hello-workbench/smoke.mjs
+```
+
+The smoke runner performs:
+
+```text
+build package
+→ install into a temporary plugin store
+→ verify manifest compatibility
+→ read plugin and connection-provider icon assets
+→ start and initialize the native sidecar
+→ test the provider connection
+→ connect the saved plugin connection
+→ invoke hello/greet
+→ list and preview files through the typed filesystem host API
+→ observe connection and progress events
+→ disconnect
+→ stop the sidecar
+→ uninstall
+```
+
+To reuse an already-built package:
+
+```bash
+node plugins/examples/hello-workbench/smoke.mjs \
+ plugins/examples/hello-workbench/dist/dbx.example.hello-1.0.0-darwin-arm64.dbxp
+```
+
+To verify a repository-signed package with marketplace policy, provide the trusted repository public keys:
+
+```bash
+DBX_PLUGIN_SMOKE_TRUSTED_KEYS_JSON='{"example-repository":"BASE64_32_BYTE_ED25519_PUBLIC_KEY"}' \
+node plugins/examples/hello-workbench/smoke.mjs \
+ plugins/examples/hello-workbench/dist/dbx.example.hello-1.0.0-darwin-arm64.signed.dbxp
+```
+
+## Sign as a custom repository operator
+
+Official plugin authors skip this section because DBX Store signs approved candidates. To exercise the custom-repository flow, generate or load a repository key and sign the already-built candidate:
+
+```bash
+dbx-plugin keygen example-repository
+source .dbx-repository-signing-key.env
+node plugins/examples/hello-workbench/repository-sign.mjs
+```
+
+The script writes a `.signed.dbxp`, creates final artifact metadata containing `signingKeyId`, and refreshes the example catalog entry. Add the corresponding Base64 public key under **Plugin Center → Custom repository trust** before installing from that catalog.
+
+Do not put the private seed in the repository or package. Distribute the repository public key through a channel independent from the `.dbxp` download.
+
+Run the complete temporary-key flow without modifying the example catalog:
+
+```bash
+node plugins/examples/hello-workbench/repository-smoke.mjs
+```
+
+This builds an unsigned candidate, generates an ephemeral repository key outside the workspace, signs the reviewed candidate, installs it with strict signature policy, exercises assets/actions/connections/filesystem/events, uninstalls it, and removes temporary keys and Cargo targets.
+
+Set `DBX_PLUGIN_OUTPUT_DIR` when automation should place candidate outputs outside the example `dist/` directory.
+
+## Connection request shape
+
+The backend lifecycle receives the hydrated connection and the final DBX transport endpoint:
+
+```json
+{
+ "provider": {
+ "id": "dbx.example.hello.connection",
+ "databaseType": "hello"
+ },
+ "connection": {
+ "id": "saved-connection-id",
+ "db_type": "plugin",
+ "plugin_id": "dbx.example.hello",
+ "plugin_connection_provider": "dbx.example.hello.connection",
+ "plugin_connection_type": "hello",
+ "external_config": {
+ "greeting": "Hello"
+ },
+ "connection_secrets": {
+ "api_token": "hydrated only for the backend"
+ }
+ },
+ "runtime": {
+ "host": "localhost",
+ "port": 22
+ }
+}
+```
+
+The workbench context is intentionally smaller:
+
+```json
+{
+ "connectionId": "saved-connection-id",
+ "providerId": "dbx.example.hello.connection",
+ "connectionType": "hello"
+}
+```
+
+## Adapt it for a real plugin
+
+- SSH/SFTP: switch to `stdio-framed`, keep PTY/SFTP sessions in a backend registry, and use binary channels for terminal/transfer data.
+- OpenDAL: keep credentials in the connection provider, implement filesystem methods in the backend, and let DBX own generic file-manager UI.
+- Other tools: add contributions rather than adding a new DBX database enum variant or importing plugin Vue code into the main window.
diff --git a/plugins/examples/hello-workbench/assets/connection.svg b/plugins/examples/hello-workbench/assets/connection.svg
new file mode 100644
index 0000000000..797688801e
--- /dev/null
+++ b/plugins/examples/hello-workbench/assets/connection.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Hello connection">
+ <defs>
+ <linearGradient id="background" x1="10" y1="8" x2="54" y2="56" gradientUnits="userSpaceOnUse">
+ <stop stop-color="#22c55e" />
+ <stop offset="1" stop-color="#0891b2" />
+ </linearGradient>
+ </defs>
+ <rect x="4" y="4" width="56" height="56" rx="16" fill="url(#background)" />
+ <path d="M20 19v10m24-10v10M16 29h32v5a16 16 0 0 1-16 16 16 16 0 0 1-16-16v-5Z" fill="none" stroke="white" stroke-width="5" stroke-linecap="round" stroke-linejoin="round" />
+ <path d="M32 50v7" stroke="white" stroke-width="5" stroke-linecap="round" />
+</svg>
diff --git a/plugins/examples/hello-workbench/assets/plugin.svg b/plugins/examples/hello-workbench/assets/plugin.svg
new file mode 100644
index 0000000000..773c7c4c0d
--- /dev/null
+++ b/plugins/examples/hello-workbench/assets/plugin.svg
@@ -0,0 +1,13 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="DBX Hello Workbench">
+ <defs>
+ <linearGradient id="background" x1="8" y1="8" x2="56" y2="56" gradientUnits="userSpaceOnUse">
+ <stop stop-color="#7c3aed" />
+ <stop offset="1" stop-color="#2563eb" />
+ </linearGradient>
+ </defs>
+ <rect x="4" y="4" width="56" height="56" rx="16" fill="url(#background)" />
+ <path d="M18 21h28v18H31l-8 7v-7h-5V21Z" fill="white" opacity=".96" />
+ <circle cx="26" cy="30" r="2.5" fill="#7c3aed" />
+ <circle cx="32" cy="30" r="2.5" fill="#6366f1" />
+ <circle cx="38" cy="30" r="2.5" fill="#2563eb" />
+</svg>
diff --git a/plugins/examples/hello-workbench/backend/Cargo.lock b/plugins/examples/hello-workbench/backend/Cargo.lock
new file mode 100644
index 0000000000..ace9fd7d7c
--- /dev/null
+++ b/plugins/examples/hello-workbench/backend/Cargo.lock
@@ -0,0 +1,115 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "dbx-example-hello"
+version = "1.0.0"
+dependencies = [
+ "dbx-plugin-sdk",
+ "serde_json",
+]
+
+[[package]]
+name = "dbx-plugin-sdk"
+version = "0.1.0"
+dependencies = [
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/plugins/examples/hello-workbench/backend/Cargo.toml b/plugins/examples/hello-workbench/backend/Cargo.toml
new file mode 100644
index 0000000000..84228513c5
--- /dev/null
+++ b/plugins/examples/hello-workbench/backend/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "dbx-example-hello"
+version = "1.0.0"
+edition = "2021"
+license = "Apache-2.0"
+
+[workspace]
+
+[dependencies]
+dbx-plugin-sdk = { path = "../../../sdk/rust/dbx-plugin-sdk" }
+serde_json = "1"
+
+[profile.release]
+strip = true
+lto = true
+codegen-units = 1
diff --git a/plugins/examples/hello-workbench/backend/src/main.rs b/plugins/examples/hello-workbench/backend/src/main.rs
new file mode 100644
index 0000000000..4bc462070e
--- /dev/null
+++ b/plugins/examples/hello-workbench/backend/src/main.rs
@@ -0,0 +1,195 @@
+use std::collections::HashMap;
+use std::sync::Mutex;
+use std::thread;
+use std::time::Duration;
+
+use dbx_plugin_sdk::{PluginEmitter, PluginError, PluginHandler, PluginMetadata, PluginServer, RequestContext};
+use serde_json::{json, Value};
+
+#[derive(Default)]
+struct HelloPlugin {
+ connections: Mutex<HashMap<String, String>>,
+}
+
+impl PluginHandler for HelloPlugin {
+ fn handle(
+ &self,
+ _context: RequestContext,
+ method: &str,
+ params: Value,
+ emitter: &PluginEmitter,
+ ) -> Result<Value, PluginError> {
+ match method {
+ "connection/test" => {
+ let connection = params.get("connection").cloned().unwrap_or_default();
+ Ok(json!({
+ "success": true,
+ "message": format!(
+ "Provider is ready for {}:{}.",
+ connection.get("host").and_then(Value::as_str).unwrap_or("localhost"),
+ connection.get("port").and_then(Value::as_u64).unwrap_or(0)
+ )
+ }))
+ }
+ "connection/connect" => {
+ let connection =
+ params.get("connection").ok_or_else(|| PluginError::new(-32602, "Missing connection"))?;
+ let connection_id = connection
+ .get("id")
+ .and_then(Value::as_str)
+ .ok_or_else(|| PluginError::new(-32602, "Missing connection id"))?;
+ let connection_name = connection.get("name").and_then(Value::as_str).unwrap_or("Hello connection");
+ self.connections
+ .lock()
+ .map_err(|_| PluginError::new(-32000, "Connection registry is poisoned"))?
+ .insert(connection_id.to_string(), connection_name.to_string());
+ emitter
+ .event("hello/connectionChanged", json!({ "connectionId": connection_id, "state": "connected" }))?;
+ Ok(json!({ "success": true }))
+ }
+ "connection/disconnect" => {
+ let connection_id = params
+ .get("connection")
+ .and_then(|connection| connection.get("id"))
+ .and_then(Value::as_str)
+ .ok_or_else(|| PluginError::new(-32602, "Missing connection id"))?;
+ self.connections
+ .lock()
+ .map_err(|_| PluginError::new(-32000, "Connection registry is poisoned"))?
+ .remove(connection_id);
+ emitter.event(
+ "hello/connectionChanged",
+ json!({ "connectionId": connection_id, "state": "disconnected" }),
+ )?;
+ Ok(json!({ "success": true }))
+ }
+ "connection/action" => {
+ match params.get("action").and_then(|action| action.get("id")).and_then(Value::as_str) {
+ Some("suggest-greeting") => Ok(json!({
+ "success": true,
+ "message": "Greeting updated by the plugin action.",
+ "fieldValues": {
+ "greeting": "Hello from plugin action"
+ }
+ })),
+ Some(action_id) => Err(PluginError::new(-32602, format!("Unknown connection action: {action_id}"))),
+ None => Err(PluginError::new(-32602, "Missing connection action id")),
+ }
+ }
+ "hello/greet" => {
+ let connection_id = params.get("connectionId").and_then(Value::as_str).unwrap_or_default();
+ let connection_name = self
+ .connections
+ .lock()
+ .map_err(|_| PluginError::new(-32000, "Connection registry is poisoned"))?
+ .get(connection_id)
+ .cloned()
+ .ok_or_else(|| PluginError::new(-32010, "Open a saved Hello connection first"))?;
+ let name = params.get("name").and_then(Value::as_str).unwrap_or("DBX");
+ emitter.event(
+ "hello/progress",
+ json!({ "stage": "started", "name": name, "connectionId": connection_id }),
+ )?;
+ thread::sleep(Duration::from_millis(120));
+ emitter.event(
+ "hello/progress",
+ json!({ "stage": "finished", "name": name, "connectionId": connection_id }),
+ )?;
+ Ok(json!({
+ "message": format!("Hello, {name}, from {connection_name}!"),
+ "connectionId": connection_id,
+ "pluginId": std::env::var("DBX_PLUGIN_ID").unwrap_or_default(),
+ "dbxVersion": std::env::var("DBX_APP_VERSION").unwrap_or_default()
+ }))
+ }
+ "filesystem/list" => {
+ require_filesystem_provider(&params)?;
+ let uri = params.get("uri").and_then(Value::as_str).unwrap_or("hello:/");
+ let entries = match uri {
+ "hello:/" => json!([
+ {
+ "name": "examples",
+ "uri": "hello:/examples/",
+ "kind": "directory",
+ "modifiedAt": "2026-07-28T00:00:00Z"
+ },
+ {
+ "name": "README.txt",
+ "uri": "hello:/README.txt",
+ "kind": "file",
+ "size": 78,
+ "modifiedAt": "2026-07-28T00:00:00Z",
+ "contentType": "text/plain"
+ }
+ ]),
+ "hello:/examples/" => json!([
+ {
+ "name": "hello.json",
+ "uri": "hello:/examples/hello.json",
+ "kind": "file",
+ "size": 55,
+ "modifiedAt": "2026-07-28T00:00:00Z",
+ "contentType": "application/json"
+ }
+ ]),
+ _ => return Err(PluginError::new(-32044, format!("Directory not found: {uri}"))),
+ };
+ Ok(json!({ "entries": entries }))
+ }
+ "filesystem/read" => {
+ require_filesystem_provider(&params)?;
+ let uri = params.get("uri").and_then(Value::as_str).unwrap_or_default();
+ let content = match uri {
+ "hello:/README.txt" => "This virtual file is rendered by DBX's host-owned plugin file manager.\n",
+ "hello:/examples/hello.json" => "{\n \"hello\": \"DBX\",\n \"provider\": \"filesystem\"\n}\n",
+ _ => return Err(PluginError::new(-32044, format!("File not found: {uri}"))),
+ };
+ let max_bytes = params.get("maxBytes").and_then(Value::as_u64).unwrap_or(content.len() as u64);
+ let preview_length = usize::try_from(max_bytes).unwrap_or(usize::MAX).min(content.len());
+ let preview = &content.as_bytes()[..preview_length];
+ Ok(json!({
+ "dataBase64": encode_base64(preview),
+ "contentType": if uri.ends_with(".json") { "application/json" } else { "text/plain" },
+ "truncated": preview_length < content.len(),
+ "etag": format!("hello-{preview_length}")
+ }))
+ }
+ _ => Err(PluginError::method_not_found(method)),
+ }
+ }
+}
+
+fn require_filesystem_provider(params: &Value) -> Result<(), PluginError> {
+ if params.get("providerId").and_then(Value::as_str) == Some("dbx.example.hello.files") {
+ Ok(())
+ } else {
+ Err(PluginError::new(-32602, "Unknown filesystem provider"))
+ }
+}
+
+fn encode_base64(bytes: &[u8]) -> String {
+ const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ let mut encoded = String::with_capacity(bytes.len().div_ceil(3) * 4);
+ for chunk in bytes.chunks(3) {
+ let first = chunk[0];
+ let second = chunk.get(1).copied().unwrap_or(0);
+ let third = chunk.get(2).copied().unwrap_or(0);
+ encoded.push(ALPHABET[(first >> 2) as usize] as char);
+ encoded.push(ALPHABET[(((first & 0x03) << 4) | (second >> 4)) as usize] as char);
+ encoded.push(if chunk.len() > 1 {
+ ALPHABET[(((second & 0x0f) << 2) | (third >> 6)) as usize] as char
+ } else {
+ '='
+ });
+ encoded.push(if chunk.len() > 2 { ALPHABET[(third & 0x3f) as usize] as char } else { '=' });
+ }
+ encoded
+}
+
+fn main() -> std::io::Result<()> {
+ let metadata = PluginMetadata::new("dbx.example.hello", env!("CARGO_PKG_VERSION"))
+ .with_capability("connections")
+ .with_capability("events")
+ .with_capability("filesystem");
+ PluginServer::new(metadata, HelloPlugin::default()).serve()
+}
diff --git a/plugins/examples/hello-workbench/manifest.json b/plugins/examples/hello-workbench/manifest.json
new file mode 100644
index 0000000000..04c0402378
--- /dev/null
+++ b/plugins/examples/hello-workbench/manifest.json
@@ -0,0 +1,237 @@
+{
+ "$schema": "../../manifest.schema.json",
+ "manifest_version": 1,
+ "id": "dbx.example.hello",
+ "name": "DBX Hello Workbench",
+ "icon": "assets/plugin.svg",
+ "version": "1.0.0",
+ "publisher": "dbx",
+ "description": "A complete DBX plugin example with a native sidecar, events, workbench UI, connection provider, and virtual filesystem provider.",
+ "source": "https://github.com/t8y2/dbx",
+ "homepage": "https://github.com/t8y2/dbx/tree/main/plugins/examples/hello-workbench",
+ "engines": {
+ "dbx": ">=0.5.68",
+ "host_api": "^1.0"
+ },
+ "permissions": ["host.events", "host.filesystem"],
+ "entrypoints": {
+ "backend": {
+ "executable": "bin/dbx-example-hello"
+ },
+ "ui": {
+ "root": "ui",
+ "entry": "ui/index.html"
+ }
+ },
+ "contributions": [
+ {
+ "type": "connection-provider",
+ "id": "dbx.example.hello.connection",
+ "label": "Hello connection",
+ "icon": "assets/connection.svg",
+ "database_type": "hello",
+ "description": "Shows how a plugin can declare connection fields without adding DBX frontend branches.",
+ "fields": [
+ {
+ "key": "display_name",
+ "label": "Connection name",
+ "type": "text",
+ "default": "Hello connection",
+ "binding": "name",
+ "required": true
+ },
+ {
+ "key": "host",
+ "label": "Host",
+ "type": "text",
+ "default": "localhost",
+ "binding": "host",
+ "required": true
+ },
+ {
+ "key": "port",
+ "label": "Port",
+ "type": "number",
+ "default": 22,
+ "binding": "port",
+ "required": true
+ },
+ {
+ "key": "greeting",
+ "label": "Greeting",
+ "type": "text",
+ "default": "Hello",
+ "binding": "config"
+ },
+ {
+ "key": "api_token",
+ "label": "Example secret token",
+ "type": "password",
+ "binding": "secret",
+ "description": "Stored in DBX connection_secrets and never written into config_json."
+ }
+ ],
+ "workbench": "dbx.example.hello.main",
+ "filesystem_provider": "dbx.example.hello.files",
+ "capabilities": ["test", "connect", "disconnect"],
+ "actions": [
+ {
+ "id": "suggest-greeting",
+ "label": "Fill example greeting",
+ "description": "Calls the plugin sidecar before saving and writes the returned value back into the form.",
+ "variant": "outline",
+ "requires_valid_form": false
+ }
+ ]
+ },
+ {
+ "type": "workbench",
+ "id": "dbx.example.hello.main",
+ "label": "Hello Workbench",
+ "description": "A sandboxed plugin UI hosted in a normal DBX workbench tab."
+ },
+ {
+ "type": "filesystem-provider",
+ "id": "dbx.example.hello.files",
+ "label": "Hello virtual files",
+ "description": "A minimal read-only filesystem provider contract example.",
+ "schemes": ["hello"],
+ "root_uri": "hello:/",
+ "capabilities": ["read"]
+ }
+ ],
+ "localizations": {
+ "zh-CN": {
+ "name": "DBX Hello 工作台",
+ "description": "完整的 DBX 插件示例,包含原生 Sidecar、事件、工作台界面、连接提供者和虚拟文件系统提供者。",
+ "contributions": {
+ "dbx.example.hello.connection": {
+ "label": "Hello 连接",
+ "description": "演示插件如何声明连接字段,而无需在 DBX 前端增加专用分支。",
+ "fields": {
+ "display_name": { "label": "连接名称" },
+ "host": { "label": "主机" },
+ "port": { "label": "端口" },
+ "greeting": { "label": "问候语" },
+ "api_token": { "label": "示例密钥令牌", "description": "保存在 DBX connection_secrets 中,不会写入 config_json。" }
+ },
+ "actions": {
+ "suggest-greeting": { "label": "填入示例问候语", "description": "保存前调用插件 Sidecar,并把返回值回填到表单。" }
+ }
+ },
+ "dbx.example.hello.main": { "label": "Hello 工作台", "description": "托管在普通 DBX 工作台标签页中的沙箱插件界面。" },
+ "dbx.example.hello.files": { "label": "Hello 虚拟文件", "description": "最小化的只读文件系统提供者契约示例。" }
+ }
+ },
+ "zh-TW": {
+ "name": "DBX Hello 工作台",
+ "description": "完整的 DBX 外掛範例,包含原生 Sidecar、事件、工作台介面、連線提供者和虛擬檔案系統提供者。",
+ "contributions": {
+ "dbx.example.hello.connection": {
+ "label": "Hello 連線",
+ "description": "示範外掛如何宣告連線欄位,而不需要在 DBX 前端增加專用分支。",
+ "fields": {
+ "display_name": { "label": "連線名稱" },
+ "host": { "label": "主機" },
+ "port": { "label": "連接埠" },
+ "greeting": { "label": "問候語" },
+ "api_token": { "label": "範例密鑰權杖", "description": "儲存在 DBX connection_secrets 中,不會寫入 config_json。" }
+ },
+ "actions": {
+ "suggest-greeting": { "label": "填入範例問候語", "description": "儲存前呼叫外掛 Sidecar,並將回傳值填回表單。" }
+ }
+ },
+ "dbx.example.hello.main": { "label": "Hello 工作台", "description": "託管在一般 DBX 工作台分頁中的沙箱外掛介面。" },
+ "dbx.example.hello.files": { "label": "Hello 虛擬檔案", "description": "最小化的唯讀檔案系統提供者契約範例。" }
+ }
+ },
+ "ja": {
+ "name": "DBX Hello ワークベンチ",
+ "description": "ネイティブ Sidecar、イベント、ワークベンチ UI、接続プロバイダー、仮想ファイルシステムプロバイダーを含む完全な DBX プラグイン例です。",
+ "contributions": {
+ "dbx.example.hello.connection": {
+ "label": "Hello 接続",
+ "description": "DBX フロントエンドに専用分岐を追加せず、プラグインが接続フィールドを宣言する方法を示します。",
+ "fields": {
+ "display_name": { "label": "接続名" },
+ "host": { "label": "ホスト" },
+ "port": { "label": "ポート" },
+ "greeting": { "label": "あいさつ" },
+ "api_token": { "label": "サンプル秘密トークン", "description": "DBX connection_secrets に保存され、config_json には書き込まれません。" }
+ },
+ "actions": {
+ "suggest-greeting": { "label": "サンプルのあいさつを入力", "description": "保存前にプラグイン Sidecar を呼び出し、返された値をフォームへ反映します。" }
+ }
+ },
+ "dbx.example.hello.main": { "label": "Hello ワークベンチ", "description": "通常の DBX ワークベンチタブ内でホストされるサンドボックス化されたプラグイン UI です。" },
+ "dbx.example.hello.files": { "label": "Hello 仮想ファイル", "description": "最小限の読み取り専用ファイルシステムプロバイダー契約例です。" }
+ }
+ },
+ "es": {
+ "name": "Área de trabajo Hello de DBX",
+ "description": "Ejemplo completo de plugin de DBX con sidecar nativo, eventos, interfaz de trabajo, proveedor de conexión y proveedor de sistema de archivos virtual.",
+ "contributions": {
+ "dbx.example.hello.connection": {
+ "label": "Conexión Hello",
+ "description": "Muestra cómo un plugin declara campos de conexión sin añadir ramas específicas al frontend de DBX.",
+ "fields": {
+ "display_name": { "label": "Nombre de conexión" },
+ "host": { "label": "Host" },
+ "port": { "label": "Puerto" },
+ "greeting": { "label": "Saludo" },
+ "api_token": { "label": "Token secreto de ejemplo", "description": "Se guarda en DBX connection_secrets y nunca se escribe en config_json." }
+ },
+ "actions": {
+ "suggest-greeting": { "label": "Rellenar saludo de ejemplo", "description": "Invoca el sidecar antes de guardar y aplica el valor devuelto al formulario." }
+ }
+ },
+ "dbx.example.hello.main": { "label": "Área de trabajo Hello", "description": "Interfaz de plugin aislada alojada en una pestaña de trabajo normal de DBX." },
+ "dbx.example.hello.files": { "label": "Archivos virtuales Hello", "description": "Ejemplo mínimo de contrato de proveedor de sistema de archivos de solo lectura." }
+ }
+ },
+ "it": {
+ "name": "Area di lavoro Hello di DBX",
+ "description": "Esempio completo di plugin DBX con sidecar nativo, eventi, interfaccia di lavoro, provider di connessione e provider di file system virtuale.",
+ "contributions": {
+ "dbx.example.hello.connection": {
+ "label": "Connessione Hello",
+ "description": "Mostra come un plugin può dichiarare campi di connessione senza aggiungere rami dedicati al frontend DBX.",
+ "fields": {
+ "display_name": { "label": "Nome connessione" },
+ "host": { "label": "Host" },
+ "port": { "label": "Porta" },
+ "greeting": { "label": "Saluto" },
+ "api_token": { "label": "Token segreto di esempio", "description": "Salvato in DBX connection_secrets e mai scritto in config_json." }
+ },
+ "actions": {
+ "suggest-greeting": { "label": "Inserisci saluto di esempio", "description": "Invoca il sidecar prima del salvataggio e applica al modulo il valore restituito." }
+ }
+ },
+ "dbx.example.hello.main": { "label": "Area di lavoro Hello", "description": "Interfaccia plugin in sandbox ospitata in una normale scheda di lavoro DBX." },
+ "dbx.example.hello.files": { "label": "File virtuali Hello", "description": "Esempio minimo di contratto provider di file system in sola lettura." }
+ }
+ },
+ "pt-BR": {
+ "name": "Área de trabalho Hello do DBX",
+ "description": "Exemplo completo de plugin do DBX com sidecar nativo, eventos, interface de trabalho, provedor de conexão e provedor de sistema de arquivos virtual.",
+ "contributions": {
+ "dbx.example.hello.connection": {
+ "label": "Conexão Hello",
+ "description": "Mostra como um plugin declara campos de conexão sem adicionar ramificações específicas ao frontend do DBX.",
+ "fields": {
+ "display_name": { "label": "Nome da conexão" },
+ "host": { "label": "Host" },
+ "port": { "label": "Porta" },
+ "greeting": { "label": "Saudação" },
+ "api_token": { "label": "Token secreto de exemplo", "description": "Armazenado em DBX connection_secrets e nunca gravado em config_json." }
+ },
+ "actions": {
+ "suggest-greeting": { "label": "Preencher saudação de exemplo", "description": "Invoca o sidecar antes de salvar e aplica ao formulário o valor retornado." }
+ }
+ },
+ "dbx.example.hello.main": { "label": "Área de trabalho Hello", "description": "Interface de plugin em sandbox hospedada em uma aba normal de trabalho do DBX." },
+ "dbx.example.hello.files": { "label": "Arquivos virtuais Hello", "description": "Exemplo mínimo de contrato de provedor de sistema de arquivos somente leitura." }
+ }
+ }
+ }
+}
diff --git a/plugins/examples/hello-workbench/package.mjs b/plugins/examples/hello-workbench/package.mjs
new file mode 100644
index 0000000000..89a7a3a496
--- /dev/null
+++ b/plugins/examples/hello-workbench/package.mjs
@@ -0,0 +1,68 @@
+import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { spawnSync } from "node:child_process";
+import os from "node:os";
+import path from "node:path";
+import process from "node:process";
+import { fileURLToPath } from "node:url";
+
+const root = path.dirname(fileURLToPath(import.meta.url));
+const dist = process.env.DBX_PLUGIN_OUTPUT_DIR ? path.resolve(process.env.DBX_PLUGIN_OUTPUT_DIR) : path.join(root, "dist");
+const buildRoot = await mkdtemp(path.join(os.tmpdir(), "dbx-hello-package-"));
+const stage = path.join(buildRoot, "stage");
+const detectedTarget = platformTarget();
+const target = process.env.DBX_PLUGIN_TARGET || detectedTarget;
+if (target !== detectedTarget) throw new Error(`DBX_PLUGIN_TARGET ${target} does not match native build host ${detectedTarget}`);
+const executableName = process.platform === "win32" ? "dbx-example-hello.exe" : "dbx-example-hello";
+const backendTarget = path.join(buildRoot, "backend-target");
+const packagerTarget = path.join(buildRoot, "packager-target");
+const output = path.join(dist, `dbx.example.hello-1.0.0-${target}.dbxp`);
+const artifactMetadata = output.replace(/\.dbxp$/, ".artifact.json");
+
+if (process.env.DBX_PLUGIN_SIGNING_KEY || process.env.DBX_PLUGIN_SIGNING_KEY_ID) {
+ throw new Error("package.mjs only builds unsigned review candidates; use repository-sign.mjs after review");
+}
+
+try {
+ await mkdir(path.join(stage, "bin", target), { recursive: true });
+ await mkdir(dist, { recursive: true });
+ run("cargo", ["build", "--locked", "--release", "--manifest-path", path.join(root, "backend", "Cargo.toml")], { CARGO_TARGET_DIR: backendTarget });
+ await cp(path.join(backendTarget, "release", executableName), path.join(stage, "bin", target, executableName));
+ const manifest = JSON.parse(await readFile(path.join(root, "manifest.json"), "utf8"));
+ manifest.entrypoints.backend = { executable: `bin/${target}/${executableName}` };
+ await writeFile(path.join(stage, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
+ await cp(path.join(root, "assets"), path.join(stage, "assets"), { recursive: true });
+ await cp(path.join(root, "ui"), path.join(stage, "ui"), { recursive: true });
+
+ const packagerArgs = [
+ "run",
+ "--locked",
+ "--release",
+ "--manifest-path",
+ path.join(root, "..", "..", "sdk", "packager", "Cargo.toml"),
+ "--",
+ stage,
+ output,
+ "--artifact-metadata",
+ artifactMetadata,
+ "--target",
+ target,
+ "--artifact-url",
+ path.basename(output),
+ ];
+ run("cargo", packagerArgs, { CARGO_TARGET_DIR: packagerTarget });
+ console.log(`Built unsigned candidate ${output}`);
+} finally {
+ await rm(buildRoot, { recursive: true, force: true });
+}
+
+function run(command, args, extraEnv = {}) {
+ const result = spawnSync(command, args, { cwd: root, env: { ...process.env, ...extraEnv }, stdio: "inherit", shell: process.platform === "win32" });
+ if (result.status !== 0) process.exit(result.status ?? 1);
+}
+
+function platformTarget() {
+ const os = { darwin: "darwin", linux: "linux", win32: "windows" }[process.platform];
+ const arch = { arm64: "arm64", x64: "x64" }[process.arch];
+ if (!os || !arch) throw new Error(`Unsupported plugin target: ${process.platform}-${process.arch}`);
+ return `${os}-${arch}`;
+}
diff --git a/plugins/examples/hello-workbench/repository-sign.mjs b/plugins/examples/hello-workbench/repository-sign.mjs
new file mode 100644
index 0000000000..a822cf54c5
--- /dev/null
+++ b/plugins/examples/hello-workbench/repository-sign.mjs
@@ -0,0 +1,83 @@
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { spawnSync } from "node:child_process";
+import os from "node:os";
+import path from "node:path";
+import process from "node:process";
+import { fileURLToPath } from "node:url";
+
+const root = path.dirname(fileURLToPath(import.meta.url));
+const target = process.env.DBX_PLUGIN_TARGET || platformTarget();
+const candidate = path.resolve(process.argv[2] || path.join(root, "dist", `dbx.example.hello-1.0.0-${target}.dbxp`));
+const signed = path.resolve(
+ process.argv[3] || path.join(root, "dist", `dbx.example.hello-1.0.0-${target}.signed.dbxp`),
+);
+const metadata = signed.replace(/\.dbxp$/, ".artifact.json");
+const keyId = process.env.DBX_PLUGIN_SIGNING_KEY_ID;
+const buildRoot = await mkdtemp(path.join(os.tmpdir(), "dbx-repository-sign-"));
+
+if (!process.env.DBX_PLUGIN_SIGNING_KEY || !keyId) {
+ throw new Error("Repository signing requires DBX_PLUGIN_SIGNING_KEY and DBX_PLUGIN_SIGNING_KEY_ID");
+}
+
+try {
+ run(
+ "cargo",
+ [
+ "run",
+ "--locked",
+ "--release",
+ "--manifest-path",
+ path.join(root, "..", "..", "sdk", "packager", "Cargo.toml"),
+ "--",
+ "sign",
+ candidate,
+ signed,
+ "--key-id",
+ keyId,
+ "--artifact-metadata",
+ metadata,
+ "--target",
+ target,
+ "--artifact-url",
+ `../hello-workbench/dist/${path.basename(signed)}`,
+ ],
+ { CARGO_TARGET_DIR: path.join(buildRoot, "cargo-target") },
+ );
+
+ if (process.env.DBX_PLUGIN_SKIP_EXAMPLE_CATALOG !== "1") await updateExampleCatalog(metadata);
+ console.log(`Repository-signed ${signed}`);
+} finally {
+ await rm(buildRoot, { recursive: true, force: true });
+}
+
+function run(command, args, extraEnv = {}) {
+ const result = spawnSync(command, args, { cwd: root, env: { ...process.env, ...extraEnv }, stdio: "inherit", shell: process.platform === "win32" });
+ if (result.status !== 0) process.exit(result.status ?? 1);
+}
+
+function platformTarget() {
+ const os = { darwin: "darwin", linux: "linux", win32: "windows" }[process.platform];
+ const arch = { arm64: "arm64", x64: "x64" }[process.arch];
+ if (!os || !arch) throw new Error(`Unsupported plugin target: ${process.platform}-${process.arch}`);
+ return `${os}-${arch}`;
+}
+
+async function updateExampleCatalog(metadataPath) {
+ const manifest = JSON.parse(await readFile(path.join(root, "manifest.json"), "utf8"));
+ const artifact = JSON.parse(await readFile(metadataPath, "utf8"));
+ const catalogPath = path.join(root, "..", "marketplace", "catalog.example.json");
+ const catalog = JSON.parse(await readFile(catalogPath, "utf8"));
+ const plugin = catalog.plugins.find((entry) => entry.id === manifest.id);
+ const version = plugin?.versions.find((entry) => entry.version === manifest.version);
+ if (!version) throw new Error(`Example marketplace catalog is missing ${manifest.id} ${manifest.version}`);
+ plugin.name = manifest.name;
+ plugin.description = manifest.description || "";
+ plugin.publisher = manifest.publisher;
+ plugin.permissions = [...(manifest.permissions || [])];
+ plugin.latestVersion = manifest.version;
+ const existingIndex = version.artifacts.findIndex((entry) => entry.target === artifact.target);
+ if (existingIndex >= 0) version.artifacts[existingIndex] = artifact;
+ else version.artifacts.push(artifact);
+ version.artifacts.sort((left, right) => left.target.localeCompare(right.target));
+ await writeFile(catalogPath, `${JSON.stringify(catalog, null, 2)}\n`);
+}
diff --git a/plugins/examples/hello-workbench/repository-smoke.mjs b/plugins/examples/hello-workbench/repository-smoke.mjs
new file mode 100644
index 0000000000..357b63d28b
--- /dev/null
+++ b/plugins/examples/hello-workbench/repository-smoke.mjs
@@ -0,0 +1,79 @@
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import { spawnSync } from "node:child_process";
+import os from "node:os";
+import path from "node:path";
+import process from "node:process";
+import { fileURLToPath } from "node:url";
+
+const root = path.dirname(fileURLToPath(import.meta.url));
+const repositoryRoot = path.resolve(root, "..", "..", "..");
+const target = platformTarget();
+const temporary = await mkdtemp(path.join(os.tmpdir(), "dbx-plugin-repository-smoke-"));
+const candidateDirectory = path.join(temporary, "candidates");
+const candidate = path.join(candidateDirectory, `dbx.example.hello-1.0.0-${target}.dbxp`);
+const keyFile = path.join(temporary, "repository-key.env");
+const signed = path.join(temporary, `dbx.example.hello-1.0.0-${target}.signed.dbxp`);
+
+try {
+ run(process.execPath, [path.join(root, "package.mjs")], { DBX_PLUGIN_OUTPUT_DIR: candidateDirectory });
+ run(
+ "cargo",
+ [
+ "run",
+ "--quiet",
+ "--locked",
+ "--manifest-path",
+ path.join(repositoryRoot, "plugins", "sdk", "cli", "Cargo.toml"),
+ "--",
+ "keygen",
+ "example-repository-smoke",
+ "--output",
+ keyFile,
+ ],
+ { CARGO_TARGET_DIR: path.join(temporary, "cli-target") },
+ );
+ const signingEnvironment = await readEnvironmentFile(keyFile);
+ run(process.execPath, [path.join(root, "repository-sign.mjs"), candidate, signed], {
+ ...signingEnvironment,
+ DBX_PLUGIN_TARGET: target,
+ DBX_PLUGIN_SKIP_EXAMPLE_CATALOG: "1",
+ });
+ run(process.execPath, [path.join(root, "smoke.mjs"), signed], {
+ CARGO_TARGET_DIR: path.join(temporary, "core-target"),
+ DBX_PLUGIN_SMOKE_TRUSTED_KEYS_JSON: JSON.stringify({
+ [signingEnvironment.DBX_PLUGIN_SIGNING_KEY_ID]: signingEnvironment.DBX_PLUGIN_SIGNING_PUBLIC_KEY,
+ }),
+ });
+ console.log("Repository signing smoke passed: candidate -> repository signature -> trusted install -> lifecycle -> uninstall");
+} finally {
+ await rm(temporary, { recursive: true, force: true });
+}
+
+function run(command, args, extraEnv = {}) {
+ const result = spawnSync(command, args, {
+ cwd: repositoryRoot,
+ env: { ...process.env, ...extraEnv },
+ stdio: "inherit",
+ shell: process.platform === "win32",
+ });
+ if (result.status !== 0) process.exit(result.status ?? 1);
+}
+
+async function readEnvironmentFile(file) {
+ const environment = {};
+ for (const line of (await readFile(file, "utf8")).split(/\r?\n/)) {
+ const match = /^export ([A-Z0-9_]+)=(.*)$/.exec(line);
+ if (match) environment[match[1]] = match[2];
+ }
+ for (const name of ["DBX_PLUGIN_SIGNING_KEY", "DBX_PLUGIN_SIGNING_KEY_ID", "DBX_PLUGIN_SIGNING_PUBLIC_KEY"]) {
+ if (!environment[name]) throw new Error(`Generated repository key file is missing ${name}`);
+ }
+ return environment;
+}
+
+function platformTarget() {
+ const osName = { darwin: "darwin", linux: "linux", win32: "windows" }[process.platform];
+ const architecture = { arm64: "arm64", x64: "x64" }[process.arch];
+ if (!osName || !architecture) throw new Error(`Unsupported plugin target: ${process.platform}-${process.arch}`);
+ return `${osName}-${architecture}`;
+}
diff --git a/plugins/examples/hello-workbench/smoke.mjs b/plugins/examples/hello-workbench/smoke.mjs
new file mode 100644
index 0000000000..3d313a1226
--- /dev/null
+++ b/plugins/examples/hello-workbench/smoke.mjs
@@ -0,0 +1,37 @@
+import { mkdtemp, rm } from "node:fs/promises";
+import { spawnSync } from "node:child_process";
+import os from "node:os";
+import path from "node:path";
+import process from "node:process";
+import { fileURLToPath } from "node:url";
+
+const root = path.dirname(fileURLToPath(import.meta.url));
+const packagePath = process.argv[2] ? path.resolve(process.argv[2]) : path.join(root, "dist", `dbx.example.hello-1.0.0-${platformTarget()}.dbxp`);
+const ownedBuildRoot = process.env.CARGO_TARGET_DIR ? null : await mkdtemp(path.join(os.tmpdir(), "dbx-plugin-smoke-"));
+const cargoTarget = process.env.CARGO_TARGET_DIR || path.join(ownedBuildRoot, "cargo-target");
+
+try {
+ if (!process.argv[2]) run(process.execPath, [path.join(root, "package.mjs")]);
+ run("cargo", ["run", "--locked", "-p", "dbx-core", "--no-default-features", "--example", "plugin_package_smoke", "--", packagePath], {
+ CARGO_TARGET_DIR: cargoTarget,
+ });
+} finally {
+ if (ownedBuildRoot) await rm(ownedBuildRoot, { recursive: true, force: true });
+}
+
+function run(command, args, extraEnv = {}) {
+ const result = spawnSync(command, args, {
+ cwd: root,
+ env: { ...process.env, ...extraEnv },
+ stdio: "inherit",
+ shell: process.platform === "win32",
+ });
+ if (result.status !== 0) process.exit(result.status ?? 1);
+}
+
+function platformTarget() {
+ const os = { darwin: "darwin", linux: "linux", win32: "windows" }[process.platform];
+ const arch = { arm64: "arm64", x64: "x64" }[process.arch];
+ if (!os || !arch) throw new Error(`Unsupported plugin target: ${process.platform}-${process.arch}`);
+ return `${os}-${arch}`;
+}
diff --git a/plugins/examples/hello-workbench/ui/index.html b/plugins/examples/hello-workbench/ui/index.html
new file mode 100644
index 0000000000..df2bceb169
--- /dev/null
+++ b/plugins/examples/hello-workbench/ui/index.html
@@ -0,0 +1,327 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>DBX Hello Workbench</title>
+ <style>
+ :root {
+ color-scheme: light dark;
+ font-family: Inter, ui-sans-serif, system-ui, sans-serif;
+ }
+ * {
+ box-sizing: border-box;
+ }
+ body {
+ margin: 0;
+ min-height: 100vh;
+ background: #0b1020;
+ color: #e8ecf8;
+ }
+ main {
+ min-height: 100vh;
+ display: grid;
+ place-items: center;
+ padding: 32px;
+ background: radial-gradient(circle at 20% 10%, rgba(77, 124, 255, 0.28), transparent 34%), radial-gradient(circle at 90% 80%, rgba(25, 214, 166, 0.2), transparent 32%);
+ }
+ .card {
+ width: min(720px, 100%);
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 20px;
+ padding: 28px;
+ background: rgba(15, 22, 42, 0.86);
+ box-shadow: 0 24px 80px rgba(0, 0, 0, 0.35);
+ }
+ .eyebrow {
+ color: #7ee7cb;
+ font-size: 12px;
+ font-weight: 700;
+ letter-spacing: 0.14em;
+ text-transform: uppercase;
+ }
+ h1 {
+ margin: 10px 0 8px;
+ font-size: clamp(28px, 5vw, 46px);
+ line-height: 1.05;
+ }
+ p {
+ color: #aeb8d0;
+ line-height: 1.65;
+ }
+ .controls {
+ display: flex;
+ gap: 10px;
+ margin-top: 22px;
+ }
+ .secondary {
+ color: #dce5f8;
+ background: rgba(255, 255, 255, 0.08);
+ }
+ input,
+ button {
+ border-radius: 10px;
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ font: inherit;
+ }
+ input {
+ min-width: 0;
+ flex: 1;
+ padding: 11px 13px;
+ color: inherit;
+ background: rgba(255, 255, 255, 0.06);
+ outline: none;
+ }
+ button {
+ padding: 11px 16px;
+ color: #06101c;
+ background: #7ee7cb;
+ font-weight: 750;
+ cursor: pointer;
+ }
+ button:disabled {
+ opacity: 0.55;
+ cursor: wait;
+ }
+ .result {
+ margin-top: 18px;
+ min-height: 74px;
+ padding: 14px;
+ border-radius: 12px;
+ background: rgba(255, 255, 255, 0.05);
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 13px;
+ white-space: pre-wrap;
+ }
+ .meta {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
+ gap: 10px;
+ margin-top: 18px;
+ }
+ .meta div {
+ padding: 12px;
+ border-radius: 12px;
+ background: rgba(255, 255, 255, 0.04);
+ }
+ .meta span {
+ display: block;
+ color: #8290ad;
+ font-size: 11px;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ }
+ .meta strong {
+ display: block;
+ margin-top: 5px;
+ overflow-wrap: anywhere;
+ }
+ </style>
+ </head>
+ <body>
+ <main>
+ <section class="card">
+ <div id="eyebrow" class="eyebrow">Sandboxed DBX plugin</div>
+ <h1 id="title-copy">Sidecar + UI, end to end.</h1>
+ <p id="description">This page cannot access Tauri or the filesystem directly. It talks only to the DBX Host Bridge, which binds every request to this plugin.</p>
+ <div class="controls">
+ <input id="name" value="DBX" aria-label="Name" />
+ <button id="greet">Invoke sidecar</button>
+ <button id="files" class="secondary">Open host files</button>
+ </div>
+ <div id="result" class="result">Waiting for the plugin host…</div>
+ <div class="meta">
+ <div><span id="plugin-label">Plugin</span><strong id="plugin">-</strong></div>
+ <div><span id="workbench-label">Workbench</span><strong id="workbench">-</strong></div>
+ <div><span id="connection-label">Connection</span><strong id="connection">-</strong></div>
+ <div><span id="event-label">Last event</span><strong id="event">-</strong></div>
+ </div>
+ </section>
+ </main>
+ <script>
+ const translations = {
+ en: {
+ eyebrow: "Sandboxed DBX plugin",
+ title: "Sidecar + UI, end to end.",
+ description: "This page cannot access Tauri or the filesystem directly. It talks only to the DBX Host Bridge, which binds every request to this plugin.",
+ name: "Name",
+ invoke: "Invoke sidecar",
+ files: "Open host files",
+ waiting: "Waiting for the plugin host…",
+ plugin: "Plugin",
+ workbench: "Workbench",
+ connection: "Connection",
+ lastEvent: "Last event",
+ noConnection: "No saved connection",
+ ready: "Ready. Click the button to invoke hello/greet.",
+ openSaved: "Open this workbench from a saved Hello connection.",
+ calling: "Calling native sidecar…",
+ error: "Error",
+ },
+ "zh-CN": {
+ eyebrow: "受沙箱保护的 DBX 插件",
+ title: "Sidecar 与界面完整联动。",
+ description: "此页面不能直接访问 Tauri 或文件系统,只能通过 DBX Host Bridge 通信;宿主会把每个请求绑定到当前插件。",
+ name: "名称",
+ invoke: "调用 Sidecar",
+ files: "打开宿主文件浏览器",
+ waiting: "正在等待插件宿主…",
+ plugin: "插件",
+ workbench: "工作台",
+ connection: "连接",
+ lastEvent: "最近事件",
+ noConnection: "未保存连接",
+ ready: "已就绪。点击按钮调用 hello/greet。",
+ openSaved: "请从已保存的 Hello 连接打开此工作台。",
+ calling: "正在调用原生 Sidecar…",
+ error: "错误",
+ },
+ "zh-TW": {
+ eyebrow: "受沙箱保護的 DBX 外掛",
+ title: "Sidecar 與介面完整串接。",
+ description: "此頁面無法直接存取 Tauri 或檔案系統,只能透過 DBX Host Bridge 通訊;主程式會將每個請求綁定到目前外掛。",
+ name: "名稱",
+ invoke: "呼叫 Sidecar",
+ files: "開啟主程式檔案瀏覽器",
+ waiting: "正在等待外掛主程式…",
+ plugin: "外掛",
+ workbench: "工作台",
+ connection: "連線",
+ lastEvent: "最近事件",
+ noConnection: "尚未儲存連線",
+ ready: "已就緒。按一下按鈕呼叫 hello/greet。",
+ openSaved: "請從已儲存的 Hello 連線開啟此工作台。",
+ calling: "正在呼叫原生 Sidecar…",
+ error: "錯誤",
+ },
+ ja: {
+ eyebrow: "サンドボックス化された DBX プラグイン",
+ title: "Sidecar と UI をエンドツーエンドで連携。",
+ description: "このページは Tauri やファイルシステムへ直接アクセスできません。各リクエストを現在のプラグインに関連付ける DBX Host Bridge のみを使用します。",
+ name: "名前",
+ invoke: "Sidecar を呼び出す",
+ files: "ホストのファイルを開く",
+ waiting: "プラグインホストを待機中…",
+ plugin: "プラグイン",
+ workbench: "ワークベンチ",
+ connection: "接続",
+ lastEvent: "最新イベント",
+ noConnection: "保存済み接続なし",
+ ready: "準備完了。ボタンをクリックして hello/greet を呼び出します。",
+ openSaved: "保存済みの Hello 接続からこのワークベンチを開いてください。",
+ calling: "ネイティブ Sidecar を呼び出し中…",
+ error: "エラー",
+ },
+ es: {
+ eyebrow: "Plugin de DBX aislado",
+ title: "Sidecar e interfaz, de extremo a extremo.",
+ description: "Esta página no puede acceder directamente a Tauri ni al sistema de archivos. Solo se comunica con DBX Host Bridge, que vincula cada solicitud a este plugin.",
+ name: "Nombre",
+ invoke: "Invocar sidecar",
+ files: "Abrir archivos del host",
+ waiting: "Esperando al host del plugin…",
+ plugin: "Plugin",
+ workbench: "Área de trabajo",
+ connection: "Conexión",
+ lastEvent: "Último evento",
+ noConnection: "Sin conexión guardada",
+ ready: "Listo. Haz clic en el botón para invocar hello/greet.",
+ openSaved: "Abre esta área de trabajo desde una conexión Hello guardada.",
+ calling: "Invocando el sidecar nativo…",
+ error: "Error",
+ },
+ it: {
+ eyebrow: "Plugin DBX in sandbox",
+ title: "Sidecar e interfaccia, end-to-end.",
+ description: "Questa pagina non può accedere direttamente a Tauri o al file system. Comunica solo con DBX Host Bridge, che associa ogni richiesta a questo plugin.",
+ name: "Nome",
+ invoke: "Invoca sidecar",
+ files: "Apri file dell'host",
+ waiting: "In attesa dell'host del plugin…",
+ plugin: "Plugin",
+ workbench: "Area di lavoro",
+ connection: "Connessione",
+ lastEvent: "Ultimo evento",
+ noConnection: "Nessuna connessione salvata",
+ ready: "Pronto. Fai clic sul pulsante per invocare hello/greet.",
+ openSaved: "Apri quest'area di lavoro da una connessione Hello salvata.",
+ calling: "Chiamata del sidecar nativo…",
+ error: "Errore",
+ },
+ "pt-BR": {
+ eyebrow: "Plugin DBX em sandbox",
+ title: "Sidecar e interface, de ponta a ponta.",
+ description: "Esta página não pode acessar diretamente o Tauri nem o sistema de arquivos. Ela se comunica apenas com o DBX Host Bridge, que vincula cada solicitação a este plugin.",
+ name: "Nome",
+ invoke: "Invocar sidecar",
+ files: "Abrir arquivos do host",
+ waiting: "Aguardando o host do plugin…",
+ plugin: "Plugin",
+ workbench: "Área de trabalho",
+ connection: "Conexão",
+ lastEvent: "Último evento",
+ noConnection: "Nenhuma conexão salva",
+ ready: "Pronto. Clique no botão para invocar hello/greet.",
+ openSaved: "Abra esta área de trabalho a partir de uma conexão Hello salva.",
+ calling: "Invocando o sidecar nativo…",
+ error: "Erro",
+ },
+ };
+ const result = document.querySelector("#result");
+ const button = document.querySelector("#greet");
+ const input = document.querySelector("#name");
+ const files = document.querySelector("#files");
+ let connectionId = "";
+ let copy = translations.en;
+
+ function applyLocale(locale) {
+ copy = translations[locale] || translations.en;
+ document.documentElement.lang = locale || "en";
+ document.querySelector("#eyebrow").textContent = copy.eyebrow;
+ document.querySelector("#title-copy").textContent = copy.title;
+ document.querySelector("#description").textContent = copy.description;
+ input.setAttribute("aria-label", copy.name);
+ button.textContent = copy.invoke;
+ files.textContent = copy.files;
+ document.querySelector("#plugin-label").textContent = copy.plugin;
+ document.querySelector("#workbench-label").textContent = copy.workbench;
+ document.querySelector("#connection-label").textContent = copy.connection;
+ document.querySelector("#event-label").textContent = copy.lastEvent;
+ }
+
+ window.dbxPlugin.onEvent((event) => {
+ document.querySelector("#event").textContent = `${event.method}: ${JSON.stringify(event.params)}`;
+ });
+ window.dbxPlugin.ready.then((context) => {
+ applyLocale(window.dbxPlugin.locale);
+ document.querySelector("#plugin").textContent = "dbx.example.hello";
+ document.querySelector("#workbench").textContent = "dbx.example.hello.main";
+ connectionId = context?.connectionId || "";
+ document.querySelector("#connection").textContent = connectionId || copy.noConnection;
+ result.textContent = connectionId ? copy.ready : copy.openSaved;
+ });
+ button.addEventListener("click", async () => {
+ button.disabled = true;
+ result.textContent = copy.calling;
+ try {
+ const response = await window.dbxPlugin.invoke("hello/greet", { name: input.value, connectionId }, { timeoutMs: 5000 });
+ result.textContent = JSON.stringify(response, null, 2);
+ } catch (error) {
+ result.textContent = `${copy.error}: ${error.message}`;
+ } finally {
+ button.disabled = false;
+ }
+ });
+ files.addEventListener("click", async () => {
+ files.disabled = true;
+ try {
+ await window.dbxPlugin.openFilesystem("dbx.example.hello.files", { connectionId });
+ } catch (error) {
+ result.textContent = `${copy.error}: ${error.message}`;
+ } finally {
+ files.disabled = false;
+ }
+ });
+ </script>
+ </body>
+</html>
diff --git a/plugins/examples/marketplace/README.md b/plugins/examples/marketplace/README.md
new file mode 100644
index 0000000000..c9b8ed0358
--- /dev/null
+++ b/plugins/examples/marketplace/README.md
@@ -0,0 +1,21 @@
+# Example marketplace catalog
+
+`catalog.example.json` demonstrates the catalog v1 shape. Its checked-in artifact fields are a schema fixture; build an unsigned `hello-workbench` candidate and then run the custom repository signing example to refresh them before using this catalog for an actual Marketplace install.
+
+Serve the `plugins/examples` directory:
+
+```bash
+python3 -m http.server 8765 --directory plugins/examples
+```
+
+Then add this custom repository in Plugin Center → Settings:
+
+```text
+ID: example-marketplace
+Name: DBX Example Marketplace
+Catalog URL: http://127.0.0.1:8765/marketplace/catalog.example.json
+```
+
+The checked-in catalog demonstrates the repository-signed artifact shape, including `signingKeyId`. `node plugins/examples/hello-workbench/package.mjs` always builds an unsigned candidate and does not rewrite the catalog. A custom repository operator then runs `node plugins/examples/hello-workbench/repository-sign.mjs`, which signs the reviewed candidate and refreshes the catalog entry. Add the matching repository public key under Custom repository trust before installing. For a quick unsigned install, use Settings → Install `.dbxp` and explicitly enable the development-package toggle.
+
+Do not reuse an example signing seed for production. Real repositories publish `.dbxp` binaries to release storage and keep only metadata, URLs, SHA-256 values, and review records in the catalog repository.
diff --git a/plugins/examples/marketplace/catalog.example.json b/plugins/examples/marketplace/catalog.example.json
new file mode 100644
index 0000000000..75cdea44f7
--- /dev/null
+++ b/plugins/examples/marketplace/catalog.example.json
@@ -0,0 +1,75 @@
+{
+ "$schema": "../../marketplace.schema.json",
+ "catalogVersion": 1,
+ "repository": {
+ "id": "example-marketplace",
+ "name": "DBX Example Marketplace",
+ "homepage": "https://plugins.example.com"
+ },
+ "generatedAt": "2026-07-28T00:00:00Z",
+ "plugins": [
+ {
+ "id": "dbx.example.hello",
+ "name": "DBX Hello Workbench",
+ "description": "Complete DBX plugin example with a native sidecar, saved connection provider, workbench UI, and virtual filesystem provider.",
+ "publisher": "dbx",
+ "verified": false,
+ "icon": "../hello-workbench/assets/plugin.svg",
+ "tags": [
+ "workbench",
+ "connection-provider",
+ "filesystem-provider"
+ ],
+ "permissions": [
+ "host.events",
+ "host.filesystem"
+ ],
+ "source": "https://github.com/t8y2/dbx",
+ "homepage": "https://github.com/t8y2/dbx/tree/main/plugins/examples/hello-workbench",
+ "license": "Apache-2.0",
+ "latestVersion": "1.0.0",
+ "versions": [
+ {
+ "version": "1.0.0",
+ "releasedAt": "2026-07-28T00:00:00Z",
+ "releaseNotes": "Initial end-to-end plugin platform example.",
+ "artifacts": [
+ {
+ "target": "darwin-arm64",
+ "url": "../hello-workbench/dist/dbx.example.hello-1.0.0-darwin-arm64.dbxp",
+ "sha256": "98261c584716ad4c55f9daffcebbde2849214167ec8a722e646c6786632f2f96",
+ "signingKeyId": "dbx-store-preview-2026",
+ "size": 329815
+ }
+ ]
+ }
+ ],
+ "localizations": {
+ "zh-CN": {
+ "name": "DBX Hello 工作台",
+ "description": "包含原生 Sidecar、可保存连接、工作台 UI 和虚拟文件系统的完整 DBX 插件示例。"
+ },
+ "zh-TW": {
+ "name": "DBX Hello 工作台",
+ "description": "包含原生 Sidecar、可儲存連線、工作台 UI 與虛擬檔案系統的完整 DBX 外掛範例。"
+ },
+ "ja": {
+ "name": "DBX Hello ワークベンチ",
+ "description": "ネイティブ Sidecar、保存可能な接続、ワークベンチ UI、仮想ファイルシステムを含む完全な DBX プラグイン例です。"
+ },
+ "es": {
+ "name": "Área de trabajo Hello de DBX",
+ "description": "Ejemplo completo con sidecar nativo, conexión guardada, interfaz de trabajo y sistema de archivos virtual."
+ },
+ "it": {
+ "name": "Area di lavoro Hello di DBX",
+ "description": "Esempio completo con sidecar nativo, connessione salvata, UI di lavoro e file system virtuale."
+ },
+ "pt-BR": {
+ "name": "Área de trabalho Hello do DBX",
+ "description": "Exemplo completo com sidecar nativo, conexão salva, interface de trabalho e sistema de arquivos virtual."
+ }
+ }
+ }
+ ]
+}
diff --git a/plugins/manifest.schema.json b/plugins/manifest.schema.json
new file mode 100644
index 0000000000..17a33bb95a
--- /dev/null
+++ b/plugins/manifest.schema.json
@@ -0,0 +1,271 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://dbx.local/schemas/plugin-manifest-v1.json",
+ "title": "DBX Plugin Manifest v1",
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["manifest_version", "id", "name", "version", "publisher", "engines"],
+ "properties": {
+ "$schema": { "type": "string" },
+ "manifest_version": { "const": 1 },
+ "id": { "$ref": "#/$defs/identifier" },
+ "name": { "type": "string", "minLength": 1 },
+ "icon": { "$ref": "#/$defs/assetPath" },
+ "version": { "type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$" },
+ "publisher": { "type": "string", "minLength": 1 },
+ "description": { "type": "string" },
+ "source": { "type": "string", "pattern": "^https?://[^\\s]+$" },
+ "homepage": { "type": "string", "pattern": "^https?://[^\\s]+$" },
+ "engines": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["host_api"],
+ "properties": {
+ "dbx": { "type": "string" },
+ "host_api": { "type": "string", "minLength": 1 }
+ }
+ },
+ "permissions": {
+ "type": "array",
+ "uniqueItems": true,
+ "items": {
+ "anyOf": [
+ { "enum": ["host.events", "host.binary", "host.workbench", "host.filesystem"] },
+ { "type": "string", "pattern": "^host\\.network:https://[A-Za-z0-9._-]+(:[0-9]+)?$" }
+ ]
+ }
+ },
+ "entrypoints": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "backend": { "$ref": "#/$defs/backendEntrypoint" },
+ "ui": { "$ref": "#/$defs/uiEntrypoint" }
+ }
+ },
+ "contributions": {
+ "type": "array",
+ "items": {
+ "oneOf": [{ "$ref": "#/$defs/connectionProviderContribution" }, { "$ref": "#/$defs/workbenchContribution" }, { "$ref": "#/$defs/filesystemProviderContribution" }, { "$ref": "#/$defs/contextMenuContribution" }, { "$ref": "#/$defs/resultViewContribution" }]
+ }
+ },
+ "localizations": {
+ "type": "object",
+ "propertyNames": { "pattern": "^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$" },
+ "additionalProperties": { "$ref": "#/$defs/manifestLocalization" }
+ }
+ },
+ "$defs": {
+ "identifier": {
+ "type": "string",
+ "maxLength": 128,
+ "pattern": "^[a-z0-9][a-z0-9._-]*$"
+ },
+ "capability": {
+ "type": "string",
+ "maxLength": 256,
+ "pattern": "^[a-z0-9][a-z0-9._:-]*$"
+ },
+ "assetPath": {
+ "type": "string",
+ "minLength": 1,
+ "pattern": "^(?!/)(?!.*\\\\)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*//).+$"
+ },
+ "backendEntrypoint": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["executable"],
+ "properties": {
+ "protocol_versions": {
+ "type": "array",
+ "minItems": 1,
+ "uniqueItems": true,
+ "items": { "type": "integer", "minimum": 1 }
+ },
+ "transport": { "enum": ["stdio-jsonl", "stdio-framed"] },
+ "executable": { "$ref": "#/$defs/assetPath" }
+ }
+ },
+ "uiEntrypoint": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["entry"],
+ "properties": {
+ "root": { "type": "string", "minLength": 1 },
+ "entry": { "type": "string", "minLength": 1 }
+ }
+ },
+ "selectOption": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["label", "value"],
+ "properties": {
+ "label": { "type": "string", "minLength": 1 },
+ "value": { "type": "string" }
+ }
+ },
+ "formFieldLocalization": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "label": { "type": "string", "minLength": 1 },
+ "description": { "type": "string" },
+ "placeholder": { "type": "string" },
+ "options": { "type": "object", "propertyNames": { "minLength": 1 }, "additionalProperties": { "type": "string", "minLength": 1 } }
+ }
+ },
+ "actionLocalization": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "label": { "type": "string", "minLength": 1 },
+ "description": { "type": "string" }
+ }
+ },
+ "contributionLocalization": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "label": { "type": "string", "minLength": 1 },
+ "description": { "type": "string" },
+ "fields": { "type": "object", "propertyNames": { "$ref": "#/$defs/identifier" }, "additionalProperties": { "$ref": "#/$defs/formFieldLocalization" } },
+ "actions": { "type": "object", "propertyNames": { "$ref": "#/$defs/identifier" }, "additionalProperties": { "$ref": "#/$defs/actionLocalization" } }
+ }
+ },
+ "manifestLocalization": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "name": { "type": "string", "minLength": 1 },
+ "description": { "type": "string" },
+ "contributions": { "type": "object", "propertyNames": { "$ref": "#/$defs/identifier" }, "additionalProperties": { "$ref": "#/$defs/contributionLocalization" } }
+ }
+ },
+ "formField": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["key", "label", "type"],
+ "properties": {
+ "key": { "$ref": "#/$defs/identifier" },
+ "label": { "type": "string", "minLength": 1 },
+ "type": { "enum": ["text", "password", "number", "boolean", "select", "radio", "textarea"] },
+ "description": { "type": ["string", "null"] },
+ "placeholder": { "type": ["string", "null"] },
+ "required": { "type": "boolean" },
+ "default": { "type": ["string", "number", "boolean", "null"] },
+ "options": { "type": "array", "items": { "$ref": "#/$defs/selectOption" } },
+ "binding": { "enum": ["config", "secret", "name", "host", "port", "username", "password", "database"] }
+ },
+ "allOf": [
+ {
+ "if": { "properties": { "type": { "enum": ["select", "radio"] } }, "required": ["type"] },
+ "then": { "required": ["options"], "properties": { "options": { "minItems": 1 } } },
+ "else": { "not": { "required": ["options"] } }
+ },
+ {
+ "if": { "properties": { "binding": { "const": "port" } }, "required": ["binding"] },
+ "then": { "properties": { "type": { "const": "number" } } }
+ },
+ {
+ "if": {
+ "properties": { "binding": { "enum": ["secret", "name", "host", "username", "password", "database"] } },
+ "required": ["binding"]
+ },
+ "then": { "properties": { "type": { "enum": ["text", "password", "select", "radio", "textarea"] } } }
+ }
+ ]
+ },
+ "connectionProviderContribution": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["type", "id", "database_type", "fields"],
+ "properties": {
+ "type": { "const": "connection-provider" },
+ "id": { "$ref": "#/$defs/identifier" },
+ "label": { "type": "string", "minLength": 1 },
+ "icon": { "$ref": "#/$defs/assetPath" },
+ "database_type": { "$ref": "#/$defs/identifier" },
+ "description": { "type": "string" },
+ "fields": { "type": "array", "items": { "$ref": "#/$defs/formField" } },
+ "workbench": { "$ref": "#/$defs/identifier" },
+ "filesystem_provider": { "$ref": "#/$defs/identifier" },
+ "capabilities": {
+ "type": "array",
+ "uniqueItems": true,
+ "items": { "enum": ["test", "connect", "disconnect"] }
+ },
+ "actions": { "type": "array", "items": { "$ref": "#/$defs/connectionAction" } }
+ }
+ },
+ "connectionAction": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["id", "label"],
+ "properties": {
+ "id": { "$ref": "#/$defs/identifier" },
+ "label": { "type": "string", "minLength": 1 },
+ "description": { "type": "string" },
+ "variant": { "enum": ["default", "outline", "secondary", "destructive", "ghost"] },
+ "when": { "enum": ["always", "create", "edit"] },
+ "close_on_success": { "type": "boolean" },
+ "requires_valid_form": { "type": "boolean" },
+ "timeout_ms": { "type": "integer", "minimum": 1, "maximum": 120000 }
+ }
+ },
+ "workbenchContribution": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["type", "id", "label"],
+ "properties": {
+ "type": { "const": "workbench" },
+ "id": { "$ref": "#/$defs/identifier" },
+ "label": { "type": "string", "minLength": 1 },
+ "description": { "type": "string" },
+ "icon": { "$ref": "#/$defs/assetPath" }
+ }
+ },
+ "contextMenuContribution": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["type", "id", "label", "menu"],
+ "properties": {
+ "type": { "const": "context-menu" },
+ "id": { "$ref": "#/$defs/identifier" },
+ "label": { "type": "string", "minLength": 1 },
+ "description": { "type": "string" },
+ "icon": { "$ref": "#/$defs/assetPath" },
+ "menu": { "const": "connection" }
+ }
+ },
+ "resultViewContribution": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["type", "id", "label"],
+ "properties": {
+ "type": { "const": "result-view" },
+ "id": { "$ref": "#/$defs/identifier" },
+ "label": { "type": "string", "minLength": 1 },
+ "description": { "type": "string" },
+ "icon": { "$ref": "#/$defs/assetPath" }
+ }
+ },
+ "filesystemProviderContribution": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["type", "id", "label", "schemes"],
+ "properties": {
+ "type": { "const": "filesystem-provider" },
+ "id": { "$ref": "#/$defs/identifier" },
+ "label": { "type": "string", "minLength": 1 },
+ "description": { "type": "string" },
+ "schemes": { "type": "array", "minItems": 1, "uniqueItems": true, "items": { "$ref": "#/$defs/capability" } },
+ "root_uri": { "type": "string", "minLength": 2, "maxLength": 4096, "pattern": "^[a-z0-9._-]+:.+$" },
+ "capabilities": {
+ "type": "array",
+ "uniqueItems": true,
+ "items": { "enum": ["read", "write", "delete", "rename", "mkdir"] }
+ }
+ }
+ }
+ }
+}
diff --git a/plugins/marketplace.schema.json b/plugins/marketplace.schema.json
new file mode 100644
index 0000000000..faa04fb87d
--- /dev/null
+++ b/plugins/marketplace.schema.json
@@ -0,0 +1,115 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://dbx.example/schemas/plugin-marketplace-v1.json",
+ "title": "DBX Plugin Marketplace Catalog",
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["catalogVersion", "repository", "plugins"],
+ "properties": {
+ "$schema": { "type": "string" },
+ "catalogVersion": { "const": 1 },
+ "repository": { "$ref": "#/$defs/repository" },
+ "generatedAt": { "type": "string", "format": "date-time" },
+ "plugins": {
+ "type": "array",
+ "items": { "$ref": "#/$defs/plugin" }
+ }
+ },
+ "$defs": {
+ "identifier": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "pattern": "^[a-z0-9][a-z0-9._-]*$"
+ },
+ "repository": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["id", "name"],
+ "properties": {
+ "id": { "$ref": "#/$defs/identifier" },
+ "name": { "type": "string", "minLength": 1, "maxLength": 128 },
+ "homepage": { "type": "string", "format": "uri" }
+ }
+ },
+ "localization": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "name": { "type": "string", "minLength": 1 },
+ "description": { "type": "string" }
+ }
+ },
+ "artifact": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["target", "url", "sha256", "signingKeyId"],
+ "properties": {
+ "target": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 64,
+ "pattern": "^[a-z0-9-]+$",
+ "description": "DBX runtime target such as darwin-arm64, windows-x64, or linux-x64. Use universal only when the same package is valid on every supported target; exact target artifacts take precedence."
+ },
+ "url": { "type": "string", "format": "uri-reference" },
+ "sha256": { "type": "string", "pattern": "^[A-Fa-f0-9]{64}$" },
+ "signingKeyId": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "pattern": "^[A-Za-z0-9._:-]+$"
+ },
+ "size": { "type": "integer", "minimum": 0, "maximum": 536870912 }
+ }
+ },
+ "version": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["version", "artifacts"],
+ "properties": {
+ "version": {
+ "type": "string",
+ "pattern": "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$"
+ },
+ "releasedAt": { "type": "string", "format": "date-time" },
+ "releaseNotes": { "type": "string" },
+ "artifacts": {
+ "type": "array",
+ "items": { "$ref": "#/$defs/artifact" }
+ }
+ }
+ },
+ "plugin": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["id", "name", "publisher", "latestVersion", "versions"],
+ "properties": {
+ "id": { "$ref": "#/$defs/identifier" },
+ "name": { "type": "string", "minLength": 1 },
+ "description": { "type": "string" },
+ "publisher": { "type": "string", "minLength": 1 },
+ "verified": { "type": "boolean", "default": false },
+ "icon": { "type": "string", "format": "uri-reference" },
+ "tags": { "type": "array", "items": { "type": "string", "minLength": 1 }, "uniqueItems": true },
+ "permissions": { "type": "array", "items": { "type": "string", "minLength": 1 }, "uniqueItems": true },
+ "source": { "type": "string", "format": "uri" },
+ "homepage": { "type": "string", "format": "uri" },
+ "license": { "type": "string", "minLength": 1 },
+ "latestVersion": {
+ "type": "string",
+ "pattern": "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$"
+ },
+ "versions": {
+ "type": "array",
+ "minItems": 1,
+ "items": { "$ref": "#/$defs/version" }
+ },
+ "localizations": {
+ "type": "object",
+ "additionalProperties": { "$ref": "#/$defs/localization" }
+ }
+ }
+ }
+ }
+}
diff --git a/plugins/sdk/cli/.gitignore b/plugins/sdk/cli/.gitignore
new file mode 100644
index 0000000000..b83d22266a
--- /dev/null
+++ b/plugins/sdk/cli/.gitignore
@@ -0,0 +1 @@
+/target/
diff --git a/plugins/sdk/cli/Cargo.lock b/plugins/sdk/cli/Cargo.lock
new file mode 100644
index 0000000000..8879f64f7b
--- /dev/null
+++ b/plugins/sdk/cli/Cargo.lock
@@ -0,0 +1,692 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "adler2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+
+[[package]]
+name = "arbitrary"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
+dependencies = [
+ "derive_arbitrary",
+]
+
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
+[[package]]
+name = "base64ct"
+version = "1.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
+
+[[package]]
+name = "bitflags"
+version = "2.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "bumpalo"
+version = "3.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "const-oid"
+version = "0.9.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crc32fast"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "curve25519-dalek-derive",
+ "digest",
+ "fiat-crypto",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "curve25519-dalek-derive"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "dbx-plugin-cli"
+version = "0.1.1"
+dependencies = [
+ "dbx-plugin-packager",
+ "semver",
+ "serde",
+ "serde_json",
+ "tempfile",
+ "toml",
+]
+
+[[package]]
+name = "dbx-plugin-packager"
+version = "0.1.0"
+dependencies = [
+ "base64",
+ "ed25519-dalek",
+ "getrandom 0.4.3",
+ "serde_json",
+ "sha2",
+ "walkdir",
+ "zip",
+]
+
+[[package]]
+name = "der"
+version = "0.7.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
+dependencies = [
+ "const-oid",
+ "zeroize",
+]
+
+[[package]]
+name = "derive_arbitrary"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+]
+
+[[package]]
+name = "ed25519"
+version = "2.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
+dependencies = [
+ "pkcs8",
+ "signature",
+]
+
+[[package]]
+name = "ed25519-dalek"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
+dependencies = [
+ "curve25519-dalek",
+ "ed25519",
+ "serde",
+ "sha2",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
+[[package]]
+name = "fastrand"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
+
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
+[[package]]
+name = "flate2"
+version = "1.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
+dependencies = [
+ "miniz_oxide",
+ "zlib-rs",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "indexmap"
+version = "2.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "libc"
+version = "0.2.189"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "log"
+version = "0.4.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "miniz_oxide"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "pkcs8"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
+dependencies = [
+ "der",
+ "spki",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+dependencies = [
+ "getrandom 0.2.17",
+]
+
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "rustix"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys",
+]
+
+[[package]]
+name = "same-file"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
+dependencies = [
+ "indexmap",
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_spanned"
+version = "0.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "signature"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
+dependencies = [
+ "rand_core",
+]
+
+[[package]]
+name = "simd-adler32"
+version = "0.3.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+
+[[package]]
+name = "spki"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
+dependencies = [
+ "base64ct",
+ "der",
+]
+
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
+dependencies = [
+ "fastrand",
+ "getrandom 0.4.3",
+ "once_cell",
+ "rustix",
+ "windows-sys",
+]
+
+[[package]]
+name = "toml"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
+dependencies = [
+ "serde",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_edit",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.22.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
+dependencies = [
+ "indexmap",
+ "serde",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_write",
+ "winnow",
+]
+
+[[package]]
+name = "toml_write"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "walkdir"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+dependencies = [
+ "same-file",
+ "winapi-util",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "winnow"
+version = "0.7.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
+
+[[package]]
+name = "zip"
+version = "4.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"
+dependencies = [
+ "arbitrary",
+ "crc32fast",
+ "flate2",
+ "indexmap",
+ "memchr",
+ "zopfli",
+]
+
+[[package]]
+name = "zlib-rs"
+version = "0.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12"
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+
+[[package]]
+name = "zopfli"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
+dependencies = [
+ "bumpalo",
+ "crc32fast",
+ "log",
+ "simd-adler32",
+]
diff --git a/plugins/sdk/cli/Cargo.toml b/plugins/sdk/cli/Cargo.toml
new file mode 100644
index 0000000000..37752a4d51
--- /dev/null
+++ b/plugins/sdk/cli/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "dbx-plugin-cli"
+version = "0.1.1"
+edition = "2021"
+license = "Apache-2.0"
+description = "Scaffold and package DBX plugins"
+
+[workspace]
+
+[[bin]]
+name = "dbx-plugin"
+path = "src/main.rs"
+
+[dependencies]
+dbx-plugin-packager = { version = "0.1.0", path = "../packager" }
+semver = "1"
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+toml = "0.8"
+
+[dev-dependencies]
+tempfile = "3"
diff --git a/plugins/sdk/cli/README.md b/plugins/sdk/cli/README.md
new file mode 100644
index 0000000000..f2a8e750d4
--- /dev/null
+++ b/plugins/sdk/cli/README.md
@@ -0,0 +1,108 @@
+# dbx-plugin CLI
+
+Creates and packages DBX plugins as frontend-only universal bundles or full-stack projects with Rust or Go sidecars. The CLI also includes a Svelte + Vite workbench starter.
+
+For a complete Chinese walkthrough covering installation, templates, local DBX testing, signing, and publishing, see [`../../GETTING_STARTED.zh-CN.md`](../../GETTING_STARTED.zh-CN.md).
+
+```bash
+npm install --global @dbx-app/plugin-cli
+
+dbx-plugin create
+cd my-plugin
+dbx-plugin dev --port 5190
+dbx-plugin package .
+```
+
+Or run the precompiled CLI without a global installation:
+
+```bash
+npx @dbx-app/plugin-cli create my-plugin
+```
+
+The npm launcher selects the matching macOS, Linux, or Windows binary and bundles the matching Rust and Go plugin SDK sources. Building the CLI from a DBX checkout is only necessary while developing the CLI itself.
+
+## Browser development
+
+`dbx-plugin dev --path /path/to/plugin --port 5190` runs a local browser development host without starting DBX. The npm package includes the prebuilt runtime; only `dev` requires Node.js 22+. Frontend-only plugins need no sidecar; Rust/Go projects are built from `[backend]` configuration. JSONL and framed v1 are supported.
+
+Optional `[dev]` `ui_build` and `ui_watch` argument arrays configure UI builds. Without them, existing UI assets are loaded and watched. The command does not install project dependencies. Development data, including plaintext credentials, defaults to `.dbx-dev/`; use `--data-dir` to override it. See [runtime documentation](../dev-host/README.md) for supported APIs, source builds and limitations.
+
+## Project templates
+
+`dbx-plugin create` offers four templates:
+
+- `frontend` — sandboxed workbench UI with no native backend; produces one `universal` package.
+- `svelte` — Svelte + Vite sandboxed workbench UI with no native backend; produces one `universal` package.
+- `rust` — sandboxed workbench UI plus a Rust sidecar; produces one package per native target.
+- `go` — sandboxed workbench UI plus a Go sidecar; produces one package per native target.
+
+Interactive terminals use a colored wizard, validate each answer, show a final summary, and ask before writing files. The default template is `frontend`.
+
+For scripts and CI:
+
+```bash
+dbx-plugin create my-plugin \
+ --template frontend \
+ --id com.example.my-plugin \
+ --name "My Plugin" \
+ --publisher example \
+ --description "My DBX plugin." \
+ --version 0.1.0 \
+ --yes
+```
+
+`--backend none|svelte|rust|go` is an alias for template selection. `--language rust|go` remains available as a compatibility alias for native projects.
+
+Generated frontend-only projects contain:
+
+```text
+my-plugin/
+├── dbx-plugin.toml
+├── manifest.json
+├── assets/plugin.svg
+├── ui/index.html
+└── .github/workflows/plugin-release.yml
+```
+
+Rust and Go templates add a `backend/` directory containing the native sidecar project.
+
+## Packaging
+
+`dbx-plugin package` reads `dbx-plugin.toml`, verifies that its optional backend matches `manifest.json`, stages only declared files, and reuses `dbx-plugin-packager` to generate:
+
+- `<id>-<version>-<target>.dbxp`
+- `<id>-<version>-<target>.artifact.json`
+
+Frontend-only projects default to target `universal`. Native projects must be built on the matching target platform. Temporary stage and backend build directories are removed after both successful and failed package attempts.
+
+Artifact metadata always includes target, URL, SHA-256, and size. The generated Release workflow publishes these files as unsigned review candidates. After approval, DBX Store signs official candidates and emits final metadata containing `signingKeyId`.
+
+Use `--sdk-root /path/to/dbx` only with Rust or Go templates while developing unpublished SDK changes from a DBX checkout. Normal npm installations use the SDK sources bundled with `@dbx-app/plugin-cli`. Generated release workflows pin the precompiled CLI version so local and CI packaging use the same SDK contract.
+
+## Signing
+
+Official plugin authors do not create or manage signing keys. They publish unsigned candidates; DBX Store signs approved packages with the official repository key.
+
+`keygen` is an advanced tool for private or custom repository operators. Packaging and signing are intentionally separate:
+
+```bash
+dbx-plugin keygen company-plugins.release
+source .dbx-repository-signing-key.env
+dbx-plugin package .
+cargo run --release \
+ --manifest-path /path/to/dbx/plugins/sdk/packager/Cargo.toml \
+ -- sign dist/plugin.unsigned.dbxp dist/plugin.dbxp \
+ --key-id "$DBX_PLUGIN_SIGNING_KEY_ID" \
+ --artifact-metadata dist/plugin.artifact.json \
+ --target universal
+```
+
+`keygen` writes `.dbx-repository-signing-key.env` with owner-only permissions on Unix and refuses to overwrite it unless `--force` is supplied. Generated plugin projects ignore this file by default.
+
+The command prints the public key and key ID for configuring a custom repository trust root. The key ID is stable public metadata; the Ed25519 private seed in the generated file is secret and must stay in a password manager or protected repository-signing CI. `dbx-plugin create` and `dbx-plugin package` intentionally have no signing-key options.
+
+## Terminal colors
+
+Colors are enabled automatically for interactive terminals. Set `NO_COLOR=1` or `CLICOLOR=0` for plain text; set `CLICOLOR_FORCE=1` to preserve colors when piping output. `NO_COLOR` always takes precedence.
+
+Run `dbx-plugin --help`, `dbx-plugin create --help`, or `dbx-plugin package --help` for the complete command reference.
diff --git a/plugins/sdk/cli/src/dev.rs b/plugins/sdk/cli/src/dev.rs
new file mode 100644
index 0000000000..e7a631c69b
--- /dev/null
+++ b/plugins/sdk/cli/src/dev.rs
@@ -0,0 +1,250 @@
+use super::{canonical_directory, executable_name, sdk_root_from_environment, value_after, ProjectConfig};
+use serde::Deserialize;
+use serde_json::{json, Value};
+use std::{
+ fs,
+ path::{Component, Path, PathBuf},
+ process::Command,
+};
+
+#[derive(Debug, Default, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub(super) struct DevConfig {
+ #[serde(default)]
+ ui_build: Vec<String>,
+ #[serde(default)]
+ ui_watch: Vec<String>,
+}
+
+#[derive(Debug, PartialEq)]
+struct Options {
+ path: PathBuf,
+ port: u16,
+ data_dir: Option<PathBuf>,
+}
+
+fn parse(arguments: &[String]) -> Result<Options, String> {
+ let mut options = Options { path: PathBuf::from("."), port: 5190, data_dir: None };
+ let mut index = 0;
+ while index < arguments.len() {
+ match arguments[index].as_str() {
+ "--path" => options.path = PathBuf::from(value_after(arguments, &mut index)?),
+ "--port" => {
+ options.port =
+ value_after(arguments, &mut index)?.parse().map_err(|_| "--port must be between 0 and 65535")?
+ }
+ "--data-dir" => options.data_dir = Some(PathBuf::from(value_after(arguments, &mut index)?)),
+ other => return Err(format!("Unknown dev argument '{other}'")),
+ }
+ index += 1;
+ }
+ Ok(options)
+}
+
+fn relative_path(path: &Path) -> Result<(), String> {
+ if path.as_os_str().is_empty() || path.components().any(|p| !matches!(p, Component::Normal(_) | Component::CurDir))
+ {
+ return Err(format!("Expected a project-relative path: {}", path.display()));
+ }
+ Ok(())
+}
+
+fn build_config(options: &Options, sdk_root: Option<&Path>) -> Result<Value, String> {
+ let project = canonical_directory(&options.path)?;
+ let config: ProjectConfig = toml::from_str(
+ &fs::read_to_string(project.join("dbx-plugin.toml"))
+ .map_err(|e| format!("Cannot read dbx-plugin.toml: {e}"))?,
+ )
+ .map_err(|e| format!("Invalid dbx-plugin.toml: {e}"))?;
+ if config.schema_version != 1 {
+ return Err("Unsupported project configuration version".into());
+ }
+ let manifest: Value = serde_json::from_str(
+ &fs::read_to_string(project.join("manifest.json")).map_err(|e| format!("Cannot read manifest.json: {e}"))?,
+ )
+ .map_err(|e| format!("Invalid manifest.json: {e}"))?;
+ let entry =
+ manifest.pointer("/entrypoints/ui/entry").and_then(Value::as_str).ok_or("dev requires a UI entrypoint")?;
+ relative_path(Path::new(entry))?;
+ let ui_root = manifest.pointer("/entrypoints/ui/root").and_then(Value::as_str).unwrap_or("ui");
+ relative_path(Path::new(ui_root))?;
+ if !Path::new(entry).starts_with(ui_root) {
+ return Err("UI entry must be inside its declared root".into());
+ }
+ for command in [&config.dev.ui_build, &config.dev.ui_watch] {
+ if command.first().is_some_and(|c| c.trim().is_empty()) {
+ return Err("dev build commands must start with an executable".into());
+ }
+ }
+ let data_dir = match &options.data_dir {
+ Some(path) if path.is_absolute() => path.clone(),
+ Some(path) => project.join(path),
+ None => project.join(".dbx-dev"),
+ };
+ let mut launch = json!({"project": project, "dataDir": data_dir, "port": options.port,
+ "commands": {"ui": config.dev.ui_build, "watch": config.dev.ui_watch}});
+ let declared_backend = manifest.pointer("/entrypoints/backend").is_some_and(|v| !v.is_null());
+ if let Some(backend) = config.backend {
+ if !declared_backend {
+ return Err("Project declares a backend but manifest does not".into());
+ }
+ relative_path(&backend.directory)?;
+ if backend.binary.is_empty()
+ || matches!(backend.binary.as_str(), "." | "..")
+ || backend.binary.contains(['/', '\\'])
+ {
+ return Err("Backend binary must be a filename".into());
+ }
+ let directory = project.join(&backend.directory);
+ launch["backendWatch"] = json!(directory);
+ let (binary, command) = match backend.language.as_str() {
+ "rust" => {
+ let cargo_manifest = directory.join("Cargo.toml");
+ let cargo: toml::Value = toml::from_str(
+ &fs::read_to_string(&cargo_manifest).map_err(|e| format!("Cannot read backend Cargo.toml: {e}"))?,
+ )
+ .map_err(|e| format!("Invalid backend Cargo.toml: {e}"))?;
+ let target = data_dir.join("rust-target");
+ let mut args = vec![
+ "build".to_string(),
+ "--manifest-path".into(),
+ cargo_manifest.to_string_lossy().into_owned(),
+ "--target-dir".into(),
+ target.to_string_lossy().into_owned(),
+ ];
+ if directory.join("Cargo.lock").is_file() {
+ args.push("--locked".into());
+ }
+ // A crates.io patch is inappropriate for explicitly pinned Git or path dependencies.
+ let dependency = cargo.get("dependencies").and_then(|d| d.get("dbx-plugin-sdk"));
+ let explicit_source = dependency.is_some_and(|d| d.get("git").is_some() || d.get("path").is_some());
+ if let Some(root) = sdk_root.filter(|_| dependency.is_some() && !explicit_source) {
+ let sdk = root.join("plugins/sdk/rust/dbx-plugin-sdk");
+ if !sdk.join("Cargo.toml").is_file() {
+ return Err("Rust SDK root is invalid".into());
+ }
+ args.extend([
+ "--config".into(),
+ format!(
+ "patch.crates-io.dbx-plugin-sdk.path={}",
+ serde_json::to_string(&sdk.to_string_lossy()).map_err(|e| e.to_string())?
+ ),
+ ]);
+ }
+ (
+ target.join("debug").join(executable_name(&backend.binary)),
+ json!({"command":"cargo", "args":args, "cwd":project}),
+ )
+ }
+ "go" => {
+ if !directory.join("go.mod").is_file() {
+ return Err("Go backend is missing go.mod".into());
+ }
+ let binary = data_dir.join("bin").join(executable_name(&backend.binary));
+ let mut command = json!({"command":"go", "args":["build","-trimpath","-o",binary,"."],"cwd":directory});
+ if let Some(root) = sdk_root {
+ let sdk = root.join("plugins/sdk/go/dbx-plugin-sdk");
+ if !sdk.join("go.mod").is_file() {
+ return Err("Go SDK root is invalid".into());
+ }
+ // The runtime materializes this workfile inside its private data directory.
+ command["goWorkspace"] = json!([directory, sdk]);
+ }
+ (binary, command)
+ }
+ _ => return Err("dev supports Rust and Go backends".into()),
+ };
+ launch["backend"] = json!(binary);
+ launch["commands"]["backend"] = command;
+ } else if declared_backend {
+ return Err("Manifest backend requires [backend] configuration".into());
+ }
+ Ok(launch)
+}
+
+pub(super) fn run(arguments: Vec<String>) -> Result<(), String> {
+ if arguments.iter().any(|a| a == "--help" || a == "-h") {
+ println!("Run a plugin without starting DBX (Node.js 22+)\n\nUsage: dbx-plugin dev [--path DIR] [--port PORT] [--data-dir DIR]\n\n --path DIR Plugin project (default: current directory)\n --port PORT Loopback port (default: 5190; occupied ports fall back to a free port)\n --data-dir DIR Development data (default: <project>/.dbx-dev)\n\nOptional [dev] ui_build and ui_watch arrays configure UI commands.\nDevelopment credentials are stored locally as plaintext.\nDBX_PLUGIN_DEV_RUNTIME overrides the runtime entrypoint; DBX_PLUGIN_NODE selects Node.");
+ return Ok(());
+ }
+ let options = parse(&arguments)?;
+ let sdk_root = sdk_root_from_environment()?;
+ let launch = build_config(&options, sdk_root.as_deref())?;
+ let runtime = std::env::var_os("DBX_PLUGIN_DEV_RUNTIME")
+ .map(PathBuf::from)
+ .unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../dev-host/dist/runtime.mjs"));
+ if !runtime.is_file() {
+ return Err("Development runtime is missing. Install @dbx-app/plugin-cli, or run 'npm ci --prefix plugins/sdk/dev-host && npm run build --prefix plugins/sdk/dev-host' in a DBX checkout and set DBX_PLUGIN_DEV_RUNTIME to dist/runtime.mjs.".into());
+ }
+ let node = std::env::var_os("DBX_PLUGIN_NODE").unwrap_or_else(|| "node".into());
+ let version = Command::new(&node)
+ .arg("--version")
+ .output()
+ .map_err(|_| "dev requires Node.js 22+; install Node or set DBX_PLUGIN_NODE")?;
+ let major = String::from_utf8_lossy(&version.stdout)
+ .trim()
+ .trim_start_matches('v')
+ .split('.')
+ .next()
+ .and_then(|v| v.parse::<u32>().ok());
+ if !version.status.success() || !major.is_some_and(|v| v >= 22) {
+ return Err("dev requires Node.js 22+".into());
+ }
+ let mut command = Command::new(node);
+ command.arg(runtime).arg("--config").arg(serde_json::to_string(&launch).map_err(|e| e.to_string())?);
+ #[cfg(unix)]
+ {
+ use std::os::unix::process::CommandExt;
+ Err(format!("Cannot launch development runtime: {}", command.exec()))
+ }
+ #[cfg(not(unix))]
+ {
+ let status = command.status().map_err(|e| format!("Cannot launch development runtime: {e}"))?;
+ if status.success() {
+ Ok(())
+ } else {
+ Err(format!("Development runtime exited with {status}"))
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn options_and_invalid_arguments() {
+ assert_eq!(parse(&[]).unwrap(), Options { path: ".".into(), port: 5190, data_dir: None });
+ assert_eq!(parse(&["--port".into(), "0".into(), "--path".into(), "space path".into()]).unwrap().port, 0);
+ for args in [vec!["--port", "65536"], vec!["--port", "no"], vec!["--path"], vec!["--unknown"]] {
+ assert!(parse(&args.into_iter().map(String::from).collect::<Vec<_>>()).is_err());
+ }
+ }
+ #[test]
+ fn frontend_needs_no_backend_and_dev_arrays_are_typed() {
+ let root = tempfile::tempdir().unwrap();
+ fs::write(root.path().join("manifest.json"), r#"{"entrypoints":{"ui":{"root":"ui","entry":"ui/index.html"}}}"#)
+ .unwrap();
+ fs::write(
+ root.path().join("dbx-plugin.toml"),
+ "schema_version=1\n[package]\ninclude=[\"ui\"]\n[dev]\nui_build=[\"npm\",\"run\",\"build\"]\n",
+ )
+ .unwrap();
+ let options = Options { path: root.path().into(), port: 5190, data_dir: None };
+ let config = build_config(&options, None).unwrap();
+ assert!(config.get("backend").is_none());
+ assert_eq!(config["commands"]["ui"][0], "npm");
+ fs::write(
+ root.path().join("dbx-plugin.toml"),
+ "schema_version=1\n[package]\ninclude=[]\n[dev]\nui_build=\"npm run build\"\n",
+ )
+ .unwrap();
+ assert!(build_config(&options, None).is_err());
+ }
+ #[test]
+ fn paths_cannot_escape_project() {
+ for path in ["../ui", "/tmp/ui", ""] {
+ assert!(relative_path(Path::new(path)).is_err());
+ }
+ assert!(relative_path(Path::new("ui/index.html")).is_ok());
+ }
+}
diff --git a/plugins/sdk/cli/src/lib.rs b/plugins/sdk/cli/src/lib.rs
new file mode 100644
index 0000000000..c6444f1cc5
--- /dev/null
+++ b/plugins/sdk/cli/src/lib.rs
@@ -0,0 +1,1942 @@
+use std::collections::BTreeMap;
+use std::ffi::OsStr;
+use std::fmt::Display;
+use std::fs::{self, OpenOptions};
+use std::io::{self, BufRead, IsTerminal, Write};
+#[cfg(unix)]
+use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
+use std::path::{Component, Path, PathBuf};
+use std::process::{Command, Stdio};
+
+use serde::Deserialize;
+use serde_json::Value;
+
+mod dev;
+
+const CLI_VERSION: &str = env!("CARGO_PKG_VERSION");
+const SDK_VERSION: &str = "0.1.0";
+const ANSI_RESET: &str = "\x1b[0m";
+const ANSI_ACCENT: &str = "1;35";
+const ANSI_PROMPT: &str = "1;36";
+const ANSI_SUCCESS: &str = "1;32";
+const ANSI_WARNING: &str = "1;33";
+const ANSI_ERROR: &str = "1;31";
+const ANSI_MUTED: &str = "2";
+
+fn color_enabled_with(
+ is_terminal: bool,
+ no_color: bool,
+ term: Option<&str>,
+ clicolor: Option<&str>,
+ clicolor_force: Option<&str>,
+) -> bool {
+ if no_color {
+ return false;
+ }
+ if clicolor_force.is_some_and(|value| !value.is_empty() && value != "0") {
+ return true;
+ }
+ if clicolor == Some("0") || term.is_some_and(|value| value.eq_ignore_ascii_case("dumb")) {
+ return false;
+ }
+ is_terminal
+}
+
+fn terminal_colors_enabled(is_terminal: bool) -> bool {
+ let term = std::env::var("TERM").ok();
+ let clicolor = std::env::var("CLICOLOR").ok();
+ let clicolor_force = std::env::var("CLICOLOR_FORCE").ok();
+ color_enabled_with(
+ is_terminal,
+ std::env::var_os("NO_COLOR").is_some(),
+ term.as_deref(),
+ clicolor.as_deref(),
+ clicolor_force.as_deref(),
+ )
+}
+
+fn styled(value: impl Display, code: &str, enabled: bool) -> String {
+ if enabled {
+ format!("\x1b[{code}m{value}{ANSI_RESET}")
+ } else {
+ value.to_string()
+ }
+}
+
+fn styled_stdout(value: impl Display, code: &str) -> String {
+ styled(value, code, terminal_colors_enabled(io::stdout().is_terminal()))
+}
+
+fn styled_stderr(value: impl Display, code: &str) -> String {
+ styled(value, code, terminal_colors_enabled(io::stderr().is_terminal()))
+}
+
+pub fn print_error(error: &str) {
+ eprintln!("{} {error}", styled_stderr("error:", ANSI_ERROR));
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum BackendLanguage {
+ Rust,
+ Go,
+}
+
+impl BackendLanguage {
+ fn parse(value: &str) -> Result<Self, String> {
+ match value.trim().to_ascii_lowercase().as_str() {
+ "rust" => Ok(Self::Rust),
+ "go" | "golang" => Ok(Self::Go),
+ _ => Err("Backend language must be 'rust' or 'go'".to_string()),
+ }
+ }
+
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::Rust => "rust",
+ Self::Go => "go",
+ }
+ }
+
+ fn label(self) -> &'static str {
+ match self {
+ Self::Rust => "Rust",
+ Self::Go => "Go",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ProjectTemplate {
+ Frontend,
+ Svelte,
+ Rust,
+ Go,
+}
+
+impl ProjectTemplate {
+ fn parse(value: &str) -> Result<Self, String> {
+ match value.trim().to_ascii_lowercase().as_str() {
+ "frontend" | "frontend-only" | "ui" | "none" => Ok(Self::Frontend),
+ "svelte" => Ok(Self::Svelte),
+ "rust" => Ok(Self::Rust),
+ "go" | "golang" => Ok(Self::Go),
+ _ => Err("Plugin template must be 'frontend', 'svelte', 'rust', or 'go'".to_string()),
+ }
+ }
+
+ fn from_language(language: BackendLanguage) -> Self {
+ match language {
+ BackendLanguage::Rust => Self::Rust,
+ BackendLanguage::Go => Self::Go,
+ }
+ }
+
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::Frontend => "frontend",
+ Self::Svelte => "svelte",
+ Self::Rust => "rust",
+ Self::Go => "go",
+ }
+ }
+
+ fn label(self) -> &'static str {
+ match self {
+ Self::Frontend => "Frontend only (universal)",
+ Self::Svelte => "Svelte + Vite (universal)",
+ Self::Rust => "Rust + frontend",
+ Self::Go => "Go + frontend",
+ }
+ }
+
+ fn backend_language(self) -> Option<BackendLanguage> {
+ match self {
+ Self::Frontend | Self::Svelte => None,
+ Self::Rust => Some(BackendLanguage::Rust),
+ Self::Go => Some(BackendLanguage::Go),
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct CreateOptions {
+ pub directory: PathBuf,
+ pub template: ProjectTemplate,
+ pub plugin_id: String,
+ pub name: String,
+ pub publisher: String,
+ pub description: String,
+ pub version: String,
+ pub sdk_root: Option<PathBuf>,
+ pub force: bool,
+}
+
+#[derive(Debug, Default)]
+struct CreateInputs {
+ directory: Option<PathBuf>,
+ template: Option<ProjectTemplate>,
+ plugin_id: Option<String>,
+ name: Option<String>,
+ publisher: Option<String>,
+ description: Option<String>,
+ version: Option<String>,
+ sdk_root: Option<PathBuf>,
+ force: bool,
+ yes: bool,
+}
+
+#[derive(Debug, Clone)]
+pub struct PackageOptions {
+ pub project: PathBuf,
+ pub target: Option<String>,
+ pub output_directory: Option<PathBuf>,
+ pub artifact_url: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+struct ProjectConfig {
+ schema_version: u32,
+ #[serde(default)]
+ backend: Option<BackendConfig>,
+ package: PackageConfig,
+ #[serde(default)]
+ dev: dev::DevConfig,
+}
+
+#[derive(Debug, Deserialize)]
+struct BackendConfig {
+ language: String,
+ directory: PathBuf,
+ binary: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct PackageConfig {
+ include: Vec<PathBuf>,
+}
+
+#[derive(Debug, Deserialize)]
+struct ManifestIdentity {
+ manifest_version: u32,
+ id: String,
+ name: String,
+ version: String,
+ publisher: String,
+ engines: ManifestEngines,
+ #[serde(default)]
+ entrypoints: ManifestEntrypoints,
+}
+
+#[derive(Debug, Deserialize)]
+struct ManifestEngines {
+ host_api: String,
+}
+
+#[derive(Debug, Default, Deserialize)]
+struct ManifestEntrypoints {
+ backend: Option<serde_json::Value>,
+}
+
+struct TemplateFile {
+ path: &'static str,
+ content: &'static str,
+}
+
+struct CleanupDirectory {
+ path: PathBuf,
+}
+
+impl CleanupDirectory {
+ fn prepare(path: PathBuf) -> Result<Self, String> {
+ if path.exists() {
+ fs::remove_dir_all(&path).map_err(|error| format!("Failed to clean {}: {error}", path.display()))?;
+ }
+ fs::create_dir_all(&path).map_err(|error| format!("Failed to create {}: {error}", path.display()))?;
+ Ok(Self { path })
+ }
+
+ fn path(&self) -> &Path {
+ &self.path
+ }
+}
+
+impl Drop for CleanupDirectory {
+ fn drop(&mut self) {
+ let _ = fs::remove_dir_all(&self.path);
+ }
+}
+
+const SHARED_TEMPLATES: &[TemplateFile] = &[
+ TemplateFile { path: ".gitignore", content: include_str!("../templates/common/gitignore") },
+ TemplateFile { path: "assets/plugin.svg", content: include_str!("../templates/common/assets/plugin.svg") },
+];
+
+const FRONTEND_TEMPLATES: &[TemplateFile] = &[
+ TemplateFile { path: "dbx-plugin.toml", content: include_str!("../templates/frontend/dbx-plugin.toml") },
+ TemplateFile { path: "manifest.json", content: include_str!("../templates/frontend/manifest.json") },
+ TemplateFile { path: "README.md", content: include_str!("../templates/frontend/README.md") },
+ TemplateFile { path: "ui/index.html", content: include_str!("../templates/frontend/ui/index.html") },
+ TemplateFile {
+ path: ".github/workflows/plugin-release.yml",
+ content: include_str!("../templates/frontend/github/plugin-release.yml"),
+ },
+];
+
+const SVELTE_TEMPLATES: &[TemplateFile] = &[
+ TemplateFile { path: "dbx-plugin.toml", content: include_str!("../templates/svelte/dbx-plugin.toml") },
+ TemplateFile { path: "manifest.json", content: include_str!("../templates/svelte/manifest.json") },
+ TemplateFile { path: "README.md", content: include_str!("../templates/svelte/README.md") },
+ TemplateFile { path: "package.json", content: include_str!("../templates/svelte/package.json") },
+ TemplateFile { path: "svelte.config.js", content: include_str!("../templates/svelte/svelte.config.js") },
+ TemplateFile { path: "vite.config.js", content: include_str!("../templates/svelte/vite.config.js") },
+ TemplateFile { path: "src/main.js", content: include_str!("../templates/svelte/src/main.js") },
+ TemplateFile { path: "src/App.svelte", content: include_str!("../templates/svelte/src/App.svelte") },
+ TemplateFile { path: "index.html", content: include_str!("../templates/svelte/index.html") },
+ TemplateFile {
+ path: ".github/workflows/plugin-release.yml",
+ content: include_str!("../templates/frontend/github/plugin-release.yml"),
+ },
+];
+
+const NATIVE_TEMPLATES: &[TemplateFile] = &[
+ TemplateFile { path: "dbx-plugin.toml", content: include_str!("../templates/common/dbx-plugin.toml") },
+ TemplateFile { path: "manifest.json", content: include_str!("../templates/common/manifest.json") },
+ TemplateFile { path: "README.md", content: include_str!("../templates/common/README.md") },
+ TemplateFile { path: "ui/index.html", content: include_str!("../templates/common/ui/index.html") },
+ TemplateFile {
+ path: ".github/workflows/plugin-release.yml",
+ content: include_str!("../templates/common/github/plugin-release.yml"),
+ },
+];
+
+const RUST_TEMPLATES: &[TemplateFile] = &[
+ TemplateFile { path: "backend/Cargo.toml", content: include_str!("../templates/rust/backend/Cargo.toml") },
+ TemplateFile { path: "backend/src/main.rs", content: include_str!("../templates/rust/backend/src/main.rs") },
+];
+
+const GO_TEMPLATES: &[TemplateFile] = &[
+ TemplateFile { path: "backend/go.mod", content: include_str!("../templates/go/backend/go.mod") },
+ TemplateFile { path: "backend/main.go", content: include_str!("../templates/go/backend/main.go") },
+];
+
+pub fn run_cli<I>(arguments: I) -> Result<(), String>
+where
+ I: IntoIterator<Item = String>,
+{
+ let mut arguments = arguments.into_iter();
+ match arguments.next().as_deref() {
+ Some("create") => run_create(arguments.collect()),
+ Some("package") => run_package(arguments.collect()),
+ Some("dev") => dev::run(arguments.collect()),
+ Some("keygen") => run_keygen(arguments.collect()),
+ Some("--version" | "-V" | "version") => {
+ println!("{} {}", styled_stdout("dbx-plugin", ANSI_ACCENT), styled_stdout(CLI_VERSION, ANSI_MUTED));
+ Ok(())
+ }
+ Some("--help" | "-h" | "help") | None => {
+ print_usage();
+ Ok(())
+ }
+ Some(command) => Err(format!("Unknown command '{command}'\n{}", usage())),
+ }
+}
+
+fn run_create(arguments: Vec<String>) -> Result<(), String> {
+ let mut inputs = CreateInputs::default();
+ let mut index = 0;
+ while index < arguments.len() {
+ match arguments[index].as_str() {
+ "--template" | "-t" | "--backend" => {
+ let template = ProjectTemplate::parse(value_after(&arguments, &mut index)?)?;
+ set_project_template(&mut inputs.template, template, &arguments[index - 1])?;
+ }
+ "--language" | "-l" => {
+ let template =
+ ProjectTemplate::from_language(BackendLanguage::parse(value_after(&arguments, &mut index)?)?);
+ set_project_template(&mut inputs.template, template, &arguments[index - 1])?;
+ }
+ "--id" => inputs.plugin_id = Some(value_after(&arguments, &mut index)?.to_string()),
+ "--name" => inputs.name = Some(value_after(&arguments, &mut index)?.to_string()),
+ "--publisher" => inputs.publisher = Some(value_after(&arguments, &mut index)?.to_string()),
+ "--description" => inputs.description = Some(value_after(&arguments, &mut index)?.to_string()),
+ "--version" => inputs.version = Some(value_after(&arguments, &mut index)?.to_string()),
+ "--signing-key-id" => {
+ return Err(
+ "--signing-key-id is no longer used when creating plugins; official packages are signed by DBX Store after review"
+ .to_string(),
+ );
+ }
+ "--sdk-root" => inputs.sdk_root = Some(PathBuf::from(value_after(&arguments, &mut index)?)),
+ "--force" => inputs.force = true,
+ "--yes" | "-y" => inputs.yes = true,
+ "--help" | "-h" => {
+ print_create_help();
+ return Ok(());
+ }
+ value if value.starts_with('-') => return Err(format!("Unknown create option '{value}'")),
+ value if inputs.directory.is_none() => inputs.directory = Some(PathBuf::from(value)),
+ value => return Err(format!("Unexpected create argument '{value}'")),
+ }
+ index += 1;
+ }
+ let interactive = !inputs.yes && io::stdin().is_terminal() && io::stdout().is_terminal();
+ let stdin = io::stdin();
+ let stdout = io::stdout();
+ let mut reader = stdin.lock();
+ let mut writer = stdout.lock();
+ let options = resolve_create_options(inputs, interactive, &mut reader, &mut writer)?;
+ drop(writer);
+ drop(reader);
+ if let Some(options) = options {
+ create_project(&options)?;
+ }
+ Ok(())
+}
+
+fn run_package(arguments: Vec<String>) -> Result<(), String> {
+ let mut project = PathBuf::from(".");
+ let mut project_set = false;
+ let mut target = None;
+ let mut output_directory = None;
+ let mut artifact_url = None;
+ let mut index = 0;
+ while index < arguments.len() {
+ match arguments[index].as_str() {
+ "--target" => target = Some(value_after(&arguments, &mut index)?.to_string()),
+ "--output-dir" => output_directory = Some(PathBuf::from(value_after(&arguments, &mut index)?)),
+ "--artifact-url" => artifact_url = Some(value_after(&arguments, &mut index)?.to_string()),
+ "--key-id" => {
+ return Err(
+ "--key-id is no longer supported by dbx-plugin package; build an unsigned candidate, then let the repository operator sign it after review"
+ .to_string(),
+ );
+ }
+ "--help" | "-h" => {
+ print_package_help();
+ return Ok(());
+ }
+ value if value.starts_with('-') => return Err(format!("Unknown package option '{value}'")),
+ value if !project_set => {
+ project = PathBuf::from(value);
+ project_set = true;
+ }
+ value => return Err(format!("Unexpected package argument '{value}'")),
+ }
+ index += 1;
+ }
+ package_project(&PackageOptions { project, target, output_directory, artifact_url })?;
+ Ok(())
+}
+
+fn run_keygen(arguments: Vec<String>) -> Result<(), String> {
+ let mut key_id = None;
+ let mut output = PathBuf::from(".dbx-repository-signing-key.env");
+ let mut force = false;
+ let mut index = 0;
+ while index < arguments.len() {
+ match arguments[index].as_str() {
+ "--key-id" => key_id = Some(value_after(&arguments, &mut index)?.to_string()),
+ "--output" | "-o" => output = PathBuf::from(value_after(&arguments, &mut index)?),
+ "--force" => force = true,
+ "--help" | "-h" => {
+ print_keygen_help();
+ return Ok(());
+ }
+ value if value.starts_with('-') => return Err(format!("Unknown keygen option '{value}'")),
+ value if key_id.is_none() => key_id = Some(value.to_string()),
+ value => return Err(format!("Unexpected keygen argument '{value}'")),
+ }
+ index += 1;
+ }
+
+ let interactive = io::stdin().is_terminal() && io::stdout().is_terminal();
+ let stdin = io::stdin();
+ let stdout = io::stdout();
+ let mut reader = stdin.lock();
+ let mut writer = stdout.lock();
+ let key_id = match key_id {
+ Some(value) => resolve_string(
+ Some(value),
+ interactive,
+ "Signing key ID",
+ "example.release".to_string(),
+ dbx_plugin_packager::validate_key_id,
+ &mut reader,
+ &mut writer,
+ )?,
+ None if interactive => resolve_string(
+ None,
+ true,
+ "Signing key ID",
+ "example.release".to_string(),
+ dbx_plugin_packager::validate_key_id,
+ &mut reader,
+ &mut writer,
+ )?,
+ None => return Err(format!("Signing key ID is required\n{}", keygen_usage())),
+ };
+ drop(writer);
+ drop(reader);
+
+ let material = generate_signing_key_file(&key_id, &output, force)?;
+ println!("{} Saved private signing material to {}", styled_stdout("Success:", ANSI_SUCCESS), output.display());
+ println!("{} {key_id}", styled_stdout("Key ID:", ANSI_PROMPT));
+ println!("{} {}", styled_stdout("Public key:", ANSI_PROMPT), material.public_key_base64);
+ println!(
+ "{} Use DBX_PLUGIN_SIGNING_KEY only in repository signing CI; publish only the repository key ID and public key.",
+ styled_stdout("Next:", ANSI_WARNING)
+ );
+ Ok(())
+}
+
+pub fn generate_signing_key_file(
+ key_id: &str,
+ output: &Path,
+ force: bool,
+) -> Result<dbx_plugin_packager::SigningKeyMaterial, String> {
+ dbx_plugin_packager::validate_key_id(key_id)?;
+ if let Some(parent) = output.parent().filter(|parent| !parent.as_os_str().is_empty()) {
+ fs::create_dir_all(parent).map_err(|error| format!("Failed to create {}: {error}", parent.display()))?;
+ }
+ let material = dbx_plugin_packager::generate_signing_key()?;
+ let mut options = OpenOptions::new();
+ options.write(true);
+ if force {
+ options.create(true).truncate(true);
+ } else {
+ options.create_new(true);
+ }
+ #[cfg(unix)]
+ options.mode(0o600);
+ let mut file = options.open(output).map_err(|error| {
+ if output.exists() && !force {
+ format!("{} already exists; use --force to replace it", output.display())
+ } else {
+ format!("Failed to create {}: {error}", output.display())
+ }
+ })?;
+ writeln!(file, "# Keep this file secret. Do not commit it.").map_err(|error| error.to_string())?;
+ writeln!(file, "export DBX_PLUGIN_SIGNING_KEY={}", material.private_seed_base64)
+ .map_err(|error| error.to_string())?;
+ writeln!(file, "export DBX_PLUGIN_SIGNING_KEY_ID={key_id}").map_err(|error| error.to_string())?;
+ writeln!(file, "export DBX_PLUGIN_SIGNING_PUBLIC_KEY={}", material.public_key_base64)
+ .map_err(|error| error.to_string())?;
+ file.sync_all().map_err(|error| error.to_string())?;
+ #[cfg(unix)]
+ fs::set_permissions(output, fs::Permissions::from_mode(0o600)).map_err(|error| error.to_string())?;
+ Ok(material)
+}
+
+fn value_after<'a>(arguments: &'a [String], index: &mut usize) -> Result<&'a str, String> {
+ *index += 1;
+ arguments.get(*index).map(String::as_str).ok_or_else(|| "Option requires a value".to_string())
+}
+
+fn set_project_template(
+ selected: &mut Option<ProjectTemplate>,
+ template: ProjectTemplate,
+ option: &str,
+) -> Result<(), String> {
+ if selected.is_some_and(|existing| existing != template) {
+ return Err(format!("{option} conflicts with the previously selected plugin template"));
+ }
+ *selected = Some(template);
+ Ok(())
+}
+
+fn resolve_create_options<R: BufRead, W: Write>(
+ inputs: CreateInputs,
+ interactive: bool,
+ reader: &mut R,
+ writer: &mut W,
+) -> Result<Option<CreateOptions>, String> {
+ if interactive {
+ writeln!(writer, "{}", styled_stdout("Create a DBX plugin", ANSI_ACCENT)).map_err(|error| error.to_string())?;
+ }
+ let directory = resolve_project_directory(inputs.directory, inputs.force, interactive, reader, writer)?;
+ let slug = project_slug(&directory)?;
+ let template = match inputs.template {
+ Some(template) => template,
+ None if interactive => prompt_project_template(reader, writer)?,
+ None => ProjectTemplate::Frontend,
+ };
+ if matches!(template, ProjectTemplate::Frontend | ProjectTemplate::Svelte) && inputs.sdk_root.is_some() {
+ return Err("--sdk-root requires the Rust or Go plugin template".to_string());
+ }
+ let plugin_id = resolve_string(
+ inputs.plugin_id,
+ interactive,
+ "Plugin ID",
+ format!("com.example.{slug}"),
+ |value| validate_identifier(value, "plugin id"),
+ reader,
+ writer,
+ )?;
+ let name = resolve_string(
+ inputs.name,
+ interactive,
+ "Display name",
+ title_from_slug(&slug),
+ |value| validate_display_text(value, "plugin name"),
+ reader,
+ writer,
+ )?;
+ let publisher = resolve_string(
+ inputs.publisher,
+ interactive,
+ "Publisher",
+ default_publisher(&plugin_id),
+ |value| validate_identifier(value, "publisher"),
+ reader,
+ writer,
+ )?;
+ let description = resolve_string(
+ inputs.description,
+ interactive,
+ "Description",
+ default_description(&name),
+ |value| validate_display_text(value, "plugin description"),
+ reader,
+ writer,
+ )?;
+ let version =
+ resolve_string(inputs.version, interactive, "Version", "0.1.0".to_string(), validate_semver, reader, writer)?;
+ let options = CreateOptions {
+ directory,
+ template,
+ plugin_id,
+ name,
+ publisher,
+ description,
+ version,
+ sdk_root: inputs.sdk_root,
+ force: inputs.force,
+ };
+ validate_create_options(&options)?;
+ if interactive {
+ print_create_summary(&options, writer)?;
+ if !prompt_confirmation(reader, writer)? {
+ writeln!(writer, "{}", styled_stdout("Cancelled.", ANSI_WARNING)).map_err(|error| error.to_string())?;
+ return Ok(None);
+ }
+ }
+ Ok(Some(options))
+}
+
+fn resolve_project_directory<R: BufRead, W: Write>(
+ directory: Option<PathBuf>,
+ force: bool,
+ interactive: bool,
+ reader: &mut R,
+ writer: &mut W,
+) -> Result<PathBuf, String> {
+ match directory {
+ Some(directory) => match validate_project_directory(&directory, force) {
+ Ok(()) => Ok(directory),
+ Err(error) if interactive => {
+ writeln!(writer, "{} project directory: {error}", styled_stdout("Invalid", ANSI_WARNING))
+ .map_err(|write_error| write_error.to_string())?;
+ prompt_project_directory(force, reader, writer)
+ }
+ Err(error) => Err(error),
+ },
+ None if interactive => prompt_project_directory(force, reader, writer),
+ None => Err(format!("Project directory is required\n{}", create_usage())),
+ }
+}
+
+fn prompt_project_directory<R: BufRead, W: Write>(
+ force: bool,
+ reader: &mut R,
+ writer: &mut W,
+) -> Result<PathBuf, String> {
+ loop {
+ let value = prompt_line("Project directory", "my-dbx-plugin", reader, writer)?;
+ let directory = PathBuf::from(value);
+ match validate_project_directory(&directory, force) {
+ Ok(()) => return Ok(directory),
+ Err(error) => writeln!(writer, "{} {error}", styled_stdout("Invalid:", ANSI_WARNING))
+ .map_err(|write_error| write_error.to_string())?,
+ }
+ }
+}
+
+fn resolve_string<R: BufRead, W: Write, F>(
+ value: Option<String>,
+ interactive: bool,
+ label: &str,
+ default: String,
+ validate: F,
+ reader: &mut R,
+ writer: &mut W,
+) -> Result<String, String>
+where
+ F: Fn(&str) -> Result<(), String>,
+{
+ if let Some(value) = value {
+ match validate(&value) {
+ Ok(()) => return Ok(value),
+ Err(error) if interactive => {
+ writeln!(writer, "{} {label}: {error}", styled_stdout("Invalid", ANSI_WARNING))
+ .map_err(|write_error| write_error.to_string())?;
+ }
+ Err(error) => return Err(error),
+ }
+ }
+ if !interactive {
+ validate(&default)?;
+ return Ok(default);
+ }
+ loop {
+ let value = prompt_line(label, &default, reader, writer)?;
+ match validate(&value) {
+ Ok(()) => return Ok(value),
+ Err(error) => writeln!(writer, "{} {error}", styled_stdout("Invalid:", ANSI_WARNING))
+ .map_err(|write_error| write_error.to_string())?,
+ }
+ }
+}
+
+fn prompt_line<R: BufRead, W: Write>(
+ label: &str,
+ default: &str,
+ reader: &mut R,
+ writer: &mut W,
+) -> Result<String, String> {
+ write!(writer, "{} {} ", styled_stdout(label, ANSI_PROMPT), styled_stdout(format!("({default}):"), ANSI_MUTED))
+ .map_err(|error| error.to_string())?;
+ writer.flush().map_err(|error| error.to_string())?;
+ let mut answer = String::new();
+ if reader.read_line(&mut answer).map_err(|error| error.to_string())? == 0 {
+ return Err(format!("Input closed while waiting for {label}"));
+ }
+ let answer = answer.trim();
+ Ok(if answer.is_empty() { default.to_string() } else { answer.to_string() })
+}
+
+fn prompt_project_template<R: BufRead, W: Write>(reader: &mut R, writer: &mut W) -> Result<ProjectTemplate, String> {
+ loop {
+ writeln!(writer, "{}", styled_stdout("Plugin template:", ANSI_PROMPT)).map_err(|error| error.to_string())?;
+ writeln!(writer, " {}) Frontend only (universal package)", styled_stdout("1", ANSI_ACCENT))
+ .map_err(|error| error.to_string())?;
+ writeln!(writer, " {}) Svelte + Vite (universal package)", styled_stdout("2", ANSI_ACCENT))
+ .map_err(|error| error.to_string())?;
+ writeln!(writer, " {}) Rust + frontend", styled_stdout("3", ANSI_ACCENT))
+ .map_err(|error| error.to_string())?;
+ writeln!(writer, " {}) Go + frontend", styled_stdout("4", ANSI_ACCENT)).map_err(|error| error.to_string())?;
+ write!(writer, "{} {} ", styled_stdout("Choose", ANSI_PROMPT), styled_stdout("(1):", ANSI_MUTED))
+ .map_err(|error| error.to_string())?;
+ writer.flush().map_err(|error| error.to_string())?;
+ let mut answer = String::new();
+ if reader.read_line(&mut answer).map_err(|error| error.to_string())? == 0 {
+ return Err("Input closed while waiting for plugin template".to_string());
+ }
+ match answer.trim().to_ascii_lowercase().as_str() {
+ "" | "1" | "frontend" | "frontend-only" | "ui" | "none" => return Ok(ProjectTemplate::Frontend),
+ "2" | "svelte" => return Ok(ProjectTemplate::Svelte),
+ "3" | "rust" => return Ok(ProjectTemplate::Rust),
+ "4" | "go" | "golang" => return Ok(ProjectTemplate::Go),
+ _ => writeln!(writer, "{} choose 1/Frontend, 2/Svelte, 3/Rust, or 4/Go", styled_stdout("Invalid:", ANSI_WARNING))
+ .map_err(|error| error.to_string())?,
+ }
+ }
+}
+
+fn print_create_summary<W: Write>(options: &CreateOptions, writer: &mut W) -> Result<(), String> {
+ writeln!(writer, "\n{}", styled_stdout("Plugin configuration:", ANSI_ACCENT)).map_err(|error| error.to_string())?;
+ writeln!(writer, " {} {}", styled_stdout("Directory:", ANSI_PROMPT), options.directory.display())
+ .map_err(|error| error.to_string())?;
+ writeln!(writer, " {} {}", styled_stdout("Template:", ANSI_PROMPT), options.template.label())
+ .map_err(|error| error.to_string())?;
+ writeln!(writer, " {} {}", styled_stdout("Plugin ID:", ANSI_PROMPT), options.plugin_id)
+ .map_err(|error| error.to_string())?;
+ writeln!(writer, " {} {}", styled_stdout("Display name:", ANSI_PROMPT), options.name)
+ .map_err(|error| error.to_string())?;
+ writeln!(writer, " {} {}", styled_stdout("Publisher:", ANSI_PROMPT), options.publisher)
+ .map_err(|error| error.to_string())?;
+ writeln!(writer, " {} {}", styled_stdout("Description:", ANSI_PROMPT), options.description)
+ .map_err(|error| error.to_string())?;
+ writeln!(writer, " {} {}", styled_stdout("Version:", ANSI_PROMPT), options.version)
+ .map_err(|error| error.to_string())?;
+ writeln!(
+ writer,
+ " {} {}",
+ styled_stdout("Release:", ANSI_PROMPT),
+ styled_stdout("builds unsigned candidates; DBX Store signs approved official releases", ANSI_MUTED)
+ )
+ .map_err(|error| error.to_string())?;
+ if let Some(sdk_root) = &options.sdk_root {
+ writeln!(writer, " {} {}", styled_stdout("SDK root:", ANSI_PROMPT), sdk_root.display())
+ .map_err(|error| error.to_string())?;
+ }
+ Ok(())
+}
+
+fn prompt_confirmation<R: BufRead, W: Write>(reader: &mut R, writer: &mut W) -> Result<bool, String> {
+ loop {
+ write!(writer, "{} {} ", styled_stdout("Create plugin?", ANSI_PROMPT), styled_stdout("[Y/n]:", ANSI_MUTED))
+ .map_err(|error| error.to_string())?;
+ writer.flush().map_err(|error| error.to_string())?;
+ let mut answer = String::new();
+ if reader.read_line(&mut answer).map_err(|error| error.to_string())? == 0 {
+ return Err("Input closed while waiting for confirmation".to_string());
+ }
+ match answer.trim().to_ascii_lowercase().as_str() {
+ "" | "y" | "yes" => return Ok(true),
+ "n" | "no" => return Ok(false),
+ _ => writeln!(writer, "{} enter y or n", styled_stdout("Invalid:", ANSI_WARNING))
+ .map_err(|error| error.to_string())?,
+ }
+ }
+}
+
+pub fn create_project(options: &CreateOptions) -> Result<(), String> {
+ validate_create_options(options)?;
+ let slug = project_slug(&options.directory)?;
+ let binary_name = format!("dbx-plugin-{slug}");
+ let method_prefix = slug.replace('_', "-");
+ let sdk_root = options.sdk_root.as_ref().map(|path| canonical_directory(path)).transpose()?;
+ let (rust_dependency, go_replace) = match options.template {
+ ProjectTemplate::Frontend | ProjectTemplate::Svelte => (String::new(), String::new()),
+ ProjectTemplate::Rust => (rust_sdk_dependency(sdk_root.as_deref())?, String::new()),
+ ProjectTemplate::Go => (String::new(), go_sdk_replace(sdk_root.as_deref())?),
+ };
+ let values = template_values(options, &slug, &binary_name, &method_prefix, rust_dependency, go_replace);
+
+ if options.directory.exists() {
+ if !options.directory.is_dir() {
+ return Err(format!("{} exists and is not a directory", options.directory.display()));
+ }
+ if !options.force && fs::read_dir(&options.directory).map_err(|error| error.to_string())?.next().is_some() {
+ return Err(format!(
+ "{} is not empty; use --force to overwrite generated files",
+ options.directory.display()
+ ));
+ }
+ } else {
+ fs::create_dir_all(&options.directory).map_err(|error| error.to_string())?;
+ }
+
+ let mut templates = SHARED_TEMPLATES.iter().collect::<Vec<_>>();
+ match options.template {
+ ProjectTemplate::Frontend => templates.extend(FRONTEND_TEMPLATES),
+ ProjectTemplate::Svelte => templates.extend(SVELTE_TEMPLATES),
+ ProjectTemplate::Rust => {
+ templates.extend(NATIVE_TEMPLATES);
+ templates.extend(RUST_TEMPLATES);
+ }
+ ProjectTemplate::Go => {
+ templates.extend(NATIVE_TEMPLATES);
+ templates.extend(GO_TEMPLATES);
+ }
+ }
+ for template in templates {
+ let destination = options.directory.join(template.path);
+ if destination.exists() && !options.force {
+ return Err(format!("{} already exists; use --force to overwrite generated files", destination.display()));
+ }
+ if let Some(parent) = destination.parent() {
+ fs::create_dir_all(parent).map_err(|error| error.to_string())?;
+ }
+ let rendered = render(template.content, &values);
+ if let Some(marker) = unresolved_template_marker(&rendered) {
+ return Err(format!("Generated template {} contains unresolved marker {{{{{marker}}}}}", template.path));
+ }
+ fs::write(&destination, rendered).map_err(|error| error.to_string())?;
+ }
+
+ println!(
+ "{} Created {} plugin at {}",
+ styled_stdout("Success:", ANSI_SUCCESS),
+ options.template.label(),
+ options.directory.display()
+ );
+ println!(
+ "{} {}",
+ styled_stdout("Next:", ANSI_PROMPT),
+ styled_stdout(format!("cd {} && dbx-plugin package .", options.directory.display()), ANSI_MUTED)
+ );
+ Ok(())
+}
+
+pub fn package_project(options: &PackageOptions) -> Result<(PathBuf, PathBuf), String> {
+ let project = canonical_directory(&options.project)?;
+ let config: ProjectConfig = toml::from_str(
+ &fs::read_to_string(project.join("dbx-plugin.toml"))
+ .map_err(|error| format!("Failed to read dbx-plugin.toml: {error}"))?,
+ )
+ .map_err(|error| format!("Invalid dbx-plugin.toml: {error}"))?;
+ if config.schema_version != 1 {
+ return Err(format!("Unsupported dbx-plugin.toml schema version {}", config.schema_version));
+ }
+ let language = config.backend.as_ref().map(|backend| BackendLanguage::parse(&backend.language)).transpose()?;
+ if let Some(backend) = &config.backend {
+ validate_relative_path(&backend.directory, "backend directory")?;
+ validate_file_name(&backend.binary, "backend binary")?;
+ }
+ for include in &config.package.include {
+ validate_relative_path(include, "package include")?;
+ if include.components().any(|part| part.as_os_str() == ".dbx-dev") {
+ return Err("Package input cannot contain .dbx-dev development data".to_owned());
+ }
+ }
+ let manifest_path = project.join("manifest.json");
+ let manifest_raw = fs::read(&manifest_path).map_err(|error| format!("Failed to read manifest.json: {error}"))?;
+ let manifest_value: Value =
+ serde_json::from_slice(&manifest_raw).map_err(|error| format!("Invalid manifest.json: {error}"))?;
+ reject_unknown_manifest_fields(&manifest_value)?;
+ let manifest: ManifestIdentity = serde_json::from_value(manifest_value.clone())
+ .map_err(|error| format!("Invalid manifest.json identity: {error}"))?;
+ if manifest.manifest_version != 1 {
+ return Err(format!(
+ "Unsupported manifest.json version {}; dbx-plugin packages require version 1",
+ manifest.manifest_version
+ ));
+ }
+ validate_identifier(&manifest.id, "manifest plugin id")?;
+ validate_display_text(&manifest.name, "manifest name")?;
+ validate_semver(&manifest.version)?;
+ validate_display_text(&manifest.publisher, "manifest publisher")?;
+ validate_display_text(&manifest.engines.host_api, "manifest engines.host_api")?;
+ if manifest.entrypoints.backend.is_some() != config.backend.is_some() {
+ return Err("dbx-plugin.toml and manifest.json must either both declare a backend or both omit it".to_string());
+ }
+
+ let detected_target = config.backend.as_ref().map(|_| current_target()).transpose()?;
+ let target = options
+ .target
+ .clone()
+ .or_else(|| std::env::var("DBX_PLUGIN_TARGET").ok())
+ .unwrap_or_else(|| detected_target.clone().unwrap_or_else(|| "universal".to_string()));
+ validate_artifact_target(&target)?;
+ if let Some(detected_target) = &detected_target {
+ if target != *detected_target {
+ return Err(format!(
+ "Native plugin target '{target}' does not match build host '{detected_target}'; run this package command on the target platform"
+ ));
+ }
+ }
+ let output_directory = match &options.output_directory {
+ Some(path) if path.is_absolute() => path.clone(),
+ Some(path) => project.join(path),
+ None => project.join("dist"),
+ };
+ fs::create_dir_all(&output_directory).map_err(|error| error.to_string())?;
+ validate_manifest_assets(&project, &manifest_value, &config.package.include)?;
+ let stage = CleanupDirectory::prepare(output_directory.join(format!(".stage-{}-{target}", manifest.id)))?;
+
+ if let (Some(backend), Some(language)) = (&config.backend, language) {
+ println!("{} {} backend", styled_stdout("Building:", ANSI_PROMPT), language.label());
+ let executable_name = executable_name(&backend.binary);
+ let binary_directory = stage.path().join("bin").join(&target);
+ fs::create_dir_all(&binary_directory).map_err(|error| error.to_string())?;
+ let staged_executable = binary_directory.join(&executable_name);
+ let build = CleanupDirectory::prepare(output_directory.join(format!(".build-{}-{target}", language.as_str())))?;
+ match language {
+ BackendLanguage::Rust => build_rust_backend(&project, backend, build.path(), &staged_executable)?,
+ BackendLanguage::Go => build_go_backend(&project, backend, build.path(), &staged_executable)?,
+ }
+ }
+ let staged_manifest = package_manifest(manifest_value, config.backend.as_ref(), &target)?;
+ fs::write(stage.path().join("manifest.json"), staged_manifest).map_err(|error| error.to_string())?;
+ for include in &config.package.include {
+ let source = project.join(include);
+ if !source.exists() {
+ return Err(format!("Package include {} does not exist", source.display()));
+ }
+ copy_path(&source, &stage.path().join(include))?;
+ }
+
+ let package_name = format!("{}-{}-{target}.dbxp", manifest.id, manifest.version);
+ let package_path = output_directory.join(&package_name);
+ let metadata_path = output_directory.join(package_name.replace(".dbxp", ".artifact.json"));
+ let artifact_url = options.artifact_url.clone().unwrap_or(package_name);
+ let packager_arguments = vec![
+ stage.path().to_string_lossy().into_owned(),
+ package_path.to_string_lossy().into_owned(),
+ "--artifact-metadata".to_string(),
+ metadata_path.to_string_lossy().into_owned(),
+ "--target".to_string(),
+ target,
+ "--artifact-url".to_string(),
+ artifact_url,
+ ];
+ println!("{} {}", styled_stdout("Packaging:", ANSI_PROMPT), package_path.display());
+ dbx_plugin_packager::run_cli_silent(packager_arguments)?;
+ println!("{} Built {}", styled_stdout("Success:", ANSI_SUCCESS), package_path.display());
+ println!("{} {}", styled_stdout("Metadata:", ANSI_PROMPT), metadata_path.display());
+ println!(
+ "{} {}",
+ styled_stdout("Signature:", ANSI_WARNING),
+ styled_stdout("unsigned review candidate", ANSI_MUTED)
+ );
+ Ok((package_path, metadata_path))
+}
+
+fn package_manifest(mut manifest: Value, backend: Option<&BackendConfig>, target: &str) -> Result<Vec<u8>, String> {
+ reject_unknown_manifest_fields(&manifest)?;
+ if let Some(ui_entrypoint) = manifest
+ .get_mut("entrypoints")
+ .and_then(Value::as_object_mut)
+ .and_then(|entrypoints| entrypoints.get_mut("ui"))
+ .and_then(Value::as_object_mut)
+ {
+ if ui_entrypoint.contains_key("kind") {
+ return Err("manifest.json entrypoints.ui.kind is obsolete; DBX plugin UI is always sandboxed".to_string());
+ }
+ }
+ if let Some(backend) = backend {
+ let entrypoints = manifest
+ .get_mut("entrypoints")
+ .and_then(Value::as_object_mut)
+ .ok_or("manifest.json entrypoints must be an object")?;
+ let backend_entrypoint = entrypoints
+ .get_mut("backend")
+ .and_then(Value::as_object_mut)
+ .ok_or("manifest.json entrypoints.backend must be an object")?;
+ if backend_entrypoint.contains_key("binaries") {
+ return Err(
+ "manifest.json entrypoints.backend.binaries is obsolete; package one target and declare executable"
+ .to_string(),
+ );
+ }
+ if backend_entrypoint.contains_key("protocol") {
+ return Err(
+ "manifest.json entrypoints.backend.protocol is obsolete; DBX manifest v1 uses the DBX JSON-RPC protocol"
+ .to_string(),
+ );
+ }
+ if backend_entrypoint
+ .get("protocol_versions")
+ .and_then(Value::as_array)
+ .is_some_and(|versions| versions.as_slice() == [Value::from(1)])
+ {
+ backend_entrypoint.remove("protocol_versions");
+ }
+ if backend_entrypoint.get("transport").and_then(Value::as_str) == Some("stdio-jsonl") {
+ backend_entrypoint.remove("transport");
+ }
+ backend_entrypoint.insert(
+ "executable".to_string(),
+ Value::String(format!("bin/{target}/{}", executable_name(&backend.binary))),
+ );
+ }
+ let mut bytes = serde_json::to_vec_pretty(&manifest).map_err(|error| error.to_string())?;
+ bytes.push(b'\n');
+ Ok(bytes)
+}
+
+fn reject_unknown_manifest_fields(manifest: &Value) -> Result<(), String> {
+ const ALLOWED_FIELDS: &[&str] = &[
+ "$schema",
+ "manifest_version",
+ "id",
+ "name",
+ "icon",
+ "version",
+ "publisher",
+ "description",
+ "source",
+ "homepage",
+ "engines",
+ "permissions",
+ "entrypoints",
+ "contributions",
+ "localizations",
+ ];
+ let object = manifest.as_object().ok_or("manifest.json must be an object")?;
+ let unknown = object.keys().filter(|key| !ALLOWED_FIELDS.contains(&key.as_str())).cloned().collect::<Vec<_>>();
+ if unknown.is_empty() {
+ Ok(())
+ } else {
+ Err(format!("manifest.json contains unknown top-level field(s): {}", unknown.join(", ")))
+ }
+}
+
+fn validate_manifest_assets(project: &Path, manifest: &Value, includes: &[PathBuf]) -> Result<(), String> {
+ if let Some(icon) = manifest.get("icon") {
+ let icon = icon.as_str().ok_or("manifest.json icon must be a string")?;
+ validate_packaged_asset(project, includes, icon, "manifest icon")?;
+ }
+
+ let Some(entrypoints) = manifest.get("entrypoints") else {
+ return Ok(());
+ };
+ let entrypoints = entrypoints.as_object().ok_or("manifest.json entrypoints must be an object")?;
+ let Some(ui) = entrypoints.get("ui") else {
+ return Ok(());
+ };
+ let ui = ui.as_object().ok_or("manifest.json entrypoints.ui must be an object")?;
+ let entry = ui.get("entry").and_then(Value::as_str).ok_or("manifest.json entrypoints.ui.entry must be a string")?;
+ validate_relative_path(Path::new(entry), "manifest UI entry")?;
+ let root = ui.get("root").and_then(Value::as_str).unwrap_or("ui");
+ validate_relative_path(Path::new(root), "manifest UI root")?;
+ if !Path::new(entry).starts_with(root) {
+ return Err(format!("manifest UI entry '{entry}' must be inside root '{root}'"));
+ }
+ validate_packaged_asset(project, includes, entry, "manifest UI entry")
+}
+
+fn validate_packaged_asset(project: &Path, includes: &[PathBuf], value: &str, label: &str) -> Result<(), String> {
+ let path = Path::new(value);
+ validate_relative_path(path, label)?;
+ let source = project.join(path);
+ if !source.is_file() {
+ return Err(format!("{label} '{value}' does not exist at {}", source.display()));
+ }
+ if !includes.iter().any(|include| path == include || path.starts_with(include)) {
+ return Err(format!("{label} '{value}' is not covered by [package].include"));
+ }
+ Ok(())
+}
+
+fn build_rust_backend(
+ project: &Path,
+ backend: &BackendConfig,
+ target_directory: &Path,
+ staged_executable: &Path,
+) -> Result<(), String> {
+ let backend_directory = project.join(&backend.directory);
+ let manifest = backend_directory.join("Cargo.toml");
+ if !manifest.is_file() {
+ return Err(format!("Rust backend is missing {}", manifest.display()));
+ }
+ let mut command = Command::new("cargo");
+ command.arg("build").arg("--release").arg("--manifest-path").arg(&manifest);
+ if backend_directory.join("Cargo.lock").is_file() {
+ command.arg("--locked");
+ }
+ if let Some(sdk_root) = sdk_root_from_environment()? {
+ let sdk = sdk_root.join("plugins/sdk/rust/dbx-plugin-sdk");
+ if !sdk.join("Cargo.toml").is_file() {
+ return Err(format!("Rust plugin SDK was not found at {}", sdk.display()));
+ }
+ command.arg("--config").arg(format!(
+ "patch.crates-io.dbx-plugin-sdk.path={}",
+ serde_json::to_string(&sdk.to_string_lossy()).map_err(|error| error.to_string())?
+ ));
+ }
+ command.env("CARGO_TARGET_DIR", target_directory);
+ run_command(&mut command, "Rust backend build")?;
+ let built = target_directory.join("release").join(executable_name(&backend.binary));
+ fs::copy(&built, staged_executable)
+ .map_err(|error| format!("Failed to copy Rust backend {}: {error}", built.display()))?;
+ Ok(())
+}
+
+fn build_go_backend(
+ project: &Path,
+ backend: &BackendConfig,
+ build_directory: &Path,
+ staged_executable: &Path,
+) -> Result<(), String> {
+ let backend_directory = project.join(&backend.directory);
+ if !backend_directory.join("go.mod").is_file() {
+ return Err(format!("Go backend is missing {}/go.mod", backend_directory.display()));
+ }
+ let mut command = Command::new("go");
+ command.current_dir(&backend_directory).arg("build").arg("-trimpath");
+ if let Some(sdk_root) = sdk_root_from_environment()? {
+ let sdk = sdk_root.join("plugins/sdk/go/dbx-plugin-sdk");
+ if !sdk.join("go.mod").is_file() {
+ return Err(format!("Go plugin SDK was not found at {}", sdk.display()));
+ }
+ fs::create_dir_all(build_directory).map_err(|error| error.to_string())?;
+ let mod_file = build_directory.join("dbx-plugin.mod");
+ fs::copy(backend_directory.join("go.mod"), &mod_file).map_err(|error| error.to_string())?;
+ if backend_directory.join("go.sum").is_file() {
+ fs::copy(backend_directory.join("go.sum"), build_directory.join("dbx-plugin.sum"))
+ .map_err(|error| error.to_string())?;
+ }
+ let sdk_module = go_module_path(&sdk.join("go.mod"))?;
+ let mut mod_command = Command::new("go");
+ mod_command
+ .current_dir(&backend_directory)
+ .arg("mod")
+ .arg("edit")
+ .arg("-modfile")
+ .arg(&mod_file)
+ .arg(format!("-replace={sdk_module}={}", sdk.display()));
+ run_command(&mut mod_command, "Go module configuration")?;
+ command.arg("-modfile").arg(mod_file).env("GOWORK", "off");
+ }
+ command.arg("-o").arg(staged_executable).arg(".");
+ run_command(&mut command, "Go backend build")
+}
+
+fn go_module_path(path: &Path) -> Result<String, String> {
+ let contents = fs::read_to_string(path).map_err(|error| format!("Failed to read {}: {error}", path.display()))?;
+ contents
+ .lines()
+ .find_map(|line| line.strip_prefix("module ").map(str::trim).filter(|module| !module.is_empty()))
+ .map(str::to_string)
+ .ok_or_else(|| format!("{} is missing a module directive", path.display()))
+}
+
+fn run_command(command: &mut Command, label: &str) -> Result<(), String> {
+ command.stdin(Stdio::inherit()).stdout(Stdio::inherit()).stderr(Stdio::inherit());
+ let status = command.status().map_err(|error| format!("Failed to start {label}: {error}"))?;
+ if status.success() {
+ Ok(())
+ } else {
+ Err(format!("{label} failed with {status}"))
+ }
+}
+
+fn copy_path(source: &Path, destination: &Path) -> Result<(), String> {
+ if source.file_name().is_some_and(|name| name == ".dbx-dev") {
+ return Err("Package input cannot contain .dbx-dev development data".to_owned());
+ }
+ let metadata = fs::symlink_metadata(source).map_err(|error| error.to_string())?;
+ if metadata.file_type().is_symlink() {
+ return Err(format!("Package input cannot contain symbolic link {}", source.display()));
+ }
+ if metadata.is_file() {
+ if let Some(parent) = destination.parent() {
+ fs::create_dir_all(parent).map_err(|error| error.to_string())?;
+ }
+ fs::copy(source, destination).map_err(|error| error.to_string())?;
+ return Ok(());
+ }
+ if !metadata.is_dir() {
+ return Err(format!("Unsupported package input {}", source.display()));
+ }
+ fs::create_dir_all(destination).map_err(|error| error.to_string())?;
+ for entry in fs::read_dir(source).map_err(|error| error.to_string())? {
+ let entry = entry.map_err(|error| error.to_string())?;
+ copy_path(&entry.path(), &destination.join(entry.file_name()))?;
+ }
+ Ok(())
+}
+
+fn template_values(
+ options: &CreateOptions,
+ slug: &str,
+ binary_name: &str,
+ method_prefix: &str,
+ rust_dependency: String,
+ go_replace: String,
+) -> BTreeMap<&'static str, String> {
+ let backend_language = options.template.backend_language();
+ BTreeMap::from([
+ ("PLUGIN_ID", options.plugin_id.clone()),
+ ("PLUGIN_NAME", options.name.clone()),
+ ("PLUGIN_NAME_JSON", json_string_content(&options.name)),
+ ("PLUGIN_NAME_HTML", escape_html(&options.name)),
+ ("PLUGIN_NAME_XML", escape_html(&options.name)),
+ ("PLUGIN_NAME_RUST", escape_code_string(&options.name)),
+ ("PLUGIN_NAME_GO", escape_code_string(&options.name)),
+ ("DESCRIPTION", options.description.clone()),
+ ("DESCRIPTION_JSON", json_string_content(&options.description)),
+ ("PUBLISHER", options.publisher.clone()),
+ ("PUBLISHER_JSON", json_string_content(&options.publisher)),
+ ("VERSION", options.version.clone()),
+ ("TEMPLATE", options.template.as_str().to_string()),
+ ("TEMPLATE_LABEL", options.template.label().to_string()),
+ ("LANGUAGE", backend_language.map(BackendLanguage::as_str).unwrap_or("none").to_string()),
+ ("LANGUAGE_LABEL", backend_language.map(BackendLanguage::label).unwrap_or("No native backend").to_string()),
+ ("BINARY_NAME", binary_name.to_string()),
+ ("METHOD_PREFIX", method_prefix.to_string()),
+ ("CONNECTION_TYPE", slug.to_string()),
+ ("RUST_SDK_DEPENDENCY", rust_dependency),
+ ("GO_MODULE", format!("github.com/{}/{slug}", options.publisher)),
+ ("GO_SDK_REPLACE", go_replace),
+ ])
+}
+
+fn render(template: &str, values: &BTreeMap<&str, String>) -> String {
+ values
+ .iter()
+ .fold(template.to_string(), |rendered, (key, value)| rendered.replace(&format!("{{{{{key}}}}}"), value))
+}
+
+fn unresolved_template_marker(rendered: &str) -> Option<String> {
+ rendered.split("{{").skip(1).find_map(|suffix| {
+ let (marker, _) = suffix.split_once("}}")?;
+ (!marker.is_empty()
+ && marker
+ .chars()
+ .all(|character| character.is_ascii_uppercase() || character.is_ascii_digit() || character == '_'))
+ .then(|| marker.to_string())
+ })
+}
+
+fn rust_sdk_dependency(sdk_root: Option<&Path>) -> Result<String, String> {
+ match sdk_root {
+ Some(root) => {
+ let path = root.join("plugins/sdk/rust/dbx-plugin-sdk");
+ if !path.join("Cargo.toml").is_file() {
+ return Err(format!("Rust plugin SDK was not found at {}", path.display()));
+ }
+ Ok(format!("{{ path = \"{}\" }}", escape_toml_path(&path)))
+ }
+ None => Ok(format!("{{ version = \"{SDK_VERSION}\" }}")),
+ }
+}
+
+fn go_sdk_replace(sdk_root: Option<&Path>) -> Result<String, String> {
+ match sdk_root {
+ Some(root) => {
+ let path = root.join("plugins/sdk/go/dbx-plugin-sdk");
+ if !path.join("go.mod").is_file() {
+ return Err(format!("Go plugin SDK was not found at {}", path.display()));
+ }
+ Ok(format!("replace github.com/t8y2/dbx/plugins/sdk/go/dbx-plugin-sdk => {}", path.display()))
+ }
+ None => Ok(String::new()),
+ }
+}
+
+fn canonical_directory(path: &Path) -> Result<PathBuf, String> {
+ let canonical = fs::canonicalize(path).map_err(|error| format!("Failed to resolve {}: {error}", path.display()))?;
+ if canonical.is_dir() {
+ Ok(canonical)
+ } else {
+ Err(format!("{} is not a directory", canonical.display()))
+ }
+}
+
+fn sdk_root_from_environment() -> Result<Option<PathBuf>, String> {
+ std::env::var_os("DBX_PLUGIN_SDK_ROOT")
+ .filter(|value| !value.is_empty())
+ .map(PathBuf::from)
+ .map(|path| canonical_directory(&path))
+ .transpose()
+}
+
+fn validate_create_options(options: &CreateOptions) -> Result<(), String> {
+ validate_project_directory(&options.directory, options.force)?;
+ validate_identifier(&options.plugin_id, "plugin id")?;
+ validate_identifier(&options.publisher, "publisher")?;
+ validate_semver(&options.version)?;
+ validate_display_text(&options.name, "plugin name")?;
+ validate_display_text(&options.description, "plugin description")?;
+ if matches!(options.template, ProjectTemplate::Frontend | ProjectTemplate::Svelte) && options.sdk_root.is_some() {
+ return Err("SDK root is only supported by Rust or Go plugin templates".to_string());
+ }
+ Ok(())
+}
+
+fn validate_project_directory(directory: &Path, force: bool) -> Result<(), String> {
+ project_slug(directory)?;
+ if !directory.exists() {
+ return Ok(());
+ }
+ if !directory.is_dir() {
+ return Err(format!("{} exists and is not a directory", directory.display()));
+ }
+ if !force && fs::read_dir(directory).map_err(|error| error.to_string())?.next().is_some() {
+ return Err(format!("{} is not empty; use --force to overwrite generated files", directory.display()));
+ }
+ Ok(())
+}
+
+fn validate_identifier(value: &str, label: &str) -> Result<(), String> {
+ if value.is_empty()
+ || value.len() > 256
+ || !value.chars().enumerate().all(|(index, character)| {
+ character.is_ascii_lowercase()
+ || character.is_ascii_digit()
+ || index > 0 && matches!(character, '.' | '_' | '-')
+ })
+ {
+ return Err(format!("{label} must use lowercase letters, digits, dots, underscores, or hyphens"));
+ }
+ Ok(())
+}
+
+fn validate_semver(value: &str) -> Result<(), String> {
+ semver::Version::parse(value)
+ .map(|_| ())
+ .map_err(|_| "Version must be valid SemVer such as 1.0.0 or 1.0.0-beta.1".to_string())
+}
+
+fn validate_display_text(value: &str, label: &str) -> Result<(), String> {
+ if value.trim().is_empty() || value.chars().any(char::is_control) {
+ return Err(format!("{label} must be non-empty and cannot contain control characters"));
+ }
+ Ok(())
+}
+
+fn validate_relative_path(path: &Path, label: &str) -> Result<(), String> {
+ if path.as_os_str().is_empty()
+ || path.is_absolute()
+ || path.components().any(|component| !matches!(component, Component::Normal(_)))
+ {
+ return Err(format!("{label} must be a safe relative path"));
+ }
+ Ok(())
+}
+
+fn validate_file_name(value: &str, label: &str) -> Result<(), String> {
+ if value.is_empty() || Path::new(value).file_name() != Some(OsStr::new(value)) {
+ return Err(format!("{label} must be a file name"));
+ }
+ Ok(())
+}
+
+fn project_slug(directory: &Path) -> Result<String, String> {
+ let name = directory.file_name().and_then(OsStr::to_str).ok_or("Project directory needs a UTF-8 name")?;
+ let slug = name
+ .chars()
+ .map(|character| if character.is_ascii_alphanumeric() { character.to_ascii_lowercase() } else { '-' })
+ .collect::<String>()
+ .split('-')
+ .filter(|part| !part.is_empty())
+ .collect::<Vec<_>>()
+ .join("-");
+ if slug.is_empty() {
+ Err("Project directory name must contain letters or digits".to_string())
+ } else {
+ Ok(slug)
+ }
+}
+
+fn title_from_slug(slug: &str) -> String {
+ slug.split('-').filter(|part| !part.is_empty()).map(title_word).collect::<Vec<_>>().join(" ")
+}
+
+fn title_word(word: &str) -> String {
+ match word {
+ "api" | "dbx" | "http" | "https" | "jdbc" | "sdk" | "sftp" | "sql" | "ssh" | "tcp" | "tls" | "udp" | "ui" => {
+ word.to_ascii_uppercase()
+ }
+ _ => {
+ let mut characters = word.chars();
+ characters
+ .next()
+ .map(|first| first.to_ascii_uppercase().to_string() + characters.as_str())
+ .unwrap_or_default()
+ }
+ }
+}
+
+fn default_description(name: &str) -> String {
+ if name.to_ascii_lowercase().ends_with(" plugin") {
+ format!("{name} for DBX.")
+ } else {
+ format!("{name} plugin for DBX.")
+ }
+}
+
+fn default_publisher(plugin_id: &str) -> String {
+ plugin_id.split('.').nth(1).filter(|value| !value.is_empty()).unwrap_or("example").to_string()
+}
+
+fn current_target() -> Result<String, String> {
+ let os = match std::env::consts::OS {
+ "macos" => "darwin",
+ "linux" => "linux",
+ "windows" => "windows",
+ value => return Err(format!("Unsupported plugin operating system '{value}'")),
+ };
+ let architecture = match std::env::consts::ARCH {
+ "aarch64" => "arm64",
+ "x86_64" => "x64",
+ value => return Err(format!("Unsupported plugin architecture '{value}'")),
+ };
+ Ok(format!("{os}-{architecture}"))
+}
+
+fn validate_artifact_target(target: &str) -> Result<(), String> {
+ if target.is_empty()
+ || target.len() > 64
+ || !target
+ .chars()
+ .all(|character| character.is_ascii_lowercase() || character.is_ascii_digit() || character == '-')
+ {
+ return Err("Artifact target contains unsupported characters".to_string());
+ }
+ Ok(())
+}
+
+fn executable_name(binary: &str) -> String {
+ if cfg!(windows) {
+ format!("{binary}.exe")
+ } else {
+ binary.to_string()
+ }
+}
+
+fn json_string_content(value: &str) -> String {
+ let encoded = serde_json::to_string(value).expect("serializing a string cannot fail");
+ encoded[1..encoded.len() - 1].to_string()
+}
+
+fn escape_html(value: &str) -> String {
+ value.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
+}
+
+fn escape_code_string(value: &str) -> String {
+ value.replace('\\', "\\\\").replace('"', "\\\"")
+}
+
+fn escape_toml_path(path: &Path) -> String {
+ path.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\"")
+}
+
+fn print_usage() {
+ println!(
+ "{} {}",
+ styled_stdout("dbx-plugin", ANSI_ACCENT),
+ styled_stdout("Create, sign, and package DBX plugins", ANSI_MUTED)
+ );
+ println!("\n{}", styled_stdout("Usage:", ANSI_PROMPT));
+ println!(" dbx-plugin <command> [options]");
+ println!("\n{}", styled_stdout("Commands:", ANSI_PROMPT));
+ println!(" {} Create a frontend-only, Svelte, Rust, or Go plugin project", styled_stdout("create", ANSI_SUCCESS));
+ println!(" {} Build a .dbxp package and artifact metadata", styled_stdout("package", ANSI_SUCCESS));
+ println!(
+ " {} Run a plugin in the local browser development host (Node.js 22+)",
+ styled_stdout("dev", ANSI_SUCCESS)
+ );
+ println!(" {} Generate an Ed25519 repository signing key", styled_stdout("keygen", ANSI_SUCCESS));
+ println!(" {} Print the CLI version", styled_stdout("version", ANSI_SUCCESS));
+ println!("\n{}", styled_stdout("Examples:", ANSI_PROMPT));
+ println!(" dbx-plugin create");
+ println!(" dbx-plugin create my-plugin --template frontend --yes");
+ println!(" dbx-plugin keygen example.release");
+ println!(" dbx-plugin package .");
+ println!("\nRun dbx-plugin <command> --help for command options.");
+}
+
+fn print_create_help() {
+ println!("{}", styled_stdout("Create a DBX plugin project", ANSI_ACCENT));
+ println!("\n{}\n {}", styled_stdout("Usage:", ANSI_PROMPT), create_usage());
+ println!("\n{}", styled_stdout("Templates:", ANSI_PROMPT));
+ println!(" {} Sandboxed UI only; packages once as universal", styled_stdout("frontend", ANSI_SUCCESS));
+ println!(" {} Svelte + Vite UI; packages once as universal", styled_stdout("svelte", ANSI_SUCCESS));
+ println!(" {} Sandboxed UI plus a Rust sidecar", styled_stdout("rust", ANSI_SUCCESS));
+ println!(" {} Sandboxed UI plus a Go sidecar", styled_stdout("go", ANSI_SUCCESS));
+ println!("\n{}", styled_stdout("Options:", ANSI_PROMPT));
+ println!(" -t, --template TYPE frontend, svelte, rust, or go (default: frontend)");
+ println!(" --backend TYPE Alias accepting none, svelte, rust, or go");
+ println!(" -l, --language LANGUAGE Compatibility alias for rust or go");
+ println!(" --id ID Reverse-domain plugin ID");
+ println!(" --name NAME Display name");
+ println!(" --publisher NAME Publisher identifier");
+ println!(" --description TEXT Plugin description");
+ println!(" --version VERSION Strict semantic version (default: 0.1.0)");
+ println!(" --sdk-root PATH Local DBX SDK checkout for Rust or Go templates");
+ println!(" --force Overwrite generated files");
+ println!(" -y, --yes Use defaults without prompts");
+ println!(" -h, --help Print this help");
+ println!("\nGenerated release workflows publish unsigned candidates for DBX Store review and signing.");
+}
+
+fn print_package_help() {
+ println!("{}", styled_stdout("Package a DBX plugin", ANSI_ACCENT));
+ println!("\n{}\n {}", styled_stdout("Usage:", ANSI_PROMPT), package_usage());
+ println!("\n{}", styled_stdout("Behavior:", ANSI_PROMPT));
+ println!(" Frontend-only projects default to target universal.");
+ println!(" Rust and Go projects build a native sidecar for the current host target.");
+ println!(" Packages are always unsigned review candidates.");
+ println!(" The official store or a custom repository operator signs approved candidates separately.");
+ println!("\n{}", styled_stdout("Options:", ANSI_PROMPT));
+ println!(" --target TARGET Artifact target or DBX_PLUGIN_TARGET");
+ println!(" --output-dir DIR Output directory (default: dist)");
+ println!(" --artifact-url URL URL recorded in artifact metadata");
+ println!(" -h, --help Print this help");
+}
+
+fn print_keygen_help() {
+ println!("{}", styled_stdout("Generate a repository signing key", ANSI_ACCENT));
+ println!("\n{}\n {}", styled_stdout("Usage:", ANSI_PROMPT), keygen_usage());
+ println!("\n{}", styled_stdout("Output:", ANSI_PROMPT));
+ println!(" Writes a private environment file with mode 0600 on Unix.");
+ println!(
+ " Intended for private or custom repository operators; official DBX Store authors do not need this command."
+ );
+ println!("\n{}", styled_stdout("Options:", ANSI_PROMPT));
+ println!(" --key-id ID Public repository key identifier");
+ println!(" -o, --output FILE Secret output file (default: .dbx-repository-signing-key.env)");
+ println!(" --force Replace an existing output file");
+ println!(" -h, --help Print this help");
+ println!("\nNever commit the generated private environment file.");
+}
+
+fn usage() -> String {
+ format!("{}\n{}\n{}\nRun 'dbx-plugin --help' for details.", create_usage(), package_usage(), keygen_usage())
+}
+
+fn create_usage() -> String {
+ "dbx-plugin create [directory] [--template frontend|rust|go] [options]".to_string()
+}
+
+fn package_usage() -> String {
+ "dbx-plugin package [project] [--target TARGET] [--output-dir DIR] [--artifact-url URL]".to_string()
+}
+
+fn keygen_usage() -> String {
+ "dbx-plugin keygen [KEY_ID] [--output FILE] [--force]".to_string()
+}
+
+#[cfg(test)]
+mod tests {
+ use std::fs;
+ use std::io::Cursor;
+ use std::path::PathBuf;
+
+ use super::{
+ color_enabled_with, create_project, generate_signing_key_file, package_manifest, package_project,
+ resolve_create_options, run_cli, styled, title_from_slug, validate_manifest_assets, validate_semver,
+ BackendConfig, CreateInputs, CreateOptions, PackageOptions, ProjectTemplate, ANSI_ACCENT,
+ };
+
+ #[test]
+ fn reads_go_module_paths() {
+ let root = tempfile::tempdir().unwrap();
+ let module_file = root.path().join("go.mod");
+ fs::write(&module_file, "module example.com/plugin\n\ngo 1.22\n").unwrap();
+ assert_eq!(super::go_module_path(&module_file).unwrap(), "example.com/plugin");
+ }
+
+ #[test]
+ fn rejects_development_data_in_package_inputs() {
+ let root = tempfile::tempdir().unwrap();
+ let input = root.path().join("ui");
+ std::fs::create_dir_all(input.join(".dbx-dev")).unwrap();
+ std::fs::write(input.join(".dbx-dev/connections.json"), "private").unwrap();
+ let output = root.path().join("stage");
+ assert!(super::copy_path(&input, &output).unwrap_err().contains(".dbx-dev"));
+ assert!(!output.join(".dbx-dev/connections.json").exists());
+ }
+
+ #[test]
+ fn enables_colors_only_for_supported_terminal_modes() {
+ assert!(color_enabled_with(true, false, Some("xterm-256color"), None, None));
+ assert!(!color_enabled_with(false, false, Some("xterm-256color"), None, None));
+ assert!(!color_enabled_with(true, true, Some("xterm-256color"), None, Some("1")));
+ assert!(!color_enabled_with(true, false, Some("dumb"), None, None));
+ assert!(!color_enabled_with(true, false, Some("xterm-256color"), Some("0"), None));
+ assert!(color_enabled_with(false, false, None, None, Some("1")));
+ }
+
+ #[test]
+ fn styles_text_without_changing_plain_output() {
+ assert_eq!(styled("DBX", ANSI_ACCENT, false), "DBX");
+ assert_eq!(styled("DBX", ANSI_ACCENT, true), "\x1b[1;35mDBX\x1b[0m");
+ }
+
+ #[test]
+ fn generates_secret_file_without_overwriting_by_default() {
+ let root = tempfile::tempdir().unwrap();
+ let output = root.path().join("repository.env");
+ let material = generate_signing_key_file("example.release", &output, false).unwrap();
+ let content = std::fs::read_to_string(&output).unwrap();
+ assert!(content.contains(&format!("export DBX_PLUGIN_SIGNING_KEY={}", material.private_seed_base64)));
+ assert!(content.contains("export DBX_PLUGIN_SIGNING_KEY_ID=example.release"));
+ assert!(content.contains(&format!("export DBX_PLUGIN_SIGNING_PUBLIC_KEY={}", material.public_key_base64)));
+ assert!(generate_signing_key_file("example.release", &output, false).is_err());
+ generate_signing_key_file("example.release", &output, true).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+
+ assert_eq!(std::fs::metadata(output).unwrap().permissions().mode() & 0o777, 0o600);
+ }
+ }
+ #[test]
+ fn noninteractive_create_defaults_to_frontend_candidate_workflow() {
+ let root = tempfile::tempdir().unwrap();
+ let directory = root.path().join("default-project");
+ let mut reader = Cursor::new(Vec::<u8>::new());
+ let mut output = Vec::new();
+ let options = resolve_create_options(
+ CreateInputs { directory: Some(directory), yes: true, ..CreateInputs::default() },
+ false,
+ &mut reader,
+ &mut output,
+ )
+ .unwrap()
+ .unwrap();
+ assert_eq!(options.template, ProjectTemplate::Frontend);
+ }
+
+ #[test]
+ fn rejects_conflicting_template_aliases() {
+ let error = run_cli(
+ ["create", "--template", "frontend", "--language", "rust", "--yes"].into_iter().map(str::to_string),
+ )
+ .unwrap_err();
+ assert!(error.contains("conflicts with the previously selected plugin template"));
+ }
+
+ #[test]
+ fn rejects_package_signing_options() {
+ let error = run_cli(["package", "--key-id", "example.release"].into_iter().map(str::to_string)).unwrap_err();
+ assert!(error.contains("build an unsigned candidate"));
+ }
+
+ #[test]
+ fn rejects_obsolete_backend_binary_maps() {
+ let manifest = serde_json::json!({
+ "entrypoints": {
+ "backend": {
+ "binaries": { "darwin-arm64": "bin/plugin" }
+ }
+ }
+ });
+ let backend =
+ BackendConfig { language: "rust".to_string(), directory: "backend".into(), binary: "plugin".to_string() };
+
+ assert!(package_manifest(manifest, Some(&backend), "darwin-arm64")
+ .unwrap_err()
+ .contains("entrypoints.backend.binaries is obsolete"));
+ }
+
+ #[test]
+ fn rejects_obsolete_fixed_entrypoint_fields() {
+ let backend =
+ BackendConfig { language: "rust".to_string(), directory: "backend".into(), binary: "plugin".to_string() };
+ let backend_manifest = serde_json::json!({
+ "entrypoints": {
+ "backend": {
+ "protocol": "dbx-jsonrpc",
+ "executable": "bin/plugin"
+ }
+ }
+ });
+ let ui_manifest = serde_json::json!({
+ "entrypoints": {
+ "ui": {
+ "kind": "sandbox-webview",
+ "entry": "ui/index.html"
+ }
+ }
+ });
+
+ assert!(package_manifest(backend_manifest, Some(&backend), "darwin-arm64")
+ .unwrap_err()
+ .contains("entrypoints.backend.protocol is obsolete"));
+ assert!(package_manifest(ui_manifest, None, "universal")
+ .unwrap_err()
+ .contains("entrypoints.ui.kind is obsolete"));
+ }
+
+ #[test]
+ fn rejects_unknown_top_level_manifest_fields() {
+ let manifest = serde_json::json!({
+ "manifest_version": 1,
+ "id": "com.example.unknown",
+ "name": "Unknown",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "host_api": "1" },
+ "activation_events": ["onStartup"]
+ });
+
+ assert!(package_manifest(manifest, None, "universal")
+ .unwrap_err()
+ .contains("unknown top-level field(s): activation_events"));
+ }
+
+ #[test]
+ fn rejects_manifest_assets_missing_from_package_inputs() {
+ let root = tempfile::tempdir().unwrap();
+ std::fs::create_dir_all(root.path().join("ui")).unwrap();
+ std::fs::write(root.path().join("ui/index.html"), "<!doctype html>").unwrap();
+ let manifest = serde_json::json!({
+ "entrypoints": { "ui": { "root": "ui", "entry": "ui/index.html" } }
+ });
+
+ let error = validate_manifest_assets(root.path(), &manifest, &[PathBuf::from("assets")]).unwrap_err();
+ assert!(error.contains("not covered by [package].include"));
+ }
+
+ #[test]
+ fn package_validation_and_failures_leave_no_temporary_directories() {
+ let root = tempfile::tempdir().unwrap();
+ let mismatch = root.path().join("mismatch");
+ create_project(&CreateOptions {
+ directory: mismatch.clone(),
+ template: ProjectTemplate::Frontend,
+ plugin_id: "com.example.mismatch".to_string(),
+ name: "Mismatch".to_string(),
+ publisher: "example".to_string(),
+ description: "Mismatch package".to_string(),
+ version: "1.0.0".to_string(),
+ sdk_root: None,
+ force: false,
+ })
+ .unwrap();
+ std::fs::write(
+ mismatch.join("dbx-plugin.toml"),
+ "schema_version = 1\n\n[backend]\nlanguage = \"rust\"\ndirectory = \"backend\"\nbinary = \"mismatch\"\n\n[package]\ninclude = [\"assets\", \"ui\"]\n",
+ )
+ .unwrap();
+ let error = package_project(&PackageOptions {
+ project: mismatch,
+ target: Some("universal".to_string()),
+ output_directory: None,
+ artifact_url: None,
+ })
+ .unwrap_err();
+ assert!(error.contains("must either both declare a backend or both omit it"));
+
+ let missing_include = root.path().join("missing-include");
+ create_project(&CreateOptions {
+ directory: missing_include.clone(),
+ template: ProjectTemplate::Frontend,
+ plugin_id: "com.example.missing-include".to_string(),
+ name: "Missing Include".to_string(),
+ publisher: "example".to_string(),
+ description: "Missing include package".to_string(),
+ version: "1.0.0".to_string(),
+ sdk_root: None,
+ force: false,
+ })
+ .unwrap();
+ std::fs::remove_dir_all(missing_include.join("ui")).unwrap();
+ assert!(package_project(&PackageOptions {
+ project: missing_include.clone(),
+ target: Some("universal".to_string()),
+ output_directory: None,
+ artifact_url: None,
+ })
+ .is_err());
+ assert!(std::fs::read_dir(missing_include.join("dist")).unwrap().all(|entry| {
+ let name = entry.unwrap().file_name();
+ let name = name.to_string_lossy();
+ !name.starts_with(".stage-") && !name.starts_with(".build-")
+ }));
+ }
+ #[test]
+ fn creates_frontend_rust_and_go_projects() {
+ let root = tempfile::tempdir().unwrap();
+ let sdk_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../..");
+ for template in [ProjectTemplate::Frontend, ProjectTemplate::Svelte, ProjectTemplate::Rust, ProjectTemplate::Go] {
+ let directory = root.path().join(template.as_str());
+ create_project(&CreateOptions {
+ directory: directory.clone(),
+ template,
+ plugin_id: format!("com.example.{}", template.as_str()),
+ name: format!("{} example", template.label()),
+ publisher: "example".to_string(),
+ description: "Generated plugin".to_string(),
+ version: "1.2.3".to_string(),
+ sdk_root: matches!(template, ProjectTemplate::Rust | ProjectTemplate::Go).then(|| sdk_root.clone()),
+ force: false,
+ })
+ .unwrap();
+
+ assert!(directory.join("manifest.json").is_file());
+ assert!(directory.join(if template == ProjectTemplate::Svelte { "index.html" } else { "ui/index.html" }).is_file());
+ assert!(directory.join(".github/workflows/plugin-release.yml").is_file());
+ let readme = std::fs::read_to_string(directory.join("README.md")).unwrap();
+ assert!(readme.contains("Plugin submission Issue"));
+ assert!(readme.contains("t8y2/dbx-store:main"));
+ assert!(readme.contains("Do not submit ordinary plugin source to `t8y2/dbx`"));
+ assert!(std::fs::read_to_string(directory.join(".gitignore"))
+ .unwrap()
+ .contains(".dbx-repository-signing-key.env"));
+ let manifest: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(directory.join("manifest.json")).unwrap()).unwrap();
+ assert_eq!(manifest["version"], "1.2.3");
+ let config: toml::Value =
+ toml::from_str(&std::fs::read_to_string(directory.join("dbx-plugin.toml")).unwrap()).unwrap();
+ let workflow = std::fs::read_to_string(directory.join(".github/workflows/plugin-release.yml")).unwrap();
+ assert!(!workflow.contains("signing-key-id"));
+ assert!(!workflow.contains("DBX_PLUGIN_SIGNING_KEY"));
+ assert!(workflow.contains("plugin-cli-version: 0.1.1"));
+ assert!(!workflow.contains("sdk-ref:"));
+
+ match template {
+ ProjectTemplate::Frontend => {
+ assert!(manifest["entrypoints"].get("backend").is_none());
+ assert!(config.get("backend").is_none());
+ assert!(!directory.join("backend").exists());
+ assert!(workflow.contains("\"target\":\"universal\""));
+ }
+ ProjectTemplate::Svelte => {
+ assert!(manifest["entrypoints"].get("backend").is_none());
+ assert!(config.get("backend").is_none());
+ assert!(directory.join("src/App.svelte").is_file());
+ assert!(directory.join("package.json").is_file());
+ assert!(directory.join("svelte.config.js").is_file());
+ assert!(directory.join("index.html").is_file());
+ assert!(workflow.contains("\"target\":\"universal\""));
+ }
+ ProjectTemplate::Rust => {
+ assert!(manifest["entrypoints"].get("backend").is_some());
+ assert!(config.get("backend").is_some());
+ assert!(directory.join("backend/src/main.rs").is_file());
+ }
+ ProjectTemplate::Go => {
+ assert!(manifest["entrypoints"].get("backend").is_some());
+ assert!(config.get("backend").is_some());
+ assert!(directory.join("backend/main.go").is_file());
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn packages_frontend_project_as_universal_without_build_residue() {
+ let root = tempfile::tempdir().unwrap();
+ let directory = root.path().join("frontend-package");
+ create_project(&CreateOptions {
+ directory: directory.clone(),
+ template: ProjectTemplate::Frontend,
+ plugin_id: "com.example.frontend-package".to_string(),
+ name: "Frontend Package".to_string(),
+ publisher: "example".to_string(),
+ description: "Frontend-only package".to_string(),
+ version: "1.2.3".to_string(),
+ sdk_root: None,
+ force: false,
+ })
+ .unwrap();
+
+ let (package, metadata) = package_project(&PackageOptions {
+ project: directory.clone(),
+ target: Some("universal".to_string()),
+ output_directory: None,
+ artifact_url: None,
+ })
+ .unwrap();
+ assert_eq!(package.file_name().unwrap(), "com.example.frontend-package-1.2.3-universal.dbxp");
+ assert!(package.is_file());
+ assert!(metadata.is_file());
+ let artifact: serde_json::Value = serde_json::from_slice(&std::fs::read(metadata).unwrap()).unwrap();
+ assert_eq!(artifact["target"], "universal");
+ assert!(std::fs::read_dir(directory.join("dist")).unwrap().all(|entry| {
+ let name = entry.unwrap().file_name();
+ let name = name.to_string_lossy();
+ !name.starts_with(".stage-") && !name.starts_with(".build-")
+ }));
+ }
+
+ #[test]
+ fn interactive_wizard_reprompts_invalid_values() {
+ let root = tempfile::tempdir().unwrap();
+ let directory = root.path().join("wizard-plugin");
+ let input = format!("{}\n5\n4\nInvalid ID\ncom.acme.wizard\n\n\n\n1\n1.2.3\nmaybe\ny\n", directory.display());
+ let mut reader = Cursor::new(input.into_bytes());
+ let mut output = Vec::new();
+ let options = resolve_create_options(CreateInputs::default(), true, &mut reader, &mut output).unwrap().unwrap();
+
+ assert_eq!(options.directory, directory);
+ assert_eq!(options.template, ProjectTemplate::Go);
+ assert_eq!(options.plugin_id, "com.acme.wizard");
+ assert_eq!(options.name, "Wizard Plugin");
+ assert_eq!(options.publisher, "acme");
+ assert_eq!(options.description, "Wizard Plugin for DBX.");
+ assert_eq!(options.version, "1.2.3");
+ let output = String::from_utf8(output).unwrap();
+ assert!(output.contains("Invalid: choose 1/Frontend, 2/Svelte, 3/Rust, or 4/Go"));
+ assert!(output.contains("Invalid: plugin id must use lowercase letters"));
+ assert!(output.contains("Invalid: Version must be valid SemVer"));
+ assert!(output.contains("DBX Store signs approved official releases"));
+ assert!(output.contains("Plugin configuration:"));
+ assert!(output.contains("Invalid: enter y or n"));
+ }
+
+ #[test]
+ fn formats_common_plugin_acronyms_and_validates_semver() {
+ assert_eq!(title_from_slug("dbx-ssh-sftp-workbench"), "DBX SSH SFTP Workbench");
+ validate_semver("1.2.3-beta.1+darwin.arm64").unwrap();
+ assert!(validate_semver("1.2.3-").is_err());
+ assert!(validate_semver("01.2.3").is_err());
+ }
+}
diff --git a/plugins/sdk/cli/src/main.rs b/plugins/sdk/cli/src/main.rs
new file mode 100644
index 0000000000..b57575e886
--- /dev/null
+++ b/plugins/sdk/cli/src/main.rs
@@ -0,0 +1,6 @@
+fn main() {
+ if let Err(error) = dbx_plugin_cli::run_cli(std::env::args().skip(1)) {
+ dbx_plugin_cli::print_error(&error);
+ std::process::exit(1);
+ }
+}
diff --git a/plugins/sdk/cli/templates/common/README.md b/plugins/sdk/cli/templates/common/README.md
new file mode 100644
index 0000000000..7baf865b79
--- /dev/null
+++ b/plugins/sdk/cli/templates/common/README.md
@@ -0,0 +1,34 @@
+# {{PLUGIN_NAME}}
+
+{{DESCRIPTION}}
+
+Generated by `dbx-plugin create` with the **{{TEMPLATE_LABEL}}** template.
+
+## Develop
+
+With Node.js 22+ and the backend compiler installed, run the browser development host without DBX:
+
+```bash
+dbx-plugin dev --path . --port 5190
+```
+
+The CLI builds the backend and loads the declared UI. Optional `[dev]` `ui_build` and `ui_watch` command arrays configure frontend builds. Development credentials are stored as local plaintext in `.dbx-dev/`; keep that directory out of commits and packages. Use the real DBX host for final integration testing.
+
+Build an installable candidate:
+
+```bash
+dbx-plugin package .
+```
+
+The command builds the native backend for the current host, stages `manifest.json`, `assets/`, and `ui/`, then writes an unsigned target-specific `.dbxp` candidate plus matching `.artifact.json` into `dist/`.
+
+## Release
+
+1. Publish a GitHub Release. The generated workflow builds unsigned candidates for every target.
+2. Open a **Plugin submission Issue** in `t8y2/dbx-store` with the source tag and `release-candidates.json` URL.
+3. After review, DBX Store signs approved candidates with the official repository key and publishes the installable assets.
+4. Open the final catalog PR against **`t8y2/dbx-store:main`** using the signed artifact metadata.
+
+Source code and unsigned candidates stay in this repository. DBX users install the DBX Store-signed assets exposed by the official catalog.
+
+Do not submit ordinary plugin source to `t8y2/dbx`; that repository accepts plugin host, SDK, CLI, schema, documentation, and official-example changes.
diff --git a/plugins/sdk/cli/templates/common/assets/plugin.svg b/plugins/sdk/cli/templates/common/assets/plugin.svg
new file mode 100644
index 0000000000..8575cb14a1
--- /dev/null
+++ b/plugins/sdk/cli/templates/common/assets/plugin.svg
@@ -0,0 +1,10 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="{{PLUGIN_NAME_XML}}">
+ <defs>
+ <linearGradient id="g" x1="8" y1="8" x2="56" y2="56" gradientUnits="userSpaceOnUse">
+ <stop stop-color="#6d5dfc"/>
+ <stop offset="1" stop-color="#2cc9a7"/>
+ </linearGradient>
+ </defs>
+ <rect width="64" height="64" rx="16" fill="url(#g)"/>
+ <path fill="#fff" d="M20 18h18a10 10 0 0 1 0 20H28v8h-8V18Zm8 8v4h10a2 2 0 1 0 0-4H28Z"/>
+</svg>
diff --git a/plugins/sdk/cli/templates/common/dbx-plugin.toml b/plugins/sdk/cli/templates/common/dbx-plugin.toml
new file mode 100644
index 0000000000..8d95398b91
--- /dev/null
+++ b/plugins/sdk/cli/templates/common/dbx-plugin.toml
@@ -0,0 +1,9 @@
+schema_version = 1
+
+[backend]
+language = "{{LANGUAGE}}"
+directory = "backend"
+binary = "{{BINARY_NAME}}"
+
+[package]
+include = ["assets", "ui"]
diff --git a/plugins/sdk/cli/templates/common/github/plugin-release.yml b/plugins/sdk/cli/templates/common/github/plugin-release.yml
new file mode 100644
index 0000000000..a07ef3c358
--- /dev/null
+++ b/plugins/sdk/cli/templates/common/github/plugin-release.yml
@@ -0,0 +1,18 @@
+name: Release DBX plugin
+
+on:
+ release:
+ types: [published]
+
+permissions:
+ contents: write
+
+jobs:
+ release:
+ uses: t8y2/dbx/.github/workflows/plugin-release-reusable.yml@plugin-sdk-v1
+ with:
+ release-tag: ${{ github.event.release.tag_name }}
+ package-command: dbx-plugin package .
+ package-path: dist/*.dbxp
+ metadata-path: dist/*.artifact.json
+ plugin-cli-version: 0.1.1
diff --git a/plugins/sdk/cli/templates/common/gitignore b/plugins/sdk/cli/templates/common/gitignore
new file mode 100644
index 0000000000..fb600935b4
--- /dev/null
+++ b/plugins/sdk/cli/templates/common/gitignore
@@ -0,0 +1,5 @@
+/dist/
+/.dbx-dev/
+.dbx-repository-signing-key.env
+.DS_Store
+*.log
diff --git a/plugins/sdk/cli/templates/common/manifest.json b/plugins/sdk/cli/templates/common/manifest.json
new file mode 100644
index 0000000000..c2e189ee57
--- /dev/null
+++ b/plugins/sdk/cli/templates/common/manifest.json
@@ -0,0 +1,89 @@
+{
+ "$schema": "https://raw.githubusercontent.com/t8y2/dbx/plugin-sdk-v1/plugins/manifest.schema.json",
+ "manifest_version": 1,
+ "id": "{{PLUGIN_ID}}",
+ "name": "{{PLUGIN_NAME_JSON}}",
+ "version": "{{VERSION}}",
+ "publisher": "{{PUBLISHER_JSON}}",
+ "description": "{{DESCRIPTION_JSON}}",
+ "icon": "assets/plugin.svg",
+ "engines": {
+ "dbx": ">=0.5.68",
+ "host_api": "1"
+ },
+ "entrypoints": {
+ "backend": {
+ "executable": "bin/{{BINARY_NAME}}"
+ },
+ "ui": {
+ "root": "ui",
+ "entry": "ui/index.html"
+ }
+ },
+ "contributions": [
+ {
+ "type": "connection-provider",
+ "id": "{{PLUGIN_ID}}.connection",
+ "label": "{{PLUGIN_NAME_JSON}} connection",
+ "icon": "assets/plugin.svg",
+ "database_type": "{{CONNECTION_TYPE}}",
+ "description": "Connection form contributed by {{PLUGIN_NAME_JSON}}.",
+ "fields": [
+ {
+ "key": "display_name",
+ "label": "Connection name",
+ "type": "text",
+ "default": "{{PLUGIN_NAME_JSON}} connection",
+ "binding": "name",
+ "required": true
+ },
+ {
+ "key": "host",
+ "label": "Host",
+ "type": "text",
+ "default": "localhost",
+ "binding": "host",
+ "required": true
+ },
+ {
+ "key": "port",
+ "label": "Port",
+ "type": "number",
+ "default": 0,
+ "binding": "port",
+ "required": true
+ }
+ ],
+ "workbench": "{{PLUGIN_ID}}.workbench",
+ "capabilities": ["test", "connect", "disconnect"]
+ },
+ {
+ "type": "workbench",
+ "id": "{{PLUGIN_ID}}.workbench",
+ "label": "{{PLUGIN_NAME_JSON}} Workbench",
+ "description": "Sandboxed UI contributed by {{PLUGIN_NAME_JSON}}.",
+ "icon": "assets/plugin.svg"
+ }
+ ],
+ "localizations": {
+ "zh-CN": {
+ "name": "{{PLUGIN_NAME_JSON}}",
+ "description": "{{DESCRIPTION_JSON}}",
+ "contributions": {
+ "{{PLUGIN_ID}}.connection": {
+ "label": "{{PLUGIN_NAME_JSON}} 连接",
+ "description": "由插件声明的连接表单。",
+ "fields": {
+ "display_name": { "label": "连接名称" },
+ "host": { "label": "主机" },
+ "port": { "label": "端口" }
+ }
+ },
+ "{{PLUGIN_ID}}.workbench": {
+ "label": "{{PLUGIN_NAME_JSON}} 工作台",
+ "description": "由插件提供的沙箱工作台界面。"
+ }
+ }
+ }
+ }
+}
diff --git a/plugins/sdk/cli/templates/common/ui/index.html b/plugins/sdk/cli/templates/common/ui/index.html
new file mode 100644
index 0000000000..807f5818f0
--- /dev/null
+++ b/plugins/sdk/cli/templates/common/ui/index.html
@@ -0,0 +1,56 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>{{PLUGIN_NAME_HTML}}</title>
+ <style>
+ :root { color-scheme: light dark; font-family: Inter, ui-sans-serif, system-ui, sans-serif; }
+ * { box-sizing: border-box; }
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 32px; background: radial-gradient(circle at top left, rgba(109,93,252,.2), transparent 40%), Canvas; color: CanvasText; }
+ main { width: min(680px, 100%); padding: 32px; border: 1px solid color-mix(in srgb, CanvasText 16%, transparent); border-radius: 20px; background: color-mix(in srgb, Canvas 92%, transparent); box-shadow: 0 24px 80px rgba(0,0,0,.12); }
+ .eyebrow { color: #6d5dfc; font-size: 12px; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; }
+ h1 { margin: 10px 0; font-size: clamp(28px, 5vw, 46px); }
+ p { line-height: 1.65; opacity: .74; }
+ button { margin-top: 20px; border: 0; border-radius: 12px; padding: 12px 18px; background: #6d5dfc; color: white; font: inherit; font-weight: 650; cursor: pointer; }
+ button:disabled { opacity: .55; cursor: wait; }
+ pre { margin-top: 20px; min-height: 92px; overflow: auto; padding: 16px; border-radius: 12px; background: color-mix(in srgb, CanvasText 7%, transparent); }
+ </style>
+ </head>
+ <body>
+ <main>
+ <div class="eyebrow" id="eyebrow">DBX plugin workbench</div>
+ <h1>{{PLUGIN_NAME_HTML}}</h1>
+ <p id="description">This sandboxed page talks to the {{LANGUAGE_LABEL}} sidecar only through the DBX Host Bridge.</p>
+ <button id="ping" type="button">Invoke sidecar</button>
+ <pre id="result">Waiting for DBX plugin host…</pre>
+ </main>
+ <script>
+ const result = document.querySelector("#result");
+ const button = document.querySelector("#ping");
+ const copy = {
+ en: { eyebrow: "DBX plugin workbench", description: "This sandboxed page talks to the {{LANGUAGE_LABEL}} sidecar only through the DBX Host Bridge.", button: "Invoke sidecar", ready: "Ready", calling: "Calling sidecar…", error: "Error" },
+ zh: { eyebrow: "DBX 插件工作台", description: "此沙箱页面仅通过 DBX Host Bridge 与 {{LANGUAGE_LABEL}} Sidecar 通信。", button: "调用 Sidecar", ready: "已就绪", calling: "正在调用 Sidecar…", error: "错误" }
+ };
+ let text = copy.en;
+ window.dbxPlugin.ready.then(() => {
+ text = window.dbxPlugin.locale.toLowerCase().startsWith("zh") ? copy.zh : copy.en;
+ document.querySelector("#eyebrow").textContent = text.eyebrow;
+ document.querySelector("#description").textContent = text.description;
+ button.textContent = text.button;
+ result.textContent = text.ready;
+ });
+ button.addEventListener("click", async () => {
+ button.disabled = true;
+ result.textContent = text.calling;
+ try {
+ result.textContent = JSON.stringify(await window.dbxPlugin.invoke("{{METHOD_PREFIX}}/ping", { connectionId: window.dbxPlugin.context?.connectionId }), null, 2);
+ } catch (error) {
+ result.textContent = `${text.error}: ${error.message}`;
+ } finally {
+ button.disabled = false;
+ }
+ });
+ </script>
+ </body>
+</html>
diff --git a/plugins/sdk/cli/templates/frontend/README.md b/plugins/sdk/cli/templates/frontend/README.md
new file mode 100644
index 0000000000..e0c9208e68
--- /dev/null
+++ b/plugins/sdk/cli/templates/frontend/README.md
@@ -0,0 +1,34 @@
+# {{PLUGIN_NAME}}
+
+{{DESCRIPTION}}
+
+Generated by `dbx-plugin create` with the **{{TEMPLATE_LABEL}}** template. This project has no native backend and produces one cross-platform `universal` package.
+
+## Develop
+
+Edit `ui/index.html` and run the browser development host with Node.js 22+:
+
+```bash
+dbx-plugin dev --path . --port 5190
+```
+
+No backend or DBX application is required. Open this plugin's workbench from the development shell; reload the page after edits. `.dbx-dev/` stores local development data and must not be committed or packaged. Use the real DBX host for final integration testing.
+
+Then package the plugin:
+
+```bash
+dbx-plugin package .
+```
+
+The command stages `manifest.json`, `assets/`, and `ui/`, then writes an unsigned universal `.dbxp` candidate plus matching `.artifact.json` into `dist/`.
+
+## Release
+
+1. Publish a GitHub Release. The generated workflow builds an unsigned universal candidate.
+2. Open a **Plugin submission Issue** in `t8y2/dbx-store` with the source tag and `release-candidates.json` URL.
+3. After review, DBX Store signs the approved candidate with the official repository key and publishes the installable asset.
+4. Open the final catalog PR against **`t8y2/dbx-store:main`** using the signed artifact metadata.
+
+Source code and the unsigned candidate stay in this repository. DBX users install the DBX Store-signed asset exposed by the official catalog.
+
+Do not submit ordinary plugin source to `t8y2/dbx`; that repository accepts plugin host, SDK, CLI, schema, documentation, and official-example changes.
diff --git a/plugins/sdk/cli/templates/frontend/dbx-plugin.toml b/plugins/sdk/cli/templates/frontend/dbx-plugin.toml
new file mode 100644
index 0000000000..f1519b6936
--- /dev/null
+++ b/plugins/sdk/cli/templates/frontend/dbx-plugin.toml
@@ -0,0 +1,4 @@
+schema_version = 1
+
+[package]
+include = ["assets", "ui"]
diff --git a/plugins/sdk/cli/templates/frontend/github/plugin-release.yml b/plugins/sdk/cli/templates/frontend/github/plugin-release.yml
new file mode 100644
index 0000000000..5b6b47d1d3
--- /dev/null
+++ b/plugins/sdk/cli/templates/frontend/github/plugin-release.yml
@@ -0,0 +1,19 @@
+name: Release DBX plugin
+
+on:
+ release:
+ types: [published]
+
+permissions:
+ contents: write
+
+jobs:
+ release:
+ uses: t8y2/dbx/.github/workflows/plugin-release-reusable.yml@plugin-sdk-v1
+ with:
+ release-tag: ${{ github.event.release.tag_name }}
+ package-command: dbx-plugin package .
+ package-path: dist/*.dbxp
+ metadata-path: dist/*.artifact.json
+ plugin-cli-version: 0.1.1
+ build-matrix: '{"include":[{"runner":"ubuntu-24.04","target":"universal"}]}'
diff --git a/plugins/sdk/cli/templates/frontend/manifest.json b/plugins/sdk/cli/templates/frontend/manifest.json
new file mode 100644
index 0000000000..3402eef2f3
--- /dev/null
+++ b/plugins/sdk/cli/templates/frontend/manifest.json
@@ -0,0 +1,41 @@
+{
+ "$schema": "https://raw.githubusercontent.com/t8y2/dbx/plugin-sdk-v1/plugins/manifest.schema.json",
+ "manifest_version": 1,
+ "id": "{{PLUGIN_ID}}",
+ "name": "{{PLUGIN_NAME_JSON}}",
+ "version": "{{VERSION}}",
+ "publisher": "{{PUBLISHER_JSON}}",
+ "description": "{{DESCRIPTION_JSON}}",
+ "icon": "assets/plugin.svg",
+ "engines": {
+ "dbx": ">=0.5.68",
+ "host_api": "1"
+ },
+ "entrypoints": {
+ "ui": {
+ "root": "ui",
+ "entry": "ui/index.html"
+ }
+ },
+ "contributions": [
+ {
+ "type": "workbench",
+ "id": "{{PLUGIN_ID}}.workbench",
+ "label": "{{PLUGIN_NAME_JSON}}",
+ "description": "Sandboxed frontend workbench contributed by {{PLUGIN_NAME_JSON}}.",
+ "icon": "assets/plugin.svg"
+ }
+ ],
+ "localizations": {
+ "zh-CN": {
+ "name": "{{PLUGIN_NAME_JSON}}",
+ "description": "{{DESCRIPTION_JSON}}",
+ "contributions": {
+ "{{PLUGIN_ID}}.workbench": {
+ "label": "{{PLUGIN_NAME_JSON}}",
+ "description": "由插件提供的沙箱前端工作台。"
+ }
+ }
+ }
+ }
+}
diff --git a/plugins/sdk/cli/templates/frontend/ui/index.html b/plugins/sdk/cli/templates/frontend/ui/index.html
new file mode 100644
index 0000000000..db51c1e1cc
--- /dev/null
+++ b/plugins/sdk/cli/templates/frontend/ui/index.html
@@ -0,0 +1,55 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>{{PLUGIN_NAME_HTML}}</title>
+ <style>
+ :root { color-scheme: light dark; font-family: Inter, ui-sans-serif, system-ui, sans-serif; }
+ * { box-sizing: border-box; }
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 32px; background: radial-gradient(circle at top left, rgba(109,93,252,.2), transparent 40%), Canvas; color: CanvasText; }
+ main { width: min(680px, 100%); padding: 32px; border: 1px solid color-mix(in srgb, CanvasText 16%, transparent); border-radius: 20px; background: color-mix(in srgb, Canvas 92%, transparent); box-shadow: 0 24px 80px rgba(0,0,0,.12); }
+ .eyebrow { color: #6d5dfc; font-size: 12px; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; }
+ h1 { margin: 10px 0; font-size: clamp(28px, 5vw, 46px); }
+ p { line-height: 1.65; opacity: .74; }
+ button { margin-top: 20px; border: 0; border-radius: 12px; padding: 12px 18px; background: #6d5dfc; color: white; font: inherit; font-weight: 650; cursor: pointer; }
+ button:disabled { opacity: .55; cursor: wait; }
+ pre { margin-top: 20px; min-height: 92px; overflow: auto; padding: 16px; border-radius: 12px; background: color-mix(in srgb, CanvasText 7%, transparent); }
+ </style>
+ </head>
+ <body>
+ <main>
+ <div class="eyebrow" id="eyebrow">DBX frontend plugin</div>
+ <h1>{{PLUGIN_NAME_HTML}}</h1>
+ <p id="description">This universal sandboxed workbench runs without a native sidecar.</p>
+ <button id="context" type="button">Show host context</button>
+ <pre id="result">Waiting for DBX plugin host…</pre>
+ </main>
+ <script>
+ const result = document.querySelector("#result");
+ const button = document.querySelector("#context");
+ const copy = {
+ en: { eyebrow: "DBX frontend plugin", description: "This universal sandboxed workbench runs without a native sidecar.", button: "Show host context", ready: "Ready", error: "Error" },
+ zh: { eyebrow: "DBX 前端插件", description: "这个通用沙箱工作台不需要原生 Sidecar。", button: "查看宿主上下文", ready: "已就绪", error: "错误" }
+ };
+ let text = copy.en;
+ window.dbxPlugin.ready.then((context) => {
+ text = window.dbxPlugin.locale.toLowerCase().startsWith("zh") ? copy.zh : copy.en;
+ document.querySelector("#eyebrow").textContent = text.eyebrow;
+ document.querySelector("#description").textContent = text.description;
+ button.textContent = text.button;
+ result.textContent = context && Object.keys(context).length ? JSON.stringify(context, null, 2) : text.ready;
+ });
+ button.addEventListener("click", async () => {
+ button.disabled = true;
+ try {
+ result.textContent = JSON.stringify(await window.dbxPlugin.request("host.getContext"), null, 2);
+ } catch (error) {
+ result.textContent = `${text.error}: ${error.message}`;
+ } finally {
+ button.disabled = false;
+ }
+ });
+ </script>
+ </body>
+</html>
diff --git a/plugins/sdk/cli/templates/go/backend/go.mod b/plugins/sdk/cli/templates/go/backend/go.mod
new file mode 100644
index 0000000000..3e55e6f4a2
--- /dev/null
+++ b/plugins/sdk/cli/templates/go/backend/go.mod
@@ -0,0 +1,6 @@
+module {{GO_MODULE}}
+
+go 1.22
+
+require github.com/t8y2/dbx/plugins/sdk/go/dbx-plugin-sdk v0.1.0
+{{GO_SDK_REPLACE}}
diff --git a/plugins/sdk/cli/templates/go/backend/main.go b/plugins/sdk/cli/templates/go/backend/main.go
new file mode 100644
index 0000000000..bf8dc5b7fe
--- /dev/null
+++ b/plugins/sdk/cli/templates/go/backend/main.go
@@ -0,0 +1,74 @@
+package main
+
+import (
+ "encoding/json"
+ "log"
+ "sync"
+
+ dbxpluginsdk "github.com/t8y2/dbx/plugins/sdk/go/dbx-plugin-sdk"
+)
+
+type plugin struct {
+ mutex sync.Mutex
+ connections map[string]struct{}
+}
+
+func (plugin *plugin) Handle(
+ _ dbxpluginsdk.RequestContext,
+ method string,
+ params json.RawMessage,
+ _ *dbxpluginsdk.Emitter,
+) (any, *dbxpluginsdk.PluginError) {
+ var values map[string]any
+ if err := json.Unmarshal(params, &values); err != nil {
+ return nil, dbxpluginsdk.NewError(-32602, "Invalid request parameters")
+ }
+ switch method {
+ case "connection/test":
+ connection, _ := values["connection"].(map[string]any)
+ return map[string]any{"success": true, "message": "{{PLUGIN_NAME_GO}} is ready", "connection": connection}, nil
+ case "connection/connect":
+ connectionID, pluginError := requestConnectionID(values)
+ if pluginError != nil {
+ return nil, pluginError
+ }
+ plugin.mutex.Lock()
+ plugin.connections[connectionID] = struct{}{}
+ plugin.mutex.Unlock()
+ return map[string]any{"success": true}, nil
+ case "connection/disconnect":
+ connectionID, pluginError := requestConnectionID(values)
+ if pluginError != nil {
+ return nil, pluginError
+ }
+ plugin.mutex.Lock()
+ delete(plugin.connections, connectionID)
+ plugin.mutex.Unlock()
+ return map[string]any{"success": true}, nil
+ case "{{METHOD_PREFIX}}/ping":
+ return map[string]any{"ok": true, "plugin": "{{PLUGIN_ID}}", "language": "go", "connectionId": values["connectionId"]}, nil
+ default:
+ return nil, dbxpluginsdk.MethodNotFound(method)
+ }
+}
+
+func requestConnectionID(values map[string]any) (string, *dbxpluginsdk.PluginError) {
+ connection, _ := values["connection"].(map[string]any)
+ connectionID, _ := connection["id"].(string)
+ if connectionID == "" {
+ return "", dbxpluginsdk.NewError(-32602, "Missing connection id")
+ }
+ return connectionID, nil
+}
+
+func main() {
+ metadata := dbxpluginsdk.Metadata{
+ ID: "{{PLUGIN_ID}}",
+ Version: "{{VERSION}}",
+ Capabilities: []string{"connections"},
+ }
+ server := dbxpluginsdk.NewServer(metadata, &plugin{connections: map[string]struct{}{}})
+ if err := server.Serve(); err != nil {
+ log.Fatal(err)
+ }
+}
diff --git a/plugins/sdk/cli/templates/rust/backend/Cargo.toml b/plugins/sdk/cli/templates/rust/backend/Cargo.toml
new file mode 100644
index 0000000000..c72ef08585
--- /dev/null
+++ b/plugins/sdk/cli/templates/rust/backend/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "{{BINARY_NAME}}"
+version = "{{VERSION}}"
+edition = "2021"
+license = "Apache-2.0"
+
+[workspace]
+
+[dependencies]
+dbx-plugin-sdk = {{RUST_SDK_DEPENDENCY}}
+serde_json = "1"
+
+# Keep plugin binaries close to the host app's size: default release settings
+# leave ~20MB of symbols and unoptimized generic code in an OpenDAL-sized backend.
+# panic stays "unwind" so the sidecar protocol can report panics as errors.
+[profile.release]
+strip = true
+lto = true
+codegen-units = 1
diff --git a/plugins/sdk/cli/templates/rust/backend/src/main.rs b/plugins/sdk/cli/templates/rust/backend/src/main.rs
new file mode 100644
index 0000000000..d7ad84760e
--- /dev/null
+++ b/plugins/sdk/cli/templates/rust/backend/src/main.rs
@@ -0,0 +1,70 @@
+use std::collections::HashSet;
+use std::sync::Mutex;
+
+use dbx_plugin_sdk::{PluginEmitter, PluginError, PluginHandler, PluginMetadata, PluginServer, RequestContext};
+use serde_json::{json, Value};
+
+#[derive(Default)]
+struct Plugin {
+ connections: Mutex<HashSet<String>>,
+}
+
+impl PluginHandler for Plugin {
+ fn handle(
+ &self,
+ _context: RequestContext,
+ method: &str,
+ params: Value,
+ _emitter: &PluginEmitter,
+ ) -> Result<Value, PluginError> {
+ match method {
+ "connection/test" => {
+ let connection = params.get("connection").cloned().unwrap_or_default();
+ Ok(json!({
+ "success": true,
+ "message": format!(
+ "{{PLUGIN_NAME_RUST}} is ready for {}:{}.",
+ connection.get("host").and_then(Value::as_str).unwrap_or("localhost"),
+ connection.get("port").and_then(Value::as_u64).unwrap_or(0)
+ )
+ }))
+ }
+ "connection/connect" => {
+ let connection_id = connection_id(&params)?;
+ self.connections
+ .lock()
+ .map_err(|_| PluginError::new(-32000, "Connection registry is poisoned"))?
+ .insert(connection_id.to_string());
+ Ok(json!({ "success": true }))
+ }
+ "connection/disconnect" => {
+ let connection_id = connection_id(&params)?;
+ self.connections
+ .lock()
+ .map_err(|_| PluginError::new(-32000, "Connection registry is poisoned"))?
+ .remove(connection_id);
+ Ok(json!({ "success": true }))
+ }
+ "{{METHOD_PREFIX}}/ping" => Ok(json!({
+ "ok": true,
+ "plugin": "{{PLUGIN_ID}}",
+ "language": "rust",
+ "connectionId": params.get("connectionId").cloned().unwrap_or(Value::Null)
+ })),
+ _ => Err(PluginError::method_not_found(method)),
+ }
+ }
+}
+
+fn connection_id(params: &Value) -> Result<&str, PluginError> {
+ params
+ .get("connection")
+ .and_then(|connection| connection.get("id"))
+ .and_then(Value::as_str)
+ .ok_or_else(|| PluginError::new(-32602, "Missing connection id"))
+}
+
+fn main() -> std::io::Result<()> {
+ let metadata = PluginMetadata::new("{{PLUGIN_ID}}", env!("CARGO_PKG_VERSION")).with_capability("connections");
+ PluginServer::new(metadata, Plugin::default()).serve()
+}
diff --git a/plugins/sdk/cli/templates/svelte/README.md b/plugins/sdk/cli/templates/svelte/README.md
new file mode 100644
index 0000000000..78771c0651
--- /dev/null
+++ b/plugins/sdk/cli/templates/svelte/README.md
@@ -0,0 +1,22 @@
+# {{PLUGIN_NAME}}
+
+{{DESCRIPTION}}
+
+Generated by `dbx-plugin create` with the **Svelte + Vite (universal)** template.
+
+## Develop
+
+Install dependencies and run the browser development host:
+
+```bash
+npm install
+dbx-plugin dev --path . --port 5190
+```
+
+The UI is compiled from `src/` into `ui/`. The generated `window.dbxPlugin` bridge exposes DBX context, locale, theme and backend methods to the Svelte workbench. Use the real DBX host for final integration testing.
+
+Build an unsigned universal candidate with `dbx-plugin package .`.
+
+## Release
+
+Publish the unsigned candidate for review, then open a **Plugin submission Issue** and submit the approved signed artifact metadata to `t8y2/dbx-store:main`. DBX Store signs approved official releases and publishes the installable package. Do not submit ordinary plugin source to `t8y2/dbx`; that repository accepts plugin host, SDK, CLI, schema, documentation, and official-example changes.
diff --git a/plugins/sdk/cli/templates/svelte/dbx-plugin.toml b/plugins/sdk/cli/templates/svelte/dbx-plugin.toml
new file mode 100644
index 0000000000..e940f692f5
--- /dev/null
+++ b/plugins/sdk/cli/templates/svelte/dbx-plugin.toml
@@ -0,0 +1,8 @@
+schema_version = 1
+
+[package]
+include = ["assets", "ui"]
+
+[dev]
+ui_build = ["npm", "run", "build"]
+ui_watch = ["npm", "run", "build:watch"]
diff --git a/plugins/sdk/cli/templates/svelte/index.html b/plugins/sdk/cli/templates/svelte/index.html
new file mode 100644
index 0000000000..68d0112453
--- /dev/null
+++ b/plugins/sdk/cli/templates/svelte/index.html
@@ -0,0 +1,8 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ </head>
+ <body><div id="app"></div><script type="module" src="/src/main.js"></script></body>
+</html>
diff --git a/plugins/sdk/cli/templates/svelte/manifest.json b/plugins/sdk/cli/templates/svelte/manifest.json
new file mode 100644
index 0000000000..8d3d109196
--- /dev/null
+++ b/plugins/sdk/cli/templates/svelte/manifest.json
@@ -0,0 +1,33 @@
+{
+ "$schema": "https://raw.githubusercontent.com/t8y2/dbx/plugin-sdk-v1/plugins/manifest.schema.json",
+ "manifest_version": 1,
+ "id": "{{PLUGIN_ID}}",
+ "name": "{{PLUGIN_NAME_JSON}}",
+ "version": "{{VERSION}}",
+ "publisher": "{{PUBLISHER_JSON}}",
+ "description": "{{DESCRIPTION_JSON}}",
+ "icon": "assets/plugin.svg",
+ "engines": { "dbx": ">=0.5.68", "host_api": "1" },
+ "entrypoints": { "ui": { "root": "ui", "entry": "ui/index.html" } },
+ "contributions": [
+ {
+ "type": "workbench",
+ "id": "{{PLUGIN_ID}}.workbench",
+ "label": "{{PLUGIN_NAME_JSON}}",
+ "description": "Svelte workbench contributed by {{PLUGIN_NAME_JSON}}.",
+ "icon": "assets/plugin.svg"
+ }
+ ],
+ "localizations": {
+ "zh-CN": {
+ "name": "{{PLUGIN_NAME_JSON}}",
+ "description": "{{DESCRIPTION_JSON}}",
+ "contributions": {
+ "{{PLUGIN_ID}}.workbench": {
+ "label": "{{PLUGIN_NAME_JSON}}",
+ "description": "由插件提供的 Svelte 沙箱工作台。"
+ }
+ }
+ }
+ }
+}
diff --git a/plugins/sdk/cli/templates/svelte/package.json b/plugins/sdk/cli/templates/svelte/package.json
new file mode 100644
index 0000000000..dd0d45bec4
--- /dev/null
+++ b/plugins/sdk/cli/templates/svelte/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "{{PLUGIN_ID}}-ui",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "build": "vite build",
+ "build:watch": "vite build --watch"
+ },
+ "devDependencies": {
+ "@sveltejs/vite-plugin-svelte": "^6.2.1",
+ "svelte": "^5.38.7",
+ "vite": "^7.1.5"
+ }
+}
diff --git a/plugins/sdk/cli/templates/svelte/src/App.svelte b/plugins/sdk/cli/templates/svelte/src/App.svelte
new file mode 100644
index 0000000000..66396e7e8e
--- /dev/null
+++ b/plugins/sdk/cli/templates/svelte/src/App.svelte
@@ -0,0 +1,44 @@
+<script>
+ let context = $state({});
+ let message = $state("Waiting for DBX plugin host…");
+
+ const copy = {
+ en: { eyebrow: "DBX Svelte plugin", description: "A Svelte-powered sandboxed workbench.", action: "Show host context", ready: "Ready" },
+ zh: { eyebrow: "DBX Svelte 插件", description: "由 Svelte 驱动的沙箱工作台。", action: "查看宿主上下文", ready: "已就绪" },
+ };
+ let text = $state(copy.en);
+
+ $effect(() => {
+ window.dbxPlugin.ready.then((value) => {
+ context = value || {};
+ text = window.dbxPlugin.locale.toLowerCase().startsWith("zh") ? copy.zh : copy.en;
+ message = text.ready;
+ });
+ });
+
+ async function showContext() {
+ context = await window.dbxPlugin.request("host.getContext");
+ message = JSON.stringify(context, null, 2);
+ }
+</script>
+
+<svelte:head><title>{{PLUGIN_NAME_HTML}}</title></svelte:head>
+
+<main>
+ <div class="eyebrow">{text.eyebrow}</div>
+ <h1>{{PLUGIN_NAME_HTML}}</h1>
+ <p>{text.description}</p>
+ <button type="button" onclick={showContext}>{text.action}</button>
+ <pre>{message}</pre>
+</main>
+
+<style>
+ :global(*) { box-sizing: border-box; }
+ :global(body) { margin: 0; min-height: 100vh; font-family: Inter, ui-sans-serif, system-ui, sans-serif; color: CanvasText; background: Canvas; }
+ main { min-height: 100vh; padding: clamp(24px, 6vw, 72px); background: radial-gradient(circle at top left, rgba(109, 93, 252, .2), transparent 42%), Canvas; }
+ .eyebrow { color: #6d5dfc; font-size: 12px; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; }
+ h1 { margin: 12px 0 8px; font-size: clamp(30px, 5vw, 54px); }
+ p { max-width: 620px; opacity: .72; line-height: 1.6; }
+ button { margin-top: 16px; border: 0; border-radius: 10px; padding: 11px 16px; color: white; background: #6d5dfc; font: inherit; cursor: pointer; }
+ pre { max-width: 760px; min-height: 70px; margin-top: 20px; padding: 14px; overflow: auto; border-radius: 10px; background: color-mix(in srgb, CanvasText 8%, transparent); }
+</style>
diff --git a/plugins/sdk/cli/templates/svelte/src/main.js b/plugins/sdk/cli/templates/svelte/src/main.js
new file mode 100644
index 0000000000..735045ab89
--- /dev/null
+++ b/plugins/sdk/cli/templates/svelte/src/main.js
@@ -0,0 +1,4 @@
+import App from "./App.svelte";
+import { mount } from "svelte";
+
+mount(App, { target: document.getElementById("app") });
diff --git a/plugins/sdk/cli/templates/svelte/svelte.config.js b/plugins/sdk/cli/templates/svelte/svelte.config.js
new file mode 100644
index 0000000000..d0e64483be
--- /dev/null
+++ b/plugins/sdk/cli/templates/svelte/svelte.config.js
@@ -0,0 +1,5 @@
+import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
+
+export default {
+ preprocess: vitePreprocess(),
+};
diff --git a/plugins/sdk/cli/templates/svelte/vite.config.js b/plugins/sdk/cli/templates/svelte/vite.config.js
new file mode 100644
index 0000000000..20a308437e
--- /dev/null
+++ b/plugins/sdk/cli/templates/svelte/vite.config.js
@@ -0,0 +1,10 @@
+import { svelte } from "@sveltejs/vite-plugin-svelte";
+import { defineConfig } from "vite";
+
+export default defineConfig({
+ plugins: [
+ svelte(),
+ { name: "dbx-build-signal", closeBundle() { console.log("DBX_UI_BUILD_SUCCESS"); } },
+ ],
+ build: { outDir: "ui", emptyOutDir: true },
+});
diff --git a/plugins/sdk/dev-host/.gitignore b/plugins/sdk/dev-host/.gitignore
new file mode 100644
index 0000000000..b0a5c349ca
--- /dev/null
+++ b/plugins/sdk/dev-host/.gitignore
@@ -0,0 +1,2 @@
+/node_modules/
+/dist/
diff --git a/plugins/sdk/dev-host/README.md b/plugins/sdk/dev-host/README.md
new file mode 100644
index 0000000000..cc6378e448
--- /dev/null
+++ b/plugins/sdk/dev-host/README.md
@@ -0,0 +1,120 @@
+# Plugin development runtime
+
+Generic browser development host for `dbx-plugin dev`. It loads declared workbenches and runs optional Rust/Go sidecars without starting the DBX desktop application.
+
+```bash
+dbx-plugin dev --path /path/to/plugin --port 5190
+```
+
+Requires Node.js 22+. Pure frontend projects do not need Rust or Go. Native projects need their own compiler and dependencies. The npm CLI bundles this runtime and a prebuilt UI; consumers do not install Vite, Vue, or build the development shell.
+
+## Build from source
+
+From the DBX repository:
+
+```bash
+npm ci --prefix plugins/sdk/dev-host
+npm run build --prefix plugins/sdk/dev-host
+cargo run --manifest-path plugins/sdk/cli/Cargo.toml -- dev --path /path/to/plugin
+```
+
+The Rust CLI locates `dist/runtime.mjs` relative to its source checkout. For a standalone native CLI, set `DBX_PLUGIN_DEV_RUNTIME` to the built entrypoint. `DBX_PLUGIN_NODE` selects Node. The npm launcher supplies both paths automatically.
+
+## Project configuration
+
+The CLI reads `manifest.json` and `dbx-plugin.toml`. Existing `[backend]` metadata selects Rust or Go and the executable name. Rust uses a cached debug target directory; Go uses a cached output directory. Explicit Git/path Rust SDK dependencies are not replaced by a crates.io patch.
+
+Optional UI commands in `dbx-plugin.toml`:
+
+```toml
+[dev]
+ui_build = ["npm", "run", "build"]
+ui_watch = ["npm", "run", "build:watch"]
+```
+
+Commands are executable/argument arrays, run in the plugin directory without a shell. No framework detection or automatic dependency installation occurs. Without these options, existing UI assets are served and watched. Manifest or runtime changes require restarting `dev`.
+
+When `ui_watch` is configured, its stdout must emit a standalone `DBX_UI_BUILD_SUCCESS` line after each successful, fully written build. Only this signal triggers automatic UI reload; partial output and failed builds do not. Add the signal to your build tool's successful completion hook (not an unconditional exit hook). Without `ui_watch`, static UI files retain debounced output watching. This protocol is independent of the frontend framework.
+
+`--path` defaults to the current directory. `--port` defaults to 5190 and falls back to an available port if occupied; `0` explicitly requests an available port. `--data-dir` defaults to `<project>/.dbx-dev/`. Packaging rejects `.dbx-dev` inputs, including nested directories. Custom data directories must stay outside package include paths and the UI resource root, and be excluded from source control.
+
+## Workbenches and connections
+
+Workbench contributions can be opened without a connection, including frontend-only plugins. Connection providers generate forms from declared fields, defaults, options and bindings. Port zero remains valid at the framework layer; plugins validate their own connection semantics.
+
+Connection testing, connecting and disconnecting use the standard lifecycle methods. Custom RPC methods and results are forwarded without interpreting their business meaning. Workbench tabs are keyed by contribution and optional connection ID, retain their iframe when switched, and reuse an existing tab when opened again. Closing the last tab for a connection disconnects it after confirmation.
+
+Lifecycle replies with `success: false` are failures, matching the real host. Browser pages have independent workbench ownership. After a page's event stream disconnects, its frames remain for a 30-second reconnect grace period, then are removed; connections still used by another page remain open. Saved connection configuration is unaffected. Manifest localization is performed only by the shell; bootstrap returns one unmodified Manifest.
+
+Import connection configurations using the UI's JSON file picker:
+
+```json
+{
+ "connections": [
+ {
+ "providerId": "example.connection",
+ "values": { "display_name": "Example", "host": "localhost", "port": 0 },
+ "readOnly": false
+ }
+ ]
+}
+```
+
+Field names come from the plugin manifest, not the runtime. Imported records get new IDs. There are no built-in protocol presets, filesystem RPCs or plugin-specific adapters.
+
+## Supported boundary
+
+- Host API 1.0 subset: `ready`, `context`, `locale`, `theme`, `request`, `invoke`, `notify`, `onInit`, `onContext`, `onEvent`, `onBinary`, `sendBinary`, resource reads and `openWorkbench`.
+- Backend transports: default `stdio-jsonl` and explicit `stdio-framed`, protocol version 1. Initialization verifies plugin identity and version. Binary channels require framed transport.
+- Permissions: event, binary and workbench navigation permissions are enforced. Unimplemented methods, such as `host.openFilesystem`, return errors. Native connection actions, query-result contributions and the DBX component kit are not emulated.
+- JSON bridge parameters: 2 MiB. UI binary messages: 8 MiB. Sidecar JSON: 8 MiB. Sidecar binary: 64 MiB. Explicit bridge timeouts are clamped to 1–120000 ms, matching the host baseline.
+- UI resources must be inline or loaded through `readAssetUrl`; relative module URLs are not a replacement for the declared asset bridge. The iframe uses `sandbox="allow-scripts"`, restrictive CSP and pure-data context snapshots. Direct networking is not enabled by the development runtime.
+
+UI rebuilds are applied by explicit reload to preserve drafts. Backend rebuilds disconnect sessions; failure does not fall back to an old binary. A timeout does not mean a write was cancelled, and requests are never automatically replayed. Reconnect after restarting the backend; reload the plugin page when needed.
+
+## Data and isolation
+
+**自动重载** is off by default and applies to all browsers connected to this server. Enabling it confirms possible draft loss. Stable UI output changes reload all open plugin frames; compiled UIs still require `[dev].ui_watch`. Backend `.rs`/`.go` files and Cargo/Go module files within the configured backend directory trigger a debounced, serialized rebuild/restart. Generated `target`, `.dbx-dev`, `vendor` and `node_modules` directories are ignored. Saved connections persist, but reconnect after a backend restart. Build failure leaves the backend stopped; writes are never replayed. Turning the option off cancels pending work, not a build already started. Restarting the dev server resets the option to off. This is reload/restart, not state-preserving HMR.
+
+The language button to the left of **调试** switches both the development shell and plugin locale between `zh-CN` and `en`. Shell controls, dialogs, diagnostic labels and manifest-localized contributions update together. Saved connection names and RPC data are not translated. With an active page, it confirms possible draft loss, then reloads that page automatically; cancellation leaves the language unchanged. Other open frames receive the standard `env` message. New pages use the selected locale. Plugin content must provide its own translations.
+
+The **调试** button to the right of **重载页面** opens a bottom panel with the latest 500 entries, level filtering, local view clearing and automatic scrolling. Entries also print to the terminal with a `[dbx-dev]` prefix. Logs include the listening port, project/UI/backend paths, HTTP routes/statuses, RPC IDs/methods/durations, expandable JSON parameters/results, structured error data, events and session rejection reasons. Password/token/credential fields and manifest-declared secret fields are redacted recursively; binary/base64 content is omitted and large/deep values are truncated. Ordinary business values remain visible: use development data only. Raw backend error messages are excluded. History is memory-only and resets on restart.
+
+The server listens only on `127.0.0.1`. Host, Origin, browser session, CSRF, resource traversal and symlink boundaries are checked. Frame source and generation are checked before routing messages, so responses from an old document cannot resolve new requests.
+
+Development configurations, including credentials, are stored as plaintext in `.dbx-dev/connections.json`. Directory/file permissions are 0700/0600 where supported. Credentials are excluded from list summaries and iframe context; diagnostics redact recognized sensitive fields as described above. Explicit editing returns form values to the local development shell. Sidecar stderr is consumed without forwarding it to logs because arbitrary plugins may log credentials.
+
+This is not an OS sandbox: sidecars run with the current user's privileges. It does not read the DBX profile or emulate Keychain, signing, installation, production lifecycle guarantees or desktop tab restoration. Validate those in the real host.
+
+## Architecture and tests
+
+### Agent diagnostics API
+
+Local agents can read the same redacted in-memory diagnostics without browser cookies:
+
+```bash
+curl -sS \
+ 'http://127.0.0.1:5190/api/diagnostics?after=0&limit=100'
+```
+
+Only `GET` is supported. Use the actual port printed by `dev`. No custom header or browser session is required; the URL can be opened directly in a browser. Host/Origin checks remain enabled and no CORS access is granted.
+
+Optional query parameters: `after` (exclusive numeric entry ID, default 0), `limit` (1–500, default 100), `level` (`debug`, `info`, `error`; exact match), and `instanceId` (from the previous response). The JSON response includes `entries`, `nextAfter`, `hasMore`, `instanceId`, `reset`, `truncated`, `oldestId`, `latestId`, `plugin`, `backendState`, and `port`.
+
+Pass `nextAfter` and `instanceId` on the next poll, retaining the same filter. `hasMore` means fetch the next page immediately; otherwise poll at a modest interval, for example once per second. `reset` means the server instance changed or the cursor exceeds current history; the response already starts from available history. `truncated` means older entries were dropped from the 500-entry ring. Changing filters should start a fresh cursor. Polling does not create diagnostic entries. History is not persistent, and this endpoint cannot invoke plugin operations.
+
+- `cli/src/dev.rs` (sibling crate): CLI arguments, configuration validation, build specifications and runtime location.
+- `runtime.mjs`: build/watch processes, signal cleanup and runtime startup.
+- `server.mjs`: HTTP/SSE sessions, declarative lifecycle and workbench routing.
+- `sidecar.mjs`: JSONL/framed codecs, concurrent request correlation, events, timeouts and process cleanup.
+- `connections.mjs`, `assets.mjs`: typed bindings, atomic configuration writes and confined resource access.
+- `browser-bridge.mjs`, `ui/`: sandbox API, forms, tabs, themes and reload controls.
+
+```bash
+npm test --prefix plugins/sdk/dev-host
+cargo test --locked --manifest-path plugins/sdk/cli/Cargo.toml
+npm test --prefix packages/plugin-cli
+DBX_PLUGIN_CLI_VERIFY_NATIVE=1 node scripts/verify-plugin-cli-package.mjs
+```
+
+The package verifier packs and installs the CLI into a temporary directory, exercises official frontend/Rust/Go templates, and starts their development runtimes without source-tree runtime dependencies. Runtime unit tests use an unrelated echo sidecar. Third-party plugins are external acceptance samples, not production runtime dependencies.
diff --git a/plugins/sdk/dev-host/assets.mjs b/plugins/sdk/dev-host/assets.mjs
new file mode 100644
index 0000000000..19b05eebda
--- /dev/null
+++ b/plugins/sdk/dev-host/assets.mjs
@@ -0,0 +1,13 @@
+import { readFile, realpath, stat } from "node:fs/promises";
+import { resolve, relative, isAbsolute, extname } from "node:path";
+export async function readAsset(root, path) {
+ if (typeof path !== "string" || !path || path.includes("\0") || isAbsolute(path)) throw new Error("Invalid asset path");
+ const base = await realpath(root),
+ file = await realpath(resolve(base, path));
+ const rel = relative(base, file);
+ if (rel.startsWith("..") || isAbsolute(rel)) throw new Error("Asset is outside UI root");
+ const info = await stat(file);
+ if (!info.isFile() || info.size > 8 * 1024 * 1024) throw new Error("Asset exceeds limit or is not a file");
+ const types = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".json": "application/json", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".svg": "image/svg+xml", ".woff2": "font/woff2" };
+ return { dataBase64: (await readFile(file)).toString("base64"), contentType: types[extname(file)] || "application/octet-stream" };
+}
diff --git a/plugins/sdk/dev-host/auto-reload.mjs b/plugins/sdk/dev-host/auto-reload.mjs
new file mode 100644
index 0000000000..19c5c6b9bc
--- /dev/null
+++ b/plugins/sdk/dev-host/auto-reload.mjs
@@ -0,0 +1,35 @@
+// Coalesce edits, serialize builds, and remember edits made during a build.
+export class AutoReload {
+ enabled = false;
+ running = false;
+ pending = false;
+ timer;
+ constructor(action, delay = 500) {
+ this.action = action;
+ this.delay = delay;
+ }
+ enable(value) {
+ this.enabled = value;
+ if (!value) {
+ clearTimeout(this.timer);
+ this.pending = false;
+ }
+ }
+ changed() {
+ if (!this.enabled) return;
+ this.pending = true;
+ clearTimeout(this.timer);
+ this.timer = setTimeout(() => void this.flush(), this.delay);
+ }
+ async flush() {
+ if (!this.enabled || !this.pending || this.running) return;
+ this.pending = false;
+ this.running = true;
+ try {
+ await this.action();
+ } finally {
+ this.running = false;
+ if (this.pending && this.enabled) this.changed();
+ }
+ }
+}
diff --git a/plugins/sdk/dev-host/browser-bridge.mjs b/plugins/sdk/dev-host/browser-bridge.mjs
new file mode 100644
index 0000000000..e60a2209db
--- /dev/null
+++ b/plugins/sdk/dev-host/browser-bridge.mjs
@@ -0,0 +1,144 @@
+// This function is serialized into the sandbox. It must not capture module state.
+function installBridge(channel) {
+ let sequence = 0,
+ context = {},
+ locale = "zh-CN",
+ theme;
+ const pending = new Map(),
+ listeners = { context: new Set(), init: new Set(), event: new Set(), binary: new Set() };
+ let resolveReady;
+ const ready = new Promise((resolve) => {
+ resolveReady = resolve;
+ });
+ let initialized = false;
+ const readyTimer = setInterval(() => {
+ if (!initialized) parent.postMessage({ source: "dbx-plugin", version: 1, channel, type: "ready" }, "*");
+ }, 200);
+ const encode = (input) => {
+ const data = input instanceof Uint8Array ? input : new Uint8Array(input);
+ let result = "";
+ for (let i = 0; i < data.length; i += 8192) result += String.fromCharCode(...data.subarray(i, i + 8192));
+ return btoa(result);
+ };
+ const decode = (value) => Uint8Array.from(atob(value), (c) => c.charCodeAt(0));
+ const request = (method, params) =>
+ new Promise((resolve, reject) => {
+ const id = ++sequence;
+ const timer = setTimeout(() => {
+ pending.delete(id);
+ reject(new Error("Mock host request timed out"));
+ }, 310000);
+ pending.set(id, { resolve, reject, timer });
+ parent.postMessage({ source: "dbx-plugin", version: 1, channel, type: "request", id, method, params }, "*");
+ });
+ const listen = (kind, callback) => {
+ listeners[kind].add(callback);
+ return () => listeners[kind].delete(callback);
+ };
+ function applyTheme(value) {
+ if (!value) return;
+ theme = value;
+ document.documentElement.dataset.dbxTheme = value.appearance;
+ for (const [name, token] of Object.entries(value.tokens || {})) {
+ if (/^--[a-z0-9-]+$/i.test(name) && typeof token === "string") document.documentElement.style.setProperty(name, token);
+ }
+ }
+ window.dbxPlugin = Object.freeze({
+ ready,
+ get context() {
+ return context;
+ },
+ get locale() {
+ return locale;
+ },
+ get theme() {
+ return theme;
+ },
+ request,
+ invoke: (method, params, options = {}) => request("backend.invoke", { method, params, timeoutMs: options.timeoutMs }),
+ notify: (method, params) => request("backend.notify", { method, params }),
+ sendBinary: (channel, data) => request("backend.sendBinary", { channel, dataBase64: typeof data === "string" ? data : encode(data) }),
+ readAsset: (path) => request("ui.readAsset", { path }),
+ readAssetUrl: async (path) => {
+ const asset = await request("ui.readAsset", { path });
+ return URL.createObjectURL(new Blob([decode(asset.dataBase64)], { type: asset.contentType }));
+ },
+ openWorkbench: (contributionId, context) => request("host.openWorkbench", { contributionId, context }),
+ openFilesystem: (providerId, context) => request("host.openFilesystem", { providerId, context }),
+ onContext: (fn) => listen("context", fn),
+ onEvent: (fn) => listen("event", fn),
+ onBinary: (fn) => listen("binary", fn),
+ onInit: (fn) => {
+ const off = listen("init", fn);
+ if (initialized) fn(context);
+ return off;
+ },
+ encodeBase64: encode,
+ decodeBase64: decode,
+ });
+ addEventListener("message", (event) => {
+ const m = event.data;
+ if (event.source !== parent || m?.source !== "dbx-host" || m.channel !== channel || m.version !== 1) return;
+ if (m.type === "init") {
+ initialized = true;
+ clearInterval(readyTimer);
+ context = m.context || {};
+ locale = m.locale || "zh-CN";
+ applyTheme(m.theme);
+ resolveReady(context);
+ for (const fn of listeners.init) fn(context);
+ dispatchEvent(new CustomEvent("dbx-plugin-init", { detail: m }));
+ }
+ if (m.type === "context") {
+ context = m.context || {};
+ for (const fn of listeners.context) fn(context);
+ dispatchEvent(new CustomEvent("dbx-plugin-context", { detail: context }));
+ }
+ if (m.type === "env") {
+ locale = m.locale || locale;
+ applyTheme(m.theme);
+ for (const fn of listeners.event) fn(m);
+ dispatchEvent(new CustomEvent("dbx-plugin-env", { detail: m }));
+ }
+ if (m.type === "event") {
+ for (const fn of listeners.event) fn(m);
+ dispatchEvent(new CustomEvent("dbx-plugin-event", { detail: m }));
+ }
+ if (m.type === "binary") {
+ const payload = { channel: m.binaryChannel, data: decode(m.dataBase64) };
+ for (const fn of listeners.binary) fn(payload);
+ dispatchEvent(new CustomEvent("dbx-plugin-binary", { detail: payload }));
+ }
+ if (m.type === "response") {
+ const waiter = pending.get(m.id);
+ if (!waiter) return;
+ pending.delete(m.id);
+ clearTimeout(waiter.timer);
+ if (m.error) waiter.reject(Object.assign(new Error(m.error.message || "Host request failed"), { code: m.error.code, data: m.error.data }));
+ else waiter.resolve(m.result);
+ }
+ });
+}
+
+export function sandboxDocument(html, channel, assets = new Map()) {
+ const csp = `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' blob:; style-src 'unsafe-inline' blob:; img-src data: blob:; font-src data: blob:; media-src data: blob:; connect-src 'none';">`;
+ const bootstrap = `<script>(${installBridge.toString()})(${JSON.stringify(channel)});</script>`;
+ const inlineAsset = (url) => {
+ const asset = assets.get(url);
+ if (!asset) return undefined;
+ return Buffer.from(asset.dataBase64, "base64").toString("utf8");
+ };
+ const withInlineScripts = html.replace(/<script\b([^>]*?)\bsrc\s*=\s*(["'])([^"']+)\2([^>]*)>\s*<\/script>/gi, (match, before, _quote, url, after) => {
+ const content = inlineAsset(url);
+ return content === undefined ? match : `<script${before}${after}>${content.replace(/<\/script/gi, "<\\/script")}</script>`;
+ });
+ const withInlineStyles = withInlineScripts.replace(/<link\b([^>]*)>/gi, (match, attributes) => {
+ if (!/\brel\s*=\s*(["'])[^"']*\bstylesheet\b[^"']*\1/i.test(attributes)) return match;
+ const href = attributes.match(/\bhref\s*=\s*(["'])([^"']+)\1/i);
+ if (!href) return match;
+ const content = inlineAsset(href[2]);
+ return content === undefined ? match : `<style>${content.replace(/<\/style/gi, "<\\/style")}</style>`;
+ });
+ if (/<head\b[^>]*>/i.test(withInlineStyles)) return withInlineStyles.replace(/<head\b[^>]*>/i, (match) => match + csp + bootstrap);
+ return `<!doctype html><html><head>${csp}${bootstrap}</head><body>${withInlineStyles}</body></html>`;
+}
diff --git a/plugins/sdk/dev-host/build.mjs b/plugins/sdk/dev-host/build.mjs
new file mode 100644
index 0000000000..2a4c5b4c8a
--- /dev/null
+++ b/plugins/sdk/dev-host/build.mjs
@@ -0,0 +1,10 @@
+import { build as viteBuild } from "vite";
+import { build } from "esbuild";
+import vue from "@vitejs/plugin-vue";
+import tailwind from "@tailwindcss/vite";
+import { viteSingleFile } from "vite-plugin-singlefile";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+const root = dirname(fileURLToPath(import.meta.url));
+await viteBuild({ configFile: false, root: resolve(root, "ui"), plugins: [vue(), tailwind(), viteSingleFile()], build: { outDir: resolve(root, "dist/ui"), emptyOutDir: true, target: "es2022" } });
+await build({ entryPoints: [resolve(root, "runtime.mjs")], outfile: resolve(root, "dist/runtime.mjs"), bundle: true, platform: "node", format: "esm", target: "node22", banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" } });
diff --git a/plugins/sdk/dev-host/connections.mjs b/plugins/sdk/dev-host/connections.mjs
new file mode 100644
index 0000000000..6fa9eb21e0
--- /dev/null
+++ b/plugins/sdk/dev-host/connections.mjs
@@ -0,0 +1,106 @@
+import { mkdir, readFile, writeFile, rename, chmod, lstat } from "node:fs/promises";
+import { join } from "node:path";
+import { randomUUID } from "node:crypto";
+
+export function providerFor(manifest, id) {
+ const provider = manifest.contributions?.find((c) => c.type === "connection-provider" && c.id === id);
+ if (!provider) throw new Error("Unknown connection provider");
+ return provider;
+}
+export function binding(field) {
+ return field.binding || (field.type === "password" ? "secret" : "config");
+}
+export function validateRecord(manifest, record, required = true) {
+ if (!record || typeof record !== "object" || Array.isArray(record)) throw new Error("Invalid connection record");
+ if (record.id !== undefined && (typeof record.id !== "string" || !/^[a-zA-Z0-9_.-]{1,128}$/.test(record.id))) throw new Error("Invalid connection ID");
+ const provider = providerFor(manifest, record.providerId);
+ if (!record.values || typeof record.values !== "object" || Array.isArray(record.values)) throw new Error("Invalid connection fields");
+ if (Object.keys(record.values).some((key) => !provider.fields.some((f) => f.key === key))) throw new Error("Unknown connection field");
+ const values = {};
+ for (const f of provider.fields) {
+ const value = record.values[f.key] ?? f.default;
+ const empty = value === undefined || value === null || value === "";
+ if (empty) {
+ if (required && f.required) throw new Error(`Missing field: ${f.key}`);
+ continue;
+ }
+ if (f.type === "number" ? typeof value !== "number" || !Number.isFinite(value) : f.type === "boolean" ? typeof value !== "boolean" : typeof value !== "string") {
+ throw new Error(`Invalid field type: ${f.key}`);
+ }
+ if (["select", "radio"].includes(f.type) && !f.options?.some((option) => option.value === value)) throw new Error(`Invalid option: ${f.key}`);
+ if (binding(f) === "port" && (!Number.isInteger(value) || value < 0 || value > 65535)) throw new Error("Port must be between 0 and 65535");
+ Object.defineProperty(values, f.key, { enumerable: true, configurable: true, writable: true, value });
+ }
+ if (record.readOnly !== undefined && typeof record.readOnly !== "boolean") throw new Error("Invalid read-only value");
+ return { id: record.id || randomUUID(), providerId: provider.id, values, readOnly: record.readOnly || false };
+}
+export function lifecyclePayload(manifest, record) {
+ const provider = providerFor(manifest, record.providerId);
+ const c = {
+ id: record.id,
+ db_type: "plugin",
+ plugin_id: manifest.id,
+ plugin_connection_provider: provider.id,
+ plugin_connection_type: provider.database_type,
+ name: provider.label,
+ host: "",
+ port: 0,
+ username: "",
+ external_config: {},
+ connection_secrets: {},
+ read_only: record.readOnly,
+ query_timeout_secs: 60,
+ idle_timeout_secs: 60,
+ };
+ for (const f of provider.fields) {
+ const value = record.values[f.key] ?? f.default;
+ if (value === undefined || value === null) continue;
+ const target = binding(f);
+ if (target === "config") Object.defineProperty(c.external_config, f.key, { value, enumerable: true });
+ else if (target === "secret") Object.defineProperty(c.connection_secrets, f.key, { value: String(value), enumerable: true });
+ else if (["name", "host", "port", "username", "password", "database"].includes(target)) c[target] = value;
+ else throw new Error("Unsupported field binding");
+ }
+ return { provider: { id: provider.id, databaseType: provider.database_type }, connection: c, runtime: null };
+}
+export function summary(manifest, record) {
+ const provider = providerFor(manifest, record.providerId);
+ const name = provider.fields.find((f) => binding(f) === "name");
+ return { id: record.id, providerId: record.providerId, name: name ? record.values[name.key] || provider.label : provider.label, label: provider.label };
+}
+
+export class ConnectionStore {
+ records = [];
+ constructor(directory, manifest) {
+ this.directory = directory;
+ this.manifest = manifest;
+ this.file = join(directory, "connections.json");
+ }
+ async load() {
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
+ if ((await lstat(this.directory)).isSymbolicLink()) throw new Error("Data directory cannot be a symlink");
+ await chmod(this.directory, 0o700);
+ try {
+ if ((await lstat(this.file)).isSymbolicLink()) throw new Error("Connection store cannot be a symlink");
+ const stored = JSON.parse(await readFile(this.file, "utf8"));
+ if (stored.pluginId !== this.manifest.id || stored.version !== 1 || !Array.isArray(stored.connections)) throw new Error("Invalid connection store");
+ this.records = stored.connections.map((r) => validateRecord(this.manifest, r, false));
+ if (new Set(this.records.map((r) => r.id)).size !== this.records.length) throw new Error("Duplicate connection IDs");
+ await chmod(this.file, 0o600);
+ } catch (error) {
+ if (error.code !== "ENOENT") throw error;
+ }
+ }
+ get(id) {
+ const record = this.records.find((r) => r.id === id);
+ if (!record) throw new Error("Connection not found");
+ return structuredClone(record);
+ }
+ async replace(records) {
+ const next = records.map((r) => validateRecord(this.manifest, r, false));
+ const temporary = join(this.directory, `.connections-${randomUUID()}.tmp`);
+ await writeFile(temporary, JSON.stringify({ version: 1, pluginId: this.manifest.id, connections: next }, null, 2), { mode: 0o600, flag: "wx" });
+ await rename(temporary, this.file);
+ this.records = next;
+ }
+}
diff --git a/plugins/sdk/dev-host/diagnostics.mjs b/plugins/sdk/dev-host/diagnostics.mjs
new file mode 100644
index 0000000000..ea2ab131ab
--- /dev/null
+++ b/plugins/sdk/dev-host/diagnostics.mjs
@@ -0,0 +1,90 @@
+import { EventEmitter } from "node:events";
+import { randomUUID } from "node:crypto";
+
+const sensitive = /password|passwd|secret|token|authorization|cookie|credential|private.?key|access.?key|api.?key|csrf/i;
+export function redact(value, secretKeys = new Set()) {
+ let budget = 8192,
+ nodes = 0;
+ const seen = new WeakSet();
+ function visit(v, key = "", depth = 0) {
+ if (sensitive.test(key) || secretKeys.has(key) || key === "headers" || key === "channel") return "[REDACTED]";
+ if (/base64|binary|^html$/i.test(key)) return "[content omitted]";
+ if (++nodes > 150 || budget <= 0 || depth > 6) return "[truncated]";
+ if (typeof v === "string") {
+ const limit = Math.min(2048, budget),
+ source = v.slice(0, limit);
+ if (/-----BEGIN [^-]*PRIVATE KEY-----/.test(source)) return "[REDACTED]";
+ const safe = source.replace(/(\b[a-z][a-z0-9+.-]{0,30}:\/\/)[^\s/@]+:[^\s/@]+@/gi, "$1[REDACTED]@").replace(/([?&](?:[^=&\s]*(?:token|key|password|secret)[^=&\s]*)=)[^&#\s]*/gi, "$1[REDACTED]");
+ budget -= source.length;
+ return safe + (v.length > limit ? " [truncated]" : "");
+ }
+ if (v === null || typeof v === "boolean" || typeof v === "number") return v;
+ if (typeof v !== "object") return String(v);
+ if (seen.has(v)) return "[circular]";
+ seen.add(v);
+ if (Array.isArray(v))
+ return v
+ .slice(0, 40)
+ .map((item) => visit(item, "", depth + 1))
+ .concat(v.length > 40 ? ["[truncated]"] : []);
+ return Object.fromEntries(
+ Object.entries(v)
+ .slice(0, 40)
+ .map(([k, item]) => [k.slice(0, 128), visit(item, k, depth + 1)]),
+ );
+ }
+ return visit(value);
+}
+
+export class Diagnostics extends EventEmitter {
+ instanceId = randomUUID();
+ entries = [];
+ sequence = 0;
+ secretKeys = new Set();
+ context = {};
+ constructor(output = (line) => console.log(line)) {
+ super();
+ this.output = output;
+ }
+ record(level, category, message, details = {}) {
+ const safe = { ...this.context };
+ for (const key of ["requestId", "status", "durationMs", "bytes", "port", "exitCode"]) {
+ if (Number.isFinite(details[key])) safe[key] = details[key];
+ }
+ for (const key of ["method", "state", "reason", "transport"]) {
+ if (typeof details[key] === "string" && /^[A-Za-z0-9._:/-]{1,256}$/.test(details[key])) safe[key] = details[key];
+ }
+ for (const key of ["path", "project", "uiRoot", "backend", "params", "result", "error"]) {
+ if (details[key] !== undefined) safe[key] = redact(details[key], this.secretKeys);
+ }
+ const entry = { id: ++this.sequence, time: new Date().toISOString(), level, category, message, details: safe };
+ this.entries.push(entry);
+ if (this.entries.length > 500) this.entries.shift();
+ this.output(`[dbx-dev] ${JSON.stringify(entry)}`);
+ this.emit("entry", entry);
+ return entry;
+ }
+ snapshot() {
+ return structuredClone(this.entries);
+ }
+ query(params) {
+ for (const key of params.keys()) if (!["after", "limit", "level", "instanceId"].includes(key) || params.getAll(key).length !== 1) throw new Error("Invalid diagnostics query");
+ const integer = (key, fallback, max) => {
+ const raw = params.get(key);
+ if (raw === null) return fallback;
+ if (!/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw)) || Number(raw) > max) throw new Error(`Invalid ${key}`);
+ return Number(raw);
+ };
+ const after = integer("after", 0, Number.MAX_SAFE_INTEGER),
+ limit = integer("limit", 100, 500);
+ const level = params.get("level");
+ if (limit < 1 || (level && !["debug", "info", "error"].includes(level))) throw new Error("Invalid diagnostics filter");
+ const reset = !!(params.get("instanceId") && params.get("instanceId") !== this.instanceId) || after > this.sequence;
+ const cursor = reset ? 0 : after,
+ oldestId = this.entries[0]?.id || 0;
+ const matched = this.entries.filter((e) => e.id > cursor && (!level || e.level === level));
+ const entries = matched.slice(0, limit),
+ hasMore = matched.length > limit;
+ return { instanceId: this.instanceId, entries: structuredClone(entries), nextAfter: hasMore ? entries.at(-1).id : this.sequence, hasMore, reset, truncated: oldestId > cursor + 1, oldestId, latestId: this.sequence };
+ }
+}
diff --git a/plugins/sdk/dev-host/docs/preview.png b/plugins/sdk/dev-host/docs/preview.png
new file mode 100644
index 0000000000..f16a6fd744
Binary files /dev/null and b/plugins/sdk/dev-host/docs/preview.png differ
diff --git a/plugins/sdk/dev-host/package-lock.json b/plugins/sdk/dev-host/package-lock.json
new file mode 100644
index 0000000000..4341b68f8e
--- /dev/null
+++ b/plugins/sdk/dev-host/package-lock.json
@@ -0,0 +1,3543 @@
+{
+ "name": "@dbx-app/plugin-dev-host-source",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@dbx-app/plugin-dev-host-source",
+ "devDependencies": {
+ "@tailwindcss/vite": "^4.1.13",
+ "@vitejs/plugin-vue": "^5.2.4",
+ "daisyui": "^5.1.10",
+ "esbuild": "^0.25.0",
+ "jsdom": "^26.1.0",
+ "lucide-vue-next": "^0.468.0",
+ "oxfmt": "^0.53.0",
+ "oxlint": "^1.68.0",
+ "semver": "^7.7.2",
+ "tailwindcss": "^4.1.13",
+ "vite": "^6.1.0",
+ "vite-plugin-singlefile": "^2.3.0",
+ "vue": "^3.5.21"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+ },
+ "node_modules/@asamuzakjp/css-color": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz",
+ "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@csstools/css-calc": "^2.1.3",
+ "@csstools/css-color-parser": "^3.0.9",
+ "@csstools/css-parser-algorithms": "^3.0.4",
+ "@csstools/css-tokenizer": "^3.0.3",
+ "lru-cache": "^10.4.3"
+ }
+ },
+ "node_modules/@babel/helper-string-parser": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
+ "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-identifier": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
+ "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/parser": {
+ "version": "7.29.8",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz",
+ "integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.29.8"
+ },
+ "bin": {
+ "parser": "bin/babel-parser.js"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@babel/types": {
+ "version": "7.29.8",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
+ "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-string-parser": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@csstools/color-helpers": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz",
+ "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT-0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@csstools/css-calc": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz",
+ "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "@csstools/css-parser-algorithms": "^3.0.5",
+ "@csstools/css-tokenizer": "^3.0.4"
+ }
+ },
+ "node_modules/@csstools/css-color-parser": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz",
+ "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@csstools/color-helpers": "^5.1.0",
+ "@csstools/css-calc": "^2.1.4"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "@csstools/css-parser-algorithms": "^3.0.5",
+ "@csstools/css-tokenizer": "^3.0.4"
+ }
+ },
+ "node_modules/@csstools/css-parser-algorithms": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz",
+ "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "@csstools/css-tokenizer": "^3.0.4"
+ }
+ },
+ "node_modules/@csstools/css-tokenizer": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz",
+ "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
+ "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
+ "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
+ "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
+ "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
+ "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
+ "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
+ "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
+ "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
+ "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
+ "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
+ "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
+ "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
+ "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
+ "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
+ "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
+ "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
+ "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
+ "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
+ "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
+ "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
+ "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
+ "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
+ "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@jridgewell/gen-mapping": {
+ "version": "0.3.13",
+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.0",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/remapping": {
+ "version": "2.3.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
+ "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/gen-mapping": "^0.3.5",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.31",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
+ "node_modules/@napi-rs/lzma-linux-x64-gnu": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz",
+ "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@oxfmt/binding-android-arm-eabi": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.53.0.tgz",
+ "integrity": "sha512-XfVM8AmIovBTKXCt14Op5wbfcoM8418nttd+nhMgM3RAVaJg1MtJc73FyWfUt0oxLyBGVwfniNVUsbV/b3VmPg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-android-arm64": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.53.0.tgz",
+ "integrity": "sha512-btHDfXckwdf9zgyAVznfZkf+GVyB0I1m1hlvaOMRx2xoyz3hphfPX97s89J3wfCN8QBETLtk4lQUaeOkrMuQOg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-darwin-arm64": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.53.0.tgz",
+ "integrity": "sha512-k2RjMcSTkHjoOlsVGbL35JVzXL+oQco3GHPl/5kjebVF4oHNfE24In8F5isqBh9LBJucycWHKDXdGrCchdWcHQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-darwin-x64": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.53.0.tgz",
+ "integrity": "sha512-65jIBE2H1l5SSs16fmv6/7b6sAx/WpvnsgDhVWK9qSjNFDUro7MPQ6q5UhpY7kl46yltfR046iAnxy/Bzqbiew==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-freebsd-x64": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.53.0.tgz",
+ "integrity": "sha512-oYe1gkz7U49PCYrS9147d2fJZj8mDI4Di6AvlsU5fu9p+Tq8S7qqOMSZjUiVTLX8bXuSA9Lk/tIxuegVjkNYRA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-arm-gnueabihf": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.53.0.tgz",
+ "integrity": "sha512-ailB2vLzGi629tymdAb2VYJyEHref7oqGxP+tRBrtRBxQrb6NV55JMT7xtGZ8uTeG2+Y9zojqW4LhJYxQnz9Pg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-arm-musleabihf": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.53.0.tgz",
+ "integrity": "sha512-abh4mWBvOvD966sobqF7r103y2yYx7Rb4WGHLOS4+5igGqLbbPxS9aK5+45D6iUY7dWMsk3Muz9a8gUtufvqJA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-arm64-gnu": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.53.0.tgz",
+ "integrity": "sha512-z73PvuhJ8qA+cDbaiqbtopHglA91U4+y5wn2sTJJrnpB957d5P33FEuyP3DQIFd7ofljmDmfVT4G0CVGHZaJWg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-arm64-musl": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.53.0.tgz",
+ "integrity": "sha512-I6bhOTroqc3ThrwZ89l2k3ivKuELhdPLbAcJhRNyjWvlgwb0vjRgEnVL1XLx5Jud04/ypNRZBykAWrSk6l/D+g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-ppc64-gnu": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.53.0.tgz",
+ "integrity": "sha512-w0p3JzB/PkkQjXALMJMqP9YfP3yq4w6zGsu5kezQmUnxRkN3b/Theg2l/nDgBsOcczxS3gL6Gam5XNAVrO6QJQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-riscv64-gnu": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.53.0.tgz",
+ "integrity": "sha512-mzBhF6k1Yq1K/dqDmVe/AAafnlJfEpx7yfUiksyeWXJk5iSzZqBSxcsa02zIytYgQFRZ7h6WPZfwHg/DoOE1Kw==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-riscv64-musl": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.53.0.tgz",
+ "integrity": "sha512-AlFCpnRQhogQFzZXWbO6xB6/Udy745L+eQNmDPGg7G/OeWsYmJc4jZYfUN5pQg0reOPWSED2mOQqKZOJM1U8cA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-s390x-gnu": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.53.0.tgz",
+ "integrity": "sha512-XD4ulY4f1DWbuuZXAqxhVn+gdPmrhnmojWtFN78ctVoupmS845fGhsUrk1HZXKQI+iymbaiz9vAjPsghHNQ7Ag==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-x64-gnu": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.53.0.tgz",
+ "integrity": "sha512-xg8KWX0QnxmYWRe60CgHYWXI0ZOtBbqTsXvWiWrcl2XUHJ3fht2QerOk2iWvylzX3zNT2GpvBRxGoR4d3sxPRQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-x64-musl": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.53.0.tgz",
+ "integrity": "sha512-MWExpYBGvl+pIvVB/gj/CcWlN2al8AizT7rUbtaYaWNoQkhWARM6W3qpgoCr72CYSN9PborzPmM5MIRe2BrNdA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-openharmony-arm64": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.53.0.tgz",
+ "integrity": "sha512-u4sajgO4nxgmJIgc/y2AqPhkdbOkQH8WugXpA1+pW0ESQhvGZ1oGq61Q4xMbJHJU1hFgtO18QNrcFYDPYH0gwQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-win32-arm64-msvc": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.53.0.tgz",
+ "integrity": "sha512-Yq9sOZoIOJ5xPjO0qOyHJS4CiPuTkB2en9auxZz7Ar2p5RaC7BzLyVVmAA7zz9/L9YnjjY1DwNxN+ivKXimN/A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-win32-ia32-msvc": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.53.0.tgz",
+ "integrity": "sha512-es1fVNZEkBqEcQtBpn19SYFgZF7FawlkCjkT/iImfEAus4gun8fBwB1E9hpV5LcR9B0DBNvRIXhW8BQk3JaE+Q==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-win32-x64-msvc": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.53.0.tgz",
+ "integrity": "sha512-QFmJs2bEu9AO4O6qsmEaZNGi6dFq8N+rT8EHAAnZIq/B9SeJDUbc4DzVxQ48MfDsL7D3sCZzo37zuTuspcURgg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-android-arm-eabi": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.68.0.tgz",
+ "integrity": "sha512-wEdsIspexXLLMCPAEOcCuFLMt6aE3AzTuA/nQKLPRnoJ+EQTturmGheDkhHuuVHx0GbutjQ3JKmEn+Gz6Ag28Q==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-android-arm64": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-android-arm64/-/binding-android-arm64-1.68.0.tgz",
+ "integrity": "sha512-6aZRNNXQTsYtgaus8HTb9nuCcsrQTlKXGnktwvwW0n/SooRWNxNb3925grDkC63aEYZuCIyOVLV16IdYIoC2aQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-darwin-arm64": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.68.0.tgz",
+ "integrity": "sha512-lVTbsE3kO4bLpZELgjRZuAJc8kP98wb83yMXWH8gaPaFZ+cM2IDeZto4ByoUAYj0Mxv2rvw+A1ssZequSepVSg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-darwin-x64": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.68.0.tgz",
+ "integrity": "sha512-nCmw2XrmQskjBUh/sfP5yKs93V68LijQgjd1cuuZ/q4SCARngLYs60/qqyzuMsg8QQ9KArDI98hxs/RDGE4KRQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-freebsd-x64": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.68.0.tgz",
+ "integrity": "sha512-TI4ovQJliYE9V6e06cEv+qEI9uj7Ao65fmif4er4HD+aouyYyh0P31q2jh3KtqsOHHcQqv2PZ61TjJFLpBDGWQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm-gnueabihf": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.68.0.tgz",
+ "integrity": "sha512-LcNnEi9g71Cmry5ZpLbKT+oVv+/zYG3hYVAbBBB5X85nOQZSk8l92CnDkxJMcxUg0NCnMCOFZuaVDlMyv4tYJw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm-musleabihf": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.68.0.tgz",
+ "integrity": "sha512-OovHahL3FX4UaK+hgSf11llUx2vszqjSdQQ61Ck9InOEI/ptZoC4XSQJurITqItVvd53JSlmkLMeaNjM1PoQew==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm64-gnu": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.68.0.tgz",
+ "integrity": "sha512-YbzTglnHLzzi9zv5or8Ztz5fykAoZE8W9iM42/bOrF4HBSB6rJTqdLQWuoP76EHQw9DuKl76K1QmFlG29sPJXQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm64-musl": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.68.0.tgz",
+ "integrity": "sha512-qVKtCZNic+OoNnOr/hCQAu22HSQzflI7Fsq/Blzkw02SnLuv163k3kfmrVpZjSBlUHgsRKj6WgQiw30d3SX02Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-ppc64-gnu": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.68.0.tgz",
+ "integrity": "sha512-zExyZ8ZOUuAyQ0y9jpTcyjKUz62YY9JhKPyVxzvjTpXzZ3ujdqiVwfPWDdnA1SsIOrxdtxHn7KErDHLWskFjXg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-riscv64-gnu": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.68.0.tgz",
+ "integrity": "sha512-6C4MPuwewyDavA7sxM14wzgRi5GGL68HPIxRCdVyS75U4MDbpFVYzKO9WNR6KLKTMPq2pcz3THwo1sK2uiqngw==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-riscv64-musl": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.68.0.tgz",
+ "integrity": "sha512-bnZooVeHAcvA+dH0EDLgx+7HY/DRi6e0hFszg3P+OBatuUjV6EvfIyNIzWOusmqAVh4L6r21GGTZtiKE4iqM4Q==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-s390x-gnu": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.68.0.tgz",
+ "integrity": "sha512-dIqnZnJSmHCMOUpUcWQOiV14o3DDPVx1DSsMaSzvdhNjC1tB1iEPZbdiMSCIEYbkgbsYznHXWqFdKL8WUB3F8g==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-x64-gnu": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.68.0.tgz",
+ "integrity": "sha512-zc9lEnfV/HreDTY6gdMlZe+irkwHSxQ4/B1pS9GyK7RVaA5LxhoZY/w6/o2vIwLLEYiXQ5ujGxOM1ZazeFAAIA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-x64-musl": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.68.0.tgz",
+ "integrity": "sha512-Dl5QEX0TCo/40Cdh1o1JdPS//+YiWqjC+Hrrya5OQmStZZr4svAFtdlqcpCrU9yq2Mo3vRVyO9B3h0dzD8s36Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-openharmony-arm64": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.68.0.tgz",
+ "integrity": "sha512-/qy6dOvi4S3/LeXq0l5BT5pRKPYA7oj3uKwJOAZOr5HRLL+HK6jdBynvWuXIA2wwfE01RzNYmbBdM7vwYx00sA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-win32-arm64-msvc": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.68.0.tgz",
+ "integrity": "sha512-fHNtVqPHSYE7UFDSLVFUjxQjnSVXxseNJmRW+XuP4pXXDwePdPda43NL7/BBCFTxHjycOc44JNDaOPtFDNui9A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-win32-ia32-msvc": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.68.0.tgz",
+ "integrity": "sha512-NnKXr4Wgo4nps3erhrE0f8shBvBPZMHg72nDsvX0JyrRvsNiP3f1JNvbCKh+A6VFvpF7ZoJxu904P3cKMhvZnA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-win32-x64-msvc": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.68.0.tgz",
+ "integrity": "sha512-zg5pA+84AlU6XHJ3ruiRxziO71QTrz8nLsk6u01JGS5+tL9/bnlakFiklFrcy4R1/V7ktWtaNitN3JZWmKnf6g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rollup/rollup-android-arm-eabi": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.63.1.tgz",
+ "integrity": "sha512-UZ8sUxPTiHWYX9QNdJedb1kDZSpS1t/VPWBWGSgqHNi9w3Cu6IXvu2mzbhiTiPvtrqgTQJ+zqiAq2iPIPilpaQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-android-arm64": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.63.1.tgz",
+ "integrity": "sha512-cQ4nFQABN5cDvDpbvJ7bMStCpnaVxynZrRMfUJYgxcIk9Sh54FIO1vtfkg0B69REjER77ioZ/ov+eAApx/KmLQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-arm64": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.63.1.tgz",
+ "integrity": "sha512-FQNqd1lRy/0QhDk3xeRIkSBiCpXCiDnZO3YLVdcDKN1UBiKToNftCzcXYNLshmPDUMlu2TdeS8tGcsU6f3YF1Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-x64": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.63.1.tgz",
+ "integrity": "sha512-pvD16V939D3CloK0+qikpGaxiPrDUXTe7Y5cWOMkMSy7m1cawa8EGy/kXYi/G/cKAC4HDAbSnzCIk1WmsoOKXg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-arm64": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.63.1.tgz",
+ "integrity": "sha512-pcFGeL2345VwdTnJhA6zLbew+YgWB0qBG2+dMtXjCicf6+rm6kO6cOoh5VnTe0ZMrMRgRyuHmCJxZWrIdzYuOw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-x64": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.63.1.tgz",
+ "integrity": "sha512-mRJlqSRulVzcKq/LKA6ICSIc3K/l4fzlVn/gePn2nXIHy8seRi5z/eeRE0d/XMBxcMldiXtQTSpRj0tkkC3g8Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.63.1.tgz",
+ "integrity": "sha512-YDUNvVM85TI3g/1OpnqKP1h4NeW/j64DfWMf+G3M809xNk1bJSnpFp4sh83NpmVE5DXnkh8ULor4LTVZKoYLHw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.63.1.tgz",
+ "integrity": "sha512-7Mcn71p9ZuQFAj+h+dhQXy/yeLePRS2yKRnmW1DijA9thKO5qap0GNOIQK4yQ6iP3SU0Mrb/yWo8h8vgRba8lw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-gnu": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.63.1.tgz",
+ "integrity": "sha512-4YiLQTX6U4CSl0L9cluep9A9W6UmTfqBDc2/CH6wlu54pl4E7Jn3cOD8oxzvBDEGk/JMKgJ47C8g+radF7mwvg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-musl": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.63.1.tgz",
+ "integrity": "sha512-2ra8F7w8OquwZN9z2/fKFnli69wa8PLwaVzRMIPGb13ByMJwC28Fbp8YcVGoUhlYMTt7j5j9bNgpysrN2UM+vw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-gnu": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.63.1.tgz",
+ "integrity": "sha512-Sy20ncyhjmBP0Ml+UvQbimjlk6VFgjW5uNP+qqwHB00mTE8Bl2C1TuHTlRwK2YoXeZbee5lP2XevBWVkAQAtSQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-musl": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.63.1.tgz",
+ "integrity": "sha512-noITLp8oNjYliPnGWmLyelIHwULGqbHloQHGw1rtxbWhTuWooRpnZarZQJ1y9EUC4szuCusCc+HEpUtxpIwYvA==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.63.1.tgz",
+ "integrity": "sha512-hlxxXd+F1mWiAcaFR7Sv9ZQT6m6UfI8+Vy/kFJzztq2pDMU/0wZ9sish0iszNZvsQDo8Gc0i5yuFEOz5dDf6fA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-musl": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.63.1.tgz",
+ "integrity": "sha512-EF7OpqQTQ/BvGqLzUi4rEHuagCV9MugAUXSHemwPW5vxZ75RR+jxO/2j95Ph2dalMpFHSVECjRoioHZgA9zOYA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.63.1.tgz",
+ "integrity": "sha512-wQO3JesW9PRkwlabQ27y7sPfVOOTLRG73I4F2UYHG5PXun3J9U3y+b7ezVKSYbsvSKGQ1k1cq8Qlun4C9kLt3w==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-musl": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.63.1.tgz",
+ "integrity": "sha512-ouAGwhO6wHRXdnOVCOsB0tRFkA7nhNB2Nwax6oECXN0YiN8EYUTBAOudADOB1PI+yDL61TeNx/u7MVCzksNbkQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-s390x-gnu": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.63.1.tgz",
+ "integrity": "sha512-q2R38Sn+1J8RxhfJ+T54wSWmyKXWec+9jgDfqO2AtArEqHO5R2aeayp5H5OYLr5UYDVGsVaZPEFUooMhYCdz5A==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-gnu": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.63.1.tgz",
+ "integrity": "sha512-gfI5T24WLLuFfSKw7Go/zDXjAAV0fny0swTaDv+WjK7vqcw4cRhFfdsyKL1n+ukI+ooBxn3bVQnyrn06WpI50w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-musl": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.63.1.tgz",
+ "integrity": "sha512-4h6XqthmB4Hspji84wvgk+ElodTsGj+dbZqHJHHtKxj4mYq0ANSEEPX9ys3moJueqsRjwpaJYH7874Itwnj2ow==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-openbsd-x64": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.63.1.tgz",
+ "integrity": "sha512-dlfCOa87o1VAYegLQ9EKilx2JCeRofiyPGhTCmqnuXZ6bMPiycO1rq1+sKoulAp7pGLIsTIw+1x5R+zgh5LhhA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-openharmony-arm64": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.63.1.tgz",
+ "integrity": "sha512-cjkLbOlfcm3QGhMM1J5zaZjsw1GggbN6rw9UTSSRrPrR1KkcXnN7Uq9rPw34xImQ9VOY9GN+6u2Zj80B9ptkcw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-arm64-msvc": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.63.1.tgz",
+ "integrity": "sha512-Li1KdUnWGE4N3e1F/B4RTB1ms+nG4WBgjByO46pkeBVX/2UBsY53xf5vK9WygVmnH3RwncIST7lkSdLSY6P9lg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-ia32-msvc": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.63.1.tgz",
+ "integrity": "sha512-t4ZYOSoLTgwhuFMrmTMLx/+i1DQVK7HYqMc6kY46EApwi8X0nIVphzdNoThU3xt6n+N5urG1/gxBdCaKDLavfg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-gnu": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.63.1.tgz",
+ "integrity": "sha512-RgroPfMmKlD1RzSDxvwgcPiy2HNQKoYV7OmwIXDsk73uKW5t6B/V8KIy27SMv/FNXFo/oSBtWc9J0X7t91ezZg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-msvc": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.63.1.tgz",
+ "integrity": "sha512-at8QVep6S3h5Y6gSbdGU06bRY5WJkf6WUduM9YtvYMbYhB1MOFfUgc6kehitQXzOtMSaT70q7f9ydPhpqu821w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@tailwindcss/node": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.3.tgz",
+ "integrity": "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/remapping": "^2.3.5",
+ "enhanced-resolve": "^5.24.1",
+ "jiti": "^2.7.0",
+ "lightningcss": "1.32.0",
+ "magic-string": "^0.30.21",
+ "source-map-js": "^1.2.1",
+ "tailwindcss": "4.3.3"
+ }
+ },
+ "node_modules/@tailwindcss/oxide": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.3.tgz",
+ "integrity": "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 20"
+ },
+ "optionalDependencies": {
+ "@tailwindcss/oxide-android-arm64": "4.3.3",
+ "@tailwindcss/oxide-darwin-arm64": "4.3.3",
+ "@tailwindcss/oxide-darwin-x64": "4.3.3",
+ "@tailwindcss/oxide-freebsd-x64": "4.3.3",
+ "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3",
+ "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3",
+ "@tailwindcss/oxide-linux-arm64-musl": "4.3.3",
+ "@tailwindcss/oxide-linux-x64-gnu": "4.3.3",
+ "@tailwindcss/oxide-linux-x64-musl": "4.3.3",
+ "@tailwindcss/oxide-wasm32-wasi": "4.3.3",
+ "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3",
+ "@tailwindcss/oxide-win32-x64-msvc": "4.3.3"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-android-arm64": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.3.tgz",
+ "integrity": "sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-darwin-arm64": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.3.tgz",
+ "integrity": "sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-darwin-x64": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.3.tgz",
+ "integrity": "sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-freebsd-x64": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.3.tgz",
+ "integrity": "sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.3.tgz",
+ "integrity": "sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-linux-arm64-gnu": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.3.tgz",
+ "integrity": "sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-linux-arm64-musl": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.3.tgz",
+ "integrity": "sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-linux-x64-gnu": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.3.tgz",
+ "integrity": "sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-linux-x64-musl": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.3.tgz",
+ "integrity": "sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.3.tgz",
+ "integrity": "sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ==",
+ "bundleDependencies": [
+ "@napi-rs/wasm-runtime",
+ "@emnapi/core",
+ "@emnapi/runtime",
+ "@tybys/wasm-util",
+ "@emnapi/wasi-threads",
+ "tslib"
+ ],
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/core": "^1.11.1",
+ "@emnapi/runtime": "^1.11.1",
+ "@emnapi/wasi-threads": "^1.2.2",
+ "@napi-rs/wasm-runtime": "^1.1.4",
+ "@tybys/wasm-util": "^0.10.2",
+ "tslib": "^2.8.1"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz",
+ "integrity": "sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-win32-x64-msvc": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.3.tgz",
+ "integrity": "sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/vite": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.3.3.tgz",
+ "integrity": "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@tailwindcss/node": "4.3.3",
+ "@tailwindcss/oxide": "4.3.3",
+ "tailwindcss": "4.3.3"
+ },
+ "peerDependencies": {
+ "vite": "^5.2.0 || ^6 || ^7 || ^8"
+ }
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@vitejs/plugin-vue": {
+ "version": "5.2.4",
+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz",
+ "integrity": "sha512-7Yx/SXSOcQq5HiiV3orevHUFn+pmMB4cgbEkDYgnkUWb0WfeQ/wa2yFv6D5ICiCQOVpjA7vYDXrC7AGO8yjDHA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ },
+ "peerDependencies": {
+ "vite": "^5.0.0 || ^6.0.0",
+ "vue": "^3.2.25"
+ }
+ },
+ "node_modules/@vue/compiler-core": {
+ "version": "3.5.42",
+ "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.42.tgz",
+ "integrity": "sha512-2Ye1ilMtKXxl8qZUrQ5j0CdgenFp/HFQmta6rfRyfEsTG69L6Wk+tWuNoHYHMx9E8tF2Slvdg1FuwDvAXdy1LQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.29.8",
+ "@vue/shared": "3.5.42",
+ "entities": "^7.0.1",
+ "estree-walker": "^2.0.2",
+ "source-map-js": "^1.2.1"
+ }
+ },
+ "node_modules/@vue/compiler-core/node_modules/entities": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
+ "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/@vue/compiler-dom": {
+ "version": "3.5.42",
+ "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.42.tgz",
+ "integrity": "sha512-qbhQZEFmycr+ni/qyuccS4sucNN7VAbDfbkvNxWOX2VfgFm90MNs3/UhRNKoPMEIVn0F8gdlYjLPvqxHwHeQOA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/compiler-core": "3.5.42",
+ "@vue/shared": "3.5.42"
+ }
+ },
+ "node_modules/@vue/compiler-sfc": {
+ "version": "3.5.42",
+ "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.42.tgz",
+ "integrity": "sha512-fkCAFB4okcAANGMThboWnScp/gzWjU0ZSkVnjTIiplmMDq2uq0tIB3j+xVu4rhv5rvOgBySCysudmbMd6xRRqw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.29.8",
+ "@vue/compiler-core": "3.5.42",
+ "@vue/compiler-dom": "3.5.42",
+ "@vue/compiler-ssr": "3.5.42",
+ "@vue/shared": "3.5.42",
+ "estree-walker": "^2.0.2",
+ "magic-string": "^0.30.21",
+ "postcss": "^8.5.19",
+ "source-map-js": "^1.2.1"
+ }
+ },
+ "node_modules/@vue/compiler-ssr": {
+ "version": "3.5.42",
+ "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.42.tgz",
+ "integrity": "sha512-xmLk3wLkbizPAiLyomjgFFosf2ys9b5Ghb+oh/k2tnvipNz8OFrQOiTcWCzyK7MpBp9KkyGtfvgfLUivbmuGYA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/compiler-dom": "3.5.42",
+ "@vue/shared": "3.5.42"
+ }
+ },
+ "node_modules/@vue/reactivity": {
+ "version": "3.5.42",
+ "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.42.tgz",
+ "integrity": "sha512-TzNNfKpb7hDxbQltwAut8VDQA5YP+BuRlxntHUuRjyKwlMvmAPbs3unhCvieijifY6vFfVBwsS7wG/C7uq+bEQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/shared": "3.5.42"
+ }
+ },
+ "node_modules/@vue/runtime-core": {
+ "version": "3.5.42",
+ "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.42.tgz",
+ "integrity": "sha512-9uACtuHs7vJGkm5Bp3xu4xRDLFTIYy5DgxpToVjqGIAhAEKwQfsaLvKINhM6nFVp6bZPRFGdDqd1g52MqKsotA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/reactivity": "3.5.42",
+ "@vue/shared": "3.5.42"
+ }
+ },
+ "node_modules/@vue/runtime-dom": {
+ "version": "3.5.42",
+ "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.42.tgz",
+ "integrity": "sha512-rsCmhiWLaRxGltLwhlCWyYkFn7WAbKRh0q17eZ1A6Dq6eqc2ACQ61IIryxz0LrsvCzHSilLA9JHovVwM8CNE2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/reactivity": "3.5.42",
+ "@vue/runtime-core": "3.5.42",
+ "@vue/shared": "3.5.42",
+ "csstype": "^3.2.3"
+ }
+ },
+ "node_modules/@vue/server-renderer": {
+ "version": "3.5.42",
+ "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.42.tgz",
+ "integrity": "sha512-2++5dUyYS4gvo7xQXSECUDhB7TS0aOl5SeVfC5qSq1Jgfhjvegw1zqhwTIR3imZ+QYPJQw9gfcFvXGAjGZ7ajQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/compiler-ssr": "3.5.42",
+ "@vue/runtime-dom": "3.5.42",
+ "@vue/shared": "3.5.42"
+ }
+ },
+ "node_modules/@vue/shared": {
+ "version": "3.5.42",
+ "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.42.tgz",
+ "integrity": "sha512-2rPxex1jQf4jvl9MOHl6YaXCPcrNqz/FstMOEh3QWY+/OME9nQTvl9WYeCwhW7AFjaR0SnngZGlp/wkR6rkI6g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/agent-base": {
+ "version": "7.1.4",
+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
+ "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/braces": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
+ "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fill-range": "^7.1.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/cssstyle": {
+ "version": "4.6.0",
+ "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz",
+ "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@asamuzakjp/css-color": "^3.2.0",
+ "rrweb-cssom": "^0.8.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/csstype": {
+ "version": "3.2.3",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/daisyui": {
+ "version": "5.7.32",
+ "resolved": "https://registry.npmjs.org/daisyui/-/daisyui-5.7.32.tgz",
+ "integrity": "sha512-8JQFneb+okHxzPimTGvRKX+5XF03GyAwGw7BaV6+6XpzW0klGuzc4rdfUpLQxIYPKEziwwlrsYfcxoltF2Rowg==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/saadeghi/daisyui?sponsor=1"
+ }
+ },
+ "node_modules/data-urls": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz",
+ "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "whatwg-mimetype": "^4.0.0",
+ "whatwg-url": "^14.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/decimal.js": {
+ "version": "10.6.0",
+ "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
+ "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/enhanced-resolve": {
+ "version": "5.24.5",
+ "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.24.5.tgz",
+ "integrity": "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "graceful-fs": "^4.2.4",
+ "tapable": "^2.3.3"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
+ "node_modules/entities": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz",
+ "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/esbuild": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
+ "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.25.12",
+ "@esbuild/android-arm": "0.25.12",
+ "@esbuild/android-arm64": "0.25.12",
+ "@esbuild/android-x64": "0.25.12",
+ "@esbuild/darwin-arm64": "0.25.12",
+ "@esbuild/darwin-x64": "0.25.12",
+ "@esbuild/freebsd-arm64": "0.25.12",
+ "@esbuild/freebsd-x64": "0.25.12",
+ "@esbuild/linux-arm": "0.25.12",
+ "@esbuild/linux-arm64": "0.25.12",
+ "@esbuild/linux-ia32": "0.25.12",
+ "@esbuild/linux-loong64": "0.25.12",
+ "@esbuild/linux-mips64el": "0.25.12",
+ "@esbuild/linux-ppc64": "0.25.12",
+ "@esbuild/linux-riscv64": "0.25.12",
+ "@esbuild/linux-s390x": "0.25.12",
+ "@esbuild/linux-x64": "0.25.12",
+ "@esbuild/netbsd-arm64": "0.25.12",
+ "@esbuild/netbsd-x64": "0.25.12",
+ "@esbuild/openbsd-arm64": "0.25.12",
+ "@esbuild/openbsd-x64": "0.25.12",
+ "@esbuild/openharmony-arm64": "0.25.12",
+ "@esbuild/sunos-x64": "0.25.12",
+ "@esbuild/win32-arm64": "0.25.12",
+ "@esbuild/win32-ia32": "0.25.12",
+ "@esbuild/win32-x64": "0.25.12"
+ }
+ },
+ "node_modules/estree-walker": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",
+ "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fill-range": {
+ "version": "7.1.1",
+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
+ "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "to-regex-range": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/graceful-fs": {
+ "version": "4.2.11",
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/html-encoding-sniffer": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz",
+ "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "whatwg-encoding": "^3.1.1"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/http-proxy-agent": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
+ "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.0",
+ "debug": "^4.3.4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/https-proxy-agent": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
+ "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.2",
+ "debug": "4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/iconv-lite": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/is-number": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.12.0"
+ }
+ },
+ "node_modules/is-potential-custom-element-name": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
+ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/jiti": {
+ "version": "2.7.0",
+ "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
+ "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "jiti": "lib/jiti-cli.mjs"
+ }
+ },
+ "node_modules/jsdom": {
+ "version": "26.1.0",
+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz",
+ "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cssstyle": "^4.2.1",
+ "data-urls": "^5.0.0",
+ "decimal.js": "^10.5.0",
+ "html-encoding-sniffer": "^4.0.0",
+ "http-proxy-agent": "^7.0.2",
+ "https-proxy-agent": "^7.0.6",
+ "is-potential-custom-element-name": "^1.0.1",
+ "nwsapi": "^2.2.16",
+ "parse5": "^7.2.1",
+ "rrweb-cssom": "^0.8.0",
+ "saxes": "^6.0.0",
+ "symbol-tree": "^3.2.4",
+ "tough-cookie": "^5.1.1",
+ "w3c-xmlserializer": "^5.0.0",
+ "webidl-conversions": "^7.0.0",
+ "whatwg-encoding": "^3.1.1",
+ "whatwg-mimetype": "^4.0.0",
+ "whatwg-url": "^14.1.1",
+ "ws": "^8.18.0",
+ "xml-name-validator": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "canvas": "^3.0.0"
+ },
+ "peerDependenciesMeta": {
+ "canvas": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/lightningcss": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
+ "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "dependencies": {
+ "detect-libc": "^2.0.3"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ },
+ "optionalDependencies": {
+ "lightningcss-android-arm64": "1.32.0",
+ "lightningcss-darwin-arm64": "1.32.0",
+ "lightningcss-darwin-x64": "1.32.0",
+ "lightningcss-freebsd-x64": "1.32.0",
+ "lightningcss-linux-arm-gnueabihf": "1.32.0",
+ "lightningcss-linux-arm64-gnu": "1.32.0",
+ "lightningcss-linux-arm64-musl": "1.32.0",
+ "lightningcss-linux-x64-gnu": "1.32.0",
+ "lightningcss-linux-x64-musl": "1.32.0",
+ "lightningcss-win32-arm64-msvc": "1.32.0",
+ "lightningcss-win32-x64-msvc": "1.32.0"
+ }
+ },
+ "node_modules/lightningcss-android-arm64": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz",
+ "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-arm64": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz",
+ "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-x64": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz",
+ "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-freebsd-x64": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz",
+ "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm-gnueabihf": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz",
+ "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-gnu": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz",
+ "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-musl": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz",
+ "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-gnu": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz",
+ "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-musl": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz",
+ "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-arm64-msvc": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz",
+ "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-x64-msvc": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz",
+ "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lru-cache": {
+ "version": "10.4.3",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
+ "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/lucide-vue-next": {
+ "version": "0.468.0",
+ "resolved": "https://registry.npmjs.org/lucide-vue-next/-/lucide-vue-next-0.468.0.tgz",
+ "integrity": "sha512-quV/6T8YB1XK0VOEnebg3Byd8Rsan5/m95cvjnuHV4vcS3qEnLAybkrSh0hk3ppavx+V7R1PjNW+mGDvcBdz4A==",
+ "deprecated": "Package deprecated. Please use @lucide/vue instead.",
+ "dev": true,
+ "license": "ISC",
+ "peerDependencies": {
+ "vue": ">=3.0.1"
+ }
+ },
+ "node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
+ "node_modules/micromatch": {
+ "version": "4.0.8",
+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
+ "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "braces": "^3.0.3",
+ "picomatch": "^2.3.1"
+ },
+ "engines": {
+ "node": ">=8.6"
+ }
+ },
+ "node_modules/micromatch/node_modules/picomatch": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
+ "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.18",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
+ "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/nwsapi": {
+ "version": "2.2.27",
+ "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.27.tgz",
+ "integrity": "sha512-gQPNF78qebCQ6tvVFBYrvJdBNOrYZm90ZlXgpIFm06p6qHDHq/XC4TnJftN6OMbxVE0UTBAoRgcsDeJBBooITw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/oxfmt": {
+ "version": "0.53.0",
+ "resolved": "https://registry.npmmirror.com/oxfmt/-/oxfmt-0.53.0.tgz",
+ "integrity": "sha512-9cB5glS3Ip6NMuZ+6NYTao9FCWkDhRtPYCtR3QBu/NxHoFbgzzTvi41N4jxz/GqGfuLKspui1qb/LlSu2IbMcw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinypool": "2.1.0"
+ },
+ "bin": {
+ "oxfmt": "bin/oxfmt"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ },
+ "optionalDependencies": {
+ "@oxfmt/binding-android-arm-eabi": "0.53.0",
+ "@oxfmt/binding-android-arm64": "0.53.0",
+ "@oxfmt/binding-darwin-arm64": "0.53.0",
+ "@oxfmt/binding-darwin-x64": "0.53.0",
+ "@oxfmt/binding-freebsd-x64": "0.53.0",
+ "@oxfmt/binding-linux-arm-gnueabihf": "0.53.0",
+ "@oxfmt/binding-linux-arm-musleabihf": "0.53.0",
+ "@oxfmt/binding-linux-arm64-gnu": "0.53.0",
+ "@oxfmt/binding-linux-arm64-musl": "0.53.0",
+ "@oxfmt/binding-linux-ppc64-gnu": "0.53.0",
+ "@oxfmt/binding-linux-riscv64-gnu": "0.53.0",
+ "@oxfmt/binding-linux-riscv64-musl": "0.53.0",
+ "@oxfmt/binding-linux-s390x-gnu": "0.53.0",
+ "@oxfmt/binding-linux-x64-gnu": "0.53.0",
+ "@oxfmt/binding-linux-x64-musl": "0.53.0",
+ "@oxfmt/binding-openharmony-arm64": "0.53.0",
+ "@oxfmt/binding-win32-arm64-msvc": "0.53.0",
+ "@oxfmt/binding-win32-ia32-msvc": "0.53.0",
+ "@oxfmt/binding-win32-x64-msvc": "0.53.0"
+ },
+ "peerDependencies": {
+ "svelte": "^5.0.0",
+ "vite-plus": "*"
+ },
+ "peerDependenciesMeta": {
+ "svelte": {
+ "optional": true
+ },
+ "vite-plus": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/oxlint": {
+ "version": "1.68.0",
+ "resolved": "https://registry.npmmirror.com/oxlint/-/oxlint-1.68.0.tgz",
+ "integrity": "sha512-dXcbq+xsmLrMy6T8d0euf3IYUfLmjHIE11pOxiUSi5LHkFZaYPv568R6sEjcavVpUxoaQe66UBuK4HEi74NxpA==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "oxlint": "bin/oxlint"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ },
+ "optionalDependencies": {
+ "@oxlint/binding-android-arm-eabi": "1.68.0",
+ "@oxlint/binding-android-arm64": "1.68.0",
+ "@oxlint/binding-darwin-arm64": "1.68.0",
+ "@oxlint/binding-darwin-x64": "1.68.0",
+ "@oxlint/binding-freebsd-x64": "1.68.0",
+ "@oxlint/binding-linux-arm-gnueabihf": "1.68.0",
+ "@oxlint/binding-linux-arm-musleabihf": "1.68.0",
+ "@oxlint/binding-linux-arm64-gnu": "1.68.0",
+ "@oxlint/binding-linux-arm64-musl": "1.68.0",
+ "@oxlint/binding-linux-ppc64-gnu": "1.68.0",
+ "@oxlint/binding-linux-riscv64-gnu": "1.68.0",
+ "@oxlint/binding-linux-riscv64-musl": "1.68.0",
+ "@oxlint/binding-linux-s390x-gnu": "1.68.0",
+ "@oxlint/binding-linux-x64-gnu": "1.68.0",
+ "@oxlint/binding-linux-x64-musl": "1.68.0",
+ "@oxlint/binding-openharmony-arm64": "1.68.0",
+ "@oxlint/binding-win32-arm64-msvc": "1.68.0",
+ "@oxlint/binding-win32-ia32-msvc": "1.68.0",
+ "@oxlint/binding-win32-x64-msvc": "1.68.0"
+ },
+ "peerDependencies": {
+ "oxlint-tsgolint": ">=0.22.1",
+ "vite-plus": "*"
+ },
+ "peerDependenciesMeta": {
+ "oxlint-tsgolint": {
+ "optional": true
+ },
+ "vite-plus": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/parse5": {
+ "version": "7.3.0",
+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz",
+ "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "entities": "^6.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.28",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
+ "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.18",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/punycode": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/rollup": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.1.tgz",
+ "integrity": "sha512-3Df9jsstwhccuEfmAMi9l8XUh/GOkVObmFTU7CCVBysEbcOZLl84jCtaAZMcPiMz2EGKsATzQcU+Xr3n/wU6cg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "1.0.9"
+ },
+ "bin": {
+ "rollup": "dist/bin/rollup"
+ },
+ "engines": {
+ "node": ">=18.0.0",
+ "npm": ">=8.0.0"
+ },
+ "optionalDependencies": {
+ "@napi-rs/lzma-linux-x64-gnu": "1.5.1",
+ "@rollup/rollup-android-arm-eabi": "4.63.1",
+ "@rollup/rollup-android-arm64": "4.63.1",
+ "@rollup/rollup-darwin-arm64": "4.63.1",
+ "@rollup/rollup-darwin-x64": "4.63.1",
+ "@rollup/rollup-freebsd-arm64": "4.63.1",
+ "@rollup/rollup-freebsd-x64": "4.63.1",
+ "@rollup/rollup-linux-arm-gnueabihf": "4.63.1",
+ "@rollup/rollup-linux-arm-musleabihf": "4.63.1",
+ "@rollup/rollup-linux-arm64-gnu": "4.63.1",
+ "@rollup/rollup-linux-arm64-musl": "4.63.1",
+ "@rollup/rollup-linux-loong64-gnu": "4.63.1",
+ "@rollup/rollup-linux-loong64-musl": "4.63.1",
+ "@rollup/rollup-linux-ppc64-gnu": "4.63.1",
+ "@rollup/rollup-linux-ppc64-musl": "4.63.1",
+ "@rollup/rollup-linux-riscv64-gnu": "4.63.1",
+ "@rollup/rollup-linux-riscv64-musl": "4.63.1",
+ "@rollup/rollup-linux-s390x-gnu": "4.63.1",
+ "@rollup/rollup-linux-x64-gnu": "4.63.1",
+ "@rollup/rollup-linux-x64-musl": "4.63.1",
+ "@rollup/rollup-openbsd-x64": "4.63.1",
+ "@rollup/rollup-openharmony-arm64": "4.63.1",
+ "@rollup/rollup-win32-arm64-msvc": "4.63.1",
+ "@rollup/rollup-win32-ia32-msvc": "4.63.1",
+ "@rollup/rollup-win32-x64-gnu": "4.63.1",
+ "@rollup/rollup-win32-x64-msvc": "4.63.1",
+ "fsevents": "~2.3.2"
+ }
+ },
+ "node_modules/rrweb-cssom": {
+ "version": "0.8.0",
+ "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz",
+ "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/saxes": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
+ "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "xmlchars": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=v12.22.7"
+ }
+ },
+ "node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/symbol-tree": {
+ "version": "3.2.4",
+ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
+ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tailwindcss": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.3.tgz",
+ "integrity": "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tapable": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz",
+ "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/webpack"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/tinypool": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/tinypool/-/tinypool-2.1.0.tgz",
+ "integrity": "sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^20.0.0 || >=22.0.0"
+ }
+ },
+ "node_modules/tldts": {
+ "version": "6.1.86",
+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz",
+ "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tldts-core": "^6.1.86"
+ },
+ "bin": {
+ "tldts": "bin/cli.js"
+ }
+ },
+ "node_modules/tldts-core": {
+ "version": "6.1.86",
+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz",
+ "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/to-regex-range": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
+ "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-number": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=8.0"
+ }
+ },
+ "node_modules/tough-cookie": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz",
+ "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "tldts": "^6.1.32"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/tr46": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz",
+ "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "punycode": "^2.3.1"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite": {
+ "version": "6.4.3",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
+ "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "^0.25.0",
+ "fdir": "^6.4.4",
+ "picomatch": "^4.0.2",
+ "postcss": "^8.5.3",
+ "rollup": "^4.34.9",
+ "tinyglobby": "^0.2.13"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
+ "jiti": ">=1.21.0",
+ "less": "*",
+ "lightningcss": "^1.21.0",
+ "sass": "*",
+ "sass-embedded": "*",
+ "stylus": "*",
+ "sugarss": "*",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "lightningcss": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vite-plugin-singlefile": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/vite-plugin-singlefile/-/vite-plugin-singlefile-2.3.3.tgz",
+ "integrity": "sha512-XVnGH0QzbOa8fxRSsHdCarVN1BSBXNi7uLMQYlrGRN5apdHkk62XQWRJhVever0lnfuyBkwn+kvVChdm/OoOUg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "micromatch": "^4.0.8"
+ },
+ "engines": {
+ "node": ">18.0.0"
+ },
+ "peerDependencies": {
+ "rollup": "^4.59.0",
+ "vite": "^5.4.21 || ^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "rollup": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vue": {
+ "version": "3.5.42",
+ "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.42.tgz",
+ "integrity": "sha512-4RyHQTbQvOPs3MfvUO1Sg0YRrKNnA0mAVtvpd12Tg1fKDN7OHBUl1IqSn8zGJjK9nI3NkNp8cgTpVrSZC5TTcA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/compiler-dom": "3.5.42",
+ "@vue/compiler-sfc": "3.5.42",
+ "@vue/runtime-dom": "3.5.42",
+ "@vue/server-renderer": "3.5.42",
+ "@vue/shared": "3.5.42"
+ },
+ "peerDependencies": {
+ "typescript": "*"
+ },
+ "peerDependenciesMeta": {
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/w3c-xmlserializer": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
+ "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "xml-name-validator": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/webidl-conversions": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
+ "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/whatwg-encoding": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz",
+ "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==",
+ "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "iconv-lite": "0.6.3"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/whatwg-mimetype": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz",
+ "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/whatwg-url": {
+ "version": "14.2.0",
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz",
+ "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tr46": "^5.1.0",
+ "webidl-conversions": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/ws": {
+ "version": "8.21.3",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
+ "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/xml-name-validator": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
+ "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/xmlchars": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
+ "dev": true,
+ "license": "MIT"
+ }
+ }
+}
diff --git a/plugins/sdk/dev-host/package.json b/plugins/sdk/dev-host/package.json
new file mode 100644
index 0000000000..35a44526ae
--- /dev/null
+++ b/plugins/sdk/dev-host/package.json
@@ -0,0 +1,30 @@
+{
+ "name": "@dbx-app/plugin-dev-host-source",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "build": "node build.mjs",
+ "test": "node --test tests/*.test.mjs",
+ "lint": "oxlint --vue-plugin --deny-warnings *.mjs ui tests",
+ "fmt": "oxfmt \"*.mjs\" \"ui/**/*.{js,vue,css,html}\" \"tests/**/*.mjs\"",
+ "fmt:check": "oxfmt --check \"*.mjs\" \"ui/**/*.{js,vue,css,html}\" \"tests/**/*.mjs\""
+ },
+ "engines": {
+ "node": ">=22"
+ },
+ "devDependencies": {
+ "@tailwindcss/vite": "^4.1.13",
+ "@vitejs/plugin-vue": "^5.2.4",
+ "daisyui": "^5.1.10",
+ "esbuild": "^0.25.0",
+ "jsdom": "^26.1.0",
+ "lucide-vue-next": "^0.468.0",
+ "oxfmt": "^0.53.0",
+ "oxlint": "^1.68.0",
+ "semver": "^7.7.2",
+ "tailwindcss": "^4.1.13",
+ "vite": "^6.1.0",
+ "vite-plugin-singlefile": "^2.3.0",
+ "vue": "^3.5.21"
+ }
+}
diff --git a/plugins/sdk/dev-host/process-tree.mjs b/plugins/sdk/dev-host/process-tree.mjs
new file mode 100644
index 0000000000..5302961b38
--- /dev/null
+++ b/plugins/sdk/dev-host/process-tree.mjs
@@ -0,0 +1,32 @@
+import { spawn } from "node:child_process";
+import { setTimeout as delay } from "node:timers/promises";
+
+// Unix children must be spawned detached so their process group belongs to us.
+export async function stopProcessTree(child) {
+ if (!child?.pid) return;
+ if (process.platform === "win32") {
+ await new Promise((resolve) => {
+ const killer = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
+ killer.once("error", resolve);
+ killer.once("close", resolve);
+ });
+ return;
+ }
+ const signal = (value) => {
+ try {
+ process.kill(-child.pid, value);
+ return true;
+ } catch (error) {
+ // macOS can return EPERM for a group containing only reparented zombies.
+ if (error.code === "ESRCH" || (value === 0 && error.code === "EPERM")) return false;
+ throw error;
+ }
+ };
+ if (!signal("SIGTERM")) return;
+ // A leader exiting does not imply that its descendants have exited.
+ for (let i = 0; i < 40; i++) {
+ await delay(50);
+ if (!signal(0)) return;
+ }
+ signal("SIGKILL");
+}
diff --git a/plugins/sdk/dev-host/runtime.mjs b/plugins/sdk/dev-host/runtime.mjs
new file mode 100644
index 0000000000..20929fbf9c
--- /dev/null
+++ b/plugins/sdk/dev-host/runtime.mjs
@@ -0,0 +1,135 @@
+import { spawn } from "node:child_process";
+import { mkdir, writeFile, chmod } from "node:fs/promises";
+import { resolve, dirname } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { createMockHost } from "./server.mjs";
+import { Diagnostics } from "./diagnostics.mjs";
+import { stopProcessTree } from "./process-tree.mjs";
+
+export async function startDevelopment(options) {
+ const diagnostics = options.diagnostics || new Diagnostics();
+ if (Number(process.versions.node.split(".")[0]) < 22) throw new Error("dbx-plugin dev requires Node.js 22+");
+ const project = resolve(options.project),
+ dataDir = resolve(options.dataDir || resolve(project, ".dbx-dev"));
+ await mkdir(dataDir, { recursive: true, mode: 0o700 });
+ await chmod(dataDir, 0o700);
+ await mkdir(resolve(dataDir, "bin"), { recursive: true });
+ const children = new Set();
+ let host,
+ stopping = false;
+ async function spawnCommand(spec, watch = false) {
+ if (stopping) throw new Error("Development host is stopping");
+ if (Array.isArray(spec)) spec = { command: spec[0], args: spec.slice(1), cwd: project };
+ if (!spec?.command || !Array.isArray(spec.args) || spec.args.some((a) => typeof a !== "string")) throw new Error("Invalid build command");
+ const env = { ...process.env };
+ if (spec.goWorkspace) {
+ const work = resolve(dataDir, "go.work");
+ await writeFile(work, `go 1.22\n\nuse (\n${spec.goWorkspace.map((p) => "\t" + JSON.stringify(p)).join("\n")}\n)\n`, { mode: 0o600 });
+ env.GOWORK = work;
+ }
+ let command = spec.command === "node" ? process.execPath : spec.command;
+ let args = spec.args;
+ // Windows npm launchers are batch files; invoke npm's JS entrypoint through Node.
+ if (process.platform === "win32" && command === "npm") {
+ const npm = process.env.npm_execpath || resolve(dirname(process.execPath), "node_modules/npm/bin/npm-cli.js");
+ command = process.execPath;
+ args = [npm, ...args];
+ }
+ if (stopping) throw new Error("Development host is stopping");
+ const child = spawn(command, args, { cwd: spec.cwd || project, env, stdio: ["ignore", watch ? "pipe" : "inherit", "inherit"], detached: process.platform !== "win32" });
+ children.add(child);
+ child.once("exit", () => {
+ child.cleanup = stopProcessTree(child);
+ child.cleanup.then(
+ () => children.delete(child),
+ () => {},
+ );
+ });
+ return child;
+ }
+ async function run(spec) {
+ diagnostics.record("info", "build", "构建命令开始");
+ const child = await spawnCommand(spec);
+ await new Promise((accept, reject) => {
+ child.once("error", () => reject(new Error("Cannot start build command")));
+ child.once("exit", (code) => (code === 0 ? accept() : reject(new Error(`Build failed (exit ${code})`))));
+ }).catch((error) => {
+ diagnostics.record("error", "build", "构建命令失败");
+ throw error;
+ });
+ diagnostics.record("info", "build", "构建命令完成");
+ if (stopping) throw new Error("Development host is stopping");
+ }
+ async function stopChildren() {
+ await Promise.all([...children].map((child) => child.cleanup || stopProcessTree(child)));
+ }
+ const stop = async () => {
+ if (stopping) return;
+ stopping = true;
+ process.removeListener("SIGINT", onSignal);
+ process.removeListener("SIGTERM", onSignal);
+ await stopChildren();
+ await host?.close();
+ };
+ const onSignal = () => void stop();
+ process.once("SIGINT", onSignal);
+ process.once("SIGTERM", onSignal);
+ try {
+ const commands = options.commands || {};
+ if (commands.backend) await run(commands.backend);
+ if (commands.ui?.length) await run(commands.ui);
+ if (stopping) throw new Error("Development host is stopping");
+ host = await createMockHost({
+ ...options,
+ project,
+ dataDir,
+ diagnostics,
+ uiBuildSignals: Boolean(commands.watch?.length),
+ shellHtml: options.shellHtml || resolve(dirname(fileURLToPath(import.meta.url)), "ui/index.html"),
+ buildBackend: commands.backend ? () => run(commands.backend) : undefined,
+ });
+ if (stopping) {
+ await host.close();
+ throw new Error("Development host is stopping");
+ }
+ if (commands.watch?.length) {
+ const watcher = await spawnCommand(commands.watch, true);
+ let line = "",
+ oversized = false;
+ watcher.stdout.setEncoding("utf8");
+ watcher.stdout.on("data", (chunk) => {
+ process.stdout.write(chunk);
+ for (const character of chunk) {
+ if (character === "\n") {
+ if (!oversized && line.replace(/\r$/, "") === "DBX_UI_BUILD_SUCCESS") {
+ void host.uiBuilt().catch(() => diagnostics.record("error", "build", "前端构建产物不可读取"));
+ }
+ line = "";
+ oversized = false;
+ } else if (line.length < 1024) line += character;
+ else oversized = true;
+ }
+ });
+ watcher.on("error", () => diagnostics.record("error", "build", "前端构建监听启动失败"));
+ watcher.on("exit", (code) => {
+ if (!stopping) diagnostics.record("error", "build", "前端构建监听已退出", { exitCode: code });
+ });
+ }
+ console.log(`Plugin dev host: ${host.origin}`);
+ console.log("Development credentials are stored locally as plaintext in the configured data directory.");
+ return { ...host, close: stop };
+ } catch (error) {
+ await stop();
+ throw error;
+ }
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ try {
+ if (process.argv[2] !== "--config" || !process.argv[3]) throw new Error("Start this runtime using dbx-plugin dev");
+ await startDevelopment(JSON.parse(process.argv[3]));
+ } catch (error) {
+ console.error(error.message);
+ process.exitCode = 1;
+ }
+}
diff --git a/plugins/sdk/dev-host/server.mjs b/plugins/sdk/dev-host/server.mjs
new file mode 100644
index 0000000000..ea5987ab2f
--- /dev/null
+++ b/plugins/sdk/dev-host/server.mjs
@@ -0,0 +1,543 @@
+import http from "node:http";
+import { randomUUID, randomBytes } from "node:crypto";
+import { readFile, realpath, watch } from "node:fs/promises";
+import { resolve, relative, isAbsolute, sep } from "node:path";
+import semver from "semver";
+import { Sidecar, protocolName } from "./sidecar.mjs";
+import { ConnectionStore, lifecyclePayload, providerFor, summary, validateRecord } from "./connections.mjs";
+import { readAsset } from "./assets.mjs";
+import { sandboxDocument } from "./browser-bridge.mjs";
+import { Diagnostics } from "./diagnostics.mjs";
+import { AutoReload } from "./auto-reload.mjs";
+
+const BRIDGE_LIMIT = 2 * 1024 * 1024,
+ UI_BINARY_LIMIT = 8 * 1024 * 1024;
+function jsonSize(value) {
+ return Buffer.byteLength(JSON.stringify(value) ?? "null");
+}
+function requirePermission(manifest, permission) {
+ if (!manifest.permissions?.includes(permission)) throw new Error(`Plugin permission required: ${permission}`);
+}
+function ensureSucceeded(result) {
+ if (result?.success === false) throw new Error(result.message || "Plugin connection operation failed");
+}
+function pageId(value = "legacy") {
+ if (typeof value !== "string" || !/^[a-zA-Z0-9-]{1,64}$/.test(value)) throw new Error("Invalid page ID");
+ return value;
+}
+function localDocumentAssetPath(url, entry) {
+ if (typeof url !== "string" || /^(?:data|blob|https?):/i.test(url) || url.startsWith("//") || url.startsWith("#")) return undefined;
+ try {
+ const parsed = new URL(url, `http://dbx-plugin.local/${entry}`);
+ if (parsed.origin !== "http://dbx-plugin.local") return undefined;
+ const path = decodeURIComponent(parsed.pathname).replace(/^\/+/, "");
+ return path || undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+export async function createMockHost(options) {
+ const diagnostics = options.diagnostics || new Diagnostics();
+ const project = resolve(options.project),
+ manifest = JSON.parse(await readFile(resolve(project, "manifest.json"), "utf8"));
+ for (const contribution of manifest.contributions || [])
+ for (const field of contribution.fields || []) {
+ if (field.type === "password" || ["password", "secret"].includes(field.binding)) diagnostics.secretKeys.add(field.key);
+ }
+ if (manifest.manifest_version !== undefined && manifest.manifest_version !== 1) throw new Error("Unsupported manifest version");
+ // DBX uses Rust semver requirements, whose comparator separators include commas.
+ if (manifest.engines?.host_api && !semver.satisfies("1.0.0", manifest.engines.host_api.replaceAll(",", " "))) throw new Error("Plugin does not support Host API 1.0.0");
+ const backendEntry = manifest.entrypoints?.backend;
+ const transport = backendEntry?.transport || "stdio-jsonl";
+ if (backendEntry && (!["stdio-framed", "stdio-jsonl"].includes(transport) || !(backendEntry.protocol_versions || [1]).includes(1))) throw new Error("Unsupported backend transport or protocol version");
+ const declaredRoot = resolve(project, manifest.entrypoints.ui.root || "ui");
+ const uiRoot = resolve(project, options.uiRoot || declaredRoot);
+ const entry = relative(declaredRoot, resolve(project, manifest.entrypoints.ui.entry));
+ await readAsset(uiRoot, entry);
+ const store = new ConnectionStore(resolve(options.dataDir), manifest);
+ await store.load();
+ const dataRelative = relative(await realpath(uiRoot), await realpath(store.directory));
+ if (!dataRelative || (!isAbsolute(dataRelative) && dataRelative !== ".." && !dataRelative.startsWith(`..${sep}`))) {
+ throw new Error("Development data directory must be outside the UI resource root");
+ }
+ if (backendEntry && !options.backend) throw new Error("Backend executable is required");
+ const sidecar = new Sidecar({ executable: backendEntry ? resolve(project, options.backend) : undefined, args: options.backendArgs || [], cwd: project, manifest, transport });
+ const connected = new Set(),
+ frames = new Map(),
+ sessions = new Map(),
+ streams = new Set();
+ const pages = new Map();
+ let revision = 0,
+ restarting = false,
+ closing = false,
+ origin,
+ cookieName;
+ let lifecycleQueue = Promise.resolve();
+ const serialize = (action) => {
+ const task = lifecycleQueue.then(action);
+ lifecycleQueue = task.catch(() => {});
+ return task;
+ };
+ let autoReload = false;
+ const backendReload = new AutoReload(async () => {
+ try {
+ await serialize(async () => {
+ if (autoReload && !closing) await restartBackend();
+ });
+ } catch {
+ broadcast("auto-reload-error", {});
+ }
+ });
+ const broadcast = (type, payload) => {
+ const message = `data: ${JSON.stringify({ type, ...payload })}\n\n`;
+ for (const stream of streams) {
+ if (stream.writableLength > 16 * 1024 * 1024) {
+ stream.destroy();
+ streams.delete(stream);
+ } else stream.write(message);
+ }
+ };
+ const onDiagnostic = (entry) => broadcast("diagnostic", { entry });
+ diagnostics.on("entry", onDiagnostic);
+ sidecar.on("diagnostic", (event) => diagnostics.record(event.level, "rpc", event.message, event.details));
+ sidecar.on("status", (state) => diagnostics.record(state === "failed" ? "error" : "info", "backend", "后端状态变化", { state, transport }));
+ sidecar.on("event", () => diagnostics.record("debug", "event", "收到后端事件"));
+ sidecar.on("binary", (event) => diagnostics.record("debug", "binary", "收到二进制帧", { bytes: Buffer.byteLength(event.dataBase64, "base64") }));
+ sidecar.on("status", (state) => {
+ if (state !== "ready") connected.clear();
+ broadcast("status", { state });
+ });
+ sidecar.on("event", (event) => {
+ if (manifest.permissions?.includes("host.events")) broadcast("event", event);
+ });
+ sidecar.on("binary", (event) => {
+ if (manifest.permissions?.includes("host.binary") && event.dataBase64.length <= (UI_BINARY_LIMIT / 3) * 4 + 4) broadcast("binary", event);
+ });
+ try {
+ await sidecar.start();
+ } catch (error) {
+ diagnostics.removeListener("entry", onDiagnostic);
+ throw error;
+ }
+
+ const listing = () => store.records.map((r) => ({ ...summary(manifest, r), connected: connected.has(r.id) }));
+ async function disconnect(id) {
+ if (connected.has(id) && sidecar.state === "ready") {
+ ensureSucceeded(await sidecar.request("connection/disconnect", lifecyclePayload(manifest, store.get(id)), 10000));
+ }
+ connected.delete(id);
+ }
+ async function connect(record) {
+ if (restarting || sidecar.state !== "ready") throw new Error("Backend is not ready; restart it first");
+ const provider = providerFor(manifest, record.providerId);
+ if (!provider.capabilities?.includes("connect")) throw new Error("Provider does not support connect");
+ validateRecord(manifest, record);
+ if (!connected.has(record.id)) {
+ ensureSucceeded(await sidecar.request("connection/connect", lifecyclePayload(manifest, record), 60000));
+ connected.add(record.id);
+ }
+ }
+ async function openFrame(session, connectionId, contributionId, suppliedContext) {
+ const record = connectionId ? store.get(connectionId) : undefined;
+ const provider = record ? providerFor(manifest, record.providerId) : undefined;
+ const contribution = manifest.contributions.find((c) => c.id === (contributionId || provider?.workbench) && c.type === "workbench");
+ if (!contribution) throw new Error("Unknown workbench contribution");
+ if (record) await connect(record);
+ const context = record ? { ...suppliedContext, connectionId: record.id, providerId: provider.id, connectionType: provider.database_type } : { ...suppliedContext };
+ const name = record ? summary(manifest, record).name : contribution.label;
+ if (jsonSize(context) > BRIDGE_LIMIT) throw new Error("Context exceeds limit");
+ const existing = [...frames.values()].find((f) => f.session === session.id && f.page === session.page && f.connectionId === connectionId && f.contributionId === contribution.id);
+ if (existing) {
+ existing.context = context;
+ existing.name = name;
+ return expose(existing);
+ }
+ const frame = { id: randomUUID(), channel: randomUUID(), session: session.id, page: session.page, connectionId, contributionId: contribution.id, context, name };
+ frames.set(frame.id, frame);
+ return expose(frame);
+ }
+ async function frameDocument(html, channel) {
+ const urls = new Set();
+ for (const match of html.matchAll(/<script\b[^>]*?\bsrc\s*=\s*(["'])([^"']+)\1[^>]*>/gi)) urls.add(match[2]);
+ for (const match of html.matchAll(/<link\b([^>]*)>/gi)) {
+ if (!/\brel\s*=\s*(["'])[^"']*\bstylesheet\b[^"']*\1/i.test(match[1])) continue;
+ const href = match[1].match(/\bhref\s*=\s*(["'])([^"']+)\1/i);
+ if (href) urls.add(href[2]);
+ }
+ const assets = new Map();
+ await Promise.all(
+ [...urls].map(async (url) => {
+ const path = localDocumentAssetPath(url, entry);
+ if (path) assets.set(url, await readAsset(uiRoot, path));
+ }),
+ );
+ return sandboxDocument(html, channel, assets);
+ }
+ function expose(frame) {
+ const { session: _session, page: _page, ...safe } = frame;
+ return structuredClone(safe);
+ }
+ function frameFor(session, id) {
+ const f = frames.get(id);
+ if (!f || f.session !== session.id || f.page !== session.page) throw new Error("Unknown workbench frame");
+ return f;
+ }
+ async function bridge(session, input) {
+ const frame = frameFor(session, input.frameId),
+ p = input.params || {};
+ if (input.channel !== frame.channel) throw new Error("Stale workbench generation");
+ if (input.method !== "backend.sendBinary" && jsonSize(p) > BRIDGE_LIMIT) throw new Error("Bridge request exceeds 2 MiB");
+ switch (input.method) {
+ case "host.getContext":
+ return structuredClone(frame.context);
+ case "backend.invoke": {
+ if (p.timeoutMs !== undefined && (typeof p.timeoutMs !== "number" || !Number.isFinite(p.timeoutMs))) throw new Error("Invalid request timeout");
+ const timeout = p.timeoutMs === undefined ? 30000 : Math.min(120000, Math.max(1, Math.round(p.timeoutMs)));
+ return sidecar.request(protocolName(p.method), p.params ?? null, timeout);
+ }
+ case "backend.notify":
+ await sidecar.notify(protocolName(p.method), p.params ?? null);
+ return null;
+ case "backend.sendBinary": {
+ requirePermission(manifest, "host.binary");
+ if (typeof p.dataBase64 !== "string" || p.dataBase64.length > Math.ceil(UI_BINARY_LIMIT / 3) * 4) throw new Error("Invalid base64 or binary exceeds limit");
+ const data = Buffer.from(p.dataBase64, "base64");
+ if (data.toString("base64") !== p.dataBase64) throw new Error("Invalid base64");
+ if (data.length > UI_BINARY_LIMIT) throw new Error("Bridge binary exceeds 8 MiB");
+ await sidecar.sendBinary(p.channel, data);
+ return null;
+ }
+ case "ui.readAsset": {
+ const prefix = (manifest.entrypoints.ui.root || "ui").replace(/\/$/, "") + "/";
+ const path = typeof p.path === "string" && p.path.startsWith(prefix) ? p.path.slice(prefix.length) : p.path;
+ return readAsset(uiRoot, path);
+ }
+ case "host.openWorkbench": {
+ requirePermission(manifest, "host.workbench");
+ return { mockHostOpenFrame: await serialize(() => openFrame(session, p.context?.connectionId || frame.connectionId, p.contributionId, p.context)) };
+ }
+ default:
+ throw new Error(`Unsupported mock host method: ${input.method}`);
+ }
+ }
+ async function api(session, route, p) {
+ if (route === "/api/bridge") return bridge(session, p);
+ if (route === "/api/frame-document") {
+ const f = frameFor(session, p.frameId);
+ const asset = await readAsset(uiRoot, entry);
+ f.channel = randomUUID();
+ return { ...expose(f), html: await frameDocument(Buffer.from(asset.dataBase64, "base64").toString("utf8"), f.channel) };
+ }
+ return serialize(async () => {
+ switch (route) {
+ case "/api/auto-reload": {
+ if (typeof p.enabled !== "boolean") throw new Error("Invalid automatic reload setting");
+ autoReload = p.enabled;
+ backendReload.enable(autoReload);
+ broadcast("auto-reload", { enabled: autoReload });
+ diagnostics.record("info", "build", autoReload ? "自动重载已启用" : "自动重载已关闭");
+ return { enabled: autoReload };
+ }
+ case "/api/workbenches/open":
+ return { frame: await openFrame(session, undefined, p.contributionId) };
+ case "/api/connections/edit":
+ return store.get(p.id);
+ case "/api/connections/save": {
+ const existing = p.id ? store.get(p.id) : undefined;
+ const record = validateRecord(manifest, p);
+ if (existing && existing.providerId !== record.providerId) throw new Error("Create a new connection to change its provider");
+ if (existing) await disconnect(existing.id);
+ await store.replace([...store.records.filter((r) => r.id !== record.id), record]);
+ return { connections: listing(), id: record.id };
+ }
+ case "/api/connections/test": {
+ const record = validateRecord(manifest, { ...p, id: randomUUID() });
+ if (!providerFor(manifest, record.providerId).capabilities?.includes("test")) throw new Error("Provider does not support test");
+ ensureSucceeded(await sidecar.request("connection/test", lifecyclePayload(manifest, record), 60000));
+ return { message: "连接测试成功" };
+ }
+ case "/api/connections/connect":
+ return { frame: await openFrame(session, p.id), connections: listing() };
+ case "/api/connections/disconnect":
+ await disconnect(p.id);
+ return { connections: listing() };
+ case "/api/connections/delete": {
+ store.get(p.id);
+ await disconnect(p.id);
+ await store.replace(store.records.filter((r) => r.id !== p.id));
+ for (const f of frames.values()) if (f.connectionId === p.id) frames.delete(f.id);
+ broadcast("frames-removed", { connectionId: p.id });
+ return { connections: listing() };
+ }
+ case "/api/connections/import": {
+ if (!Array.isArray(p.connections) || p.connections.length > 100) throw new Error("Invalid connection import");
+ const imported = p.connections.map((r) => validateRecord(manifest, { ...r, id: randomUUID() }));
+ await store.replace([...store.records, ...imported]);
+ return { connections: listing() };
+ }
+ case "/api/frames/close": {
+ const f = frameFor(session, p.id);
+ if (f.connectionId && ![...frames.values()].some((other) => other.id !== f.id && other.connectionId === f.connectionId)) await disconnect(f.connectionId);
+ frames.delete(f.id);
+ return { connections: listing() };
+ }
+ case "/api/backend/restart":
+ return restartBackend();
+ default:
+ throw new Error("Unknown mock host endpoint");
+ }
+ });
+ }
+ async function restartBackend() {
+ restarting = true;
+ diagnostics.record("info", "build", "开始重建后端");
+ try {
+ for (const id of connected) await disconnect(id).catch(() => connected.delete(id));
+ await sidecar.stop();
+ if (options.buildBackend) await options.buildBackend();
+ await sidecar.start();
+ diagnostics.record("info", "build", "后端重建完成");
+ return { connections: listing(), state: sidecar.state };
+ } catch (error) {
+ diagnostics.record("error", "build", "后端重建失败");
+ throw error;
+ } finally {
+ restarting = false;
+ }
+ }
+ const server = http.createServer(async (request, response) => {
+ const started = performance.now();
+ let route = "unknown",
+ rejection;
+ response.on("finish", () => {
+ if (route === "diagnostics" || route === "events" || (route === "bootstrap" && response.statusCode < 400)) return;
+ diagnostics.record(response.statusCode >= 400 ? "error" : "debug", "http", "HTTP 请求完成", {
+ method: route,
+ path: route === "unknown" ? "[unknown route]" : route.startsWith("/") ? route : `/api/${route}`,
+ status: response.statusCode,
+ durationMs: Math.round(performance.now() - started),
+ reason: rejection,
+ });
+ });
+ response.setHeader("Cache-Control", "no-store");
+ response.setHeader("X-Content-Type-Options", "nosniff");
+ response.setHeader("Referrer-Policy", "no-referrer");
+ try {
+ if (request.headers.host !== new URL(origin).host) {
+ rejection = "invalid-host";
+ return respond(response, 403, { error: { message: "Invalid Host" } });
+ }
+ if (request.headers["sec-fetch-site"] === "cross-site" || (request.headers.origin && request.headers.origin !== origin)) {
+ rejection = "invalid-origin";
+ return respond(response, 403, { error: { message: "Invalid Origin" } });
+ }
+ const path = new URL(request.url, origin).pathname;
+ const known = [
+ "/",
+ "/api/bootstrap",
+ "/api/events",
+ "/api/bridge",
+ "/api/frame-document",
+ "/api/workbenches/open",
+ "/api/connections/edit",
+ "/api/connections/save",
+ "/api/connections/test",
+ "/api/connections/connect",
+ "/api/connections/disconnect",
+ "/api/connections/delete",
+ "/api/connections/import",
+ "/api/frames/close",
+ "/api/backend/restart",
+ ];
+ route = known.includes(path) ? path.replace("/api/", "") || "/" : "unknown";
+ if (path === "/api/diagnostics") {
+ route = "diagnostics";
+ if (request.method !== "GET") return respond(response, 405, { error: { message: "Diagnostics is read-only; use GET" } });
+ return respond(response, 200, { ...diagnostics.query(new URL(request.url, origin).searchParams), plugin: { id: manifest.id, version: manifest.version }, backendState: sidecar.state, port: server.address().port });
+ }
+ const cookie = (request.headers.cookie || "")
+ .split(";")
+ .map((part) => part.trim())
+ .find((part) => part.startsWith(`${cookieName}=`))
+ ?.slice(cookieName.length + 1);
+ let session = sessions.get(cookie);
+ if (path === "/api/bootstrap" && request.method === "GET") {
+ if (!session) {
+ if (sessions.size >= 128) throw new Error("Too many browser sessions");
+ session = { id: randomBytes(24).toString("hex"), csrf: randomBytes(24).toString("hex") };
+ sessions.set(session.id, session);
+ response.setHeader("Set-Cookie", `${cookieName}=${session.id}; HttpOnly; SameSite=Strict; Path=/`);
+ }
+ return respond(response, 200, { manifest, connections: listing(), csrf: session.csrf, state: sidecar.state, revision, autoReload, diagnostics: diagnostics.snapshot() });
+ }
+ if (path === "/api/events" && request.method === "GET" && session) {
+ const page = pageId(new URL(request.url, origin).searchParams.get("page") || undefined);
+ const key = `${session.id}:${page}`;
+ let lease = pages.get(key);
+ if (!lease) {
+ lease = { count: 0 };
+ pages.set(key, lease);
+ }
+ clearTimeout(lease.timer);
+ lease.count++;
+ response.writeHead(200, { "Content-Type": "text/event-stream", Connection: "keep-alive" });
+ response.write(`data: ${JSON.stringify({ type: "page-frames", ids: [...frames.values()].filter((f) => f.session === session.id && f.page === page).map((f) => f.id) })}\n\n`);
+ response.write(`data: ${JSON.stringify({ type: "status", state: sidecar.state })}\n\n`);
+ streams.add(response);
+ response.write(`data: ${JSON.stringify({ type: "auto-reload", enabled: autoReload })}\n\n`);
+ response.write(`data: ${JSON.stringify({ type: "diagnostic-history", entries: diagnostics.snapshot() })}\n\n`);
+ const heartbeat = setInterval(() => response.write(": heartbeat\n\n"), 20000);
+ response.on("close", () => {
+ streams.delete(response);
+ clearInterval(heartbeat);
+ if (--lease.count || closing) return;
+ // Keep frames during EventSource reconnects; retire abandoned browser pages.
+ lease.timer = setTimeout(() => {
+ void serialize(async () => {
+ if (closing || lease.count || pages.get(key) !== lease) return;
+ pages.delete(key);
+ const ids = new Set();
+ for (const f of frames.values()) {
+ if (f.session !== session.id || f.page !== page) continue;
+ frames.delete(f.id);
+ if (f.connectionId) ids.add(f.connectionId);
+ }
+ for (const id of ids) {
+ if ([...frames.values()].some((f) => f.connectionId === id)) continue;
+ try {
+ await disconnect(id);
+ } catch {
+ diagnostics.record("error", "backend", "页面回收时断开连接失败");
+ }
+ }
+ broadcast("connections", { connections: listing() });
+ });
+ }, options.pageGraceMs ?? 30000);
+ });
+ return;
+ }
+ if (path.startsWith("/api/")) {
+ if (request.method !== "POST" || !session || request.headers.origin !== origin || request.headers["x-mock-csrf"] !== session.csrf || !request.headers["content-type"]?.startsWith("application/json")) {
+ rejection = request.method !== "POST" ? "invalid-method" : !session ? "missing-or-expired-session" : request.headers.origin !== origin ? "missing-origin" : request.headers["x-mock-csrf"] !== session.csrf ? "csrf-mismatch" : "invalid-content-type";
+ return respond(response, 403, { error: { message: "Invalid browser session or request" } });
+ }
+ let bytes = 0;
+ const chunks = [];
+ for await (const chunk of request) {
+ bytes += chunk.length;
+ if (bytes > 12 * 1024 * 1024) throw new Error("HTTP payload exceeds limit");
+ chunks.push(chunk);
+ }
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
+ const page = pageId(request.headers["x-dbx-page"]);
+ return respond(response, 200, { value: await api({ ...session, page }, path, body) });
+ }
+ if (path === "/" && request.method === "GET") {
+ response.setHeader("Content-Type", "text/html; charset=utf-8");
+ response.setHeader(
+ "Content-Security-Policy",
+ "default-src 'self'; script-src 'self' 'unsafe-inline' blob:; style-src 'self' 'unsafe-inline' blob:; img-src 'self' data: blob:; font-src 'self' data: blob:; media-src 'self' data: blob:; frame-src 'self' blob:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'",
+ );
+ return response.end(await readFile(options.shellHtml));
+ }
+ respond(response, 404, { error: { message: "Not found" } });
+ } catch (error) {
+ const rpc = error.rpc;
+ rejection = rpc ? "backend-error" : error.message?.startsWith("Plugin permission required:") ? "permission-denied" : error.message?.startsWith("Unsupported mock host method:") ? "unsupported-method" : error.message === "Stale workbench generation" ? "stale-frame" : "operation-failed";
+ // Do not reflect raw filesystem/process errors, paths or request bodies.
+ const message = error.code ? "Local development service operation failed" : error.message;
+ respond(response, 400, { error: { message, ...(rpc ? { code: rpc.code, data: rpc.data } : {}) } });
+ }
+ });
+ server.requestTimeout = 320000;
+ try {
+ await new Promise((accept, reject) => {
+ server.once("error", (error) => {
+ if (error.code === "EADDRINUSE") {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", accept);
+ } else reject(error);
+ });
+ server.listen(options.port ?? 5190, "127.0.0.1", accept);
+ });
+ } catch (error) {
+ await sidecar.stop();
+ throw error;
+ }
+ origin = `http://127.0.0.1:${server.address().port}`;
+ // Cookies are scoped by host, not port; concurrent development hosts need distinct names.
+ cookieName = `dbx_dev_session_${server.address().port}`;
+ diagnostics.context = { port: server.address().port };
+ diagnostics.record("info", "server", "调试服务已启动", { port: server.address().port, project, uiRoot, backend: options.backend });
+ const watchStop = new AbortController();
+ if (options.backendWatch && options.buildBackend)
+ void (async () => {
+ try {
+ for await (const event of watch(options.backendWatch, { signal: watchStop.signal, recursive: true })) {
+ const path = String(event.filename || "").replaceAll("\\", "/");
+ if (path.split("/").some((p) => ["target", ".git", ".dbx-dev", "node_modules", "vendor"].includes(p))) continue;
+ if (/\.(rs|go)$|(^|\/)(Cargo\.toml|Cargo\.lock|build\.rs|go\.mod|go\.sum)$/.test(path)) backendReload.changed();
+ }
+ } catch (error) {
+ if (error.name !== "AbortError") {
+ diagnostics.record("error", "build", "后端源码监听已停止");
+ broadcast("auto-reload-error", {});
+ }
+ }
+ })();
+ let debounce;
+ void (async () => {
+ try {
+ for await (const _event of watch(uiRoot, { signal: watchStop.signal, recursive: true })) {
+ if (options.uiBuildSignals) continue;
+ clearTimeout(debounce);
+ debounce = setTimeout(async () => {
+ try {
+ await readAsset(uiRoot, entry);
+ broadcast("ui-rebuilt", { revision: ++revision });
+ } catch {
+ broadcast("watch-error", {});
+ }
+ }, 500);
+ }
+ } catch (error) {
+ if (error.name !== "AbortError") broadcast("watch-error", {});
+ }
+ })();
+ return {
+ origin,
+ server,
+ sidecar,
+ store,
+ diagnostics,
+ async uiBuilt() {
+ await readAsset(uiRoot, entry);
+ broadcast("ui-rebuilt", { revision: ++revision });
+ },
+ async close() {
+ if (closing) return;
+ closing = true;
+ for (const lease of pages.values()) clearTimeout(lease.timer);
+ pages.clear();
+ backendReload.enable(false);
+ watchStop.abort();
+ clearTimeout(debounce);
+ for (const stream of streams) stream.end();
+ streams.clear();
+ server.close();
+ await serialize(async () => {
+ for (const id of connected) await disconnect(id).catch(() => {});
+ await sidecar.stop();
+ });
+ server.closeAllConnections();
+ diagnostics.record("info", "server", "调试服务已停止");
+ diagnostics.removeListener("entry", onDiagnostic);
+ },
+ };
+}
+function respond(response, code, value) {
+ if (response.headersSent || response.destroyed) return;
+ response.writeHead(code, { "Content-Type": "application/json; charset=utf-8" });
+ response.end(JSON.stringify(value));
+}
diff --git a/plugins/sdk/dev-host/sidecar.mjs b/plugins/sdk/dev-host/sidecar.mjs
new file mode 100644
index 0000000000..645ee25907
--- /dev/null
+++ b/plugins/sdk/dev-host/sidecar.mjs
@@ -0,0 +1,212 @@
+import { EventEmitter } from "node:events";
+import { spawn } from "node:child_process";
+import { stopProcessTree } from "./process-tree.mjs";
+
+export const JSON_LIMIT = 8 * 1024 * 1024;
+export const BINARY_LIMIT = 64 * 1024 * 1024;
+export function protocolName(value) {
+ if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/.test(value)) throw new Error("Invalid protocol name");
+ return value;
+}
+export function frame(kind, payload) {
+ const header = Buffer.alloc(5);
+ header[0] = kind;
+ header.writeUInt32BE(payload.length, 1);
+ return Buffer.concat([header, payload]);
+}
+export function binaryPayload(channel, data) {
+ const name = Buffer.from(protocolName(channel));
+ if (data.length > BINARY_LIMIT) throw new Error("Binary payload exceeds limit");
+ const header = Buffer.alloc(2);
+ header.writeUInt16BE(name.length);
+ return Buffer.concat([header, name, data]);
+}
+
+export class FrameDecoder {
+ buffer = Buffer.alloc(0);
+ constructor(onFrame) {
+ this.onFrame = onFrame;
+ }
+ push(chunk) {
+ this.buffer = Buffer.concat([this.buffer, chunk]);
+ while (this.buffer.length >= 5) {
+ const kind = this.buffer[0],
+ length = this.buffer.readUInt32BE(1);
+ if (![0, 1].includes(kind)) throw new Error("Unknown frame kind");
+ if (length > (kind === 0 ? JSON_LIMIT : BINARY_LIMIT + 1024)) throw new Error("Frame exceeds limit");
+ if (this.buffer.length < length + 5) return;
+ const payload = this.buffer.subarray(5, length + 5);
+ this.buffer = this.buffer.subarray(length + 5);
+ if (kind === 0) this.onFrame({ kind, message: JSON.parse(payload.toString("utf8")) });
+ else {
+ if (payload.length < 2) throw new Error("Invalid binary frame");
+ const size = payload.readUInt16BE(0);
+ if (!size || size + 2 > payload.length) throw new Error("Invalid binary channel");
+ const channel = protocolName(new TextDecoder("utf-8", { fatal: true }).decode(payload.subarray(2, 2 + size)));
+ this.onFrame({ kind, channel, data: payload.subarray(2 + size) });
+ }
+ }
+ }
+}
+
+export class JsonLineDecoder {
+ buffer = Buffer.alloc(0);
+ constructor(onFrame) {
+ this.onFrame = onFrame;
+ }
+ push(chunk) {
+ this.buffer = Buffer.concat([this.buffer, chunk]);
+ let newline;
+ while ((newline = this.buffer.indexOf(10)) !== -1) {
+ if (newline > JSON_LIMIT) throw new Error("JSON line exceeds limit");
+ const line = this.buffer.subarray(0, newline).toString("utf8").trim();
+ this.buffer = this.buffer.subarray(newline + 1);
+ if (line) this.onFrame({ kind: 0, message: JSON.parse(line) });
+ }
+ if (this.buffer.length > JSON_LIMIT) throw new Error("JSON line exceeds limit");
+ }
+}
+
+export class Sidecar extends EventEmitter {
+ pending = new Map();
+ sequence = 0;
+ state = "stopped";
+ constructor({ executable, args = [], cwd, manifest, transport }) {
+ super();
+ Object.assign(this, { executable, args, cwd, manifest });
+ this.transport = transport || manifest.entrypoints?.backend?.transport || "stdio-jsonl";
+ }
+ async start() {
+ if (!this.executable) {
+ this.state = "frontend";
+ this.emit("status", this.state);
+ return null;
+ }
+ if (this.child) throw new Error("Sidecar is already running");
+ this.state = "starting";
+ this.emit("status", this.state);
+ const child = spawn(this.executable, this.args, { cwd: this.cwd, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32" });
+ this.child = child;
+ const Decoder = this.transport === "stdio-framed" ? FrameDecoder : JsonLineDecoder;
+ const decoder = new Decoder((packet) => {
+ if (packet.kind === 1) return this.emit("binary", { channel: packet.channel, dataBase64: packet.data.toString("base64") });
+ const message = packet.message;
+ if (message.jsonrpc !== "2.0") throw new Error("Invalid JSON-RPC message");
+ if (message.id !== undefined) {
+ const waiter = this.pending.get(message.id);
+ if (!waiter) return;
+ this.pending.delete(message.id);
+ clearTimeout(waiter.timer);
+ if (message.error) waiter.reject(Object.assign(new Error(message.error.message || "Sidecar error"), { rpc: message.error }));
+ else waiter.resolve(message.result);
+ } else if (message.method) this.emit("event", { method: protocolName(message.method), params: message.params });
+ });
+ child.stdout.on("data", (chunk) => {
+ try {
+ decoder.push(chunk);
+ } catch {
+ this.emit("diagnostic", { level: "error", message: "后端协议解析失败", details: { reason: "invalid-frame" } });
+ this.fail("Invalid sidecar frame");
+ child.kill();
+ }
+ });
+ // Sidecar stderr may contain credentials. Consume it without copying it into HTTP or logs.
+ child.stderr.resume();
+ child.on("error", () => this.fail("Cannot start sidecar executable"));
+ child.stdin.on("error", () => this.fail("Sidecar input closed"));
+ child.on("exit", (code) => {
+ this.emit("diagnostic", { level: this.state === "stopping" ? "info" : "error", message: "后端进程退出", details: { exitCode: code } });
+ this.child = undefined;
+ this.cleanup = stopProcessTree(child);
+ if (this.state !== "stopping") this.fail("Sidecar exited");
+ else {
+ this.state = "stopped";
+ this.emit("status", this.state);
+ }
+ });
+ try {
+ const info = await this.request("plugin/initialize", { host: { protocolVersions: [1] } }, 10000);
+ if (info?.protocolVersion !== 1 || info?.plugin?.id !== this.manifest.id || info?.plugin?.version !== this.manifest.version) {
+ throw new Error("Sidecar identity or protocol does not match manifest");
+ }
+ this.state = "ready";
+ this.emit("status", this.state);
+ return info;
+ } catch (error) {
+ await this.stop();
+ this.fail(error.message);
+ throw error;
+ }
+ }
+ fail(message, state = "failed") {
+ this.state = state;
+ for (const waiter of this.pending.values()) {
+ clearTimeout(waiter.timer);
+ waiter.reject(new Error(message));
+ }
+ this.pending.clear();
+ this.emit("status", this.state);
+ }
+ write(kind, payload) {
+ if (!this.executable) return Promise.reject(new Error("This plugin has no backend"));
+ if (kind === 1 && this.transport !== "stdio-framed") return Promise.reject(new Error("Binary channels require stdio-framed transport"));
+ if (!this.child || !["starting", "ready"].includes(this.state)) return Promise.reject(new Error("Sidecar is not ready"));
+ if (kind === 0 && payload.length > JSON_LIMIT) return Promise.reject(new Error("JSON payload exceeds limit"));
+ if (this.child.stdin.writableLength > 16 * 1024 * 1024) return Promise.reject(new Error("Sidecar input is busy"));
+ const output = this.transport === "stdio-framed" ? frame(kind, payload) : Buffer.concat([payload, Buffer.from("\n")]);
+ return new Promise((resolve, reject) => this.child.stdin.write(output, (error) => (error ? reject(new Error("Sidecar write failed")) : resolve())));
+ }
+ request(method, params = null, timeoutMs = 30000) {
+ protocolName(method);
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 300000) throw new Error("Invalid request timeout");
+ if (this.pending.size >= 256) return Promise.reject(new Error("Too many pending requests"));
+ const id = ++this.sequence;
+ const started = performance.now();
+ this.emit("diagnostic", { level: "debug", message: "RPC 开始", details: { requestId: id, method, transport: this.transport, params } });
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pending.delete(id);
+ reject(new Error("Sidecar request timed out; operation may still be running"));
+ }, timeoutMs);
+ this.pending.set(id, { resolve, reject, timer });
+ this.write(0, Buffer.from(JSON.stringify({ jsonrpc: "2.0", id, method, params }))).catch((error) => {
+ clearTimeout(timer);
+ this.pending.delete(id);
+ reject(error);
+ });
+ }).then(
+ (result) => {
+ this.emit("diagnostic", { level: "debug", message: "RPC 完成", details: { requestId: id, method, result, durationMs: Math.round(performance.now() - started) } });
+ return result;
+ },
+ (error) => {
+ const reason = error.message.startsWith("Sidecar request timed out") ? "timeout" : error.rpc ? "backend-error" : "transport-error";
+ this.emit("diagnostic", { level: "error", message: "RPC 失败", details: { requestId: id, method, reason, error: error.rpc ? { code: error.rpc.code, data: error.rpc.data } : { reason }, durationMs: Math.round(performance.now() - started) } });
+ throw error;
+ },
+ );
+ }
+ notify(method, params) {
+ return this.write(0, Buffer.from(JSON.stringify({ jsonrpc: "2.0", method: protocolName(method), params })));
+ }
+ sendBinary(channel, data) {
+ return this.write(1, binaryPayload(channel, data));
+ }
+ async stop() {
+ const child = this.child;
+ if (!child) {
+ await this.cleanup;
+ return;
+ }
+ if (!child.pid) {
+ this.child = undefined;
+ this.state = "stopped";
+ return;
+ }
+ this.fail("Sidecar stopped", "stopping");
+ // Keep the Windows leader alive until taskkill has discovered its descendants.
+ if (process.platform !== "win32") child.stdin.end();
+ await stopProcessTree(child);
+ await this.cleanup;
+ }
+}
diff --git a/plugins/sdk/dev-host/tests/auto-reload.test.mjs b/plugins/sdk/dev-host/tests/auto-reload.test.mjs
new file mode 100644
index 0000000000..4b510a1191
--- /dev/null
+++ b/plugins/sdk/dev-host/tests/auto-reload.test.mjs
@@ -0,0 +1,35 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { AutoReload } from "../auto-reload.mjs";
+
+test("auto reload defaults off, coalesces edits and queues edits during builds", async () => {
+ let calls = 0,
+ release;
+ const scheduler = new AutoReload(async () => {
+ calls++;
+ await new Promise((resolve) => {
+ release = resolve;
+ });
+ }, 10000);
+ scheduler.changed();
+ await scheduler.flush();
+ assert.equal(calls, 0);
+ scheduler.enable(true);
+ scheduler.changed();
+ scheduler.changed();
+ const first = scheduler.flush();
+ assert.equal(calls, 1);
+ scheduler.changed();
+ await scheduler.flush();
+ assert.equal(calls, 1);
+ release();
+ await first;
+ const second = scheduler.flush();
+ assert.equal(calls, 2);
+ release();
+ await second;
+ scheduler.changed();
+ scheduler.enable(false);
+ await scheduler.flush();
+ assert.equal(calls, 2);
+});
diff --git a/plugins/sdk/dev-host/tests/browser-bridge.test.mjs b/plugins/sdk/dev-host/tests/browser-bridge.test.mjs
new file mode 100644
index 0000000000..24b6ad0af3
--- /dev/null
+++ b/plugins/sdk/dev-host/tests/browser-bridge.test.mjs
@@ -0,0 +1,74 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { reactive } from "vue";
+import { JSDOM } from "jsdom";
+import { sandboxDocument } from "../browser-bridge.mjs";
+import { hostMessage } from "../ui/messages.js";
+
+test("bridge delivers host-compatible environment, lifecycle and binary events", async (t) => {
+ const dom = new JSDOM(sandboxDocument("<head></head>", "test"), { runScripts: "dangerously" });
+ t.after(() => dom.window.close());
+ const w = dom.window;
+ const send = (payload) => w.dispatchEvent(new w.MessageEvent("message", { source: w, data: hostMessage("test", payload) }));
+ const events = [];
+ for (const type of ["init", "context", "env", "event", "binary"]) w.addEventListener(`dbx-plugin-${type}`, (event) => events.push(event));
+ let initialized = 0,
+ notifications = 0,
+ binary;
+ w.dbxPlugin.onInit(() => initialized++);
+ w.dbxPlugin.onEvent(() => notifications++);
+ w.dbxPlugin.onBinary((value) => {
+ binary = value;
+ });
+ send({ type: "init", context: { value: 1 } });
+ await w.dbxPlugin.ready;
+ assert.equal(initialized, 1);
+ w.dbxPlugin.onInit(() => initialized++);
+ assert.equal(initialized, 2);
+ send({ type: "context", context: { value: 2 } });
+ send({ type: "env", locale: "en" });
+ send({ type: "event", method: "arbitrary/event" });
+ send({ type: "binary", binaryChannel: "bytes", dataBase64: "AP8=" });
+ assert.equal(notifications, 2);
+ assert.ok(binary.data instanceof w.Uint8Array);
+ assert.deepEqual([...binary.data], [0, 255]);
+ assert.equal(binary.channel, "bytes");
+ assert.equal(events.length, 5);
+ assert.equal(events[1].detail.value, 2);
+});
+
+test("host messages snapshot nested reactive context and permissions before postMessage", () => {
+ const source = reactive({ context: { connectionId: "one" }, permissions: ["host.events"] });
+ const message = hostMessage("generation", { type: "init", ...source });
+ assert.doesNotThrow(() => structuredClone(message));
+ source.context.connectionId = "two";
+ source.permissions.push("host.binary");
+ assert.equal(message.context.connectionId, "one");
+ assert.deepEqual(message.permissions, ["host.events"]);
+});
+test("sandbox bootstrap handles initialization, generation filtering and context listeners", async () => {
+ const dom = new JSDOM(sandboxDocument("<html><head></head><body></body></html>", "generation"), { runScripts: "dangerously" });
+ const w = dom.window,
+ send = (value) => w.dispatchEvent(new w.MessageEvent("message", { source: w, data: value }));
+ send(hostMessage("generation", { type: "init", context: { connectionId: "one" }, locale: "zh-CN" }));
+ await w.dbxPlugin.ready;
+ assert.equal(w.dbxPlugin.context.connectionId, "one");
+ assert.equal(w.dbxPlugin.locale, "zh-CN");
+ send(hostMessage("old", { type: "env", locale: "ja" }));
+ assert.equal(w.dbxPlugin.locale, "zh-CN");
+ send(hostMessage("generation", { type: "env", locale: "en" }));
+ assert.equal(w.dbxPlugin.locale, "en");
+ send(hostMessage("generation", { type: "env", theme: { appearance: "dark" } }));
+ assert.equal(w.dbxPlugin.locale, "en");
+ assert.equal(w.dbxPlugin.context.connectionId, "one");
+ let calls = 0;
+ const off = w.dbxPlugin.onContext(() => calls++);
+ send(hostMessage("old", { type: "context", context: { connectionId: "bad" } }));
+ assert.equal(w.dbxPlugin.context.connectionId, "one");
+ send(hostMessage("generation", { type: "context", context: { connectionId: "two" } }));
+ assert.equal(calls, 1);
+ off();
+ send(hostMessage("generation", { type: "context", context: { connectionId: "three" } }));
+ assert.equal(calls, 1);
+ dom.window.close();
+});
diff --git a/plugins/sdk/dev-host/tests/diagnostics.test.mjs b/plugins/sdk/dev-host/tests/diagnostics.test.mjs
new file mode 100644
index 0000000000..753233cd38
--- /dev/null
+++ b/plugins/sdk/dev-host/tests/diagnostics.test.mjs
@@ -0,0 +1,63 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { Diagnostics, redact } from "../diagnostics.mjs";
+
+test("diagnostics bound history and serialize only allowed metadata", () => {
+ const lines = [],
+ log = new Diagnostics((line) => lines.push(line));
+ let emitted;
+ log.on("entry", (entry) => {
+ emitted = entry;
+ });
+ for (let n = 0; n < 505; n++)
+ log.record("debug", "rpc", "RPC 完成", {
+ requestId: n,
+ durationMs: 3,
+ method: "example/echo",
+ params: { password: "private-value" },
+ result: { count: 3, access_token: "private-value" },
+ cookie: "private-value",
+ });
+ const entries = log.snapshot();
+ assert.equal(entries.length, 500);
+ assert.equal(entries[0].id, 6);
+ assert.equal(emitted.id, 505);
+ assert.equal(
+ lines.some((line) => line.includes("private-value")),
+ false,
+ );
+ assert.deepEqual(entries[0].details, { requestId: 5, durationMs: 3, method: "example/echo", params: { password: "[REDACTED]" }, result: { count: 3, access_token: "[REDACTED]" } });
+ entries[0].details.method = "changed";
+ assert.equal(log.snapshot()[0].details.method, "example/echo");
+});
+
+test("payload diagnostics retain types and paths while redacting nested secrets and bounding content", () => {
+ const input = { path: "/folder/test.txt", port: 9000, enabled: false, nested: [{ credential: "private", custom: "private" }], url: "https://user:[email protected]/path?token=private", dataBase64: "private", text: "a".repeat(10000) };
+ const safe = redact(input, new Set(["custom"]));
+ assert.equal(safe.path, input.path);
+ assert.equal(safe.port, 9000);
+ assert.equal(safe.enabled, false);
+ assert.equal(JSON.stringify(safe).includes("private"), false);
+ assert.match(safe.text, /truncated/);
+ assert.ok(safe.text.length < 2100);
+ assert.equal(input.nested[0].custom, "private");
+ const cycle = {};
+ cycle.self = cycle;
+ assert.equal(redact(cycle).self, "[circular]");
+});
+
+test("diagnostic queries paginate, filter and detect overwritten history and restarts", () => {
+ const log = new Diagnostics(() => {});
+ for (let i = 0; i < 503; i++) log.record(i % 2 ? "error" : "info", "rpc", "RPC 完成");
+ const first = log.query(new URLSearchParams("limit=2&level=error"));
+ assert.equal(first.entries.length, 2);
+ assert.equal(first.hasMore, true);
+ assert.equal(first.truncated, true);
+ const next = log.query(new URLSearchParams(`after=${first.nextAfter}&level=error&limit=500`));
+ assert.ok(next.entries.every((e) => e.id > first.nextAfter && e.level === "error"));
+ assert.equal(next.nextAfter, 503);
+ assert.equal(next.hasMore, false);
+ assert.equal(log.query(new URLSearchParams("after=503")).entries.length, 0);
+ assert.equal(log.query(new URLSearchParams("after=503&instanceId=old")).reset, true);
+ for (const query of ["limit=0", "after=-1", "limit=501", "level=unknown", "after=1&after=2", "token=secret"]) assert.throws(() => log.query(new URLSearchParams(query)));
+});
diff --git a/plugins/sdk/dev-host/tests/echo-sidecar.mjs b/plugins/sdk/dev-host/tests/echo-sidecar.mjs
new file mode 100644
index 0000000000..e880bca09f
--- /dev/null
+++ b/plugins/sdk/dev-host/tests/echo-sidecar.mjs
@@ -0,0 +1,23 @@
+import { FrameDecoder, JsonLineDecoder, frame, binaryPayload } from "../sidecar.mjs";
+import { spawn } from "node:child_process";
+const jsonl = process.argv.includes("--jsonl");
+const send = (message) => {
+ const bytes = Buffer.from(JSON.stringify({ jsonrpc: "2.0", ...message }));
+ process.stdout.write(jsonl ? Buffer.concat([bytes, Buffer.from("\n")]) : frame(0, bytes));
+};
+const decoder = new (jsonl ? JsonLineDecoder : FrameDecoder)((packet) => {
+ if (packet.kind === 1) return process.stdout.write(frame(1, binaryPayload(packet.channel, packet.data)));
+ const { id, method, params } = packet.message;
+ if (method === "plugin/initialize") return send({ id, result: { protocolVersion: 1, plugin: { id: "example.echo", version: "1.0.0" } } });
+ if (method === "die") return process.exit(1);
+ if (method === "spawn-child") {
+ const child = spawn(process.execPath, ["-e", 'process.on("SIGTERM", () => {}); process.on("SIGHUP", () => {}); setInterval(() => {}, 1000)'], { stdio: "ignore" });
+ child.unref();
+ return send({ id, result: child.pid });
+ }
+ if (method === "emit") return send({ method: "example/event", params });
+ if (method === "fail") return send({ id, error: { code: -32000, message: "Example failure", data: { category: "example" } } });
+ if (method === "slow") return setTimeout(() => send({ id, result: params }), 80);
+ if (id !== undefined) send({ id, result: method.startsWith("connection/") ? { success: true } : params });
+});
+process.stdin.on("data", (data) => decoder.push(data));
diff --git a/plugins/sdk/dev-host/tests/i18n.test.mjs b/plugins/sdk/dev-host/tests/i18n.test.mjs
new file mode 100644
index 0000000000..9efb830138
--- /dev/null
+++ b/plugins/sdk/dev-host/tests/i18n.test.mjs
@@ -0,0 +1,31 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import { english, localizeManifest, translate } from "../ui/i18n.js";
+
+test("shell labels and diagnostics translate without altering arbitrary business data", async () => {
+ for (const file of ["App.vue", "DebugPanel.vue"]) {
+ const source = await readFile(new URL(`../ui/${file}`, import.meta.url), "utf8");
+ for (const match of source.matchAll(/\bt\('([^']+)'/g)) {
+ assert.ok(english[match[1]], `Missing English label: ${match[1]}`);
+ }
+ }
+ assert.equal(translate("en", "RPC 完成"), "RPC completed");
+ assert.equal(translate("zh-CN", "RPC 完成"), "RPC 完成");
+ assert.equal(translate("en", "自定义连接"), "自定义连接");
+ assert.match(translate("en", "删除连接“{name}”?其页面将关闭,未保存修改会丢失。", { name: "My DB" }), /My DB/);
+});
+
+test("manifest localization switches from original labels and preserves defaults", () => {
+ const source = {
+ name: "Example",
+ contributions: [{ id: "main", label: "Page", fields: [{ key: "mode", label: "Mode", default: "one", options: [{ value: "one", label: "One" }] }] }],
+ localizations: { "zh-CN": { name: "示例", contributions: { main: { label: "页面", fields: { mode: { label: "模式", options: { one: "一" } } } } } } },
+ };
+ const chinese = localizeManifest(source, "zh-CN");
+ assert.equal(chinese.name, "示例");
+ assert.equal(chinese.contributions[0].fields[0].options[0].label, "一");
+ assert.equal(chinese.contributions[0].fields[0].default, "one");
+ assert.equal(localizeManifest(source, "en").contributions[0].label, "Page");
+ assert.equal(source.name, "Example");
+});
diff --git a/plugins/sdk/dev-host/tests/runtime.test.mjs b/plugins/sdk/dev-host/tests/runtime.test.mjs
new file mode 100644
index 0000000000..f7247ed8c7
--- /dev/null
+++ b/plugins/sdk/dev-host/tests/runtime.test.mjs
@@ -0,0 +1,83 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
+import { startDevelopment } from "../runtime.mjs";
+import { Diagnostics } from "../diagnostics.mjs";
+
+async function project(t) {
+ const root = await mkdtemp(join(tmpdir(), "dbx-dev-runtime-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ await mkdir(join(root, "ui"));
+ await writeFile(join(root, "ui/index.html"), "<html><head></head><body>Test</body></html>");
+ await writeFile(
+ join(root, "manifest.json"),
+ JSON.stringify({
+ manifest_version: 1,
+ id: "example.frontend",
+ version: "1.0.0",
+ name: "Example",
+ entrypoints: { ui: { root: "ui", entry: "ui/index.html" } },
+ contributions: [],
+ permissions: [],
+ }),
+ );
+ return { project: root, port: 0, shellHtml: join(root, "ui/index.html"), diagnostics: new Diagnostics(() => {}) };
+}
+
+test("failed build does not start a host or retain signal listeners", async (t) => {
+ const options = await project(t);
+ const before = process.listenerCount("SIGTERM");
+ await assert.rejects(
+ startDevelopment({
+ ...options,
+ commands: {
+ backend: {
+ command: process.execPath,
+ args: ["-e", "process.exit(7)"],
+ },
+ },
+ }),
+ /Build failed/,
+ );
+ assert.equal(process.listenerCount("SIGTERM"), before);
+});
+
+test("development credentials cannot be placed inside UI resources", async (t) => {
+ const options = await project(t);
+ await assert.rejects(startDevelopment({ ...options, dataDir: join(options.project, "ui", "private") }), /outside the UI/);
+});
+
+test("closing development host terminates its UI watcher and releases its port", async (t) => {
+ const options = await project(t),
+ pidFile = join(options.project, "watcher.pid");
+ const host = await startDevelopment({ ...options, commands: { watch: [process.execPath, "-e", 'require("node:fs").writeFileSync(process.argv[1], String(process.pid)); setInterval(() => {}, 1000)', pidFile] } });
+ t.after(() => host.close());
+ let pid;
+ for (let attempt = 0; attempt < 100; attempt++) {
+ try {
+ pid = Number(await readFile(pidFile, "utf8"));
+ break;
+ } catch {
+ await delay(20);
+ }
+ }
+ assert.ok(pid, "watcher started");
+ await host.close();
+ assert.throws(() => process.kill(pid, 0), { code: "ESRCH" });
+ await assert.rejects(fetch(host.origin));
+});
+
+test("watcher success markers trigger reload only after a complete line", async (t) => {
+ const options = await project(t);
+ const host = await startDevelopment({ ...options, commands: { watch: [process.execPath, "-e", 'process.stdout.write("x".repeat(1100)+"DBX_UI_BUILD_SUCCESS\\n"); process.stdout.write("DBX_UI_BUILD_"); setTimeout(() => process.stdout.write("SUCCESS\\n"), 100); setInterval(() => {}, 1000)'] } });
+ t.after(() => host.close());
+ let revision = 0;
+ for (let i = 0; i < 100 && !revision; i++) {
+ await delay(20);
+ revision = (await (await fetch(`${host.origin}/api/bootstrap`)).json()).revision;
+ }
+ assert.equal(revision, 1);
+});
diff --git a/plugins/sdk/dev-host/tests/server.test.mjs b/plugins/sdk/dev-host/tests/server.test.mjs
new file mode 100644
index 0000000000..612c232fea
--- /dev/null
+++ b/plugins/sdk/dev-host/tests/server.test.mjs
@@ -0,0 +1,399 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, rm, stat, symlink } from "node:fs/promises";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { fileURLToPath } from "node:url";
+import http from "node:http";
+import { createMockHost } from "../server.mjs";
+import { ConnectionStore, lifecyclePayload, validateRecord } from "../connections.mjs";
+import { readAsset } from "../assets.mjs";
+import { Diagnostics } from "../diagnostics.mjs";
+
+const manifest = {
+ id: "example.echo",
+ version: "1.0.0",
+ name: "Generic echo",
+ engines: { host_api: ">=1.0.0, <2.0.0" },
+ permissions: ["host.events", "host.binary"],
+ entrypoints: { backend: { transport: "stdio-framed", protocol_versions: [1] }, ui: { root: "ui", entry: "ui/index.html" } },
+ contributions: [
+ {
+ type: "connection-provider",
+ id: "example.connection",
+ database_type: "example",
+ label: "Example",
+ workbench: "example.main",
+ capabilities: ["test", "connect", "disconnect"],
+ fields: [
+ { key: "name", type: "text", binding: "name", required: true },
+ { key: "endpoint", type: "text", binding: "config", required: true },
+ { key: "count", type: "number", binding: "config" },
+ { key: "enabled", type: "boolean", binding: "config" },
+ { key: "password", type: "password", binding: "secret" },
+ ],
+ },
+ { type: "workbench", id: "example.main", label: "Main" },
+ ],
+};
+const values = { name: "Example connection", endpoint: "test-endpoint", count: 7, enabled: true, password: "test-password" };
+
+test("radio fields accept only declared options", () => {
+ const radioManifest = {
+ ...manifest,
+ contributions: manifest.contributions.map((contribution) =>
+ contribution.id === "example.connection"
+ ? {
+ ...contribution,
+ fields: [
+ ...contribution.fields,
+ {
+ key: "protocol",
+ type: "radio",
+ binding: "config",
+ default: "https",
+ options: [
+ { label: "HTTPS", value: "https" },
+ { label: "HTTP", value: "http" },
+ ],
+ },
+ ],
+ }
+ : contribution,
+ ),
+ };
+ const valid = validateRecord(radioManifest, { providerId: "example.connection", values: { ...values, protocol: "http" } });
+ assert.equal(valid.values.protocol, "http");
+ assert.throws(() => validateRecord(radioManifest, { providerId: "example.connection", values: { ...values, protocol: "ftp" } }), /Invalid option: protocol/);
+});
+test("lifecycle failures do not report success or discard a live connection", async (t) => {
+ const { host, request } = await fixture(t);
+ const original = host.sidecar.request.bind(host.sidecar);
+ let fail;
+ host.sidecar.request = (method, ...args) => (method === fail ? Promise.resolve({ success: false, message: "Expected failure" }) : original(method, ...args));
+ fail = "connection/test";
+ assert.equal((await request("connections/test", { providerId: "example.connection", values })).status, 400);
+ const saved = (await request("connections/save", { providerId: "example.connection", values })).value;
+ fail = "connection/connect";
+ assert.equal((await request("connections/connect", { id: saved.id })).status, 400);
+ const snapshot = async () => (await (await fetch(`${host.origin}/api/bootstrap`)).json()).connections;
+ assert.equal((await snapshot())[0].connected, false);
+ fail = undefined;
+ const frame = (await request("connections/connect", { id: saved.id })).value.frame;
+ const document = (await request("frame-document", { frameId: frame.id })).value;
+ fail = "custom/operation";
+ const result = await request("bridge", { frameId: frame.id, channel: document.channel, method: "backend.invoke", params: { method: fail } });
+ assert.equal(result.status, 200);
+ assert.equal(result.value.success, false, "custom RPC results remain transparent");
+ fail = "connection/disconnect";
+ assert.equal((await request("frames/close", { id: frame.id })).status, 400);
+ assert.equal((await snapshot())[0].connected, true);
+ fail = undefined;
+ assert.equal((await request("frames/close", { id: frame.id })).value.connections[0].connected, false);
+});
+
+test("page reconnects preserve frames, abandoned pages release their last connection", async (t) => {
+ const { host, request, headers } = await fixture(t, false, { pageGraceMs: 150 });
+ const page = { "X-DBX-Page": "browser-page" };
+ const events = async () => {
+ const response = await fetch(`${host.origin}/api/events?page=browser-page`, { headers });
+ const reader = response.body.getReader();
+ await reader.read();
+ t.after(() => reader.cancel());
+ return reader;
+ };
+ const first = await events();
+ const saved = (await request("connections/save", { providerId: "example.connection", values }, page)).value;
+ const opened = (await request("connections/connect", { id: saved.id }, page)).value.frame;
+ await first.cancel();
+ const second = await events();
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ assert.equal((await request("frame-document", { frameId: opened.id }, page)).status, 200);
+ await second.cancel();
+ let connected = true;
+ for (let i = 0; i < 100 && connected; i++) {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ connected = (await (await fetch(`${host.origin}/api/bootstrap`)).json()).connections[0].connected;
+ }
+ assert.equal(connected, false);
+ assert.equal((await request("frame-document", { frameId: opened.id }, page)).status, 400);
+ assert.equal(host.store.get(saved.id).values.name, values.name, "saved configuration survives page cleanup");
+});
+test("pages sharing a cookie have independent workbench generations", async (t) => {
+ const { request } = await fixture(t, true);
+ const a = { "X-DBX-Page": "page-a" },
+ b = { "X-DBX-Page": "page-b" };
+ const open = (headers) => request("workbenches/open", { contributionId: "example.main" }, headers);
+ const first = (await open(a)).value.frame;
+ const second = (await open(b)).value.frame;
+ assert.notEqual(first.id, second.id);
+ assert.equal((await open(a)).value.frame.id, first.id);
+ const document = (await request("frame-document", { frameId: first.id }, a)).value;
+ await request("frame-document", { frameId: second.id }, b);
+ assert.equal((await request("frame-document", { frameId: first.id }, b)).status, 400);
+ const result = await request("bridge", { frameId: first.id, channel: document.channel, method: "host.getContext" }, a);
+ assert.equal(result.status, 200, JSON.stringify(result));
+});
+
+test("compiled UI output waits for a successful build signal", async (t) => {
+ const { host, root } = await fixture(t, true, { uiBuildSignals: true });
+ const revision = async () => (await (await fetch(`${host.origin}/api/bootstrap`)).json()).revision;
+ await writeFile(join(root, "ui/index.html"), "<head></head>Partial output");
+ await new Promise((resolve) => setTimeout(resolve, 650));
+ assert.equal(await revision(), 0);
+ await host.uiBuilt();
+ assert.equal(await revision(), 1);
+});
+test("refresh cleanup does not disconnect a connection still used by another page", async (t) => {
+ const { host, request, headers } = await fixture(t, false, { pageGraceMs: 50 });
+ const response = await fetch(`${host.origin}/api/events?page=old`, { headers });
+ const reader = response.body.getReader();
+ t.after(() => reader.cancel());
+ await reader.read();
+ const saved = (await request("connections/save", { providerId: "example.connection", values })).value;
+ const old = (await request("connections/connect", { id: saved.id }, { "X-DBX-Page": "old" })).value.frame;
+ const fresh = (await request("connections/connect", { id: saved.id }, { "X-DBX-Page": "fresh" })).value.frame;
+ await reader.cancel();
+ let status = 200;
+ for (let i = 0; i < 100 && status === 200; i++) {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ status = (await request("frame-document", { frameId: old.id }, { "X-DBX-Page": "old" })).status;
+ }
+ assert.equal(status, 400);
+ const bootstrap = await (await fetch(`${host.origin}/api/bootstrap`)).json();
+ assert.equal(bootstrap.connections[0].connected, true);
+ assert.deepEqual(bootstrap.manifest, manifest);
+ assert.equal(Object.hasOwn(bootstrap, "rawManifest"), false);
+ const closed = await request("frames/close", { id: fresh.id }, { "X-DBX-Page": "fresh" });
+ assert.equal(closed.value.connections[0].connected, false);
+});
+async function fixture(t, frontend = false, overrides = {}) {
+ const root = await mkdtemp(join(tmpdir(), "dbx-mock-test-"));
+ await mkdir(join(root, "ui"));
+ await writeFile(join(root, "ui/index.html"), "<html><head></head><body>Test</body></html>");
+ const actual = frontend ? { ...manifest, entrypoints: { ui: manifest.entrypoints.ui }, contributions: manifest.contributions.filter((c) => c.type === "workbench") } : manifest;
+ await writeFile(join(root, "manifest.json"), JSON.stringify(actual));
+ const host = await createMockHost({
+ project: root,
+ uiRoot: "ui",
+ backend: process.execPath,
+ diagnostics: new Diagnostics(() => {}),
+ backendArgs: [fileURLToPath(new URL("./echo-sidecar.mjs", import.meta.url))],
+ dataDir: join(root, "data"),
+ shellHtml: join(root, "ui/index.html"),
+ port: 0,
+ backendWatch: root,
+ buildBackend: async () => {
+ throw new Error("Intentional build failure");
+ },
+ ...overrides,
+ });
+ t.after(async () => {
+ await host.close();
+ await rm(root, { recursive: true, force: true });
+ });
+ const response = await fetch(`${host.origin}/api/bootstrap`),
+ bootstrap = await response.json();
+ const cookie = response.headers.get("set-cookie").split(";")[0];
+ const headers = { Cookie: cookie, Origin: host.origin, "X-Mock-Csrf": bootstrap.csrf, "Content-Type": "application/json" };
+ const request = async (path, data = {}, overrides = {}) => {
+ const response = await fetch(`${host.origin}/api/${path}`, { method: "POST", headers: { ...headers, ...overrides }, body: JSON.stringify(data) });
+ return { status: response.status, ...(await response.json()) };
+ };
+ return { root, host, request, headers };
+}
+test("hosts on different ports keep independent browser cookies", async (t) => {
+ const first = await fixture(t, true),
+ second = await fixture(t, true);
+ const jar = new Map();
+ const sessions = [];
+ for (const host of [first.host, second.host]) {
+ const response = await fetch(`${host.origin}/api/bootstrap`, { headers: { Cookie: [...jar].map(([k, v]) => `${k}=${v}`).join("; ") } });
+ const [key, value] = response.headers.get("set-cookie").split(";")[0].split("=");
+ jar.set(key, value);
+ sessions.push(await response.json());
+ }
+ for (const [index, host] of [first.host, second.host].entries()) {
+ const response = await fetch(`${host.origin}/api/workbenches/open`, {
+ method: "POST",
+ headers: { Cookie: [...jar].map(([k, v]) => `${k}=${v}`).join("; "), Origin: host.origin, "X-Mock-Csrf": sessions[index].csrf, "Content-Type": "application/json" },
+ body: JSON.stringify({ contributionId: "example.main" }),
+ });
+ assert.equal(response.status, 200, JSON.stringify(await response.json()));
+ }
+});
+test("diagnostics distinguish session failures and exclude connection credentials", async (t) => {
+ const { host, request } = await fixture(t);
+ const saved = await request("connections/save", { providerId: "example.connection", values });
+ await request("connections/connect", { id: saved.value.id });
+ const denied = await request("connections/save", { providerId: "example.connection", values }, { "X-Mock-Csrf": "secret-token" });
+ assert.equal(denied.status, 403);
+ const entries = host.diagnostics.snapshot();
+ assert.ok(entries.some((e) => e.details.reason === "csrf-mismatch" && e.details.status === 403));
+ assert.ok(entries.some((e) => e.details.method === "plugin/initialize" && e.message === "RPC 完成"));
+ assert.ok(entries.some((e) => e.details.method === "connections/save" && e.details.status === 200));
+ const text = JSON.stringify(entries);
+ for (const secret of ["test-password", "secret-token"]) assert.equal(text.includes(secret), false);
+ assert.ok(text.includes("test-endpoint"));
+ assert.ok(entries.some((e) => e.details.port === Number(new URL(host.origin).port)));
+ const response = await fetch(`${host.origin}/api/bootstrap`);
+ assert.deepEqual((await response.json()).diagnostics, entries);
+});
+test("source watching is opt-in and automatic restarts preserve saved connections", async (t) => {
+ let builds = 0;
+ const { root, host, request } = await fixture(t, false, {
+ buildBackend: async () => {
+ builds++;
+ },
+ });
+ const saved = await request("connections/save", { providerId: "example.connection", values });
+ await writeFile(join(root, "example.rs"), "// disabled");
+ await new Promise((resolve) => setTimeout(resolve, 650));
+ assert.equal(builds, 0);
+ assert.equal((await request("auto-reload", { enabled: true })).value.enabled, true);
+ await writeFile(join(root, "example.rs"), "// enabled");
+ for (let i = 0; i < 100 && !host.diagnostics.snapshot().some((e) => e.message === "后端重建完成"); i++) await new Promise((resolve) => setTimeout(resolve, 30));
+ assert.equal(builds, 1);
+ assert.equal(host.sidecar.state, "ready");
+ assert.equal(host.store.get(saved.value.id).values.name, values.name);
+ await request("auto-reload", { enabled: false });
+ await writeFile(join(root, "example.rs"), "// disabled again");
+ await new Promise((resolve) => setTimeout(resolve, 650));
+ assert.equal(builds, 1);
+});
+test("agent diagnostics is read-only, bounded and does not log its own polling", async (t) => {
+ const { host } = await fixture(t, true);
+ const url = `${host.origin}/api/diagnostics`,
+ headers = {};
+ const first = await (await fetch(url, { headers })).json();
+ assert.ok(first.entries.length);
+ assert.equal(first.plugin.id, manifest.id);
+ const next = await (await fetch(`${url}?after=${first.nextAfter}`, { headers })).json();
+ assert.deepEqual(next.entries, []);
+ assert.equal(next.nextAfter, first.nextAfter);
+ assert.equal((await fetch(url)).status, 200);
+ assert.equal((await fetch(url, { headers, method: "POST" })).status, 405);
+ assert.equal((await fetch(url, { headers: { ...headers, Origin: "https://other.test" } })).status, 403);
+ assert.equal((await fetch(`${url}?limit=501`, { headers })).status, 400);
+});
+test("configuration mapping preserves typed external config and separates secrets", () => {
+ const record = validateRecord(manifest, { providerId: "example.connection", values });
+ const c = lifecyclePayload(manifest, record).connection;
+ assert.deepEqual(c.external_config, { endpoint: "test-endpoint", count: 7, enabled: true });
+ assert.deepEqual(c.connection_secrets, { password: "test-password" });
+ assert.throws(() => validateRecord(manifest, { providerId: record.providerId, values: { ...values, count: "7" } }), /type/);
+ assert.throws(() => validateRecord(manifest, { providerId: record.providerId, values: { ...values, endpoint: "" } }), /Missing/);
+});
+
+test("a frontend-only workbench opens without a connection or sidecar", async (t) => {
+ const { host, request } = await fixture(t, true);
+ assert.equal(host.sidecar.state, "frontend");
+ assert.equal(host.sidecar.child, undefined);
+ const opened = await request("workbenches/open", { contributionId: "example.main" });
+ assert.equal(opened.status, 200);
+ assert.deepEqual(opened.value.frame.context, {});
+ assert.equal((await request("workbenches/open", { contributionId: "example.main" })).value.frame.id, opened.value.frame.id);
+ const f = (await request("frame-document", { frameId: opened.value.frame.id })).value;
+ const rpc = await request("bridge", { frameId: f.id, channel: f.channel, method: "backend.invoke", params: { method: "echo" } });
+ assert.equal(rpc.status, 400);
+ assert.match(rpc.error.message, /no backend/);
+ assert.equal((await request("frames/close", { id: f.id })).status, 200);
+});
+test("srcdoc workbench documents inline local Vite scripts and styles", async (t) => {
+ const { root, request } = await fixture(t, true);
+ await mkdir(join(root, "ui/assets"));
+ await writeFile(join(root, "ui/assets/app.js"), "document.body.dataset.loaded = 'yes';");
+ await writeFile(join(root, "ui/assets/app.css"), "body { color: red; }");
+ await writeFile(join(root, "ui/index.html"), '<html><head><link rel="stylesheet" href="/assets/app.css"></head><body><script type="module" src="/assets/app.js"></script></body></html>');
+ const opened = await request("workbenches/open", { contributionId: "example.main" });
+ const document = (await request("frame-document", { frameId: opened.value.frame.id })).value;
+ assert.match(document.html, /document\.body\.dataset\.loaded/);
+ assert.match(document.html, /body \{ color: red; \}/);
+ assert.doesNotMatch(document.html, /src="\/assets\/app\.js"/);
+ assert.doesNotMatch(document.html, /href="\/assets\/app\.css"/);
+});
+test("save, reload, iframe isolation, generic RPC and close lifecycle", async (t) => {
+ const { root, host, request } = await fixture(t);
+ const saved = await request("connections/save", { providerId: "example.connection", values });
+ assert.equal(saved.status, 200);
+ const id = saved.value.id;
+ assert.equal(JSON.stringify(saved).includes("test-password"), false);
+ const stored = new ConnectionStore(join(root, "data"), manifest);
+ await stored.load();
+ assert.deepEqual(stored.get(id).values, values);
+ if (process.platform !== "win32") {
+ assert.equal((await stat(join(root, "data"))).mode & 0o777, 0o700);
+ assert.equal((await stat(join(root, "data/connections.json"))).mode & 0o777, 0o600);
+ }
+ const opened = await request("connections/connect", { id });
+ const f = opened.value.frame;
+ assert.equal((await request("connections/connect", { id })).value.frame.id, f.id);
+ assert.deepEqual(f.context, { connectionId: id, providerId: "example.connection", connectionType: "example" });
+ assert.equal(JSON.stringify(f).includes("test-password"), false);
+ const document = (await request("frame-document", { frameId: f.id })).value;
+ assert.match(document.html, /Content-Security-Policy/);
+ assert.match(document.html, /window.dbxPlugin/);
+ const call = (method, params) => request("bridge", { frameId: f.id, channel: document.channel, method, params });
+ assert.deepEqual((await call("backend.invoke", { method: "echo", params: { anyBusiness: 123 } })).value, { anyBusiness: 123 });
+ assert.equal((await call("host.openWorkbench", { contributionId: "example.main" })).status, 400);
+ assert.equal((await call("host.openFilesystem", {})).status, 400);
+ assert.equal((await call("backend.invoke", { method: "echo", params: "x".repeat(2 * 1024 * 1024) })).status, 400);
+ assert.equal((await request("bridge", { frameId: f.id, channel: "old", method: "host.getContext" })).status, 400);
+ await request("connections/save", { id, providerId: "example.connection", values: { ...values, name: "Renamed connection" } });
+ const renamed = (await request("connections/connect", { id })).value.frame;
+ assert.equal(renamed.id, f.id);
+ assert.equal(renamed.name, "Renamed connection");
+ assert.equal((await request("frames/close", { id: f.id })).value.connections[0].connected, false);
+ const failedBuild = await request("backend/restart");
+ assert.equal(failedBuild.status, 400);
+ assert.equal(host.sidecar.state, "stopped");
+});
+test("loopback endpoint rejects cross-origin, forged Host, CSRF and unowned frames", async (t) => {
+ const { host, request, headers } = await fixture(t);
+ assert.equal((await request("connections/save", {}, { Origin: "https://evil.example" })).status, 403);
+ assert.equal((await request("connections/save", {}, { "X-Mock-Csrf": "wrong" })).status, 403);
+ const bad = await new Promise((resolve, reject) => {
+ const request = http.get(`${host.origin}/api/bootstrap`, { headers: { Host: "evil.example" } }, (response) => {
+ response.resume();
+ resolve(response.statusCode);
+ });
+ request.on("error", reject);
+ });
+ assert.equal(bad, 403);
+ const saved = await request("connections/save", { providerId: "example.connection", values });
+ const f = (await request("connections/connect", { id: saved.value.id })).value.frame;
+ const other = await fetch(`${host.origin}/api/bootstrap`);
+ const boot = await other.json();
+ assert.equal((await request("frame-document", { frameId: f.id }, { ...headers, Cookie: other.headers.get("set-cookie").split(";")[0], "X-Mock-Csrf": boot.csrf })).status, 400);
+});
+test("asset reader rejects traversal and symlinks outside the UI root", async (t) => {
+ const { root } = await fixture(t);
+ await writeFile(join(root, "secret"), "test-secret");
+ await symlink(join(root, "secret"), join(root, "ui/link"));
+ await assert.rejects(readAsset(join(root, "ui"), "../secret"), /outside/);
+ await assert.rejects(readAsset(join(root, "ui"), "link"), /outside/);
+ assert.equal(Buffer.from((await readAsset(join(root, "ui"), "index.html")).dataBase64, "base64").toString(), await readFile(join(root, "ui/index.html"), "utf8"));
+});
+
+test("UI root overrides and port collision fallback work without changing the plugin manifest", async (t) => {
+ const { root, host } = await fixture(t);
+ await mkdir(join(root, "alternate-ui"));
+ await writeFile(join(root, "alternate-ui/index.html"), "<html>Alternate output</html>");
+ const second = await createMockHost({
+ project: root,
+ uiRoot: "alternate-ui",
+ backend: process.execPath,
+ backendArgs: [fileURLToPath(new URL("./echo-sidecar.mjs", import.meta.url))],
+ dataDir: join(root, "second-data"),
+ shellHtml: join(root, "alternate-ui/index.html"),
+ port: Number(new URL(host.origin).port),
+ });
+ try {
+ assert.notEqual(second.origin, host.origin);
+ assert.equal((await fetch(second.origin)).status, 200);
+ } finally {
+ await second.close();
+ }
+ await writeFile(join(root, "manifest.json"), JSON.stringify({ ...manifest, engines: { host_api: ">=2.0.0" } }));
+ await assert.rejects(createMockHost({ project: root }), /does not support Host API/);
+});
diff --git a/plugins/sdk/dev-host/tests/sidecar.test.mjs b/plugins/sdk/dev-host/tests/sidecar.test.mjs
new file mode 100644
index 0000000000..68ad17e976
--- /dev/null
+++ b/plugins/sdk/dev-host/tests/sidecar.test.mjs
@@ -0,0 +1,107 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { fileURLToPath } from "node:url";
+import { once } from "node:events";
+import { setTimeout as delay } from "node:timers/promises";
+import { FrameDecoder, JsonLineDecoder, frame, binaryPayload, Sidecar, JSON_LIMIT } from "../sidecar.mjs";
+
+const config = { executable: process.execPath, args: [fileURLToPath(new URL("./echo-sidecar.mjs", import.meta.url))], transport: "stdio-framed", manifest: { id: "example.echo", version: "1.0.0" } };
+test("sidecar shutdown terminates descendants even after the leader exits", async (t) => {
+ const sidecar = new Sidecar(config);
+ t.after(() => sidecar.stop());
+ await sidecar.start();
+ const pid = await sidecar.request("spawn-child");
+ t.after(() => {
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch {}
+ });
+ await delay(100);
+ await sidecar.stop();
+ let alive = true;
+ for (let i = 0; i < 100 && alive; i++) {
+ try {
+ process.kill(pid, 0);
+ await delay(20);
+ } catch {
+ alive = false;
+ }
+ }
+ assert.equal(alive, false, "sidecar descendant must be terminated");
+});
+test("decoder handles split headers, payloads, concatenated frames and binary channels", () => {
+ const got = [],
+ decoder = new FrameDecoder((packet) => got.push(packet));
+ const input = Buffer.concat([frame(0, Buffer.from('{"result":1}')), frame(1, binaryPayload("test/bytes", Buffer.from([0, 255, 13])))]);
+ for (const byte of input) decoder.push(Buffer.from([byte]));
+ assert.equal(got[0].message.result, 1);
+ assert.deepEqual(got[1].data, Buffer.from([0, 255, 13]));
+ assert.equal(decoder.buffer.length, 0);
+});
+test("decoder rejects oversized and malformed frames before allocating payloads", () => {
+ const header = Buffer.alloc(5);
+ header.writeUInt32BE(JSON_LIMIT + 1, 1);
+ assert.throws(() => new FrameDecoder(() => {}).push(header), /limit/);
+ assert.throws(() => new FrameDecoder(() => {}).push(frame(9, Buffer.alloc(0))), /kind/);
+ assert.throws(() => new FrameDecoder(() => {}).push(frame(1, Buffer.from([0, 20]))), /channel/);
+});
+test("generic sidecar correlates out-of-order replies and preserves structured errors", async (t) => {
+ const sidecar = new Sidecar(config);
+ t.after(() => sidecar.stop());
+ await sidecar.start();
+ const order = [];
+ const a = sidecar.request("slow", { a: 1 }).then((value) => {
+ order.push("slow");
+ return value;
+ });
+ const b = sidecar.request("echo", { b: 2 }).then((value) => {
+ order.push("fast");
+ return value;
+ });
+ assert.deepEqual(await b, { b: 2 });
+ assert.deepEqual(await a, { a: 1 });
+ assert.deepEqual(order, ["fast", "slow"]);
+ await assert.rejects(sidecar.request("fail"), (e) => e.rpc.data.category === "example");
+});
+test("events, binary, timeout and process death are observable without business RPC knowledge", async (t) => {
+ const sidecar = new Sidecar(config);
+ t.after(() => sidecar.stop());
+ await sidecar.start();
+ const event = once(sidecar, "event");
+ await sidecar.notify("emit", { event: true });
+ assert.equal((await event)[0].params.event, true);
+ const binary = once(sidecar, "binary");
+ await sidecar.sendBinary("channel", Buffer.from("bytes"));
+ assert.equal((await binary)[0].dataBase64, Buffer.from("bytes").toString("base64"));
+ await assert.rejects(sidecar.request("slow", {}, 5), /timed out/);
+ const slow = sidecar.request("slow");
+ const slowAssertion = assert.rejects(slow, /exited/);
+ await sidecar.notify("die");
+ await slowAssertion;
+ assert.equal(sidecar.pending.size, 0);
+});
+test("handshake rejects wrong identity and missing executables terminate promptly", async () => {
+ const wrong = new Sidecar({ ...config, manifest: { id: "wrong", version: "1.0.0" } });
+ await assert.rejects(wrong.start(), /identity/);
+ const missing = new Sidecar({ ...config, executable: "/definitely/missing/mock-sidecar" });
+ await assert.rejects(missing.start(), /start/);
+ await missing.stop();
+});
+
+test("JSONL supports split lines, concurrent RPC, events and rejects binary channels", async (t) => {
+ const packets = [],
+ decoder = new JsonLineDecoder((packet) => packets.push(packet));
+ decoder.push(Buffer.from('{"a":'));
+ decoder.push(Buffer.from('1}\n\n{"b":2}\n'));
+ assert.equal(packets.length, 2);
+ assert.equal(packets[1].message.b, 2);
+ assert.throws(() => new JsonLineDecoder(() => {}).push(Buffer.alloc(JSON_LIMIT + 1, 65)), /limit/);
+ const sidecar = new Sidecar({ ...config, transport: "stdio-jsonl", args: [...config.args, "--jsonl"] });
+ t.after(() => sidecar.stop());
+ await sidecar.start();
+ assert.deepEqual(await sidecar.request("echo", { arbitrary: "value" }), { arbitrary: "value" });
+ const event = once(sidecar, "event");
+ await sidecar.notify("emit", { ok: true });
+ assert.equal((await event)[0].params.ok, true);
+ await assert.rejects(sidecar.sendBinary("bytes", Buffer.from("data")), /framed/);
+});
diff --git a/plugins/sdk/dev-host/ui/App.vue b/plugins/sdk/dev-host/ui/App.vue
new file mode 100644
index 0000000000..0583d0bb3c
--- /dev/null
+++ b/plugins/sdk/dev-host/ui/App.vue
@@ -0,0 +1,448 @@
+<script setup>
+import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
+import { Plus, Upload, Plug, Unplug, Pencil, Trash2, X, RefreshCw, Sun, Moon, Terminal, Settings2, Languages } from "lucide-vue-next";
+import { hostMessage } from "./messages.js";
+import DebugPanel from "./DebugPanel.vue";
+import { localizeManifest, translate } from "./i18n.js";
+const rawManifest = ref(),
+ connections = ref([]),
+ frames = ref([]),
+ active = ref(""),
+ state = ref("starting");
+const error = ref(""),
+ notice = ref(""),
+ busy = ref(false),
+ rebuilt = ref(false),
+ dark = ref(false);
+const debugOpen = ref(false),
+ diagnostics = ref([]);
+const locale = ref("zh-CN");
+const pageId = crypto.randomUUID();
+const t = (text, values) => translate(locale.value, text, values);
+const manifest = computed(() => localizeManifest(rawManifest.value ? JSON.parse(JSON.stringify(rawManifest.value)) : undefined, locale.value));
+const frameName = (frame) => (frame.connectionId ? frame.name : manifest.value?.contributions.find((c) => c.id === frame.contributionId)?.label || frame.name);
+watch(
+ locale,
+ (value) => {
+ window.document.documentElement.lang = value;
+ window.document.title = t("插件调试");
+ },
+ { immediate: true },
+);
+const autoReload = ref(false),
+ pendingReload = ref(false);
+async function toggleAutoReload(event) {
+ event.target.checked = autoReload.value;
+ await run(async () => {
+ if (!autoReload.value && !(await ask("启用自动重载?所有打开的插件页面会在更新后刷新,未保存修改将丢失;后端源码变化会重建并断开连接。此设置影响同一调试服务的所有浏览器页面。"))) return;
+ autoReload.value = (await api("auto-reload", { enabled: !autoReload.value })).enabled;
+ });
+}
+watch([busy, autoReload, pendingReload], async () => {
+ if (!autoReload.value) {
+ pendingReload.value = false;
+ return;
+ }
+ if (busy.value || !pendingReload.value) return;
+ pendingReload.value = false;
+ await run(async () => {
+ for (const frame of frames.value) Object.assign(frame, await api("frame-document", { frameId: frame.id }));
+ rebuilt.value = false;
+ });
+});
+async function changeLocale() {
+ await run(async () => {
+ const current = frames.value.find((frame) => frame.id === active.value);
+ if (current && !(await ask("切换语言并重载当前页面?未保存修改将丢失。"))) return;
+ const document = current ? await api("frame-document", { frameId: current.id }) : undefined;
+ locale.value = locale.value === "zh-CN" ? "en" : "zh-CN";
+ for (const frame of frames.value) post(frame, { type: "env", locale: locale.value });
+ if (current) {
+ Object.assign(current, document);
+ rebuilt.value = false;
+ }
+ });
+}
+function mergeDiagnostics(entries) {
+ diagnostics.value = [...new Map([...diagnostics.value, ...entries].map((e) => [e.id, e])).values()].sort((a, b) => a.id - b.id).slice(-500);
+}
+const editor = ref(),
+ askDialog = ref(),
+ importing = ref(),
+ question = ref(""),
+ draft = ref(),
+ editing = ref(false);
+const windows = new Map();
+let csrf, stream, finishAsk;
+const providers = computed(() => manifest.value?.contributions.filter((c) => c.type === "connection-provider") || []);
+const workbenches = computed(() => manifest.value?.contributions.filter((c) => c.type === "workbench") || []);
+const provider = computed(() => providers.value.find((p) => p.id === draft.value?.providerId));
+const themes = () => ({
+ appearance: dark.value ? "dark" : "light",
+ tokens: dark.value
+ ? {
+ "--color-background": "#18181b",
+ "--color-foreground": "#f4f4f5",
+ "--color-muted": "#27272a",
+ "--color-border": "#3f3f46",
+ "--color-primary": "#60a5fa",
+ }
+ : { "--color-background": "#ffffff", "--color-foreground": "#27272a", "--color-muted": "#f4f4f5", "--color-border": "#e4e4e7", "--color-primary": "#2563eb" },
+});
+function post(frame, message) {
+ const snapshot = hostMessage(frame.channel, message);
+ windows.get(frame.id)?.contentWindow?.postMessage(snapshot, "*");
+}
+function init(frame) {
+ post(frame, { type: "init", context: JSON.parse(JSON.stringify(frame.context)), locale: locale.value, theme: themes(), permissions: manifest.value.permissions || [] });
+}
+function theme() {
+ dark.value = !dark.value;
+ document.documentElement.dataset.theme = dark.value ? "dark" : "light";
+ for (const f of frames.value) post(f, { type: "env", theme: themes() });
+}
+async function api(path, params = {}) {
+ const response = await fetch(`/api/${path}`, { method: "POST", headers: { "Content-Type": "application/json", "X-Mock-Csrf": csrf, "X-DBX-Page": pageId }, body: JSON.stringify(params) });
+ const result = await response.json();
+ if (!response.ok) throw Object.assign(new Error(result.error?.message || "请求失败"), { code: result.error?.code, data: result.error?.data });
+ return result.value;
+}
+async function run(action) {
+ if (busy.value) return;
+ busy.value = true;
+ error.value = "";
+ notice.value = "";
+ try {
+ await action();
+ } catch (e) {
+ error.value = e.message;
+ } finally {
+ busy.value = false;
+ }
+}
+async function ask(message) {
+ question.value = message;
+ const promise = new Promise((resolve) => {
+ finishAsk = resolve;
+ });
+ await nextTick();
+ askDialog.value.showModal();
+ return promise;
+}
+function answer(yes) {
+ askDialog.value.close();
+ finishAsk?.(yes);
+ finishAsk = undefined;
+}
+async function bootstrap() {
+ const response = await fetch("/api/bootstrap");
+ if (!response.ok) throw new Error("无法读取模拟宿主状态");
+ const data = await response.json();
+ csrf = data.csrf;
+ rawManifest.value = data.manifest;
+ connections.value = data.connections;
+ state.value = data.state;
+ diagnostics.value = data.diagnostics || [];
+ autoReload.value = data.autoReload || false;
+}
+function newDraft() {
+ draft.value = { providerId: providers.value[0]?.id, values: {}, readOnly: false };
+ editing.value = false;
+ defaults();
+ editor.value.showModal();
+}
+function defaults() {
+ draft.value.values = Object.fromEntries((provider.value?.fields || []).filter((f) => f.default !== undefined).map((f) => [f.key, f.default]));
+}
+async function edit(record) {
+ await run(async () => {
+ draft.value = await api("connections/edit", { id: record.id });
+ editing.value = true;
+ editor.value.showModal();
+ });
+}
+async function save() {
+ await run(async () => {
+ const result = await api("connections/save", draft.value);
+ connections.value = result.connections;
+ for (const f of frames.value) if (f.connectionId === result.id) f.name = result.connections.find((c) => c.id === result.id)?.name || f.name;
+ editor.value.close();
+ draft.value = undefined;
+ notice.value = "连接已保存";
+ });
+}
+async function test() {
+ await run(async () => {
+ await api("connections/test", draft.value);
+ notice.value = "连接测试成功";
+ });
+}
+async function addFrame(frame) {
+ const previous = frames.value.find((f) => f.id === frame.id);
+ if (previous) {
+ previous.context = frame.context;
+ previous.name = frame.name;
+ post(previous, { type: "context", context: frame.context });
+ } else {
+ const document = await api("frame-document", { frameId: frame.id });
+ frames.value.push(document);
+ }
+ active.value = frame.id;
+}
+async function connect(record) {
+ await run(async () => {
+ const result = await api("connections/connect", { id: record.id });
+ connections.value = result.connections;
+ await addFrame(result.frame);
+ });
+}
+async function openWorkbench(contribution) {
+ await run(async () => {
+ await addFrame((await api("workbenches/open", { contributionId: contribution.id })).frame);
+ });
+}
+async function disconnect(record) {
+ await run(async () => {
+ if (!(await ask("断开连接将中断该连接正在进行的操作。继续?"))) return;
+ connections.value = (await api("connections/disconnect", { id: record.id })).connections;
+ });
+}
+async function remove(record) {
+ await run(async () => {
+ if (!(await ask(t("删除连接“{name}”?其页面将关闭,未保存修改会丢失。", { name: record.name })))) return;
+ connections.value = (await api("connections/delete", { id: record.id })).connections;
+ removeFrames(record.id);
+ });
+}
+function removeFrames(connectionId) {
+ for (const f of frames.value.filter((f) => f.connectionId === connectionId)) windows.delete(f.id);
+ frames.value = frames.value.filter((f) => f.connectionId !== connectionId);
+ if (!frames.value.some((f) => f.id === active.value)) active.value = frames.value[0]?.id || "";
+}
+async function closeFrame(frame) {
+ await run(async () => {
+ if (!(await ask("关闭此页面?未保存修改将丢失;最后一个关联页面关闭后会断开连接。"))) return;
+ connections.value = (await api("frames/close", { id: frame.id })).connections;
+ windows.delete(frame.id);
+ frames.value = frames.value.filter((f) => f.id !== frame.id);
+ if (active.value === frame.id) active.value = frames.value[0]?.id || "";
+ });
+}
+async function reload() {
+ await run(async () => {
+ const f = frames.value.find((f) => f.id === active.value);
+ if (!f) return;
+ if (!(await ask("重载当前页面?未保存修改将丢失。"))) return;
+ const document = await api("frame-document", { frameId: f.id });
+ Object.assign(f, document);
+ rebuilt.value = false;
+ });
+}
+async function restart() {
+ await run(async () => {
+ if (!(await ask("重建并重启后端将断开所有连接、中断传输。页面不会自动重载,写操作不会自动重试。继续?"))) return;
+ state.value = "building";
+ const result = await api("backend/restart");
+ connections.value = result.connections;
+ state.value = result.state;
+ notice.value = "后端已启动,请重新连接";
+ });
+}
+async function importFile(event) {
+ const file = event.target.files?.[0];
+ if (!file) return;
+ await run(async () => {
+ if (file.size > 2 * 1024 * 1024) throw new Error("导入文件超过 2 MiB");
+ const data = JSON.parse(await file.text());
+ connections.value = (await api("connections/import", data)).connections;
+ });
+ event.target.value = "";
+}
+async function onMessage(event) {
+ const m = event.data;
+ const f = frames.value.find((f) => windows.get(f.id)?.contentWindow === event.source);
+ if (!f || m?.source !== "dbx-plugin" || m.version !== 1 || m.channel !== f.channel) return;
+ if (m.type === "ready") {
+ init(f);
+ return;
+ }
+ if (m.type !== "request") return;
+ const channel = f.channel;
+ try {
+ const result = await api("bridge", { frameId: f.id, channel, method: m.method, params: m.params });
+ if (f.channel !== channel || !windows.has(f.id)) return;
+ if (m.method === "host.openWorkbench" && result?.mockHostOpenFrame) {
+ await addFrame(result.mockHostOpenFrame);
+ post(f, { type: "response", id: m.id, result: null });
+ } else post(f, { type: "response", id: m.id, result });
+ } catch (e) {
+ if (f.channel === channel) post(f, { type: "response", id: m.id, error: { message: e.message, code: e.code, data: e.data } });
+ }
+}
+onMounted(async () => {
+ window.addEventListener("message", onMessage);
+ await run(async () => {
+ await bootstrap();
+ stream = new EventSource(`/api/events?page=${pageId}`);
+ stream.onmessage = (event) => {
+ const m = JSON.parse(event.data);
+ if (m.type === "connections") connections.value = m.connections;
+ if (m.type === "page-frames") {
+ for (const f of frames.value) if (!m.ids.includes(f.id)) windows.delete(f.id);
+ frames.value = frames.value.filter((f) => m.ids.includes(f.id));
+ if (!frames.value.some((f) => f.id === active.value)) active.value = frames.value[0]?.id || "";
+ }
+ if (m.type === "diagnostic") mergeDiagnostics([m.entry]);
+ if (m.type === "diagnostic-history") mergeDiagnostics(m.entries);
+ if (m.type === "status") {
+ state.value = m.state;
+ if (m.state !== "ready") connections.value = connections.value.map((c) => ({ ...c, connected: false }));
+ }
+ if (m.type === "ui-rebuilt") {
+ rebuilt.value = true;
+ if (autoReload.value) pendingReload.value = true;
+ }
+ if (m.type === "auto-reload") autoReload.value = m.enabled;
+ if (m.type === "auto-reload-error") error.value = "自动重载失败,请查看调试日志;修复源码后可重试";
+ if (m.type === "frames-removed") removeFrames(m.connectionId);
+ if (m.type === "watch-error") error.value = "页面构建监听已停止,请重启调试服务";
+ if (m.type === "event" || m.type === "binary") for (const f of frames.value) post(f, { ...m, binaryChannel: m.channel });
+ };
+ stream.onerror = () => {
+ error.value = "调试服务连接中断,正在重新连接";
+ };
+ });
+});
+onBeforeUnmount(() => {
+ stream?.close();
+ window.removeEventListener("message", onMessage);
+});
+</script>
+
+<template>
+ <main class="flex h-full flex-col bg-base-100 text-base-content">
+ <header class="flex min-h-14 flex-wrap items-center gap-3 border-b border-base-300 px-4 py-2">
+ <Terminal :size="20" class="text-success" />
+ <h1 class="text-sm font-semibold">{{ t("插件调试") }}</h1>
+ <span class="mr-auto text-xs text-base-content/60">{{ manifest?.name }}</span>
+ <span class="text-xs" :class="['ready', 'frontend'].includes(state) ? 'text-success' : 'text-warning'" role="status">{{
+ t({ frontend: "纯前端", ready: "后端运行中", building: "正在构建", starting: "正在启动", stopped: "后端已停止", stopping: "正在停止", failed: "后端异常" }[state] || state)
+ }}</span>
+ <button v-if="manifest?.entrypoints?.backend" class="btn btn-sm" :disabled="busy" @click="restart"><RefreshCw :size="14" />{{ t("重建后端") }}</button>
+ <button class="btn btn-sm shrink-0" :class="rebuilt ? 'text-info' : ''" :disabled="busy || !active" @click="reload"><RefreshCw :size="14" />{{ t(rebuilt ? "有新构建 · 重载页面" : "重载页面") }}</button>
+ <button class="btn btn-sm w-28 shrink-0" :disabled="busy" :aria-label="t('切换插件语言')" :title="t('切换插件语言')" @click="changeLocale"><Languages :size="14" />{{ t(locale === "zh-CN" ? "中文" : "English") }}</button>
+ <button class="btn btn-sm" :class="debugOpen ? 'btn-active' : ''" :aria-expanded="debugOpen" aria-controls="debug-panel" @click="debugOpen = !debugOpen"><Terminal :size="14" />{{ t("调试") }}</button>
+ <label class="flex shrink-0 items-center gap-2 text-xs"><input type="checkbox" class="toggle toggle-xs" :aria-label="t('自动重载')" :checked="autoReload" :disabled="busy" @change="toggleAutoReload" />{{ t("自动重载") }}</label>
+ <button class="btn btn-sm btn-square btn-ghost" :aria-label="t(dark ? '浅色主题' : '深色主题')" :title="t(dark ? '浅色主题' : '深色主题')" @click="theme"><Sun v-if="dark" :size="16" /><Moon v-else :size="16" /></button>
+ </header>
+ <div v-if="error && !draft" role="alert" class="flex gap-2 border-b border-error/30 bg-error/10 px-4 py-2 text-sm text-error">
+ <span class="min-w-0 flex-1 break-words">{{ t(error) }}</span
+ ><button class="btn btn-xs btn-square btn-ghost" :aria-label="t('关闭错误')" @click="error = ''"><X :size="14" /></button>
+ </div>
+ <div v-if="notice && !draft" role="status" class="border-b border-base-300 px-4 py-2 text-xs text-success">{{ t(notice) }}</div>
+ <div class="flex min-h-0 flex-1">
+ <aside class="flex w-56 shrink-0 flex-col border-r border-base-300 bg-base-200 max-sm:w-40" :aria-label="t('连接列表')">
+ <div v-if="workbenches.length" class="border-b border-base-300 p-2">
+ <h2 class="px-1 py-2 text-xs font-semibold">{{ t("工作台") }}</h2>
+ <button v-for="workbench in workbenches" :key="workbench.id" class="btn btn-sm btn-ghost w-full justify-start" :title="workbench.label" :disabled="busy" @click="openWorkbench(workbench)">
+ <Terminal :size="14" /><span class="truncate">{{ workbench.label }}</span>
+ </button>
+ </div>
+ <div class="flex items-center gap-1 border-b border-base-300 p-2">
+ <h2 class="mr-auto text-xs font-semibold">{{ t("连接") }}</h2>
+ <button class="btn btn-sm btn-square btn-ghost" :aria-label="t('新建连接')" :title="t('新建连接')" :disabled="busy || !providers.length" @click="newDraft"><Plus :size="16" /></button
+ ><button class="btn btn-sm btn-square btn-ghost" :aria-label="t('导入连接')" :title="t('导入连接')" :disabled="busy" @click="importing.click()"><Upload :size="16" /></button><input ref="importing" type="file" accept="application/json,.json" hidden @change="importFile" />
+ </div>
+ <div class="min-h-0 flex-1 overflow-auto p-2">
+ <div v-for="c in connections" :key="c.id" class="mb-1 border-b border-base-300 pb-2" :data-connection="c.id">
+ <button class="flex w-full min-w-0 items-center gap-2 py-2 text-left text-sm" :title="c.name" :disabled="busy || state !== 'ready'" @click="connect(c)">
+ <Plug :size="15" class="shrink-0" :class="c.connected ? 'text-success' : 'text-base-content/40'" /><span class="truncate">{{ c.name }}</span>
+ </button>
+ <div class="flex items-center gap-1">
+ <span class="mr-auto truncate text-xs text-base-content/60">{{ providers.find((p) => p.id === c.providerId)?.label || c.label }}</span
+ ><button class="btn btn-xs btn-square btn-ghost" :aria-label="t('编辑') + ' ' + c.name" :title="t('编辑')" :disabled="busy" @click="edit(c)"><Pencil :size="13" /></button
+ ><button class="btn btn-xs btn-square btn-ghost" :aria-label="t('断开') + ' ' + c.name" :title="t('断开')" :disabled="busy || !c.connected" @click="disconnect(c)"><Unplug :size="13" /></button
+ ><button class="btn btn-xs btn-square btn-ghost" :aria-label="t('删除') + ' ' + c.name" :title="t('删除')" :disabled="busy" @click="remove(c)"><Trash2 :size="13" /></button>
+ </div>
+ </div>
+ <p v-if="!connections.length" class="py-8 text-center text-xs text-base-content/50">{{ t("暂无连接") }}</p>
+ </div>
+ </aside>
+ <section class="flex min-h-0 min-w-0 flex-1 flex-col" :aria-label="t('工作台')">
+ <div class="flex min-h-10 items-center border-b border-base-300">
+ <div class="flex min-w-0 flex-1 overflow-x-auto" role="tablist">
+ <div v-for="f in frames" :key="f.id" class="flex shrink-0 items-center border-r border-base-300" :class="active === f.id ? 'bg-base-200 border-b-2 border-b-info' : ''">
+ <button role="tab" class="max-w-44 truncate px-3 py-2 text-xs" :aria-selected="active === f.id" :title="frameName(f)" @click="active = f.id">{{ frameName(f) }}</button
+ ><button class="btn btn-xs btn-square btn-ghost mr-1" :aria-label="t('关闭') + ' ' + frameName(f)" :disabled="busy" @click="closeFrame(f)"><X :size="12" /></button>
+ </div>
+ </div>
+ </div>
+ <div class="relative min-h-0 flex-1">
+ <iframe v-for="f in frames" v-show="active === f.id" :key="f.id" :ref="(el) => (el ? windows.set(f.id, el) : windows.delete(f.id))" :srcdoc="f.html" sandbox="allow-scripts" referrerpolicy="no-referrer" :title="frameName(f)" class="absolute inset-0" @load="init(f)" />
+ <div v-if="!frames.length" class="grid h-full place-items-center text-sm text-base-content/50">
+ <div class="flex items-center gap-2"><Settings2 :size="18" />{{ t("尚未打开工作台") }}</div>
+ </div>
+ </div>
+ </section>
+ </div>
+ <DebugPanel v-if="debugOpen" :entries="diagnostics" :locale="locale" @close="debugOpen = false" />
+ <dialog ref="editor" class="modal" @cancel="draft = undefined">
+ <form v-if="draft" class="modal-box max-w-xl rounded-lg" @submit.prevent="save">
+ <div class="flex items-center justify-between">
+ <h2 class="text-base font-semibold">{{ t(editing ? "编辑连接" : "新建连接") }}</h2>
+ <button
+ type="button"
+ class="btn btn-sm btn-square btn-ghost"
+ :aria-label="t('关闭表单')"
+ :disabled="busy"
+ @click="
+ editor.close();
+ draft = undefined;
+ "
+ >
+ <X :size="16" />
+ </button>
+ </div>
+ <label class="mt-4 block text-xs"
+ >{{ t("连接类型")
+ }}<select v-model="draft.providerId" class="select select-sm mt-1 w-full" :disabled="editing || busy" @change="defaults">
+ <option v-for="p in providers" :key="p.id" :value="p.id">{{ p.label }}</option>
+ </select></label
+ >
+ <div class="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2">
+ <label v-for="field in provider?.fields || []" :key="field.key" class="min-w-0 text-xs" :class="field.type === 'textarea' ? 'sm:col-span-2' : ''"
+ >{{ field.label }}{{ field.required ? " *" : "" }}
+ <select v-if="field.type === 'select'" v-model="draft.values[field.key]" class="select select-sm mt-1 w-full" :aria-label="field.label" :required="field.required" :disabled="busy">
+ <option v-for="option in field.options" :key="option.value" :value="option.value">{{ option.label }}</option>
+ </select>
+ <div v-else-if="field.type === 'radio'" class="mt-2 flex flex-wrap gap-x-4 gap-y-2" role="radiogroup" :aria-label="field.label">
+ <label v-for="option in field.options" :key="option.value" class="flex items-center gap-2">
+ <input v-model="draft.values[field.key]" type="radio" :name="field.key" :value="option.value" :disabled="busy" />
+ <span>{{ option.label }}</span>
+ </label>
+ </div>
+ <input v-else-if="field.type === 'boolean'" v-model="draft.values[field.key]" type="checkbox" class="checkbox checkbox-sm ml-2" :aria-label="field.label" :disabled="busy" />
+ <textarea v-else-if="field.type === 'textarea'" v-model="draft.values[field.key]" class="textarea mt-1 w-full" :aria-label="field.label" :required="field.required" :disabled="busy" />
+ <input v-else-if="field.type === 'number'" v-model.number="draft.values[field.key]" type="number" class="input input-sm mt-1 w-full" :aria-label="field.label" :required="field.required" :disabled="busy" />
+ <input v-else v-model="draft.values[field.key]" :type="field.type === 'password' ? 'password' : 'text'" class="input input-sm mt-1 w-full" :aria-label="field.label" :required="field.required" :disabled="busy" autocomplete="off" />
+ <span v-if="field.description" class="mt-1 block text-xs text-base-content/50">{{ field.description }}</span>
+ </label>
+ </div>
+ <label class="mt-4 flex items-center gap-2 text-xs"><input v-model="draft.readOnly" type="checkbox" class="checkbox checkbox-sm" :disabled="busy" />{{ t("只读连接") }}</label>
+ <p v-if="error" role="alert" class="mt-3 break-words text-sm text-error">{{ t(error) }}</p>
+ <p v-if="notice" role="status" class="mt-3 text-sm text-success">{{ t(notice) }}</p>
+ <div class="modal-action">
+ <button type="button" class="btn btn-sm" :disabled="busy || state !== 'ready' || !provider?.capabilities?.includes('test')" @click="test">{{ t("测试连接") }}</button><button class="btn btn-sm" :disabled="busy">{{ t("保存") }}</button>
+ </div>
+ </form>
+ </dialog>
+ <dialog ref="askDialog" class="modal" @cancel.prevent="answer(false)">
+ <div class="modal-box max-w-sm rounded-lg">
+ <p class="text-sm">{{ t(question) }}</p>
+ <div class="modal-action">
+ <button class="btn btn-sm" @click="answer(false)">{{ t("取消") }}</button><button class="btn btn-sm" @click="answer(true)">{{ t("确认") }}</button>
+ </div>
+ </div>
+ </dialog>
+ </main>
+</template>
diff --git a/plugins/sdk/dev-host/ui/DebugPanel.vue b/plugins/sdk/dev-host/ui/DebugPanel.vue
new file mode 100644
index 0000000000..177497ed43
--- /dev/null
+++ b/plugins/sdk/dev-host/ui/DebugPanel.vue
@@ -0,0 +1,66 @@
+<script setup>
+import { computed, nextTick, ref, watch } from "vue";
+import { ArrowDownToLine, Trash2, X } from "lucide-vue-next";
+import { translate } from "./i18n.js";
+const props = defineProps({ entries: { type: Array, default: () => [] }, locale: { type: String, default: "zh-CN" } });
+const t = (text) => translate(props.locale, text);
+defineEmits(["close"]);
+const level = ref("all"),
+ follow = ref(true),
+ cleared = ref(0),
+ viewport = ref();
+const visible = computed(() => props.entries.filter((e) => e.id > cleared.value && (level.value === "all" || e.level === level.value)));
+function clear() {
+ cleared.value = props.entries.at(-1)?.id || 0;
+}
+watch(
+ [visible, follow],
+ async () => {
+ if (follow.value) {
+ await nextTick();
+ viewport.value?.scrollTo({ top: viewport.value.scrollHeight });
+ }
+ },
+ { immediate: true },
+);
+</script>
+
+<template>
+ <section id="debug-panel" :aria-label="t('调试信息')" class="flex h-64 max-h-[40vh] min-h-0 shrink-0 flex-col border-t border-base-300 bg-base-200">
+ <div class="flex shrink-0 flex-wrap items-center gap-2 border-b border-base-300 px-3 py-2">
+ <h2 class="mr-auto text-xs font-semibold">
+ {{ t("调试信息") }}<span class="ml-2 font-normal text-base-content/60">{{ visible.length }} / 500</span>
+ </h2>
+ <select v-model="level" :aria-label="t('日志级别')" class="select select-xs w-32">
+ <option value="all">{{ t("全部级别") }}</option>
+ <option value="error">{{ t("错误") }}</option>
+ <option value="info">{{ t("信息") }}</option>
+ <option value="debug">{{ t("调试") }}</option>
+ </select>
+ <button class="btn btn-xs btn-square btn-ghost" :class="follow ? 'btn-active' : ''" :aria-pressed="follow" :aria-label="t('自动滚动')" :title="t('自动滚动')" @click="follow = !follow"><ArrowDownToLine :size="14" /></button>
+ <button class="btn btn-xs btn-square btn-ghost" :aria-label="t('清空调试信息')" :title="t('清空当前视图')" @click="clear"><Trash2 :size="14" /></button>
+ <button class="btn btn-xs btn-square btn-ghost" :aria-label="t('关闭调试信息')" :title="t('关闭调试信息')" @click="$emit('close')"><X :size="14" /></button>
+ </div>
+ <div ref="viewport" class="min-h-0 flex-1 overflow-auto px-3 py-1 font-mono text-xs" role="log" aria-live="off" tabindex="0">
+ <div v-for="entry in visible" :key="entry.id" class="flex flex-wrap gap-x-3 border-b border-base-300/50 py-1.5" :class="entry.level === 'error' ? 'text-error' : ''">
+ <time class="shrink-0 text-base-content/60" :datetime="entry.time">{{ new Date(entry.time).toLocaleTimeString(locale, { hour12: false }) }}</time>
+ <span class="w-12 shrink-0 uppercase">{{ entry.level }}</span>
+ <span class="w-14 shrink-0 text-base-content/60">{{ entry.category }}</span>
+ <div class="min-w-0 flex-1 break-words">
+ <span>{{ t(entry.message) }}</span>
+ <span class="ml-2 text-base-content/60">{{
+ Object.entries(entry.details)
+ .filter(([k]) => !["params", "result", "error"].includes(k))
+ .map(([k, v]) => `${k}=${v}`)
+ .join(" · ")
+ }}</span>
+ <details v-for="key in ['params', 'result', 'error'].filter((k) => k in entry.details)" :key="key" class="mt-1">
+ <summary class="cursor-pointer text-info">{{ t({ params: "入参", result: "出参", error: "错误详情" }[key]) }}</summary>
+ <pre class="mt-1 whitespace-pre-wrap break-all text-base-content">{{ JSON.stringify(entry.details[key], null, 2) }}</pre>
+ </details>
+ </div>
+ </div>
+ <p v-if="!visible.length" class="py-4 text-center text-base-content/50">{{ t("暂无调试记录") }}</p>
+ </div>
+ </section>
+</template>
diff --git a/plugins/sdk/dev-host/ui/i18n.js b/plugins/sdk/dev-host/ui/i18n.js
new file mode 100644
index 0000000000..662baf08fa
--- /dev/null
+++ b/plugins/sdk/dev-host/ui/i18n.js
@@ -0,0 +1,118 @@
+export const english = {
+ 插件调试: "Plugin Debug",
+ 纯前端: "Frontend only",
+ 后端运行中: "Backend running",
+ 正在构建: "Building",
+ 正在启动: "Starting",
+ 后端已停止: "Backend stopped",
+ 正在停止: "Stopping",
+ 后端异常: "Backend failed",
+ 重建后端: "Rebuild backend",
+ 重载页面: "Reload page",
+ "有新构建 · 重载页面": "New build · Reload page",
+ 调试: "Debug",
+ 自动重载: "Auto reload",
+ 切换插件语言: "Switch language",
+ 浅色主题: "Light theme",
+ 深色主题: "Dark theme",
+ 关闭错误: "Dismiss error",
+ 连接列表: "Connections",
+ 工作台: "Workbench",
+ 连接: "Connections",
+ 新建连接: "New connection",
+ 导入连接: "Import connections",
+ 编辑: "Edit",
+ 断开: "Disconnect",
+ 删除: "Delete",
+ 关闭: "Close",
+ 暂无连接: "No connections",
+ 尚未打开工作台: "No workbench open",
+ 编辑连接: "Edit connection",
+ 关闭表单: "Close form",
+ 连接类型: "Connection type",
+ 只读连接: "Read-only connection",
+ 测试连接: "Test connection",
+ 保存: "Save",
+ 取消: "Cancel",
+ 确认: "Confirm",
+ 调试信息: "Diagnostics",
+ 日志级别: "Log level",
+ 全部级别: "All levels",
+ 错误: "Error",
+ 信息: "Info",
+ 自动滚动: "Auto scroll",
+ 清空调试信息: "Clear diagnostics",
+ 清空当前视图: "Clear current view",
+ 关闭调试信息: "Close diagnostics",
+ 入参: "Parameters",
+ 出参: "Result",
+ 错误详情: "Error details",
+ 暂无调试记录: "No diagnostic entries",
+ "启用自动重载?所有打开的插件页面会在更新后刷新,未保存修改将丢失;后端源码变化会重建并断开连接。此设置影响同一调试服务的所有浏览器页面。":
+ "Enable auto reload? Updated plugin pages will reload and unsaved changes will be lost. Backend changes rebuild and disconnect sessions. This affects all browsers using this development server.",
+ "切换语言并重载当前页面?未保存修改将丢失。": "Switch language and reload the current page? Unsaved changes will be lost.",
+ "断开连接将中断该连接正在进行的操作。继续?": "Disconnecting will interrupt operations on this connection. Continue?",
+ "删除连接“{name}”?其页面将关闭,未保存修改会丢失。": 'Delete connection "{name}"? Its pages will close and unsaved changes will be lost.',
+ "关闭此页面?未保存修改将丢失;最后一个关联页面关闭后会断开连接。": "Close this page? Unsaved changes will be lost. Closing the last associated page disconnects the connection.",
+ "重载当前页面?未保存修改将丢失。": "Reload the current page? Unsaved changes will be lost.",
+ "重建并重启后端将断开所有连接、中断传输。页面不会自动重载,写操作不会自动重试。继续?": "Rebuild and restart the backend? All connections and transfers will be interrupted. Pages will not reload automatically and writes will not be retried.",
+ 请求失败: "Request failed",
+ 无法读取模拟宿主状态: "Unable to load development host state",
+ 连接已保存: "Connection saved",
+ 连接测试成功: "Connection test succeeded",
+ "后端已启动,请重新连接": "Backend started. Reconnect to continue.",
+ "导入文件超过 2 MiB": "Import exceeds 2 MiB",
+ "自动重载失败,请查看调试日志;修复源码后可重试": "Auto reload failed. Check diagnostics and fix the source to retry.",
+ "页面构建监听已停止,请重启调试服务": "UI build watcher stopped. Restart the development server.",
+ "调试服务连接中断,正在重新连接": "Connection to the development server lost. Reconnecting.",
+ 构建命令开始: "Build command started",
+ 构建命令完成: "Build command completed",
+ 构建命令失败: "Build command failed",
+ 后端状态变化: "Backend state changed",
+ 后端进程退出: "Backend process exited",
+ 后端协议解析失败: "Backend protocol parsing failed",
+ "RPC 开始": "RPC started",
+ "RPC 完成": "RPC completed",
+ "RPC 失败": "RPC failed",
+ "HTTP 请求完成": "HTTP request completed",
+ 收到后端事件: "Backend event received",
+ 收到二进制帧: "Binary frame received",
+ 开始重建后端: "Backend rebuild started",
+ 后端重建完成: "Backend rebuild completed",
+ 后端重建失败: "Backend rebuild failed",
+ 调试服务已启动: "Development server started",
+ 调试服务已停止: "Development server stopped",
+ 前端构建监听启动失败: "UI watcher failed to start",
+ 前端构建监听已退出: "UI watcher exited",
+ 页面回收时断开连接失败: "Failed to disconnect an abandoned page's connection",
+ 后端源码监听已停止: "Backend source watcher stopped",
+ 自动重载已启用: "Auto reload enabled",
+ 自动重载已关闭: "Auto reload disabled",
+};
+
+export function translate(locale, text, values = {}) {
+ const translated = locale === "en" ? english[text] || text : text;
+ return String(translated ?? "").replace(/\{(\w+)\}/g, (match, key) => values[key] ?? match);
+}
+
+export function localizeManifest(source, locale) {
+ if (!source) return source;
+ const result = structuredClone(source),
+ translation = source.localizations?.[locale];
+ if (!translation) return result;
+ result.name = translation.name || result.name;
+ for (const contribution of result.contributions || []) {
+ const item = translation.contributions?.[contribution.id];
+ if (!item) continue;
+ contribution.label = item.label || contribution.label;
+ contribution.description = item.description || contribution.description;
+ for (const field of contribution.fields || []) {
+ const localized = item.fields?.[field.key];
+ if (!localized) continue;
+ field.label = localized.label || field.label;
+ field.description = localized.description || field.description;
+ for (const option of field.options || []) option.label = localized.options?.[option.value] || option.label;
+ }
+ }
+ return result;
+}
diff --git a/plugins/sdk/dev-host/ui/index.html b/plugins/sdk/dev-host/ui/index.html
new file mode 100644
index 0000000000..c46670e962
--- /dev/null
+++ b/plugins/sdk/dev-host/ui/index.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="zh-CN">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>插件调试</title>
+ </head>
+ <body>
+ <div id="app"></div>
+ <script type="module" src="./main.js"></script>
+ </body>
+</html>
diff --git a/plugins/sdk/dev-host/ui/main.js b/plugins/sdk/dev-host/ui/main.js
new file mode 100644
index 0000000000..ede816aaaa
--- /dev/null
+++ b/plugins/sdk/dev-host/ui/main.js
@@ -0,0 +1,4 @@
+import { createApp } from "vue";
+import App from "./App.vue";
+import "./style.css";
+createApp(App).mount("#app");
diff --git a/plugins/sdk/dev-host/ui/messages.js b/plugins/sdk/dev-host/ui/messages.js
new file mode 100644
index 0000000000..6b26f3d314
--- /dev/null
+++ b/plugins/sdk/dev-host/ui/messages.js
@@ -0,0 +1,3 @@
+export function hostMessage(channel, message) {
+ return JSON.parse(JSON.stringify({ ...message, source: "dbx-host", version: 1, channel }));
+}
diff --git a/plugins/sdk/dev-host/ui/style.css b/plugins/sdk/dev-host/ui/style.css
new file mode 100644
index 0000000000..a7c6e8c360
--- /dev/null
+++ b/plugins/sdk/dev-host/ui/style.css
@@ -0,0 +1,39 @@
+@import "tailwindcss";
+@plugin "daisyui" {
+ themes:
+ light --default,
+ dark;
+}
+html,
+body,
+#app {
+ height: 100%;
+ margin: 0;
+ overflow: hidden;
+}
+:root {
+ font:
+ 14px -apple-system,
+ BlinkMacSystemFont,
+ "Segoe UI",
+ sans-serif;
+ letter-spacing: 0;
+ --radius-box: 0.5rem;
+ --radius-field: 0.25rem;
+}
+* {
+ letter-spacing: 0;
+}
+button:not(:disabled) {
+ cursor: pointer;
+}
+button:focus-visible {
+ outline: 2px solid var(--color-info);
+ outline-offset: -2px;
+}
+iframe {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ background: var(--color-base-100);
+}
diff --git a/plugins/sdk/go/dbx-plugin-sdk/README.md b/plugins/sdk/go/dbx-plugin-sdk/README.md
new file mode 100644
index 0000000000..a24a95b3b3
--- /dev/null
+++ b/plugins/sdk/go/dbx-plugin-sdk/README.md
@@ -0,0 +1,17 @@
+# DBX Go plugin SDK
+
+Go SDK for DBX native sidecar plugins using protocol v1 over JSON Lines stdin/stdout.
+
+```go
+metadata := dbxpluginsdk.Metadata{
+ ID: "vendor.example",
+ Version: "1.0.0",
+ Capabilities: []string{"events"},
+}
+server := dbxpluginsdk.NewServer(metadata, handler)
+if err := server.Serve(); err != nil {
+ log.Fatal(err)
+}
+```
+
+Keep stdout reserved for protocol messages. Write diagnostics to stderr.
diff --git a/plugins/sdk/go/dbx-plugin-sdk/go.mod b/plugins/sdk/go/dbx-plugin-sdk/go.mod
new file mode 100644
index 0000000000..794318df43
--- /dev/null
+++ b/plugins/sdk/go/dbx-plugin-sdk/go.mod
@@ -0,0 +1,3 @@
+module github.com/t8y2/dbx/plugins/sdk/go/dbx-plugin-sdk
+
+go 1.22
diff --git a/plugins/sdk/go/dbx-plugin-sdk/sdk.go b/plugins/sdk/go/dbx-plugin-sdk/sdk.go
new file mode 100644
index 0000000000..7fc4d7b691
--- /dev/null
+++ b/plugins/sdk/go/dbx-plugin-sdk/sdk.go
@@ -0,0 +1,244 @@
+package dbxpluginsdk
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "sync"
+)
+
+const ProtocolVersion = 1
+
+const maxJSONBytes = 8 * 1024 * 1024
+
+type Metadata struct {
+ ID string
+ Version string
+ Capabilities []string
+}
+
+type RequestContext struct {
+ RequestID json.RawMessage
+ Driver string
+}
+
+type PluginError struct {
+ Code int `json:"code"`
+ Message string `json:"message"`
+ Data any `json:"data,omitempty"`
+}
+
+func NewError(code int, message string) *PluginError {
+ return &PluginError{Code: code, Message: message}
+}
+
+func MethodNotFound(method string) *PluginError {
+ return NewError(-32601, fmt.Sprintf("Method not found: %s", method))
+}
+
+type Handler interface {
+ Handle(context RequestContext, method string, params json.RawMessage, emitter *Emitter) (any, *PluginError)
+}
+
+type HandlerFunc func(context RequestContext, method string, params json.RawMessage, emitter *Emitter) (any, *PluginError)
+
+func (handler HandlerFunc) Handle(
+ context RequestContext,
+ method string,
+ params json.RawMessage,
+ emitter *Emitter,
+) (any, *PluginError) {
+ return handler(context, method, params, emitter)
+}
+
+type Emitter struct {
+ writer io.Writer
+ mutex *sync.Mutex
+}
+
+func (emitter *Emitter) Event(method string, params any) *PluginError {
+ if !validProtocolName(method) {
+ return NewError(-32600, "Invalid event method")
+ }
+ return emitter.write(map[string]any{
+ "jsonrpc": "2.0",
+ "method": method,
+ "params": params,
+ })
+}
+
+func (emitter *Emitter) respond(id json.RawMessage, result any, pluginError *PluginError) *PluginError {
+ response := map[string]any{"jsonrpc": "2.0", "id": id}
+ if pluginError != nil {
+ response["error"] = pluginError
+ } else {
+ response["result"] = result
+ }
+ return emitter.write(response)
+}
+
+func (emitter *Emitter) write(value any) *PluginError {
+ payload, err := json.Marshal(value)
+ if err != nil {
+ return NewError(-32603, err.Error())
+ }
+ if len(payload) > maxJSONBytes {
+ return NewError(-32600, "JSON message is too large")
+ }
+ emitter.mutex.Lock()
+ defer emitter.mutex.Unlock()
+ if _, err := emitter.writer.Write(append(payload, '\n')); err != nil {
+ return NewError(-32000, err.Error())
+ }
+ return nil
+}
+
+type Server struct {
+ metadata Metadata
+ handler Handler
+ input io.Reader
+ output io.Writer
+ errors io.Writer
+}
+
+func NewServer(metadata Metadata, handler Handler) *Server {
+ return &Server{
+ metadata: metadata,
+ handler: handler,
+ input: os.Stdin,
+ output: os.Stdout,
+ errors: os.Stderr,
+ }
+}
+
+func (server *Server) WithIO(input io.Reader, output io.Writer, errorsWriter io.Writer) *Server {
+ server.input = input
+ server.output = output
+ server.errors = errorsWriter
+ return server
+}
+
+func (server *Server) Serve() error {
+ if server.handler == nil {
+ return errors.New("plugin handler is required")
+ }
+ if !validProtocolName(server.metadata.ID) {
+ return errors.New("plugin id is invalid")
+ }
+ emitter := &Emitter{writer: server.output, mutex: &sync.Mutex{}}
+ scanner := bufio.NewScanner(server.input)
+ scanner.Buffer(make([]byte, 64*1024), maxJSONBytes)
+ var workers sync.WaitGroup
+ for scanner.Scan() {
+ payload := bytes.TrimSpace(scanner.Bytes())
+ if len(payload) == 0 {
+ continue
+ }
+ request, err := decodeRequest(payload)
+ if err != nil {
+ fmt.Fprintf(server.errors, "[dbx-plugin-sdk-go] %v\n", err)
+ continue
+ }
+ if request.Method == "plugin/initialize" {
+ if len(request.ID) == 0 {
+ fmt.Fprintln(server.errors, "[dbx-plugin-sdk-go] plugin/initialize must be a request")
+ continue
+ }
+ result, pluginError := server.initialize(request.Params)
+ if writeError := emitter.respond(request.ID, result, pluginError); writeError != nil {
+ return errors.New(writeError.Message)
+ }
+ continue
+ }
+ workers.Add(1)
+ go func(request protocolRequest) {
+ defer workers.Done()
+ result, pluginError := server.handler.Handle(
+ RequestContext{RequestID: request.ID, Driver: request.Driver},
+ request.Method,
+ request.Params,
+ emitter,
+ )
+ if len(request.ID) == 0 {
+ if pluginError != nil {
+ fmt.Fprintf(server.errors, "[dbx-plugin-sdk-go] %s\n", pluginError.Message)
+ }
+ return
+ }
+ if writeError := emitter.respond(request.ID, result, pluginError); writeError != nil {
+ fmt.Fprintf(server.errors, "[dbx-plugin-sdk-go] failed to write response: %s\n", writeError.Message)
+ }
+ }(request)
+ }
+ workers.Wait()
+ return scanner.Err()
+}
+
+func (server *Server) initialize(params json.RawMessage) (any, *PluginError) {
+ var request struct {
+ Host struct {
+ ProtocolVersions []int `json:"protocolVersions"`
+ } `json:"host"`
+ }
+ if err := json.Unmarshal(params, &request); err != nil {
+ return nil, NewError(-32602, "Invalid initialize parameters")
+ }
+ for _, version := range request.Host.ProtocolVersions {
+ if version == ProtocolVersion {
+ return map[string]any{
+ "protocolVersion": ProtocolVersion,
+ "capabilities": server.metadata.Capabilities,
+ "plugin": map[string]string{
+ "id": server.metadata.ID,
+ "version": server.metadata.Version,
+ },
+ }, nil
+ }
+ }
+ return nil, NewError(-32001, "DBX and plugin do not share a protocol version")
+}
+
+type protocolRequest struct {
+ JSONRPC string `json:"jsonrpc"`
+ ID json.RawMessage `json:"id"`
+ Driver string `json:"driver"`
+ Method string `json:"method"`
+ Params json.RawMessage `json:"params"`
+}
+
+func decodeRequest(payload []byte) (protocolRequest, error) {
+ var request protocolRequest
+ if err := json.Unmarshal(payload, &request); err != nil {
+ return request, err
+ }
+ if request.JSONRPC != "2.0" {
+ return request, errors.New("request does not declare jsonrpc 2.0")
+ }
+ if !validProtocolName(request.Method) {
+ return request, errors.New("request method is invalid")
+ }
+ if len(request.Params) == 0 {
+ request.Params = json.RawMessage("null")
+ }
+ return request, nil
+}
+
+func validProtocolName(value string) bool {
+ if len(value) == 0 || len(value) > 256 {
+ return false
+ }
+ for index, character := range value {
+ if character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' || character >= '0' && character <= '9' {
+ continue
+ }
+ if index > 0 && (character == '.' || character == '_' || character == ':' || character == '/' || character == '-') {
+ continue
+ }
+ return false
+ }
+ return true
+}
diff --git a/plugins/sdk/go/dbx-plugin-sdk/sdk_test.go b/plugins/sdk/go/dbx-plugin-sdk/sdk_test.go
new file mode 100644
index 0000000000..b8aa97ca92
--- /dev/null
+++ b/plugins/sdk/go/dbx-plugin-sdk/sdk_test.go
@@ -0,0 +1,62 @@
+package dbxpluginsdk
+
+import (
+ "bytes"
+ "encoding/json"
+ "sync"
+ "testing"
+)
+
+func TestServerInitializesAndDispatches(t *testing.T) {
+ input := bytes.NewBufferString(
+ "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"plugin/initialize\",\"params\":{\"host\":{\"protocolVersions\":[1]}}}\n" +
+ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"sample/ping\",\"params\":{\"name\":\"DBX\"}}\n",
+ )
+ var output bytes.Buffer
+ server := NewServer(
+ Metadata{ID: "sample.plugin", Version: "1.0.0", Capabilities: []string{"commands"}},
+ HandlerFunc(func(_ RequestContext, method string, _ json.RawMessage, _ *Emitter) (any, *PluginError) {
+ if method != "sample/ping" {
+ return nil, MethodNotFound(method)
+ }
+ return map[string]any{"ok": true}, nil
+ }),
+ ).WithIO(input, &output, &bytes.Buffer{})
+ if err := server.Serve(); err != nil {
+ t.Fatal(err)
+ }
+ var responses []map[string]any
+ for _, line := range bytes.Split(bytes.TrimSpace(output.Bytes()), []byte{'\n'}) {
+ var response map[string]any
+ if err := json.Unmarshal(line, &response); err != nil {
+ t.Fatal(err)
+ }
+ responses = append(responses, response)
+ }
+ if len(responses) != 2 {
+ t.Fatalf("expected 2 responses, got %d", len(responses))
+ }
+ initialize := responses[0]["result"].(map[string]any)
+ if initialize["protocolVersion"] != float64(ProtocolVersion) {
+ t.Fatalf("unexpected initialize response: %#v", initialize)
+ }
+ pong := responses[1]["result"].(map[string]any)
+ if pong["ok"] != true {
+ t.Fatalf("unexpected handler response: %#v", pong)
+ }
+}
+
+func TestEmitterWritesEvents(t *testing.T) {
+ var output bytes.Buffer
+ emitter := &Emitter{writer: &output, mutex: &sync.Mutex{}}
+ if pluginError := emitter.Event("sample/progress", map[string]any{"value": 1}); pluginError != nil {
+ t.Fatal(pluginError.Message)
+ }
+ var event map[string]any
+ if err := json.Unmarshal(bytes.TrimSpace(output.Bytes()), &event); err != nil {
+ t.Fatal(err)
+ }
+ if event["method"] != "sample/progress" {
+ t.Fatalf("unexpected event: %#v", event)
+ }
+}
diff --git a/plugins/sdk/packager/.gitignore b/plugins/sdk/packager/.gitignore
new file mode 100644
index 0000000000..b83d22266a
--- /dev/null
+++ b/plugins/sdk/packager/.gitignore
@@ -0,0 +1 @@
+/target/
diff --git a/plugins/sdk/packager/Cargo.lock b/plugins/sdk/packager/Cargo.lock
new file mode 100644
index 0000000000..e3f9595bd7
--- /dev/null
+++ b/plugins/sdk/packager/Cargo.lock
@@ -0,0 +1,621 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "adler2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+
+[[package]]
+name = "arbitrary"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
+dependencies = [
+ "derive_arbitrary",
+]
+
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
+[[package]]
+name = "base64ct"
+version = "1.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
+
+[[package]]
+name = "bitflags"
+version = "2.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "bumpalo"
+version = "3.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "const-oid"
+version = "0.9.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crc32fast"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "curve25519-dalek-derive",
+ "digest",
+ "fiat-crypto",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "curve25519-dalek-derive"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "dbx-plugin-packager"
+version = "0.1.0"
+dependencies = [
+ "base64",
+ "ed25519-dalek",
+ "getrandom 0.4.3",
+ "serde_json",
+ "sha2",
+ "tempfile",
+ "walkdir",
+ "zip",
+]
+
+[[package]]
+name = "der"
+version = "0.7.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
+dependencies = [
+ "const-oid",
+ "zeroize",
+]
+
+[[package]]
+name = "derive_arbitrary"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+]
+
+[[package]]
+name = "ed25519"
+version = "2.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
+dependencies = [
+ "pkcs8",
+ "signature",
+]
+
+[[package]]
+name = "ed25519-dalek"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
+dependencies = [
+ "curve25519-dalek",
+ "ed25519",
+ "serde",
+ "sha2",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
+[[package]]
+name = "fastrand"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
+
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
+[[package]]
+name = "flate2"
+version = "1.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
+dependencies = [
+ "miniz_oxide",
+ "zlib-rs",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "indexmap"
+version = "2.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "libc"
+version = "0.2.189"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "log"
+version = "0.4.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "miniz_oxide"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "pkcs8"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
+dependencies = [
+ "der",
+ "spki",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+dependencies = [
+ "getrandom 0.2.17",
+]
+
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "rustix"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys",
+]
+
+[[package]]
+name = "same-file"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
+dependencies = [
+ "indexmap",
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "signature"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
+dependencies = [
+ "rand_core",
+]
+
+[[package]]
+name = "simd-adler32"
+version = "0.3.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+
+[[package]]
+name = "spki"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
+dependencies = [
+ "base64ct",
+ "der",
+]
+
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
+dependencies = [
+ "fastrand",
+ "getrandom 0.4.3",
+ "once_cell",
+ "rustix",
+ "windows-sys",
+]
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "walkdir"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+dependencies = [
+ "same-file",
+ "winapi-util",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
+
+[[package]]
+name = "zip"
+version = "4.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"
+dependencies = [
+ "arbitrary",
+ "crc32fast",
+ "flate2",
+ "indexmap",
+ "memchr",
+ "zopfli",
+]
+
+[[package]]
+name = "zlib-rs"
+version = "0.6.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b142a20ec14a91d5bc708c1dc21b080c550113d8aa77afa29635673a65dd02c5"
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+
+[[package]]
+name = "zopfli"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
+dependencies = [
+ "bumpalo",
+ "crc32fast",
+ "log",
+ "simd-adler32",
+]
diff --git a/plugins/sdk/packager/Cargo.toml b/plugins/sdk/packager/Cargo.toml
new file mode 100644
index 0000000000..f89a70b009
--- /dev/null
+++ b/plugins/sdk/packager/Cargo.toml
@@ -0,0 +1,29 @@
+[package]
+name = "dbx-plugin-packager"
+version = "0.1.0"
+edition = "2021"
+license = "Apache-2.0"
+description = "Build .dbxp archives for DBX plugins"
+autobins = false
+
+[workspace]
+
+[lib]
+name = "dbx_plugin_packager"
+path = "src/main.rs"
+
+[[bin]]
+name = "dbx-plugin-packager"
+path = "src/bin/dbx-plugin-packager.rs"
+
+[dependencies]
+base64 = "0.22"
+ed25519-dalek = "2"
+getrandom = "0.4"
+serde_json = { version = "1", features = ["preserve_order"] }
+sha2 = "0.10"
+walkdir = "2"
+zip = { version = "4", default-features = false, features = ["deflate"] }
+
+[dev-dependencies]
+tempfile = "3"
diff --git a/plugins/sdk/packager/README.md b/plugins/sdk/packager/README.md
new file mode 100644
index 0000000000..ce44910b13
--- /dev/null
+++ b/plugins/sdk/packager/README.md
@@ -0,0 +1,61 @@
+# dbx-plugin-packager
+
+Builds an unsigned `.dbxp` candidate from a staged plugin directory and signs an already-reviewed candidate as a separate repository operation.
+
+## Usage
+
+```bash
+cargo run --release \
+ --manifest-path plugins/sdk/packager/Cargo.toml \
+ -- path/to/stage path/to/vendor.example-1.0.0-darwin-arm64.dbxp \
+ --artifact-metadata path/to/vendor.example-1.0.0-darwin-arm64.artifact.json \
+ --target darwin-arm64 \
+ --artifact-url vendor.example-1.0.0-darwin-arm64.dbxp
+```
+
+The stage directory must contain `manifest.json` and the current-platform files referenced by the manifest. The packager:
+
+- walks regular files without following symlinks;
+- rejects symlinks, oversized files, oversized stages, excessive entries, and output paths inside the stage;
+- writes archive entries in deterministic path order;
+- hashes and writes files as streams instead of loading the whole package into memory;
+- preserves executable permissions;
+- creates exact SHA-256 coverage in `checksums.json`;
+- optionally writes candidate artifact metadata containing the target, URL, package SHA-256, and size;
+- writes through a temporary file so a failed build does not truncate the previous package.
+
+Use `--target universal` only when the same `.dbxp` is valid on every DBX target. This is normally appropriate for frontend-only plugins. When a catalog contains both an exact platform artifact and `universal`, DBX selects the exact artifact first.
+
+The generated metadata has the shape expected by marketplace catalog v1:
+
+```json
+{
+ "target": "darwin-arm64",
+ "url": "vendor.example-1.0.0-darwin-arm64.dbxp",
+ "sha256": "...",
+ "size": 123456
+}
+```
+
+## Repository signing
+
+Only a repository operator should sign packages. Plugin authors submit unsigned candidates. `DBX_PLUGIN_SIGNING_KEY` is a base64-encoded 32-byte Ed25519 repository private-key seed, and `--key-id` identifies the corresponding repository public key in DBX's trust store.
+
+```bash
+DBX_PLUGIN_SIGNING_KEY="..." \
+cargo run --release \
+ --manifest-path plugins/sdk/packager/Cargo.toml \
+ -- sign path/to/vendor.example-1.0.0-darwin-arm64.unsigned.dbxp path/to/vendor.example-1.0.0-darwin-arm64.dbxp \
+ --key-id vendor-release \
+ --artifact-metadata path/to/vendor.example-1.0.0-darwin-arm64.artifact.json \
+ --target darwin-arm64 \
+ --artifact-url https://plugins.example.com/vendor.example-1.0.0-darwin-arm64.dbxp
+```
+
+The signing command validates the existing archive, rejects symlinks, duplicate entries, invalid checksums, path traversal, oversized content, and pre-existing `signature.json`, then appends the repository signature and computes metadata for the final signed bytes.
+
+Keep the private seed in protected repository-signing CI. Set `DBX_PLUGIN_SIGNING_PUBLIC_KEY` there as well to make the packager reject a private key that does not derive the configured repository public key. Publish the Base64 32-byte public key through an independent trusted channel. Do not give the official repository key to plugin authors.
+
+## GitHub Releases
+
+`../../templates/github/plugin-release.yml` is a caller template for DBX's reusable multi-platform author workflow. It uploads unsigned `.dbxp` candidates and publishes merged `release-candidates.json` metadata for review. Repository signing happens later in protected repository infrastructure.
diff --git a/plugins/sdk/packager/src/bin/dbx-plugin-packager.rs b/plugins/sdk/packager/src/bin/dbx-plugin-packager.rs
new file mode 100644
index 0000000000..54c03c6e6a
--- /dev/null
+++ b/plugins/sdk/packager/src/bin/dbx-plugin-packager.rs
@@ -0,0 +1,3 @@
+fn main() {
+ dbx_plugin_packager::main_entry();
+}
diff --git a/plugins/sdk/packager/src/main.rs b/plugins/sdk/packager/src/main.rs
new file mode 100644
index 0000000000..ee77086941
--- /dev/null
+++ b/plugins/sdk/packager/src/main.rs
@@ -0,0 +1,806 @@
+use std::collections::{BTreeMap, HashSet};
+use std::fs::{File, OpenOptions};
+use std::io::{Read, Write};
+use std::path::{Path, PathBuf};
+
+use base64::Engine;
+use ed25519_dalek::{Signer, SigningKey};
+use sha2::{Digest, Sha256};
+use walkdir::WalkDir;
+use zip::write::SimpleFileOptions;
+use zip::ZipArchive;
+
+const MAX_PACKAGE_BYTES: u64 = 512 * 1024 * 1024;
+const MAX_UNCOMPRESSED_BYTES: u64 = 1024 * 1024 * 1024;
+const MAX_FILE_BYTES: u64 = 256 * 1024 * 1024;
+const MAX_ARCHIVE_ENTRIES: usize = 10_000;
+
+struct PackageFile {
+ source: PathBuf,
+ size: u64,
+ permissions: u32,
+ sha256: String,
+}
+
+struct ArtifactMetadataRequest {
+ output: PathBuf,
+ target: String,
+ url: Option<String>,
+ signing_key_id: Option<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SigningKeyMaterial {
+ pub private_seed_base64: String,
+ pub public_key_base64: String,
+}
+
+pub fn generate_signing_key() -> Result<SigningKeyMaterial, String> {
+ let mut seed = [0u8; 32];
+ getrandom::fill(&mut seed).map_err(|error| format!("Failed to generate signing key: {error}"))?;
+ let signing_key = SigningKey::from_bytes(&seed);
+ Ok(SigningKeyMaterial {
+ private_seed_base64: base64::engine::general_purpose::STANDARD.encode(seed),
+ public_key_base64: base64::engine::general_purpose::STANDARD.encode(signing_key.verifying_key().to_bytes()),
+ })
+}
+
+pub fn main_entry() {
+ if let Err(error) = run_cli(std::env::args().skip(1)) {
+ eprintln!("dbx-plugin-packager: {error}");
+ std::process::exit(1);
+ }
+}
+
+pub fn run_cli<I>(arguments: I) -> Result<(), String>
+where
+ I: IntoIterator<Item = String>,
+{
+ run_cli_with_output(arguments, true)
+}
+
+pub fn run_cli_silent<I>(arguments: I) -> Result<(), String>
+where
+ I: IntoIterator<Item = String>,
+{
+ run_cli_with_output(arguments, false)
+}
+
+fn run_cli_with_output<I>(arguments: I, print_output: bool) -> Result<(), String>
+where
+ I: IntoIterator<Item = String>,
+{
+ let arguments = arguments.into_iter().collect::<Vec<_>>();
+ if arguments.first().map(String::as_str) == Some("sign") {
+ return run_sign_cli(arguments.into_iter().skip(1), print_output);
+ }
+ run_package_cli(arguments, print_output)
+}
+
+fn run_package_cli<I>(arguments: I, print_output: bool) -> Result<(), String>
+where
+ I: IntoIterator<Item = String>,
+{
+ let mut arguments = arguments.into_iter();
+ let source = arguments.next().map(PathBuf::from).ok_or(usage())?;
+ let output = arguments.next().map(PathBuf::from).ok_or(usage())?;
+ let mut key_id = None;
+ let mut artifact_metadata = None;
+ let mut artifact_target = None;
+ let mut artifact_url = None;
+ while let Some(argument) = arguments.next() {
+ match argument.as_str() {
+ "--key-id" => key_id = Some(arguments.next().ok_or("--key-id requires a value")?),
+ "--artifact-metadata" => {
+ artifact_metadata =
+ Some(PathBuf::from(arguments.next().ok_or("--artifact-metadata requires a value")?));
+ }
+ "--target" => artifact_target = Some(arguments.next().ok_or("--target requires a value")?),
+ "--artifact-url" => artifact_url = Some(arguments.next().ok_or("--artifact-url requires a value")?),
+ _ => return Err(format!("Unknown argument '{argument}'\n{}", usage())),
+ }
+ }
+ let artifact_metadata =
+ artifact_metadata_request(artifact_metadata, artifact_target, artifact_url, key_id.as_deref())?;
+ if output.extension().and_then(|extension| extension.to_str()) != Some("dbxp") {
+ return Err("Output file must use the .dbxp extension".to_string());
+ }
+ let source = std::fs::canonicalize(&source)
+ .map_err(|error| format!("Failed to resolve package source {}: {error}", source.display()))?;
+ if !source.join("manifest.json").is_file() {
+ return Err(format!("{} is missing manifest.json", source.display()));
+ }
+ let output = absolute_output_path(&output)?;
+ let output_parent = output.parent().ok_or("Output path has no parent")?;
+ std::fs::create_dir_all(output_parent).map_err(|error| error.to_string())?;
+ let output_parent = std::fs::canonicalize(output_parent).map_err(|error| error.to_string())?;
+ let output = output_parent.join(output.file_name().ok_or("Output path has no file name")?);
+ if output.starts_with(&source) {
+ return Err("Output package must be outside the source directory".to_string());
+ }
+ let artifact_metadata =
+ artifact_metadata.map(|request| prepare_artifact_metadata_request(request, &source, &output)).transpose()?;
+
+ let mut files = BTreeMap::new();
+ let mut total_size = 0u64;
+ for entry in WalkDir::new(&source).follow_links(false) {
+ let entry = entry.map_err(|error| error.to_string())?;
+ if entry.file_type().is_symlink() {
+ return Err(format!("Package source cannot contain symbolic link {}", entry.path().display()));
+ }
+ if !entry.file_type().is_file() {
+ continue;
+ }
+ if files.len() >= MAX_ARCHIVE_ENTRIES {
+ return Err(format!("Package source contains more than {MAX_ARCHIVE_ENTRIES} files"));
+ }
+ let relative = entry.path().strip_prefix(&source).map_err(|error| error.to_string())?;
+ let name = archive_name(relative)?;
+ if matches!(name.as_str(), "checksums.json" | "signature.json") {
+ continue;
+ }
+ let metadata = entry.metadata().map_err(|error| error.to_string())?;
+ if metadata.len() > MAX_FILE_BYTES {
+ return Err(format!("Package file '{name}' exceeds {MAX_FILE_BYTES} bytes"));
+ }
+ total_size = total_size.checked_add(metadata.len()).ok_or("Package source size overflow")?;
+ if total_size > MAX_UNCOMPRESSED_BYTES {
+ return Err(format!("Package source exceeds {MAX_UNCOMPRESSED_BYTES} uncompressed bytes"));
+ }
+ files.insert(
+ name,
+ PackageFile {
+ source: entry.path().to_path_buf(),
+ size: metadata.len(),
+ permissions: executable_permissions(entry.path()),
+ sha256: sha256_file(entry.path())?,
+ },
+ );
+ }
+ let checksums = files.iter().map(|(path, file)| (path.clone(), file.sha256.clone())).collect::<BTreeMap<_, _>>();
+ let checksums = serde_json::to_vec_pretty(&serde_json::json!({
+ "algorithm": "sha256",
+ "files": checksums
+ }))
+ .map_err(|error| error.to_string())?;
+ let signature = signing_key(key_id.as_deref())?
+ .map(|(key_id, key)| {
+ serde_json::to_vec_pretty(&serde_json::json!({
+ "algorithm": "ed25519",
+ "key_id": key_id,
+ "signature": base64::engine::general_purpose::STANDARD.encode(key.sign(&checksums).to_bytes())
+ }))
+ .map_err(|error| error.to_string())
+ })
+ .transpose()?;
+
+ let temporary = output_parent.join(format!(
+ ".{}.{}.tmp",
+ output.file_name().and_then(|name| name.to_str()).unwrap_or("plugin.dbxp"),
+ std::process::id()
+ ));
+ let package_result = write_package(&temporary, files, &checksums, signature.as_deref());
+ if let Err(error) = package_result {
+ let _ = std::fs::remove_file(&temporary);
+ return Err(error);
+ }
+ let package_size = std::fs::metadata(&temporary).map_err(|error| error.to_string())?.len();
+ if package_size > MAX_PACKAGE_BYTES {
+ let _ = std::fs::remove_file(&temporary);
+ return Err(format!("Output package exceeds {MAX_PACKAGE_BYTES} bytes"));
+ }
+ if output.exists() {
+ std::fs::remove_file(&output).map_err(|error| error.to_string())?;
+ }
+ std::fs::rename(&temporary, &output).map_err(|error| error.to_string())?;
+ sync_directory(&output_parent)?;
+ if let Some(request) = artifact_metadata {
+ write_artifact_metadata(&request, &output, package_size)?;
+ }
+ if print_output {
+ println!("{}", output.display());
+ }
+ Ok(())
+}
+
+fn run_sign_cli<I>(arguments: I, print_output: bool) -> Result<(), String>
+where
+ I: IntoIterator<Item = String>,
+{
+ let mut arguments = arguments.into_iter();
+ let input = arguments.next().map(PathBuf::from).ok_or(sign_usage())?;
+ let output = arguments.next().map(PathBuf::from).ok_or(sign_usage())?;
+ let mut key_id = None;
+ let mut artifact_metadata = None;
+ let mut artifact_target = None;
+ let mut artifact_url = None;
+ while let Some(argument) = arguments.next() {
+ match argument.as_str() {
+ "--key-id" => key_id = Some(arguments.next().ok_or("--key-id requires a value")?),
+ "--artifact-metadata" => {
+ artifact_metadata =
+ Some(PathBuf::from(arguments.next().ok_or("--artifact-metadata requires a value")?));
+ }
+ "--target" => artifact_target = Some(arguments.next().ok_or("--target requires a value")?),
+ "--artifact-url" => artifact_url = Some(arguments.next().ok_or("--artifact-url requires a value")?),
+ _ => return Err(format!("Unknown argument '{argument}'\n{}", sign_usage())),
+ }
+ }
+ let key_id = key_id.ok_or("sign requires --key-id")?;
+ let (_, signing_key) = signing_key(Some(&key_id))?.ok_or("DBX_PLUGIN_SIGNING_KEY is required")?;
+ let artifact_metadata = artifact_metadata_request(artifact_metadata, artifact_target, artifact_url, Some(&key_id))?;
+ sign_existing_package(&input, &output, &key_id, &signing_key, artifact_metadata, print_output)
+}
+
+fn sign_existing_package(
+ input: &Path,
+ output: &Path,
+ key_id: &str,
+ signing_key: &SigningKey,
+ artifact_metadata: Option<ArtifactMetadataRequest>,
+ print_output: bool,
+) -> Result<(), String> {
+ validate_key_id(key_id)?;
+ if input.extension().and_then(|extension| extension.to_str()) != Some("dbxp") {
+ return Err("Input file must use the .dbxp extension".to_string());
+ }
+ if output.extension().and_then(|extension| extension.to_str()) != Some("dbxp") {
+ return Err("Output file must use the .dbxp extension".to_string());
+ }
+ let input = std::fs::canonicalize(input)
+ .map_err(|error| format!("Failed to resolve candidate package {}: {error}", input.display()))?;
+ if std::fs::metadata(&input).map_err(|error| error.to_string())?.len() > MAX_PACKAGE_BYTES {
+ return Err(format!("Candidate package exceeds {MAX_PACKAGE_BYTES} bytes"));
+ }
+ let checksums = validate_unsigned_candidate(&input)?;
+ let signature = serde_json::to_vec_pretty(&serde_json::json!({
+ "algorithm": "ed25519",
+ "key_id": key_id,
+ "signature": base64::engine::general_purpose::STANDARD.encode(signing_key.sign(&checksums).to_bytes())
+ }))
+ .map_err(|error| error.to_string())?;
+
+ let output = absolute_output_path(output)?;
+ let output_parent = output.parent().ok_or("Output path has no parent")?;
+ std::fs::create_dir_all(output_parent).map_err(|error| error.to_string())?;
+ let output_parent = std::fs::canonicalize(output_parent).map_err(|error| error.to_string())?;
+ let output = output_parent.join(output.file_name().ok_or("Output path has no file name")?);
+ if output == input {
+ return Err("Signed output must differ from the unsigned candidate package".to_string());
+ }
+ let artifact_metadata =
+ artifact_metadata.map(|request| prepare_artifact_metadata_request(request, &input, &output)).transpose()?;
+ let temporary = output_parent.join(format!(
+ ".{}.{}.tmp",
+ output.file_name().and_then(|name| name.to_str()).unwrap_or("plugin.dbxp"),
+ std::process::id()
+ ));
+ std::fs::copy(&input, &temporary).map_err(|error| error.to_string())?;
+ let append_result = (|| {
+ let file = OpenOptions::new().read(true).write(true).open(&temporary).map_err(|error| error.to_string())?;
+ let mut archive = zip::ZipWriter::new_append(file).map_err(|error| error.to_string())?;
+ archive
+ .start_file(
+ "signature.json",
+ SimpleFileOptions::default()
+ .compression_method(zip::CompressionMethod::Deflated)
+ .unix_permissions(0o644),
+ )
+ .map_err(|error| error.to_string())?;
+ archive.write_all(&signature).map_err(|error| error.to_string())?;
+ archive.finish().map_err(|error| error.to_string())?.sync_all().map_err(|error| error.to_string())
+ })();
+ if let Err(error) = append_result {
+ let _ = std::fs::remove_file(&temporary);
+ return Err(error);
+ }
+ let package_size = std::fs::metadata(&temporary).map_err(|error| error.to_string())?.len();
+ if package_size > MAX_PACKAGE_BYTES {
+ let _ = std::fs::remove_file(&temporary);
+ return Err(format!("Signed package exceeds {MAX_PACKAGE_BYTES} bytes"));
+ }
+ if output.exists() {
+ std::fs::remove_file(&output).map_err(|error| error.to_string())?;
+ }
+ std::fs::rename(&temporary, &output).map_err(|error| error.to_string())?;
+ sync_directory(&output_parent)?;
+ if let Some(request) = artifact_metadata {
+ write_artifact_metadata(&request, &output, package_size)?;
+ }
+ if print_output {
+ println!("{}", output.display());
+ }
+ Ok(())
+}
+
+fn validate_unsigned_candidate(input: &Path) -> Result<Vec<u8>, String> {
+ let file = File::open(input).map_err(|error| error.to_string())?;
+ let mut archive = ZipArchive::new(file).map_err(|error| format!("Failed to read candidate package: {error}"))?;
+ if archive.len() > MAX_ARCHIVE_ENTRIES {
+ return Err(format!("Candidate package contains more than {MAX_ARCHIVE_ENTRIES} entries"));
+ }
+ let mut names = HashSet::new();
+ let mut actual_checksums = BTreeMap::new();
+ let mut checksums_raw = None;
+ let mut total_size = 0u64;
+ for index in 0..archive.len() {
+ let mut entry = archive.by_index(index).map_err(|error| error.to_string())?;
+ if entry.is_dir() {
+ return Err(format!("Candidate package contains directory entry '{}'", entry.name()));
+ }
+ let name = entry.name().to_string();
+ validate_archive_entry_name(&name)?;
+ if !names.insert(name.clone()) {
+ return Err(format!("Candidate package contains duplicate entry '{name}'"));
+ }
+ if entry.unix_mode().is_some_and(|mode| mode & 0o170000 == 0o120000) {
+ return Err(format!("Candidate package contains symbolic link '{name}'"));
+ }
+ if entry.size() > MAX_FILE_BYTES {
+ return Err(format!("Candidate package file '{name}' exceeds {MAX_FILE_BYTES} bytes"));
+ }
+ total_size = total_size.checked_add(entry.size()).ok_or("Candidate package size overflow")?;
+ if total_size > MAX_UNCOMPRESSED_BYTES {
+ return Err(format!("Candidate package exceeds {MAX_UNCOMPRESSED_BYTES} uncompressed bytes"));
+ }
+ if name == "signature.json" {
+ return Err(
+ "Candidate package is already signed; official signing requires an unsigned package".to_string()
+ );
+ }
+ let mut bytes = Vec::with_capacity(entry.size() as usize);
+ entry.read_to_end(&mut bytes).map_err(|error| error.to_string())?;
+ if name == "checksums.json" {
+ checksums_raw = Some(bytes);
+ } else {
+ actual_checksums.insert(name, hex_digest(Sha256::digest(bytes)));
+ }
+ }
+ if !names.contains("manifest.json") {
+ return Err("Candidate package is missing manifest.json".to_string());
+ }
+ let checksums_raw = checksums_raw.ok_or("Candidate package is missing checksums.json")?;
+ let checksums: serde_json::Value =
+ serde_json::from_slice(&checksums_raw).map_err(|error| format!("Failed to parse checksums.json: {error}"))?;
+ if checksums.get("algorithm").and_then(serde_json::Value::as_str) != Some("sha256") {
+ return Err("Candidate package uses an unsupported checksum algorithm".to_string());
+ }
+ let declared = checksums
+ .get("files")
+ .and_then(serde_json::Value::as_object)
+ .ok_or("Candidate package checksums.json files must be an object")?;
+ if declared.len() != actual_checksums.len() {
+ return Err("Candidate package checksums do not cover the package exactly".to_string());
+ }
+ for (path, actual) in actual_checksums {
+ let expected = declared
+ .get(&path)
+ .and_then(serde_json::Value::as_str)
+ .ok_or_else(|| format!("Candidate package checksums are missing '{path}'"))?;
+ if !expected.eq_ignore_ascii_case(&actual) {
+ return Err(format!("Candidate package checksum mismatch for '{path}'"));
+ }
+ }
+ Ok(checksums_raw)
+}
+
+fn validate_archive_entry_name(name: &str) -> Result<(), String> {
+ if name.is_empty() || name.contains('\\') || archive_name(Path::new(name))? != name {
+ return Err(format!("Candidate package contains unsafe path '{name}'"));
+ }
+ Ok(())
+}
+
+fn artifact_metadata_request(
+ output: Option<PathBuf>,
+ target: Option<String>,
+ url: Option<String>,
+ signing_key_id: Option<&str>,
+) -> Result<Option<ArtifactMetadataRequest>, String> {
+ match (output, target, url) {
+ (None, None, None) => Ok(None),
+ (Some(output), Some(target), url) => {
+ validate_artifact_target(&target)?;
+ if let Some(signing_key_id) = signing_key_id {
+ validate_key_id(signing_key_id)?;
+ }
+ if url.as_deref().is_some_and(|value| value.trim().is_empty()) {
+ return Err("--artifact-url cannot be empty".to_string());
+ }
+ Ok(Some(ArtifactMetadataRequest {
+ output,
+ target,
+ url,
+ signing_key_id: signing_key_id.map(str::to_string),
+ }))
+ }
+ (None, Some(_), _) => Err("--target requires --artifact-metadata".to_string()),
+ (None, None, Some(_)) => Err("--artifact-url requires --artifact-metadata and --target".to_string()),
+ (Some(_), None, _) => Err("--artifact-metadata requires --target".to_string()),
+ }
+}
+
+fn prepare_artifact_metadata_request(
+ mut request: ArtifactMetadataRequest,
+ source: &Path,
+ package_output: &Path,
+) -> Result<ArtifactMetadataRequest, String> {
+ request.output = absolute_output_path(&request.output)?;
+ let parent = request.output.parent().ok_or("Artifact metadata path has no parent")?;
+ std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
+ let parent = std::fs::canonicalize(parent).map_err(|error| error.to_string())?;
+ request.output = parent.join(request.output.file_name().ok_or("Artifact metadata path has no file name")?);
+ if request.output.starts_with(source) {
+ return Err("Artifact metadata must be outside the package source directory".to_string());
+ }
+ if request.output == package_output {
+ return Err("Artifact metadata path must differ from the package output".to_string());
+ }
+ Ok(request)
+}
+
+fn write_artifact_metadata(
+ request: &ArtifactMetadataRequest,
+ package_output: &Path,
+ package_size: u64,
+) -> Result<(), String> {
+ let url = request.url.clone().unwrap_or_else(|| {
+ package_output.file_name().and_then(|name| name.to_str()).unwrap_or("plugin.dbxp").to_string()
+ });
+ let mut metadata = serde_json::json!({
+ "target": request.target,
+ "url": url,
+ "sha256": sha256_file(package_output)?,
+ "size": package_size
+ });
+ if let Some(signing_key_id) = &request.signing_key_id {
+ metadata["signingKeyId"] = serde_json::Value::String(signing_key_id.clone());
+ }
+ let mut metadata = serde_json::to_vec_pretty(&metadata).map_err(|error| error.to_string())?;
+ metadata.push(b'\n');
+ write_bytes_atomically(&request.output, &metadata)
+}
+
+fn write_bytes_atomically(path: &Path, bytes: &[u8]) -> Result<(), String> {
+ let parent = path.parent().ok_or("Output path has no parent")?;
+ let temporary = parent.join(format!(
+ ".{}.{}.tmp",
+ path.file_name().and_then(|name| name.to_str()).unwrap_or("artifact.json"),
+ std::process::id()
+ ));
+ let mut file =
+ OpenOptions::new().write(true).create_new(true).open(&temporary).map_err(|error| error.to_string())?;
+ if let Err(error) = file.write_all(bytes).and_then(|_| file.sync_all()) {
+ let _ = std::fs::remove_file(&temporary);
+ return Err(error.to_string());
+ }
+ if path.exists() {
+ std::fs::remove_file(path).map_err(|error| error.to_string())?;
+ }
+ std::fs::rename(&temporary, path).map_err(|error| error.to_string())?;
+ sync_directory(parent)
+}
+
+fn write_package(
+ output: &Path,
+ files: BTreeMap<String, PackageFile>,
+ checksums: &[u8],
+ signature: Option<&[u8]>,
+) -> Result<(), String> {
+ let file = OpenOptions::new().write(true).create_new(true).open(output).map_err(|error| error.to_string())?;
+ let mut archive = zip::ZipWriter::new(file);
+ for (path, package_file) in files {
+ archive
+ .start_file(
+ path,
+ SimpleFileOptions::default()
+ .compression_method(zip::CompressionMethod::Deflated)
+ .unix_permissions(package_file.permissions),
+ )
+ .map_err(|error| error.to_string())?;
+ let mut source = File::open(&package_file.source).map_err(|error| error.to_string())?;
+ let mut digest = Sha256::new();
+ let mut copied = 0u64;
+ let mut buffer = [0u8; 64 * 1024];
+ loop {
+ let read = source.read(&mut buffer).map_err(|error| error.to_string())?;
+ if read == 0 {
+ break;
+ }
+ copied = copied.checked_add(read as u64).ok_or("Package source size overflow")?;
+ if copied > package_file.size {
+ break;
+ }
+ digest.update(&buffer[..read]);
+ archive.write_all(&buffer[..read]).map_err(|error| error.to_string())?;
+ }
+ if copied != package_file.size || hex_digest(digest.finalize()) != package_file.sha256 {
+ return Err(format!("Package source changed while reading {}", package_file.source.display()));
+ }
+ }
+ archive
+ .start_file(
+ "checksums.json",
+ SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated).unix_permissions(0o644),
+ )
+ .map_err(|error| error.to_string())?;
+ archive.write_all(checksums).map_err(|error| error.to_string())?;
+ if let Some(signature) = signature {
+ archive
+ .start_file(
+ "signature.json",
+ SimpleFileOptions::default()
+ .compression_method(zip::CompressionMethod::Deflated)
+ .unix_permissions(0o644),
+ )
+ .map_err(|error| error.to_string())?;
+ archive.write_all(signature).map_err(|error| error.to_string())?;
+ }
+ archive.finish().map_err(|error| error.to_string())?.sync_all().map_err(|error| error.to_string())?;
+ Ok(())
+}
+
+fn signing_key(key_id: Option<&str>) -> Result<Option<(String, SigningKey)>, String> {
+ let encoded = std::env::var("DBX_PLUGIN_SIGNING_KEY").ok();
+ match (key_id, encoded) {
+ (None, None) => Ok(None),
+ (Some(_), None) => Err("DBX_PLUGIN_SIGNING_KEY is required when --key-id is provided".to_string()),
+ (None, Some(_)) => Err("--key-id is required when DBX_PLUGIN_SIGNING_KEY is set".to_string()),
+ (Some(key_id), Some(encoded)) => {
+ validate_key_id(key_id)?;
+ let signing_key = decode_signing_key(&encoded)?;
+ if let Ok(expected_public_key) = std::env::var("DBX_PLUGIN_SIGNING_PUBLIC_KEY") {
+ verify_signing_public_key(&signing_key, &expected_public_key)?;
+ }
+ Ok(Some((key_id.to_string(), signing_key)))
+ }
+ }
+}
+
+fn decode_signing_key(encoded: &str) -> Result<SigningKey, String> {
+ let bytes = base64::engine::general_purpose::STANDARD
+ .decode(encoded.trim())
+ .map_err(|error| format!("Invalid DBX_PLUGIN_SIGNING_KEY: {error}"))?;
+ let bytes: [u8; 32] = bytes.try_into().map_err(|_| "DBX_PLUGIN_SIGNING_KEY must contain 32 bytes".to_string())?;
+ Ok(SigningKey::from_bytes(&bytes))
+}
+
+fn verify_signing_public_key(signing_key: &SigningKey, expected: &str) -> Result<(), String> {
+ let expected = base64::engine::general_purpose::STANDARD
+ .decode(expected.trim())
+ .map_err(|error| format!("Invalid DBX_PLUGIN_SIGNING_PUBLIC_KEY: {error}"))?;
+ let expected: [u8; 32] =
+ expected.try_into().map_err(|_| "DBX_PLUGIN_SIGNING_PUBLIC_KEY must contain 32 bytes".to_string())?;
+ if signing_key.verifying_key().to_bytes() != expected {
+ return Err("DBX_PLUGIN_SIGNING_KEY does not match DBX_PLUGIN_SIGNING_PUBLIC_KEY".to_string());
+ }
+ Ok(())
+}
+
+fn absolute_output_path(output: &Path) -> Result<PathBuf, String> {
+ if output.is_absolute() {
+ return Ok(output.to_path_buf());
+ }
+ std::env::current_dir().map(|current| current.join(output)).map_err(|error| error.to_string())
+}
+
+pub fn validate_key_id(key_id: &str) -> Result<(), String> {
+ if key_id.is_empty()
+ || key_id.len() > 128
+ || !key_id
+ .chars()
+ .all(|character| character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_' | ':'))
+ {
+ return Err("Signing key id contains unsupported characters".to_string());
+ }
+ Ok(())
+}
+
+fn validate_artifact_target(target: &str) -> Result<(), String> {
+ if target.is_empty()
+ || target.len() > 64
+ || !target
+ .chars()
+ .all(|character| character.is_ascii_lowercase() || character.is_ascii_digit() || character == '-')
+ {
+ return Err("Artifact target contains unsupported characters".to_string());
+ }
+ Ok(())
+}
+
+fn archive_name(path: &Path) -> Result<String, String> {
+ path.components()
+ .map(|component| match component {
+ std::path::Component::Normal(value) => {
+ value.to_str().map(str::to_string).ok_or("Package path is not UTF-8".to_string())
+ }
+ _ => Err(format!("Unsafe package path: {}", path.display())),
+ })
+ .collect::<Result<Vec<_>, _>>()
+ .map(|parts| parts.join("/"))
+}
+
+fn sha256_file(path: &Path) -> Result<String, String> {
+ let mut file = File::open(path).map_err(|error| error.to_string())?;
+ let mut digest = Sha256::new();
+ let mut buffer = [0u8; 64 * 1024];
+ loop {
+ let read = file.read(&mut buffer).map_err(|error| error.to_string())?;
+ if read == 0 {
+ break;
+ }
+ digest.update(&buffer[..read]);
+ }
+ Ok(hex_digest(digest.finalize()))
+}
+
+fn hex_digest(bytes: impl AsRef<[u8]>) -> String {
+ use std::fmt::Write as _;
+
+ bytes.as_ref().iter().fold(String::with_capacity(64), |mut output, byte| {
+ let _ = write!(output, "{byte:02x}");
+ output
+ })
+}
+
+#[cfg(unix)]
+fn executable_permissions(path: &Path) -> u32 {
+ use std::os::unix::fs::PermissionsExt;
+
+ std::fs::metadata(path).map(|metadata| metadata.permissions().mode() & 0o777).unwrap_or(0o644)
+}
+
+#[cfg(unix)]
+fn sync_directory(path: &Path) -> Result<(), String> {
+ File::open(path).and_then(|directory| directory.sync_all()).map_err(|error| error.to_string())
+}
+
+#[cfg(not(unix))]
+fn sync_directory(_path: &Path) -> Result<(), String> {
+ Ok(())
+}
+
+#[cfg(not(unix))]
+fn executable_permissions(path: &Path) -> u32 {
+ path.parent()
+ .and_then(Path::file_name)
+ .is_some_and(|parent| parent.to_string_lossy().contains('-'))
+ .then_some(0o755)
+ .unwrap_or(0o644)
+}
+
+fn usage() -> String {
+ format!(
+ "Usage: dbx-plugin-packager <source-dir> <output.dbxp> [--key-id ID] [--artifact-metadata FILE --target TARGET [--artifact-url URL]]\n {}",
+ sign_usage()
+ )
+}
+
+fn sign_usage() -> String {
+ "dbx-plugin-packager sign <unsigned.dbxp> <signed.dbxp> --key-id ID [--artifact-metadata FILE --target TARGET [--artifact-url URL]]".to_string()
+}
+
+#[cfg(test)]
+mod tests {
+ use std::io::Read;
+ use std::path::Path;
+
+ use base64::Engine;
+ use ed25519_dalek::{Signature, SigningKey, Verifier};
+ use zip::ZipArchive;
+
+ use super::{
+ archive_name, artifact_metadata_request, decode_signing_key, generate_signing_key, hex_digest, run_package_cli,
+ sign_existing_package, validate_artifact_target, validate_key_id, verify_signing_public_key,
+ };
+
+ #[test]
+ fn generates_matching_ed25519_key_material() {
+ let material = generate_signing_key().unwrap();
+ let seed: [u8; 32] =
+ base64::engine::general_purpose::STANDARD.decode(material.private_seed_base64).unwrap().try_into().unwrap();
+ let public_key: [u8; 32] =
+ base64::engine::general_purpose::STANDARD.decode(material.public_key_base64).unwrap().try_into().unwrap();
+ assert_eq!(SigningKey::from_bytes(&seed).verifying_key().to_bytes(), public_key);
+ }
+
+ #[test]
+ fn validates_configured_repository_public_key() {
+ let signing_key = decode_signing_key(&base64::engine::general_purpose::STANDARD.encode([7u8; 32])).unwrap();
+ let matching = base64::engine::general_purpose::STANDARD.encode(signing_key.verifying_key().to_bytes());
+ verify_signing_public_key(&signing_key, &matching).unwrap();
+
+ let different = base64::engine::general_purpose::STANDARD
+ .encode(SigningKey::from_bytes(&[8u8; 32]).verifying_key().to_bytes());
+ assert!(verify_signing_public_key(&signing_key, &different).unwrap_err().contains("does not match"));
+ }
+
+ #[test]
+ fn validates_signing_key_ids() {
+ validate_key_id("vendor.release:2026-07").unwrap();
+ assert!(validate_key_id("contains spaces").is_err());
+ assert!(validate_key_id("").is_err());
+ }
+
+ #[test]
+ fn validates_artifact_targets() {
+ validate_artifact_target("darwin-arm64").unwrap();
+ validate_artifact_target("universal").unwrap();
+ assert!(validate_artifact_target("Darwin ARM64").is_err());
+ }
+
+ #[test]
+ fn requires_target_for_artifact_metadata() {
+ assert!(artifact_metadata_request(Some("artifact.json".into()), None, None, Some("vendor.release")).is_err());
+ assert!(artifact_metadata_request(None, Some("universal".to_string()), None, Some("vendor.release")).is_err());
+ assert!(artifact_metadata_request(
+ Some("artifact.json".into()),
+ Some("universal".to_string()),
+ Some("plugin.dbxp".to_string()),
+ None,
+ )
+ .unwrap()
+ .is_some());
+ assert!(artifact_metadata_request(
+ Some("artifact.json".into()),
+ Some("universal".to_string()),
+ Some("plugin.dbxp".to_string()),
+ Some("vendor.release"),
+ )
+ .unwrap()
+ .is_some());
+ }
+
+ #[test]
+ fn normalizes_safe_archive_names_and_rejects_parent_paths() {
+ assert_eq!(archive_name(Path::new("bin/darwin-arm64/plugin")).unwrap(), "bin/darwin-arm64/plugin");
+ assert!(archive_name(Path::new("../plugin")).is_err());
+ }
+
+ #[test]
+ fn renders_lowercase_sha256_hex() {
+ assert_eq!(hex_digest([0x00, 0x7f, 0xa5, 0xff]), "007fa5ff");
+ }
+
+ #[test]
+ fn store_signs_an_existing_unsigned_candidate_package() {
+ let root = tempfile::tempdir().unwrap();
+ let source = root.path().join("source");
+ std::fs::create_dir_all(&source).unwrap();
+ std::fs::write(source.join("manifest.json"), r#"{"manifest_version":1,"id":"example.plugin"}"#).unwrap();
+ std::fs::write(source.join("asset.txt"), "candidate").unwrap();
+ let unsigned = root.path().join("unsigned.dbxp");
+ let signed = root.path().join("signed.dbxp");
+ run_package_cli([source.to_string_lossy().into_owned(), unsigned.to_string_lossy().into_owned()], false)
+ .unwrap();
+
+ let signing_key = SigningKey::from_bytes(&[7u8; 32]);
+ sign_existing_package(&unsigned, &signed, "dbx-store.test", &signing_key, None, false).unwrap();
+
+ let mut archive = ZipArchive::new(std::fs::File::open(&signed).unwrap()).unwrap();
+ let mut checksums = Vec::new();
+ archive.by_name("checksums.json").unwrap().read_to_end(&mut checksums).unwrap();
+ let signature: serde_json::Value = {
+ let mut raw = Vec::new();
+ archive.by_name("signature.json").unwrap().read_to_end(&mut raw).unwrap();
+ serde_json::from_slice(&raw).unwrap()
+ };
+ assert_eq!(signature["key_id"], "dbx-store.test");
+ let signature_bytes: [u8; 64] = base64::engine::general_purpose::STANDARD
+ .decode(signature["signature"].as_str().unwrap())
+ .unwrap()
+ .try_into()
+ .unwrap();
+ signing_key.verifying_key().verify(&checksums, &Signature::from_bytes(&signature_bytes)).unwrap();
+ assert!(sign_existing_package(
+ &signed,
+ &root.path().join("resigned.dbxp"),
+ "dbx-store.test",
+ &signing_key,
+ None,
+ false
+ )
+ .unwrap_err()
+ .contains("already signed"));
+ }
+}
diff --git a/plugins/sdk/rust/dbx-plugin-sdk/.gitignore b/plugins/sdk/rust/dbx-plugin-sdk/.gitignore
new file mode 100644
index 0000000000..5a44eef09a
--- /dev/null
+++ b/plugins/sdk/rust/dbx-plugin-sdk/.gitignore
@@ -0,0 +1 @@
+/Cargo.lock
diff --git a/plugins/sdk/rust/dbx-plugin-sdk/Cargo.toml b/plugins/sdk/rust/dbx-plugin-sdk/Cargo.toml
new file mode 100644
index 0000000000..f7d970ba85
--- /dev/null
+++ b/plugins/sdk/rust/dbx-plugin-sdk/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "dbx-plugin-sdk"
+version = "0.1.0"
+edition = "2021"
+license = "Apache-2.0"
+description = "Sidecar protocol SDK for DBX plugins"
+
+[workspace]
+
+[dependencies]
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
diff --git a/plugins/sdk/rust/dbx-plugin-sdk/README.md b/plugins/sdk/rust/dbx-plugin-sdk/README.md
new file mode 100644
index 0000000000..83e2710774
--- /dev/null
+++ b/plugins/sdk/rust/dbx-plugin-sdk/README.md
@@ -0,0 +1,87 @@
+# dbx-plugin-sdk
+
+Rust SDK for DBX sidecar protocol v1.
+
+It provides:
+
+- `plugin/initialize` negotiation and backend identity reporting;
+- concurrent JSON-RPC request dispatch through a bounded worker pool;
+- JSON-RPC responses and plugin events;
+- JSON Lines and framed transports;
+- binary input/output channels for framed plugins;
+- bounded JSON and binary message sizes.
+
+## Minimal sidecar
+
+```rust
+use dbx_plugin_sdk::{
+ PluginEmitter, PluginError, PluginHandler, PluginMetadata, PluginServer,
+ RequestContext,
+};
+use serde_json::{json, Value};
+
+struct Example;
+
+impl PluginHandler for Example {
+ fn handle(
+ &self,
+ _context: RequestContext,
+ method: &str,
+ params: Value,
+ emitter: &PluginEmitter,
+ ) -> Result<Value, PluginError> {
+ match method {
+ "example/echo" => {
+ emitter.event("example/progress", json!({ "done": true }))?;
+ Ok(params)
+ }
+ _ => Err(PluginError::method_not_found(method)),
+ }
+ }
+}
+
+fn main() -> std::io::Result<()> {
+ PluginServer::new(
+ PluginMetadata::new("vendor.example", env!("CARGO_PKG_VERSION"))
+ .with_capability("events"),
+ Example,
+ )
+ .serve()
+}
+```
+
+The metadata ID and version must exactly match `manifest.json`; DBX rejects a mismatched backend during initialization.
+
+## Framed transport
+
+Use framed transport for PTY, SFTP, file transfer, or other binary streams:
+
+```rust
+use dbx_plugin_sdk::{PluginServer, PluginTransport};
+
+PluginServer::new(metadata, handler)
+ .transport(PluginTransport::Framed)
+ .serve()?;
+```
+
+Implement `PluginHandler::handle_binary` for host-to-plugin frames and call `PluginEmitter::binary` for plugin-to-host frames. The manifest must declare `"transport": "stdio-framed"`; workbench UI binary access requires the `host.binary` permission.
+
+The server defaults to 2-16 worker threads (based on available parallelism) and a 256-job queue. CPU-heavy or latency-sensitive plugins can tune both without falling back to unbounded thread creation:
+
+```rust
+PluginServer::new(metadata, handler)
+ .worker_threads(8)
+ .work_queue_capacity(512)
+ .serve()?;
+```
+
+## Process rules
+
+- Reserve stdout for protocol traffic.
+- Write diagnostics to stderr.
+- Keep plugin-owned sessions in the handler or another process-wide registry.
+- Make connect/disconnect idempotent.
+- Use application-level cancellation and chunk acknowledgements for long-running transfers.
+- Never send connection secrets in plugin events or workbench context.
+
+See `plugins/examples/hello-workbench` for a complete package.
diff --git a/plugins/sdk/rust/dbx-plugin-sdk/src/lib.rs b/plugins/sdk/rust/dbx-plugin-sdk/src/lib.rs
new file mode 100644
index 0000000000..767336b9b6
--- /dev/null
+++ b/plugins/sdk/rust/dbx-plugin-sdk/src/lib.rs
@@ -0,0 +1,432 @@
+use std::io::{self, BufRead, BufReader, Read, Write};
+use std::sync::{mpsc, Arc, Mutex};
+use std::thread;
+
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+pub const PROTOCOL_VERSION: u32 = 1;
+const MAX_JSON_BYTES: usize = 8 * 1024 * 1024;
+const MAX_BINARY_BYTES: usize = 64 * 1024 * 1024;
+const FRAME_KIND_JSON: u8 = 0;
+const FRAME_KIND_BINARY: u8 = 1;
+const DEFAULT_WORK_QUEUE_CAPACITY: usize = 256;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PluginTransport {
+ JsonLines,
+ Framed,
+}
+
+#[derive(Debug, Clone)]
+pub struct PluginMetadata {
+ pub id: String,
+ pub version: String,
+ pub capabilities: Vec<String>,
+}
+
+impl PluginMetadata {
+ pub fn new(id: impl Into<String>, version: impl Into<String>) -> Self {
+ Self { id: id.into(), version: version.into(), capabilities: Vec::new() }
+ }
+
+ pub fn with_capability(mut self, capability: impl Into<String>) -> Self {
+ self.capabilities.push(capability.into());
+ self
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct RequestContext {
+ pub request_id: Option<u64>,
+ pub driver: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct PluginError {
+ pub code: i32,
+ pub message: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub data: Option<Value>,
+}
+
+impl PluginError {
+ pub fn new(code: i32, message: impl Into<String>) -> Self {
+ Self { code, message: message.into(), data: None }
+ }
+
+ pub fn method_not_found(method: &str) -> Self {
+ Self::new(-32601, format!("Method not found: {method}"))
+ }
+}
+
+pub trait PluginHandler: Send + Sync + 'static {
+ fn handle(
+ &self,
+ context: RequestContext,
+ method: &str,
+ params: Value,
+ emitter: &PluginEmitter,
+ ) -> Result<Value, PluginError>;
+
+ fn handle_binary(&self, _channel: &str, _data: Vec<u8>, _emitter: &PluginEmitter) -> Result<(), PluginError> {
+ Err(PluginError::new(-32601, "Binary input is not supported"))
+ }
+}
+
+#[derive(Clone)]
+pub struct PluginEmitter {
+ output: Arc<Mutex<Box<dyn Write + Send>>>,
+ transport: PluginTransport,
+}
+
+impl PluginEmitter {
+ pub fn event(&self, method: &str, params: Value) -> Result<(), PluginError> {
+ validate_protocol_name(method)?;
+ self.write_json(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "method": method,
+ "params": params
+ }))
+ }
+
+ pub fn binary(&self, channel: &str, data: &[u8]) -> Result<(), PluginError> {
+ if self.transport != PluginTransport::Framed {
+ return Err(PluginError::new(-32000, "Binary messages require framed transport"));
+ }
+ validate_protocol_name(channel)?;
+ if data.len() > MAX_BINARY_BYTES {
+ return Err(PluginError::new(-32600, "Binary message is too large"));
+ }
+ let channel = channel.as_bytes();
+ if channel.len() > u16::MAX as usize {
+ return Err(PluginError::new(-32600, "Binary channel is too long"));
+ }
+ let payload_len = 2 + channel.len() + data.len();
+ let mut output = self.output.lock().map_err(|_| PluginError::new(-32000, "Plugin output lock is poisoned"))?;
+ output.write_all(&[FRAME_KIND_BINARY]).map_err(io_error)?;
+ output.write_all(&(payload_len as u32).to_be_bytes()).map_err(io_error)?;
+ output.write_all(&(channel.len() as u16).to_be_bytes()).map_err(io_error)?;
+ output.write_all(channel).map_err(io_error)?;
+ output.write_all(data).map_err(io_error)?;
+ output.flush().map_err(io_error)
+ }
+
+ fn respond(&self, id: u64, result: Result<Value, PluginError>) -> Result<(), PluginError> {
+ match result {
+ Ok(result) => self.write_json(&serde_json::json!({ "jsonrpc": "2.0", "id": id, "result": result })),
+ Err(error) => self.write_json(&serde_json::json!({ "jsonrpc": "2.0", "id": id, "error": error })),
+ }
+ }
+
+ fn write_json(&self, value: &Value) -> Result<(), PluginError> {
+ let payload = serde_json::to_vec(value).map_err(|error| PluginError::new(-32603, error.to_string()))?;
+ if payload.len() > MAX_JSON_BYTES {
+ return Err(PluginError::new(-32600, "JSON message is too large"));
+ }
+ let mut output = self.output.lock().map_err(|_| PluginError::new(-32000, "Plugin output lock is poisoned"))?;
+ match self.transport {
+ PluginTransport::JsonLines => {
+ output.write_all(&payload).map_err(io_error)?;
+ output.write_all(b"\n").map_err(io_error)?;
+ }
+ PluginTransport::Framed => {
+ output.write_all(&[FRAME_KIND_JSON]).map_err(io_error)?;
+ output.write_all(&(payload.len() as u32).to_be_bytes()).map_err(io_error)?;
+ output.write_all(&payload).map_err(io_error)?;
+ }
+ }
+ output.flush().map_err(io_error)
+ }
+}
+
+pub struct PluginServer<H> {
+ metadata: PluginMetadata,
+ handler: Arc<H>,
+ transport: PluginTransport,
+ worker_threads: usize,
+ work_queue_capacity: usize,
+}
+
+impl<H: PluginHandler> PluginServer<H> {
+ pub fn new(metadata: PluginMetadata, handler: H) -> Self {
+ Self {
+ metadata,
+ handler: Arc::new(handler),
+ transport: PluginTransport::JsonLines,
+ worker_threads: default_worker_threads(),
+ work_queue_capacity: DEFAULT_WORK_QUEUE_CAPACITY,
+ }
+ }
+
+ pub fn transport(mut self, transport: PluginTransport) -> Self {
+ self.transport = transport;
+ self
+ }
+
+ pub fn worker_threads(mut self, worker_threads: usize) -> Self {
+ self.worker_threads = worker_threads.max(1);
+ self
+ }
+
+ pub fn work_queue_capacity(mut self, work_queue_capacity: usize) -> Self {
+ self.work_queue_capacity = work_queue_capacity.max(1);
+ self
+ }
+
+ pub fn serve(self) -> io::Result<()> {
+ let emitter = PluginEmitter { output: Arc::new(Mutex::new(Box::new(io::stdout()))), transport: self.transport };
+ let workers = WorkerPool::new(self.worker_threads, self.work_queue_capacity)?;
+ match self.transport {
+ PluginTransport::JsonLines => self.serve_json_lines(BufReader::new(io::stdin()), emitter, &workers),
+ PluginTransport::Framed => self.serve_framed(io::stdin(), emitter, &workers),
+ }
+ }
+
+ fn serve_json_lines<R: BufRead>(
+ &self,
+ mut input: R,
+ emitter: PluginEmitter,
+ workers: &WorkerPool,
+ ) -> io::Result<()> {
+ loop {
+ let Some(line) = read_limited_line(&mut input, MAX_JSON_BYTES)? else {
+ return Ok(());
+ };
+ if line.iter().all(u8::is_ascii_whitespace) {
+ continue;
+ }
+ if let Err(error) = self.dispatch_json(&line, emitter.clone(), workers) {
+ eprintln!("[dbx-plugin-sdk] {error}");
+ }
+ }
+ }
+
+ fn serve_framed<R: Read>(&self, mut input: R, emitter: PluginEmitter, workers: &WorkerPool) -> io::Result<()> {
+ loop {
+ let mut header = [0u8; 5];
+ match input.read_exact(&mut header) {
+ Ok(()) => {}
+ Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => return Ok(()),
+ Err(error) => return Err(error),
+ }
+ let kind = header[0];
+ let length = u32::from_be_bytes(header[1..5].try_into().unwrap()) as usize;
+ let maximum = if kind == FRAME_KIND_JSON { MAX_JSON_BYTES } else { MAX_BINARY_BYTES + 1024 };
+ if length > maximum {
+ return Err(io::Error::new(io::ErrorKind::InvalidData, "plugin frame is too large"));
+ }
+ let mut payload = vec![0; length];
+ input.read_exact(&mut payload)?;
+ match kind {
+ FRAME_KIND_JSON => {
+ if let Err(error) = self.dispatch_json(&payload, emitter.clone(), workers) {
+ eprintln!("[dbx-plugin-sdk] {error}");
+ }
+ }
+ FRAME_KIND_BINARY => {
+ if let Err(error) = self.dispatch_binary(payload, emitter.clone(), workers) {
+ eprintln!("[dbx-plugin-sdk] {error}");
+ }
+ }
+ _ => return Err(io::Error::new(io::ErrorKind::InvalidData, "unknown plugin frame kind")),
+ }
+ }
+ }
+
+ fn dispatch_json(&self, payload: &[u8], emitter: PluginEmitter, workers: &WorkerPool) -> Result<(), String> {
+ let request: ProtocolRequest = serde_json::from_slice(payload).map_err(|error| error.to_string())?;
+ if request.jsonrpc.as_deref() != Some("2.0") {
+ return Err("request does not declare jsonrpc 2.0".to_string());
+ }
+ validate_protocol_name(&request.method).map_err(|error| error.message)?;
+ if request.method == "plugin/initialize" {
+ let id = request.id.ok_or("plugin/initialize must be a request")?;
+ let supported = request
+ .params
+ .get("host")
+ .and_then(|host| host.get("protocolVersions"))
+ .and_then(Value::as_array)
+ .is_some_and(|versions| {
+ versions.iter().any(|version| version.as_u64() == Some(PROTOCOL_VERSION as u64))
+ });
+ let result = if supported {
+ Ok(serde_json::json!({
+ "protocolVersion": PROTOCOL_VERSION,
+ "capabilities": self.metadata.capabilities,
+ "plugin": { "id": self.metadata.id, "version": self.metadata.version }
+ }))
+ } else {
+ Err(PluginError::new(-32001, "DBX and plugin do not share a protocol version"))
+ };
+ return emitter.respond(id, result).map_err(|error| error.message);
+ }
+
+ let handler = self.handler.clone();
+ workers.submit(move || {
+ let context = RequestContext { request_id: request.id, driver: request.driver };
+ let result = handler.handle(context, &request.method, request.params, &emitter);
+ if let Some(id) = request.id {
+ if let Err(error) = emitter.respond(id, result) {
+ eprintln!("[dbx-plugin-sdk] failed to write response: {}", error.message);
+ }
+ }
+ })
+ }
+
+ fn dispatch_binary(&self, payload: Vec<u8>, emitter: PluginEmitter, workers: &WorkerPool) -> Result<(), String> {
+ if payload.len() < 2 {
+ return Err("invalid binary frame".to_string());
+ }
+ let channel_len = u16::from_be_bytes([payload[0], payload[1]]) as usize;
+ if channel_len == 0 || payload.len() < 2 + channel_len {
+ return Err("invalid binary channel".to_string());
+ }
+ let channel = std::str::from_utf8(&payload[2..2 + channel_len])
+ .map_err(|_| "binary channel is not UTF-8".to_string())?
+ .to_string();
+ validate_protocol_name(&channel).map_err(|error| error.message)?;
+ let data = payload[2 + channel_len..].to_vec();
+ let handler = self.handler.clone();
+ workers.submit(move || {
+ if let Err(error) = handler.handle_binary(&channel, data, &emitter) {
+ eprintln!("[dbx-plugin-sdk] binary handler failed: {}", error.message);
+ }
+ })
+ }
+}
+
+#[derive(Debug, Deserialize)]
+struct ProtocolRequest {
+ jsonrpc: Option<String>,
+ #[serde(default)]
+ id: Option<u64>,
+ #[serde(default)]
+ driver: Option<String>,
+ method: String,
+ #[serde(default)]
+ params: Value,
+}
+
+type PluginJob = Box<dyn FnOnce() + Send + 'static>;
+
+struct WorkerPool {
+ sender: mpsc::SyncSender<PluginJob>,
+}
+
+impl WorkerPool {
+ fn new(worker_threads: usize, queue_capacity: usize) -> io::Result<Self> {
+ let (sender, receiver) = mpsc::sync_channel::<PluginJob>(queue_capacity);
+ let receiver = Arc::new(Mutex::new(receiver));
+ for index in 0..worker_threads {
+ let receiver = receiver.clone();
+ thread::Builder::new().name(format!("dbx-plugin-worker-{index}")).spawn(move || loop {
+ let job = match receiver.lock() {
+ Ok(receiver) => receiver.recv(),
+ Err(_) => return,
+ };
+ match job {
+ Ok(job) => job(),
+ Err(_) => return,
+ }
+ })?;
+ }
+ Ok(Self { sender })
+ }
+
+ fn submit(&self, job: impl FnOnce() + Send + 'static) -> Result<(), String> {
+ self.sender.send(Box::new(job)).map_err(|_| "plugin worker pool is unavailable".to_string())
+ }
+}
+
+fn default_worker_threads() -> usize {
+ thread::available_parallelism().map(usize::from).unwrap_or(4).clamp(2, 16)
+}
+
+fn read_limited_line<R: BufRead>(reader: &mut R, maximum: usize) -> io::Result<Option<Vec<u8>>> {
+ let mut output = Vec::new();
+ loop {
+ let available = reader.fill_buf()?;
+ if available.is_empty() {
+ return if output.is_empty() { Ok(None) } else { Ok(Some(output)) };
+ }
+ let take = available.iter().position(|byte| *byte == b'\n').map(|index| index + 1).unwrap_or(available.len());
+ if output.len().saturating_add(take) > maximum {
+ return Err(io::Error::new(io::ErrorKind::InvalidData, "plugin JSON line is too large"));
+ }
+ output.extend_from_slice(&available[..take]);
+ reader.consume(take);
+ if output.last() == Some(&b'\n') {
+ return Ok(Some(output));
+ }
+ }
+}
+
+fn validate_protocol_name(value: &str) -> Result<(), PluginError> {
+ if value.is_empty() || value.len() > 256 || value.chars().any(char::is_whitespace) {
+ return Err(PluginError::new(-32600, "Protocol name is invalid"));
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use std::io::Cursor;
+ use std::sync::mpsc;
+ use std::time::Duration;
+
+ use super::{
+ read_limited_line, PluginError, PluginHandler, PluginMetadata, PluginServer, RequestContext, WorkerPool,
+ };
+ use crate::PluginEmitter;
+ use serde_json::Value;
+
+ struct NoopHandler;
+
+ impl PluginHandler for NoopHandler {
+ fn handle(
+ &self,
+ _context: RequestContext,
+ method: &str,
+ _params: Value,
+ _emitter: &PluginEmitter,
+ ) -> Result<Value, PluginError> {
+ Err(PluginError::method_not_found(method))
+ }
+ }
+
+ #[test]
+ fn worker_pool_executes_queued_jobs() {
+ let pool = WorkerPool::new(2, 4).unwrap();
+ let (sender, receiver) = mpsc::channel();
+ for value in 0..4 {
+ let sender = sender.clone();
+ pool.submit(move || sender.send(value).unwrap()).unwrap();
+ }
+ drop(sender);
+
+ let mut values = (0..4).map(|_| receiver.recv_timeout(Duration::from_secs(1)).unwrap()).collect::<Vec<_>>();
+ values.sort_unstable();
+ assert_eq!(values, vec![0, 1, 2, 3]);
+ }
+
+ #[test]
+ fn server_configuration_clamps_zero_worker_values() {
+ let server = PluginServer::new(PluginMetadata::new("sample", "1.0.0"), NoopHandler)
+ .worker_threads(0)
+ .work_queue_capacity(0);
+
+ assert_eq!(server.worker_threads, 1);
+ assert_eq!(server.work_queue_capacity, 1);
+ }
+
+ #[test]
+ fn limited_line_reader_rejects_oversized_messages() {
+ let mut reader = Cursor::new(b"12345\n".to_vec());
+ assert!(read_limited_line(&mut reader, 4).unwrap_err().to_string().contains("too large"));
+ }
+}
+
+fn io_error(error: io::Error) -> PluginError {
+ PluginError::new(-32000, error.to_string())
+}
diff --git a/plugins/sdk/templates/github/plugin-release.yml b/plugins/sdk/templates/github/plugin-release.yml
new file mode 100644
index 0000000000..2cb96e8691
--- /dev/null
+++ b/plugins/sdk/templates/github/plugin-release.yml
@@ -0,0 +1,20 @@
+name: Release DBX plugin
+
+on:
+ release:
+ types: [published]
+
+permissions:
+ contents: write
+
+jobs:
+ release:
+ uses: t8y2/dbx/.github/workflows/plugin-release-reusable.yml@plugin-sdk-v1
+ with:
+ release-tag: ${{ github.event.release.tag_name }}
+ package-command: dbx-plugin package .
+ package-path: dist/*.dbxp
+ metadata-path: dist/*.artifact.json
+ plugin-cli-version: 0.1.0
+ # Frontend-only plugins can publish one cross-platform package instead:
+ # build-matrix: '{"include":[{"runner":"ubuntu-24.04","target":"universal"}]}'
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9ab6f6e3dc..bd1ea52adb 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -353,6 +353,39 @@ importers:
specifier: ^5.8.3
version: 5.9.3
+ packages/plugin-cli:
+ optionalDependencies:
+ '@dbx-app/plugin-cli-darwin-arm64':
+ specifier: 0.1.1
+ version: link:../plugin-cli-darwin-arm64
+ '@dbx-app/plugin-cli-darwin-x64':
+ specifier: 0.1.1
+ version: link:../plugin-cli-darwin-x64
+ '@dbx-app/plugin-cli-linux-arm64-gnu':
+ specifier: 0.1.1
+ version: link:../plugin-cli-linux-arm64-gnu
+ '@dbx-app/plugin-cli-linux-x64-gnu':
+ specifier: 0.1.1
+ version: link:../plugin-cli-linux-x64-gnu
+ '@dbx-app/plugin-cli-win32-arm64':
+ specifier: 0.1.1
+ version: link:../plugin-cli-win32-arm64
+ '@dbx-app/plugin-cli-win32-x64':
+ specifier: 0.1.1
+ version: link:../plugin-cli-win32-x64
+
+ packages/plugin-cli-darwin-arm64: {}
+
+ packages/plugin-cli-darwin-x64: {}
+
+ packages/plugin-cli-linux-arm64-gnu: {}
+
+ packages/plugin-cli-linux-x64-gnu: {}
+
+ packages/plugin-cli-win32-arm64: {}
+
+ packages/plugin-cli-win32-x64: {}
+
packages:
diff --git a/scripts/verify-package-install.mjs b/scripts/verify-package-install.mjs
index cb51ef859d..317410a2f7 100644
--- a/scripts/verify-package-install.mjs
+++ b/scripts/verify-package-install.mjs
@@ -7,6 +7,7 @@ const packageDirectory = resolve(process.argv[2] ?? "/tmp/dbx-pack-check");
const expectedPackages = [
"@dbx-app/cli",
"@dbx-app/mcp-server",
+ "@dbx-app/plugin-cli",
];
const tarballs = readdirSync(packageDirectory)
.filter((file) => file.endsWith(".tgz"))
diff --git a/scripts/verify-plugin-cli-package.mjs b/scripts/verify-plugin-cli-package.mjs
new file mode 100644
index 0000000000..7523d48c40
--- /dev/null
+++ b/scripts/verify-plugin-cli-package.mjs
@@ -0,0 +1,208 @@
+import { spawnSync, spawn } from "node:child_process";
+import {
+ chmodSync,
+ copyFileSync,
+ cpSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { basename, dirname, join, resolve } from "node:path";
+
+const repositoryRoot = resolve(import.meta.dirname, "..");
+const platformPackages = {
+ "darwin-arm64": ["plugin-cli-darwin-arm64", "dbx-plugin"],
+ "darwin-x64": ["plugin-cli-darwin-x64", "dbx-plugin"],
+ "linux-arm64": ["plugin-cli-linux-arm64-gnu", "dbx-plugin"],
+ "linux-x64": ["plugin-cli-linux-x64-gnu", "dbx-plugin"],
+ "win32-arm64": ["plugin-cli-win32-arm64", "dbx-plugin.exe"],
+ "win32-x64": ["plugin-cli-win32-x64", "dbx-plugin.exe"],
+};
+const platformKey = `${process.platform}-${process.arch}`;
+const platformPackage = platformPackages[platformKey];
+if (!platformPackage) {
+ throw new Error(`No DBX Plugin CLI package smoke test is defined for ${platformKey}.`);
+}
+
+const temporaryRoot = mkdtempSync(join(tmpdir(), "dbx-plugin-cli-package-"));
+const cargoTarget = join(temporaryRoot, "cargo-target");
+const tarballDirectory = join(temporaryRoot, "tarballs");
+const installDirectory = join(temporaryRoot, "install");
+const stagedPlatformDirectory = join(temporaryRoot, platformPackage[0]);
+
+try {
+ run(
+ "cargo",
+ [
+ "build",
+ "--locked",
+ "--release",
+ "--manifest-path",
+ join(repositoryRoot, "plugins/sdk/cli/Cargo.toml"),
+ ],
+ { env: { ...process.env, CARGO_TARGET_DIR: cargoTarget } },
+ );
+
+ cpSync(join(repositoryRoot, "packages", platformPackage[0]), stagedPlatformDirectory, { recursive: true });
+ const stagedBinaryDirectory = join(stagedPlatformDirectory, "bin");
+ mkdirSync(stagedBinaryDirectory, { recursive: true });
+ const sourceBinary = join(cargoTarget, "release", process.platform === "win32" ? "dbx-plugin.exe" : "dbx-plugin");
+ const stagedBinary = join(stagedBinaryDirectory, platformPackage[1]);
+ copyFileSync(sourceBinary, stagedBinary);
+ if (process.platform !== "win32") chmodSync(stagedBinary, 0o755);
+
+ mkdirSync(tarballDirectory, { recursive: true });
+ run("npm", ["pack", stagedPlatformDirectory, "--pack-destination", tarballDirectory]);
+ run("npm", ["pack", join(repositoryRoot, "packages/plugin-cli"), "--pack-destination", tarballDirectory]);
+
+ const tarballs = readdirSync(tarballDirectory)
+ .filter((file) => file.endsWith(".tgz"))
+ .map((file) => join(tarballDirectory, file));
+ if (tarballs.length !== 2) {
+ throw new Error(`Expected two npm tarballs, found ${tarballs.map(basename).join(", ")}.`);
+ }
+
+ mkdirSync(installDirectory, { recursive: true });
+ writeFileSync(
+ join(installDirectory, "package.json"),
+ `${JSON.stringify({ name: "dbx-plugin-cli-package-smoke", private: true }, null, 2)}\n`,
+ );
+ run("npm", ["install", "--ignore-scripts", "--no-audit", "--no-fund", ...tarballs], { cwd: installDirectory });
+
+ const command = join(
+ installDirectory,
+ "node_modules",
+ ".bin",
+ process.platform === "win32" ? "dbx-plugin.cmd" : "dbx-plugin",
+ );
+ const version = run(command, ["--version"], { cwd: installDirectory, capture: true });
+ if (!version.stdout.includes("dbx-plugin 0.1.1")) {
+ throw new Error(`Unexpected installed CLI version output: ${version.stdout.trim()}`);
+ }
+
+ await verifyTemplate(command, installDirectory, "frontend");
+ if (process.env.DBX_PLUGIN_CLI_VERIFY_NATIVE === "1") {
+ await verifyTemplate(command, installDirectory, "rust");
+ if (commandAvailable("go")) await verifyTemplate(command, installDirectory, "go");
+ }
+
+ const installedManifest = JSON.parse(
+ readFileSync(join(installDirectory, "node_modules/@dbx-app/plugin-cli/package.json"), "utf8"),
+ );
+ if (installedManifest.name !== "@dbx-app/plugin-cli") {
+ throw new Error(`Installed unexpected npm package ${installedManifest.name}.`);
+ }
+ console.log(`Verified @dbx-app/plugin-cli on ${platformKey} without compiling the CLI during npm install.`);
+} finally {
+ rmSync(join(repositoryRoot, "packages/plugin-cli/sdk-root"), { recursive: true, force: true });
+ rmSync(temporaryRoot, { recursive: true, force: true });
+}
+
+async function verifyTemplate(command, workingDirectory, template) {
+ const project = join(workingDirectory, `${template}-plugin`);
+ run(command, [
+ "create",
+ project,
+ "--template",
+ template,
+ "--yes",
+ "--id",
+ `com.example.npm-${template}`,
+ "--name",
+ `NPM ${template} smoke`,
+ "--publisher",
+ "example",
+ "--description",
+ `NPM ${template} package smoke`,
+ ]);
+ run(command, ["package", project]);
+ const packages = readdirSync(join(project, "dist")).filter((file) => file.endsWith(".dbxp"));
+ if (packages.length !== 1 || !existsSync(join(project, "dist", packages[0]))) {
+ throw new Error(`Expected one ${template} .dbxp package, found ${packages.join(", ")}.`);
+ }
+ await verifyDev(workingDirectory, project, template);
+}
+
+async function verifyDev(workingDirectory, project, template) {
+ const packageRoot = join(workingDirectory, 'node_modules/@dbx-app/plugin-cli');
+ if (!existsSync(join(packageRoot, 'dev-runtime/runtime.mjs')) || !existsSync(join(packageRoot, 'dev-runtime/ui/index.html'))) throw new Error('Packed CLI has no dev runtime');
+ const child = spawn(process.execPath, [join(packageRoot, 'bin/dbx-plugin.js'), 'dev', '--path', project, '--port', '0'], {
+ cwd: workingDirectory, env: { ...process.env, DBX_PLUGIN_DEV_RUNTIME: '', DBX_PLUGIN_NODE: '', DBX_PLUGIN_SDK_ROOT: '' },
+ stdio: ['ignore', 'pipe', 'pipe'], detached: process.platform !== 'win32',
+ });
+ let output = '';
+ child.stderr.on('data', chunk => { output = (output + chunk).slice(-64000); });
+ try {
+ const origin = await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('Installed dev runtime did not start')), 180000);
+ child.on('error', error => { clearTimeout(timer); reject(error); });
+ child.on('exit', code => { clearTimeout(timer); reject(new Error(`Installed dev exited ${code}: ${output}`)); });
+ child.stdout.on('data', chunk => { output = (output + chunk).slice(-64000); const url = /Plugin dev host: (http:\/\/127\.0\.0\.1:\d+)/.exec(output)?.[1]; if (url) { clearTimeout(timer); resolve(url); } });
+ });
+ const bootstrap = await fetch(`${origin}/api/bootstrap`), boot = await bootstrap.json();
+ const cookie = bootstrap.headers.get('set-cookie').split(';')[0];
+ const post = async (path, body) => {
+ const response = await fetch(`${origin}/api/${path}`, { method: 'POST', headers: { Cookie: cookie, Origin: origin, 'Content-Type': 'application/json', 'X-Mock-Csrf': boot.csrf }, body: JSON.stringify(body) });
+ const result = await response.json(); if (!response.ok) throw new Error(JSON.stringify(result)); return result.value;
+ };
+ const workbench = boot.manifest.contributions.find(c => c.type === 'workbench');
+ let opened;
+ if (template === 'frontend') opened = await post('workbenches/open', { contributionId: workbench.id });
+ else {
+ const provider = boot.manifest.contributions.find(c => c.type === 'connection-provider');
+ const record = { providerId: provider.id, values: Object.fromEntries(provider.fields.filter(f => f.default !== undefined).map(f => [f.key, f.default])) };
+ await post('connections/test', record);
+ const saved = await post('connections/save', record); opened = await post('connections/connect', { id: saved.id });
+ }
+ const frame = await post('frame-document', { frameId: opened.frame.id });
+ const call = (method, params) => post('bridge', { frameId: frame.id, channel: frame.channel, method, params });
+ await call('host.getContext', {});
+ if (template !== 'frontend') {
+ const method = readFileSync(join(project, 'ui/index.html'), 'utf8').match(/\.invoke\("([^\"]+)"/)?.[1];
+ if (!method) throw new Error('Native template has no invoke example');
+ const result = await call('backend.invoke', { method, params: { connectionId: frame.context.connectionId } });
+ if (result.language !== template || !result.ok) throw new Error('Native dev RPC returned unexpected result');
+ }
+ await post('frames/close', { id: frame.id });
+ console.log(`Verified installed ${template} dev runtime without source-tree dependencies.`);
+ } finally {
+ if (child.exitCode === null && !child.signalCode) {
+ await new Promise(resolve => {
+ const timer = setTimeout(() => { if (process.platform === 'win32') spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F']); else { try { process.kill(-child.pid, 'SIGKILL'); } catch {} } }, 7000);
+ child.once('close', () => { clearTimeout(timer); resolve(); });
+ if (process.platform === 'win32') spawn('taskkill', ['/pid', String(child.pid), '/T', '/F']); else process.kill(-child.pid, 'SIGTERM');
+ });
+ }
+ }
+}
+
+function commandAvailable(command) {
+ const result = spawnSync(command, ["version"], { stdio: "ignore" });
+ return !result.error && result.status === 0;
+}
+
+function run(command, args, options = {}) {
+ if (process.platform === "win32" && command === "npm") {
+ args = [process.env.npm_execpath || join(dirname(process.execPath), "node_modules/npm/bin/npm-cli.js"), ...args];
+ command = process.execPath;
+ } else if (process.platform === "win32" && command.endsWith("dbx-plugin.cmd")) {
+ args = [join(dirname(command), "../@dbx-app/plugin-cli/bin/dbx-plugin.js"), ...args];
+ command = process.execPath;
+ }
+ const result = spawnSync(command, args, {
+ cwd: options.cwd ?? repositoryRoot,
+ encoding: "utf8",
+ env: options.env ?? process.env,
+ stdio: options.capture ? "pipe" : "inherit",
+ });
+ if (result.error) throw result.error;
+ if (result.status !== 0) {
+ throw new Error(`${command} ${args.join(" ")} failed with exit code ${result.status}.`);
+ }
+ return result;
+}
diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rs
index 36e7dadc34..5f5cb23814 100644
--- a/src-tauri/src/commands/connection.rs
+++ b/src-tauri/src/commands/connection.rs
@@ -276,6 +276,10 @@ mod tests {
gbase_server: String::new(),
informix_server: String::new(),
external_config: None,
+ plugin_id: None,
+ plugin_connection_provider: None,
+ plugin_connection_type: None,
+ connection_secrets: Default::default(),
jdbc_driver_class: None,
jdbc_driver_paths: Vec::new(),
one_time: false,
@@ -1150,6 +1154,13 @@ async fn test_connection_with_info_inner(
let idle_timeout = std::time::Duration::from_secs(config.idle_timeout_secs);
let gaussdb_m_jdbc_config = gaussdb_m_jdbc_command_config(&config, &host, port);
log::info!("[test_connection] db_type={:?} target={}", config.db_type, target);
+ if config.db_type == DatabaseType::Plugin {
+ let result = state.plugin_host.test_connection(&config, &host, port).await;
+ if has_transport_layers {
+ state.reset_connection_transport_for_config(&tunnel_id, &config).await;
+ }
+ return result;
+ }
let mut database_info = None;
let result = match probe_result {
Err(e) => Err(e),
@@ -1679,7 +1690,9 @@ pub async fn connect_db(
state.reset_connection_transport_for_config(&id, &db_config).await;
return Err(err);
}
- probe_connection_endpoint(&db_config, &host, port).await?;
+ if db_config.db_type != DatabaseType::Plugin {
+ probe_connection_endpoint(&db_config, &host, port).await?;
+ }
if let Err(err) = state.ensure_current_connection_attempt(&id, Some(attempt)).await {
state.reset_connection_transport_for_config(&id, &db_config).await;
return Err(err);
@@ -2026,6 +2039,9 @@ pub async fn connect_db(
DatabaseType::Mqtt => {
return Err("MQTT support is not compiled in this build. Rebuild with the 'mq-admin' feature.".to_string());
}
+ DatabaseType::Plugin => {
+ PoolKind::PluginConnection(state.plugin_host.connect_connection(&db_config, &host, port).await?)
+ }
db_type => return Err(format!("Unsupported database type: {db_type:?}")),
};
diff --git a/src-tauri/src/commands/plugins.rs b/src-tauri/src/commands/plugins.rs
index b9fb457b35..cbf2a5efcb 100644
--- a/src-tauri/src/commands/plugins.rs
+++ b/src-tauri/src/commands/plugins.rs
@@ -1,20 +1,489 @@
use std::sync::Arc;
+use std::time::Duration;
+
+use base64::Engine;
+use serde::Serialize;
use tauri::{Emitter, State};
use dbx_core::agent_service::AgentProgressEvent;
use dbx_core::jdbc::{
self, JdbcDriverInfo, JdbcLocalBundleInfo, JdbcMavenBundleInfo, JdbcMavenInstallRequest, JdbcPluginStatus,
};
-use dbx_core::plugins::InstalledPlugin;
+use dbx_core::models::connection::ConnectionConfig;
+use dbx_core::plugins::{
+ ActivePluginSession, InstalledPlugin, InstalledPluginInfo, PluginConnectionActionResult,
+ PluginFilesystemListResult, PluginFilesystemMutationResult, PluginFilesystemReadResult, PluginInstallPolicy,
+ PluginInstallResponse, PluginMarketplace, PluginMarketplaceInstallRequest, PluginPackageInstaller,
+ PluginRepository, PluginRepositoryCatalogResult, PluginRollbackResponse, PluginTrustStore, PluginTrustedKey,
+ PluginUiAsset,
+};
use super::connection::AppState;
#[tauri::command]
-pub async fn list_plugins(state: State<'_, Arc<AppState>>) -> Result<Vec<InstalledPlugin>, String> {
+pub async fn list_plugins(state: State<'_, Arc<AppState>>) -> Result<Vec<InstalledPluginInfo>, String> {
+ let registry = state.plugins.clone();
+ tauri::async_runtime::spawn_blocking(move || {
+ registry.list_installed().map(|plugins| plugins.into_iter().map(|plugin| plugin.info()).collect())
+ })
+ .await
+ .map_err(|err| err.to_string())?
+}
+
+#[tauri::command]
+pub async fn list_plugin_trusted_keys(state: State<'_, Arc<AppState>>) -> Result<Vec<PluginTrustedKey>, String> {
let root_dir = state.plugins.root_dir().to_path_buf();
- tauri::async_runtime::spawn_blocking(move || dbx_core::plugins::PluginRegistry::new(root_dir).list_installed())
+ tauri::async_runtime::spawn_blocking(move || PluginTrustStore::list_base64_keys(&root_dir))
.await
- .map_err(|err| err.to_string())?
+ .map_err(|error| error.to_string())?
+}
+
+#[tauri::command]
+pub async fn save_plugin_trusted_key(
+ state: State<'_, Arc<AppState>>,
+ key_id: String,
+ public_key: String,
+) -> Result<Vec<PluginTrustedKey>, String> {
+ let root_dir = state.plugins.root_dir().to_path_buf();
+ tauri::async_runtime::spawn_blocking(move || {
+ PluginTrustStore::save_base64_key(&root_dir, &key_id, &public_key)?;
+ PluginTrustStore::list_base64_keys(&root_dir)
+ })
+ .await
+ .map_err(|error| error.to_string())?
+}
+
+#[tauri::command]
+pub async fn remove_plugin_trusted_key(
+ state: State<'_, Arc<AppState>>,
+ key_id: String,
+) -> Result<Vec<PluginTrustedKey>, String> {
+ let root_dir = state.plugins.root_dir().to_path_buf();
+ tauri::async_runtime::spawn_blocking(move || {
+ PluginTrustStore::remove_key(&root_dir, &key_id)?;
+ PluginTrustStore::list_base64_keys(&root_dir)
+ })
+ .await
+ .map_err(|error| error.to_string())?
+}
+
+#[tauri::command]
+pub async fn list_plugin_repositories(state: State<'_, Arc<AppState>>) -> Result<Vec<PluginRepository>, String> {
+ let root_dir = state.plugins.root_dir().to_path_buf();
+ let app_version = state.plugins.app_version().to_string();
+ tauri::async_runtime::spawn_blocking(move || PluginMarketplace::new(root_dir, app_version)?.repositories().list())
+ .await
+ .map_err(|error| error.to_string())?
+}
+
+#[tauri::command]
+pub async fn save_plugin_repository(
+ state: State<'_, Arc<AppState>>,
+ repository: PluginRepository,
+) -> Result<Vec<PluginRepository>, String> {
+ let root_dir = state.plugins.root_dir().to_path_buf();
+ let app_version = state.plugins.app_version().to_string();
+ tauri::async_runtime::spawn_blocking(move || {
+ PluginMarketplace::new(root_dir, app_version)?.repositories().save(repository)
+ })
+ .await
+ .map_err(|error| error.to_string())?
+}
+
+#[tauri::command]
+pub async fn remove_plugin_repository(
+ state: State<'_, Arc<AppState>>,
+ repository_id: String,
+) -> Result<Vec<PluginRepository>, String> {
+ let root_dir = state.plugins.root_dir().to_path_buf();
+ let app_version = state.plugins.app_version().to_string();
+ tauri::async_runtime::spawn_blocking(move || {
+ PluginMarketplace::new(root_dir, app_version)?.repositories().remove(&repository_id)
+ })
+ .await
+ .map_err(|error| error.to_string())?
+}
+
+#[tauri::command]
+pub async fn fetch_plugin_marketplace_catalogs(
+ state: State<'_, Arc<AppState>>,
+) -> Result<Vec<PluginRepositoryCatalogResult>, String> {
+ let marketplace =
+ PluginMarketplace::new(state.plugins.root_dir().to_path_buf(), state.plugins.app_version().to_string())?;
+ Ok(marketplace.fetch_catalogs().await)
+}
+
+#[tauri::command]
+pub async fn install_marketplace_plugin(
+ state: State<'_, Arc<AppState>>,
+ request: PluginMarketplaceInstallRequest,
+) -> Result<PluginInstallResponse, String> {
+ let marketplace =
+ PluginMarketplace::new(state.plugins.root_dir().to_path_buf(), state.plugins.app_version().to_string())?;
+ let result = marketplace.install(request).await?;
+ stop_replaced_plugin_runtime(&state, &result.plugin).await;
+ Ok(result.response())
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginUiAssetPayload {
+ content_type: String,
+ data_base64: String,
+ etag: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PluginBinaryEventPayload {
+ plugin_id: String,
+ channel: String,
+ data_base64: String,
+}
+
+pub fn install_plugin_event_bridge(app: &tauri::AppHandle, state: Arc<AppState>) {
+ let app_handle = app.clone();
+ let mut events = state.plugin_host.subscribe_events();
+ tauri::async_runtime::spawn(async move {
+ loop {
+ match events.recv().await {
+ Ok(event) => {
+ let _ = app_handle.emit("dbx-plugin-event", event);
+ }
+ Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
+ log::warn!("Desktop plugin event bridge skipped {skipped} events");
+ }
+ Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
+ }
+ }
+ });
+
+ let app_handle = app.clone();
+ let mut binary = state.plugin_host.subscribe_binary();
+ tauri::async_runtime::spawn(async move {
+ loop {
+ match binary.recv().await {
+ Ok(message) => {
+ let payload = PluginBinaryEventPayload {
+ plugin_id: message.plugin_id,
+ channel: message.channel,
+ data_base64: base64::engine::general_purpose::STANDARD.encode(message.data),
+ };
+ let _ = app_handle.emit("dbx-plugin-binary", payload);
+ }
+ Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
+ log::warn!("Desktop plugin binary bridge skipped {skipped} messages");
+ }
+ Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
+ }
+ }
+ });
+}
+
+#[tauri::command]
+pub async fn install_plugin_package(
+ state: State<'_, Arc<AppState>>,
+ path: String,
+ allow_unsigned: bool,
+) -> Result<PluginInstallResponse, String> {
+ let root_dir = state.plugins.root_dir().to_path_buf();
+ let app_version = state.plugins.app_version().to_string();
+ let policy = if allow_unsigned { PluginInstallPolicy::LocalDevelopment } else { PluginInstallPolicy::LocalSigned };
+ let path = std::path::PathBuf::from(path);
+ let result = tauri::async_runtime::spawn_blocking(move || {
+ PluginPackageInstaller::new(root_dir, app_version)?.install_file(&path, policy)
+ })
+ .await
+ .map_err(|error| error.to_string())??;
+ stop_replaced_plugin_runtime(&state, &result.plugin).await;
+ Ok(result.response())
+}
+
+#[tauri::command]
+pub async fn rollback_plugin(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+) -> Result<PluginRollbackResponse, String> {
+ state.remove_plugin_connection_pools(&plugin_id).await;
+ state.plugin_host.stop(&plugin_id).await;
+ let root_dir = state.plugins.root_dir().to_path_buf();
+ let app_version = state.plugins.app_version().to_string();
+ let result = tauri::async_runtime::spawn_blocking(move || {
+ PluginPackageInstaller::new(root_dir, app_version)?.rollback(&plugin_id)
+ })
+ .await
+ .map_err(|error| error.to_string())??;
+ stop_external_driver_pools(&state, &result.plugin).await;
+ Ok(result.response())
+}
+
+#[tauri::command]
+pub async fn uninstall_plugin(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+) -> Result<Vec<InstalledPluginInfo>, String> {
+ let dependent_connections = state
+ .storage
+ .load_connections()
+ .await?
+ .into_iter()
+ .filter(|connection| {
+ connection.db_type == dbx_core::models::connection::DatabaseType::Plugin
+ && connection.plugin_id.as_deref() == Some(plugin_id.as_str())
+ })
+ .map(|connection| connection.name)
+ .collect::<Vec<_>>();
+ if !dependent_connections.is_empty() {
+ return Err(format!(
+ "Cannot uninstall plugin '{plugin_id}' while these connections still use it: {}",
+ dependent_connections.join(", ")
+ ));
+ }
+ let plugin = state.plugins.find_plugin(&plugin_id)?;
+ state.remove_plugin_connection_pools(&plugin_id).await;
+ state.plugin_host.stop(&plugin_id).await;
+ if let Some(plugin) = &plugin {
+ stop_external_driver_pools(&state, plugin).await;
+ }
+ let root_dir = state.plugins.root_dir().to_path_buf();
+ let app_version = state.plugins.app_version().to_string();
+ tauri::async_runtime::spawn_blocking(move || {
+ PluginPackageInstaller::new(root_dir, app_version)?.uninstall(&plugin_id)
+ })
+ .await
+ .map_err(|error| error.to_string())??;
+ list_plugins(state).await
+}
+
+#[tauri::command]
+pub async fn activate_plugin(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+) -> Result<Vec<ActivePluginSession>, String> {
+ state.plugin_host.activate(&plugin_id).await?;
+ Ok(state.plugin_host.list_active().await)
+}
+
+#[tauri::command]
+pub async fn list_active_plugins(state: State<'_, Arc<AppState>>) -> Result<Vec<ActivePluginSession>, String> {
+ Ok(state.plugin_host.list_active().await)
+}
+
+#[tauri::command]
+pub async fn stop_plugin(state: State<'_, Arc<AppState>>, plugin_id: String) -> Result<(), String> {
+ state.plugin_host.stop(&plugin_id).await;
+ Ok(())
+}
+
+#[tauri::command]
+pub async fn invoke_plugin(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+ method: String,
+ params: serde_json::Value,
+ timeout_ms: Option<u64>,
+) -> Result<serde_json::Value, String> {
+ let timeout = timeout_ms.map(|milliseconds| Duration::from_millis(milliseconds.clamp(1, 120_000)));
+ state.plugin_host.invoke(&plugin_id, &method, params, None, timeout).await
+}
+
+#[tauri::command]
+pub async fn invoke_plugin_connection_action(
+ state: State<'_, Arc<AppState>>,
+ config: ConnectionConfig,
+ action_id: String,
+) -> Result<PluginConnectionActionResult, String> {
+ state.invoke_plugin_connection_action(config, &action_id).await
+}
+
+#[tauri::command]
+pub async fn notify_plugin(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+ method: String,
+ params: serde_json::Value,
+) -> Result<(), String> {
+ state.plugin_host.notify(&plugin_id, &method, params, None).await
+}
+
+#[tauri::command]
+pub async fn send_plugin_binary(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+ channel: String,
+ data_base64: String,
+) -> Result<(), String> {
+ let data = base64::engine::general_purpose::STANDARD
+ .decode(data_base64)
+ .map_err(|error| format!("Invalid plugin binary payload: {error}"))?;
+ state.plugin_host.send_binary(&plugin_id, &channel, &data, None).await
+}
+
+#[tauri::command]
+pub async fn list_plugin_filesystem_entries(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+ provider_id: String,
+ connection_id: Option<String>,
+ uri: Option<String>,
+ cursor: Option<String>,
+ limit: Option<u32>,
+) -> Result<PluginFilesystemListResult, String> {
+ state
+ .plugin_host
+ .list_filesystem_entries(
+ &plugin_id,
+ &provider_id,
+ connection_id.as_deref(),
+ uri.as_deref(),
+ cursor.as_deref(),
+ limit,
+ )
+ .await
+}
+
+#[tauri::command]
+pub async fn read_plugin_filesystem_file(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+ provider_id: String,
+ connection_id: Option<String>,
+ uri: String,
+ max_bytes: Option<u64>,
+) -> Result<PluginFilesystemReadResult, String> {
+ state.plugin_host.read_filesystem_file(&plugin_id, &provider_id, connection_id.as_deref(), &uri, max_bytes).await
+}
+
+#[tauri::command]
+pub async fn write_plugin_filesystem_file(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+ provider_id: String,
+ connection_id: Option<String>,
+ uri: String,
+ data_base64: String,
+ create: bool,
+ overwrite: bool,
+ etag: Option<String>,
+) -> Result<PluginFilesystemMutationResult, String> {
+ state
+ .plugin_host
+ .write_filesystem_file(
+ &plugin_id,
+ &provider_id,
+ connection_id.as_deref(),
+ &uri,
+ &data_base64,
+ create,
+ overwrite,
+ etag.as_deref(),
+ )
+ .await
+}
+
+#[tauri::command]
+pub async fn create_plugin_filesystem_directory(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+ provider_id: String,
+ connection_id: Option<String>,
+ uri: String,
+) -> Result<PluginFilesystemMutationResult, String> {
+ state.plugin_host.create_filesystem_directory(&plugin_id, &provider_id, connection_id.as_deref(), &uri).await
+}
+
+#[tauri::command]
+pub async fn delete_plugin_filesystem_entry(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+ provider_id: String,
+ connection_id: Option<String>,
+ uri: String,
+ recursive: bool,
+) -> Result<PluginFilesystemMutationResult, String> {
+ state.plugin_host.delete_filesystem_entry(&plugin_id, &provider_id, connection_id.as_deref(), &uri, recursive).await
+}
+
+#[tauri::command]
+pub async fn rename_plugin_filesystem_entry(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+ provider_id: String,
+ connection_id: Option<String>,
+ source_uri: String,
+ target_uri: String,
+ overwrite: bool,
+) -> Result<PluginFilesystemMutationResult, String> {
+ state
+ .plugin_host
+ .rename_filesystem_entry(
+ &plugin_id,
+ &provider_id,
+ connection_id.as_deref(),
+ &source_uri,
+ &target_uri,
+ overwrite,
+ )
+ .await
+}
+
+#[tauri::command]
+pub async fn read_plugin_ui_entry(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+) -> Result<PluginUiAssetPayload, String> {
+ let registry = state.plugins.clone();
+ let asset = tauri::async_runtime::spawn_blocking(move || registry.read_ui_entry(&plugin_id))
+ .await
+ .map_err(|error| error.to_string())??;
+ Ok(asset_payload(asset))
+}
+
+#[tauri::command]
+pub async fn read_plugin_asset(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+ path: String,
+) -> Result<PluginUiAssetPayload, String> {
+ let registry = state.plugins.clone();
+ let asset = tauri::async_runtime::spawn_blocking(move || registry.read_asset(&plugin_id, &path))
+ .await
+ .map_err(|error| error.to_string())??;
+ Ok(asset_payload(asset))
+}
+
+#[tauri::command]
+pub async fn read_plugin_ui_asset(
+ state: State<'_, Arc<AppState>>,
+ plugin_id: String,
+ path: String,
+) -> Result<PluginUiAssetPayload, String> {
+ let registry = state.plugins.clone();
+ let asset = tauri::async_runtime::spawn_blocking(move || registry.read_ui_asset(&plugin_id, &path))
+ .await
+ .map_err(|error| error.to_string())??;
+ Ok(asset_payload(asset))
+}
+
+fn asset_payload(asset: PluginUiAsset) -> PluginUiAssetPayload {
+ PluginUiAssetPayload {
+ content_type: asset.content_type,
+ data_base64: base64::engine::general_purpose::STANDARD.encode(asset.bytes),
+ etag: asset.etag,
+ }
+}
+
+async fn stop_replaced_plugin_runtime(state: &Arc<AppState>, plugin: &InstalledPlugin) {
+ state.remove_plugin_connection_pools(&plugin.manifest.id).await;
+ stop_external_driver_pools(state, plugin).await;
+ state.plugin_host.stop(&plugin.manifest.id).await;
+}
+
+async fn stop_external_driver_pools(state: &Arc<AppState>, plugin: &InstalledPlugin) {
+ for driver in &plugin.manifest.drivers {
+ let driver_id = driver.database_type.as_deref().unwrap_or(&driver.id);
+ state.remove_external_driver_pools(driver_id).await;
+ }
}
#[tauri::command]
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 9bc0d598a5..e8d94383fc 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1604,6 +1604,7 @@ pub fn run() {
}));
let state = Arc::new(state);
app.manage(state.clone());
+ commands::plugins::install_plugin_event_bridge(app.handle(), state.clone());
let mcp_http_server = Arc::new(commands::mcp_http_server::McpHttpServerState::new(data_dir.clone()));
app.manage(mcp_http_server.clone());
let mcp_http_state = state.clone();
@@ -1811,6 +1812,33 @@ pub fn run() {
commands::connection::save_sidebar_layout,
commands::connection::load_sidebar_layout,
commands::plugins::list_plugins,
+ commands::plugins::list_plugin_trusted_keys,
+ commands::plugins::save_plugin_trusted_key,
+ commands::plugins::remove_plugin_trusted_key,
+ commands::plugins::list_plugin_repositories,
+ commands::plugins::save_plugin_repository,
+ commands::plugins::remove_plugin_repository,
+ commands::plugins::fetch_plugin_marketplace_catalogs,
+ commands::plugins::install_marketplace_plugin,
+ commands::plugins::install_plugin_package,
+ commands::plugins::rollback_plugin,
+ commands::plugins::uninstall_plugin,
+ commands::plugins::activate_plugin,
+ commands::plugins::list_active_plugins,
+ commands::plugins::stop_plugin,
+ commands::plugins::invoke_plugin,
+ commands::plugins::invoke_plugin_connection_action,
+ commands::plugins::notify_plugin,
+ commands::plugins::send_plugin_binary,
+ commands::plugins::list_plugin_filesystem_entries,
+ commands::plugins::read_plugin_filesystem_file,
+ commands::plugins::write_plugin_filesystem_file,
+ commands::plugins::create_plugin_filesystem_directory,
+ commands::plugins::delete_plugin_filesystem_entry,
+ commands::plugins::rename_plugin_filesystem_entry,
+ commands::plugins::read_plugin_ui_entry,
+ commands::plugins::read_plugin_asset,
+ commands::plugins::read_plugin_ui_asset,
commands::plugins::list_jdbc_drivers,
commands::plugins::list_jdbc_maven_bundles,
commands::plugins::list_jdbc_local_bundles,