Files
Reims-Go/internal/plugin/contract.go
T
球球 7fd1947bef feat(plugin,host,macos,ui): 实现 Agent 受控接管、受保护阶段确认、离线预配置与自动装机基础 (#103, #105, #129) (#134)
* feat(plugin,host,ui): add agent session takeover, protected-phase confirmation, and autoinstall host foundation

* feat(macos,ui,cli): add offline REIMSPROV first-boot provisioning to skip Setup Assistant (#129)

Builds a per-VM read-only REIMSPROV disk image containing a pure-Go XAR Distribution flat package (provision.pkg) and an offline Recovery fallback script (provision-offline.sh). Passwords are hashed in memory to Apple SALTED-SHA512-PBKDF2 bplist00 ShadowHashData (never persisted in plaintext, no auto-login or NOPASSWD sudo). Uses native OpenDirectory.framework (JXA NSData) + dseditgroup under SIP-enabled live bootinstalld and dslocal plist + PlistBuddy under offline Recovery, skips Setup Assistant and Keyboard Setup Assistant, pre-stages Guest Tools, integrates with CreateWizard / VMPage / vm provision CLI / StartAutoInstall, and zero-wipes on finish_install, normal cold start, or DeleteVM.

* feat(autoinstall,host,ui): add input-locked session shield, recovery-only mode, and restart grace cap

Adds the real-machine end-to-end verified baseline for automatic macOS installation: (1) takeover_policy 'lock' with transparent Win32 VM client-area input shield, low-level key/mouse lock preserving host escape shortcuts (Alt+Tab/Alt+Esc/Win), HUD & UI Pause/Resume controls, and write guards while paused; (2) decoupled recovery_only vs full (REIMSPROV) modes in StartAutoInstall, CreateWizard, and VMAutoInstallPanel; (3) graceful_timeout_sec cap (default 10s) on automated built-in macOS host/vm.restart so Setup Assistant/Login Window restarts do not stall 90s on ACPI; (4) additional modifier aliases in console manager and agent-session/telemetry cleanup on VM deletion.

* feat(autoinstall,overlay,plugin): add built-in macOS auto-install plugin, dynamic island overlay, and review fixes

* fix(app,host,macos,ui): address PR #134 automated review findings

- Frontend & i18n:
  - Fix UTF-8/GBK mojibake in VMPage.tsx.
  - Emit reims:confirm-resolved on timeout/cancel/resolve so frontend modals auto-close and surface errors cleanly; stop submitCreate from continuing after PrepareVMProvision failure.
  - Gate AutoInstallPanel RapidOCR download button on preflight can_download_ocr when pinned default assets are unavailable.
- App / Sessions / Confirm / Lifecycle:
  - Add 30s denial cooldown for protected-phase confirmation prompts and revoke (pluginID, vmKey) grants on non-completed session exits.
  - Fix sessionOverlay / activeAgentSessions data race, remove duplicate permission-denied invocation, guard against clobbering other sessions or completed overlays, and unify VM key normalization.
  - Grant protected-phase confirmation and attach lock-mode session + watcher when resuming auto-install without an active session.
  - Unify FinishInstall and host/vm.finishInstall result handling and persist .reims-go-provision-ready across restarts.
  - Preserve non-timeout stop errors in restartMacOSVMLocked instead of force-killing.
- Host Takeover Hooks:
  - Require both keyboard and mouse WH_*_LL hooks (rolling back partial installs), initialize thread message queue before ready, reset started state on error/exit for retry, and report hook failures.
- macOS Provisioning & Autoinstall Engine:
  - Track REIMSPROV staged/wipe-pending/ready lifecycle markers, exclude "restore" recovery marker from re-attaching REIMSPROV, fail explicitly on offline admin plist creation failure, and report wipe failures.
  - Serialize per-VM Start/Stop/Resume with stop generation tokens, guard ROI fast-path against maxDim overflow, switch hostclient early-event buffer to FIFO eviction, fix untyped nil Engine return, tighten negation & high-risk fuzzy matching, preserve ackedQemuErrors across RebootWindow resets, and re-orient/expire stale inherited running checkpoints.
  - Document verified Windows SDK IDL vtable slots for WinOCR (live-tested on Windows) and add regression tests across app, host, macosdriver, startprep, installer, and autoinstall packages.

* fix(app,cli,host,macos,ui): address PR #134 second automated review findings

- CLI & Desktop Control Channel:
  - Add __reims_host__ / autoinstall desktop control channel with data_root verification so CLI status, resume, and stop talk directly to the live desktop runner instead of splitting checkpoint state or launching doomed short-lived CLI runners.
  - Merge live runners with on-disk checkpoints when listing status without a VM argument.
- App Sessions, Confirmations, Downloads & Telemetry:
  - Scope single-VM not_authorized errors to the target VM in handleSessionBegin and resolveComputerUseVM so active sessions on other VMs are not aborted.
  - Exclude stopped and suspended VMs from hasUnboundAgentSession fast-polling.
  - Revoke protected-phase grants when a VM disappears from poll results.
  - Require manifest Secret:true validation before storing auto-install passwords and remove the unsafe default account_password fallback.
  - Reject userinfo URLs in allow_custom_mirror, gate custom-mirror exemption strictly on plugin.ErrNetOriginNotDeclared, and keep redirect SSRF checks enabled on loopback custom mirrors.
  - Preserve VM telemetry milestones across suspend-resume and Win10 cold-reboot restarts while still resetting on fresh cold boots.
  - Log a warning when Guest Tools bridge is unavailable while preparing REIMSPROV.
  - Clarify CallHostAPI authorization/audit contract and add regression test proving built-in plugins enforce catalog permissions and audit logging.
- Host Takeover & Guest Tools:
  - Track locked mouse button presses via a 5-button bitmask so ButtonUp events from drags started outside the VM window are never swallowed.
  - Align active-window-reporter.js permissions to 0o100755 across ToolsDiskFiles, ToolsProvisionFiles, and postinstall.
- macOS Provisioning & Autoinstall Engine (OCR / Vision / Rules / Runner):
  - Never delete an unwiped REIMSPROV image on OpenFile/Write/Sync failure; persist wipe-pending marker and return error for retry.
  - Harden live postinstall preference writes with chmod 600, plutil -lint, chown, and cfprefsd flush.
  - Rewrite Windows RapidOCR C ABI structs and result extraction to match RapidAI/RapidOcrOnnx@675e73fe4c include/OcrLiteCApi.h:27-70 and src/OcrLiteCApi.cpp:12-160 (5-arg OcrInit verified).
  - Inspect PE32/PE32+ IMAGE_DIRECTORY_ENTRY_IMPORT directly to require onnxruntime.dll only for dynamically linked RapidOcrOnnx.dll builds.
  - Validate cfg.VM and use collision-free SHA-256-suffixed checkpoint paths with read fallback; redact PII/paths/UUIDs/MACs/IPs/tokens in diagnostic summaries; snapshot checkpoints before releasing r.mu for serialized disk I/O.
  - Add contrast/border/focus-ring ok return to DetectInputFieldNearLabel, enforce mask-dots verification in fillAccountForm and login screens, refuse blind password typing on clock-only lock screens, confirm shell readiness before typing install.sh, and prefer isolated button lines over modal prose in FindHit.
- Frontend:
  - Require explicit Apple SLA confirmation in both recovery_only and full modes across AutoInstallPanel and CreateWizard, with unit tests in frontend/scripts/test-autoinstall.mjs.

* fix(app,cli,host,macos,ui): address PR #134 third automated review findings

Addresses all confirmed findings from Review #6204465334 (commit d516350)
with targeted regression tests and hardens verified COM vtable bindings:

- App & Session Lifecycle:
  - Track hostPaused separately in agentSession so plugin host/session.update
    (paused_for_user=false) cannot clear physical user takeover or explicit
    PauseAgentSession holds; only host ResumeAgentSession or timed takeover
    expiry clears them.
  - Give each auto-install session watcher a monotonic watchGen + cancelable
    child context so restarting/resuming auto-install on the same VM cancels
    any superseded watcher and prevents stale timeout or secret cleanup.
  - Bound fast 500ms unbound-PID discovery for running VMs to
    sessionDiscoverGraceWindow via unboundSince (refreshed on restart/rebind).
  - Keep non-blocking buffered confirm resolution send inside confirmMu for
    clear mutual exclusion with cancelPendingConfirmations.
  - Clear cold-reboot telemetry preserveNextBoot via defer on all early-return
    and StartVM-failure paths in watchColdReboot.
  - Rebuild REIMSPROV with current StartAutoInstall credentials (preserving
    install_guest_tools) whenever VM is stopped instead of reusing stale images.
- CLI & macOS Provisioning / StartPrep:
  - Refuse `vm provision --clear` and overwriting existing REIMSPROV while the
    VM is running or paused.
  - Guard live "/" root in postinstall against macOS Recovery/Installer
    (/System/Installation/CDIS), forbid "/" in provision-offline.sh, and scope
    chmod 644 strictly to com.apple.keyboardtype.plist.
  - Reject unknown -* options in REIMSHELP/install.sh (including after --erase).
  - Defer clearing the one-shot REIMSPROV staged marker until after
    setExtraArgs (startprep) and StartWithCompat (macosdriver) succeed.
  - Preserve pending RestartFrom guards in AdvancePostInstallHandoff when
    checkpoint is already at StepDesktop.
- Host Input & Session Overlay:
  - Filter injected keyboard events (LLKHF_INJECTED / LLKHF_LOWER_IL_INJECTED)
    in locked-input mode consistently with the mouse hook.
  - Clean up exited overlay entries in entry.run() and recreate dead entries on
    Manager.Upsert when CreateWindowExW fails or exits early.
  - Cache the static island base surface (shell + icons + DirectWrite text) and
    measured text metrics across breathing frames, raising timerBreathMs to 100ms.
  - Replace magic Direct2D/DirectWrite vtable indices with named d2d1.h /
    dwrite.h constants, check EndDraw HRESULT, and add a live Windows DirectWrite
    rendering smoke test.
- Autoinstall OCR, Rules, Watchdog & Runner:
  - Persist and verify a per-file SHA-256 manifest.json in <dataDir>/ocr/
    before loading RapidOcrOnnx.dll / onnxruntime.dll; reject duplicate
    whitelisted basenames in offline zip imports.
  - Signal WinOCREngine.Close() before acquiring e.mu and add bounded wait +
    channel wakeup in Recognize so Close() immediately cancels in-flight OCR.
  - Fall back to installed RapidOCR when WinOCR initialization fails in Open(),
    and distinguish needs_rapidocr_import from needs_rapidocr_download in Probe.
  - Pause instead of pressing Return when post-TypeSecret login screenshot fails.
  - Re-baseline ColdRebootCount in Watchdog.ResetRebootWindow / ResetAfterResume.
  - Tighten recovery.main specificity (drop bare "Disk Utility"), guard 4-5 char
    pure-ASCII needles from sliding-window fuzzy collisions, use Unicode word
    boundaries for short names (<4 runes) in RedactDiagnosticText, and honor
    rule verify.wait_change_ms with early exit on visual frame diff.

* fix(autoinstall): handle CJK short-name redaction, sh-3.2 prompt bound, and OCR re-import pruning
2026-12-06 15:46:39 +08:00

599 lines
23 KiB
Go

package plugin
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"regexp"
"sort"
"strings"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
// Contract catalogs (see docs/plugin-architecture.md).
//
// Every public contract entry is either stable or experimental. Stable entries
// are implemented by the host and covered by the compatibility promise;
// experimental entries are part of the published shape, accepted by manifest
// validation, reported by `plugin doctor`, and not yet acted on. An entry is
// promoted in the same change that implements it. Slots, layout options, icon
// names and view locations mirror frontend/src/styles/ui-contract.ts, bridge
// methods mirror frontend/src/lib/bridgeContract.ts; contract_test.go keeps
// them identical.
// ContractStatus marks whether a contract entry is implemented.
type ContractStatus string
const (
ContractStable ContractStatus = "stable"
ContractExperimental ContractStatus = "experimental"
)
// ContributionCatalog lists every `contributes` key (its JSON name).
var ContributionCatalog = map[string]ContractStatus{
"themes": ContractStable,
"channels": ContractStable,
"uiScripts": ContractExperimental, // theme.uiScript is the implemented path
"locales": ContractStable,
"inputFilters": ContractStable,
"vmTemplates": ContractExperimental,
"runtimeSources": ContractExperimental,
"runtimeKinds": ContractStable,
"runtimes": ContractExperimental,
"guestDrivers": ContractStable,
"downloaders": ContractStable,
"hooks": ContractStable,
"ruleHooks": ContractStable,
"commands": ContractStable,
"menus": ContractStable,
"vmCards": ContractExperimental,
"settingsPages": ContractExperimental,
"statusItems": ContractExperimental,
"panels": ContractStable,
"imageSources": ContractStable,
"autoInstallers": ContractStable,
"views": ContractStable,
"diagnostics": ContractExperimental,
}
// ThemeFieldCatalog lists theme fields whose host support is still pending.
// Fields not listed here are stable.
var ThemeFieldCatalog = map[string]ContractStatus{
"icons": ContractStable,
"brandMark": ContractStable,
"layout": ContractStable,
}
// Slot content kinds.
const (
SlotDecoration = "decoration" // theme decorations
SlotMount = "mount" // UI SDK mountSlot
SlotPanel = "panel" // panels
SlotMenu = "menu" // menus
SlotStatusItem = "statusItem" // statusItems
SlotVMCard = "vmCard" // vmCards
SlotSettingsPage = "settingsPage" // settingsPages
)
// SlotSpec describes one UI slot: whether its anchor is rendered (Status),
// how many plugin items it takes, and which content kinds it accepts.
type SlotSpec struct {
Status ContractStatus
Max int
Accepts map[string]ContractStatus
}
func anchorSlot(status ContractStatus, max int, extra map[string]ContractStatus) SlotSpec {
accepts := map[string]ContractStatus{SlotDecoration: status, SlotMount: status}
for k, v := range extra {
accepts[k] = v
}
return SlotSpec{Status: status, Max: max, Accepts: accepts}
}
// UISlotCatalog lists every supported UI slot and accepted contribution kinds.
var UISlotCatalog = map[string]SlotSpec{
"sidebar.footer": anchorSlot(ContractStable, 2, map[string]ContractStatus{SlotPanel: ContractExperimental}),
"statusbar.right": anchorSlot(ContractStable, 4, map[string]ContractStatus{SlotStatusItem: ContractExperimental}),
"vm.card": anchorSlot(ContractStable, 6, map[string]ContractStatus{SlotVMCard: ContractExperimental, SlotPanel: ContractExperimental}),
"settings.plugin": anchorSlot(ContractStable, 16, map[string]ContractStatus{SlotPanel: ContractStable, SlotSettingsPage: ContractExperimental}),
"vm.preview.tl": anchorSlot(ContractStable, 2, nil),
"vm.preview.tr": anchorSlot(ContractStable, 2, nil),
"vm.preview.bl": anchorSlot(ContractStable, 2, nil),
"vm.preview.br": anchorSlot(ContractStable, 2, nil),
"empty.state": anchorSlot(ContractStable, 2, nil),
"titlebar.center": anchorSlot(ContractStable, 1, nil),
"sidebar.header": anchorSlot(ContractStable, 2, nil),
"nav.item.trailing": anchorSlot(ContractStable, 2, nil),
"vm.header.trailing": anchorSlot(ContractStable, 4, map[string]ContractStatus{SlotMenu: ContractExperimental}),
"vm.toolbar": anchorSlot(ContractStable, 8, map[string]ContractStatus{SlotMenu: ContractStable}),
"statusbar.left": anchorSlot(ContractStable, 4, map[string]ContractStatus{SlotStatusItem: ContractExperimental}),
"create.source": anchorSlot(ContractStable, 4, map[string]ContractStatus{SlotPanel: ContractExperimental}),
}
// ViewLocationSpec describes one place a plugin view can appear.
type ViewLocationSpec struct {
Status ContractStatus
PerPlugin int // views one plugin may declare at this location
}
// ViewLocationCatalog lists `views[].location` values.
var ViewLocationCatalog = map[string]ViewLocationSpec{
"sidebar": {Status: ContractStable, PerPlugin: 2},
"vm.tab": {Status: ContractStable, PerPlugin: 4},
"settings": {Status: ContractStable, PerPlugin: 1},
"dialog": {Status: ContractStable, PerPlugin: 8},
}
// UILayerCatalog lists full-window layers.
var UILayerCatalog = map[string]ContractStatus{
"layer.background": ContractStable,
"layer.overlay": ContractStable,
}
// ThemeLayoutCatalog lists theme `layout` options and their allowed values.
var ThemeLayoutCatalog = map[string][]string{
"sidebarPosition": {"left", "right"},
"sidebarMode": {"full", "rail", "floating"},
"density": {"compact", "regular", "comfortable"},
"titlebar": {"standard", "compact"},
}
// ThemeIconNames lists icon names a theme `icons` map may override.
var ThemeIconNames = []string{
"start", "stop", "force-stop", "restart", "suspend", "resume", "new-vm",
"settings", "plugin", "folder", "logs", "screenshot", "fullscreen", "window",
"snapshot", "clone", "delete", "info", "warning", "error",
"vm.state.running", "vm.state.stopped", "vm.state.suspended", "vm.state.busy", "vm.state.error",
"guest-linux", "guest-windows", "guest-android", "remote-desktop", "remote-control", "terminal",
}
// GuestDriverFieldCatalog lists `guestDrivers[]` fields whose host support is
// not stable. Fields not listed here are stable.
var GuestDriverFieldCatalog = map[string]ContractStatus{
"consoleEndpoint": ContractStable, // console router: qmp proxy or a driver-served console
"pasteCombo": ContractStable,
"keymap": ContractStable,
}
// HostCapabilityCatalog lists the driver-side and Host API features added by
// pluginApi 1.1 and 1.2. Stable entries are advertised as `driver.*` / `host.*`
// features in the Sidecar handshake.
var HostCapabilityCatalog = map[string]ContractStatus{
"driver.snapshot": ContractStable,
"driver.clone": ContractStable,
"driver.disk": ContractStable,
"driver.logs": ContractStable,
"driver.phase": ContractStable,
"driver.runtimeKind.external": ContractStable,
"driver.pasteCombo": ContractStable,
"driver.keymap": ContractStable,
"driver.hosted": ContractStable,
"host.vm.spawn.ref": ContractStable,
"host.vm.reportState": ContractStable,
"driver.console": ContractStable,
"host.download": ContractStable,
"host.download.timeouts": ContractStable,
"host.download.customMirror": ContractStable,
"host.elevate.request": ContractStable,
"host.secret.materialize": ContractStable,
"host.ui.confirm": ContractStable,
"host.session": ContractStable,
"host.console.screenshot.region": ContractStable,
"host.vm.finishInstall": ContractStable,
"host.vm.restart": ContractStable,
"host.vm.telemetry": ContractStable,
"event.vm.phaseChanged": ContractStable,
}
// BridgeMethodSpec describes one plugin UI bridge method.
type BridgeMethodSpec struct {
Status ContractStatus
Permission string // "" = always allowed for the calling plugin's own data
}
// BridgeMethodCatalog lists bridgeApi 1.0 methods.
var BridgeMethodCatalog = map[string]BridgeMethodSpec{
"hello": {Status: ContractStable},
"i18n.getBundle": {Status: ContractStable},
"ui.notify": {Status: ContractStable, Permission: "ui:notify"},
"ui.confirm": {Status: ContractStable, Permission: "ui:notify"},
"ui.copy": {Status: ContractStable, Permission: "ui:slot"},
"ui.openExternal": {Status: ContractStable, Permission: "ui:slot"},
"vm.list": {Status: ContractStable, Permission: "vm:read"},
"command.invoke": {Status: ContractStable, Permission: "ui:slot"},
"storage.get": {Status: ContractStable, Permission: "fs:plugin_data"},
"storage.set": {Status: ContractStable, Permission: "fs:plugin_data"},
"storage.list": {Status: ContractStable, Permission: "fs:plugin_data"},
"storage.delete": {Status: ContractStable, Permission: "fs:plugin_data"},
"ui.showForm": {Status: ContractStable, Permission: "ui:slot"},
"ui.setTitle": {Status: ContractStable, Permission: "ui:slot"},
"ui.setBadge": {Status: ContractStable, Permission: "ui:slot"},
"ui.openView": {Status: ContractStable, Permission: "ui:slot"},
"ui.close": {Status: ContractStable, Permission: "ui:slot"},
"ui.navigate": {Status: ContractStable, Permission: "ui:slot"},
"vm.get": {Status: ContractStable, Permission: "vm:read"},
"settings.get": {Status: ContractStable},
"settings.set": {Status: ContractStable},
"file.pick": {Status: ContractStable, Permission: "fs:pick"},
"file.save": {Status: ContractStable, Permission: "fs:pick"},
"file.read": {Status: ContractStable, Permission: "fs:pick"},
"file.write": {Status: ContractStable, Permission: "fs:pick"},
"task.start": {Status: ContractStable, Permission: "task:progress"},
"task.update": {Status: ContractStable, Permission: "task:progress"},
"task.finish": {Status: ContractStable, Permission: "task:progress"},
"net.fetch": {Status: ContractStable, Permission: "net:"}, // matched against net:<origin>
"events.subscribe": {Status: ContractStable},
"events.unsubscribe": {Status: ContractStable},
}
// BridgeMethodAliases maps pre-1.0 method names to their bridgeApi 1.0 names.
var BridgeMethodAliases = map[string]string{"notify": "ui.notify"}
// BridgeEventCatalog lists bridgeApi 1.0 events.
var BridgeEventCatalog = map[string]ContractStatus{
"theme.changed": ContractStable,
"locale.changed": ContractStable,
"vm.stateChanged": ContractStable,
"view.visibilityChanged": ContractStable,
"task.updated": ContractStable,
}
// ResolveBridgeMethod maps an incoming method name to its catalog entry.
func ResolveBridgeMethod(method string) (string, BridgeMethodSpec, bool) {
if to, ok := BridgeMethodAliases[method]; ok {
method = to
}
spec, ok := BridgeMethodCatalog[method]
return method, spec, ok
}
// HostFeatures lists the stable host features advertised in the Sidecar and
// bridge handshakes, sorted. Plugins feature-detect with these instead
// of comparing version numbers.
func HostFeatures() []string {
var out []string
for k, st := range ContributionCatalog {
if st == ContractStable {
out = append(out, "contrib."+k)
}
}
for id, spec := range UISlotCatalog {
if spec.Status == ContractStable {
out = append(out, "slot."+id)
}
for kind, st := range spec.Accepts {
if st == ContractStable && kind != SlotDecoration && kind != SlotMount {
out = append(out, "slot."+id+"."+kind)
}
}
}
for loc, spec := range ViewLocationCatalog {
if spec.Status == ContractStable {
out = append(out, "view."+loc)
}
}
for id, st := range UILayerCatalog {
if st == ContractStable {
out = append(out, id)
}
}
for field, st := range ThemeFieldCatalog {
if st == ContractStable {
out = append(out, "theme."+field)
}
}
for m, spec := range BridgeMethodCatalog {
if spec.Status == ContractStable {
out = append(out, "bridge."+m)
}
}
for ev, st := range BridgeEventCatalog {
if st == ContractStable {
out = append(out, "event."+ev)
}
}
for feature, st := range HostCapabilityCatalog {
if st == ContractStable {
out = append(out, feature)
}
}
// Every stable host/* method is advertised from the wire contract catalog,
// so a plugin can feature-detect a method without comparing versions.
out = append(out, pluginproto.Features()...)
sort.Strings(out)
// Two catalogs may name the same feature; advertise each one once.
unique := out[:0]
for i, feature := range out {
if i > 0 && out[i-1] == feature {
continue
}
unique = append(unique, feature)
}
return unique
}
var reContributionID = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]*$`)
// validateUIContract checks the UI-facing parts of a manifest against the
// catalogs: unknown slots, locations, layout values or icon names are errors;
// experimental ones are accepted and reported by ContractFindings.
func validateUIContract(m Manifest) error {
channelIDs := make(map[string]bool, len(m.Contributes.Channels))
for _, channel := range m.Contributes.Channels {
if channel.ID != strings.TrimSpace(channel.ID) || !reContributionID.MatchString(channel.ID) {
return fmt.Errorf("invalid channel id %q", channel.ID)
}
if channelIDs[channel.ID] {
return fmt.Errorf("duplicate channel id %q", channel.ID)
}
channelIDs[channel.ID] = true
if channel.Framing != "jsonl" {
return fmt.Errorf("channel %q uses unsupported framing %q", channel.ID, channel.Framing)
}
}
if len(channelIDs) > 0 && strings.TrimSpace(m.Entry.Sidecar) == "" {
return fmt.Errorf("plugin channels require a Sidecar entry")
}
checkSlot := func(what, id, slot, kind string) error {
spec, ok := UISlotCatalog[slot]
if !ok {
return fmt.Errorf("%s %q targets unknown slot %q", what, id, slot)
}
if _, ok := spec.Accepts[kind]; !ok {
return fmt.Errorf("%s %q: slot %q does not accept %s contributions", what, id, slot, kind)
}
return nil
}
for _, p := range m.Contributes.Panels {
if err := checkSlot("panel", p.ID, p.Slot, SlotPanel); err != nil {
return err
}
}
for _, mc := range m.Contributes.Menus {
if err := checkSlot("menu", mc.ID, mc.Slot, SlotMenu); err != nil {
return err
}
}
for _, si := range m.Contributes.StatusItems {
if err := checkSlot("status item", si.ID, si.Slot, SlotStatusItem); err != nil {
return err
}
}
seenImageSources := map[string]bool{}
for _, src := range m.Contributes.ImageSources {
if !reContributionID.MatchString(src.ID) {
return fmt.Errorf("invalid image source id %q", src.ID)
}
if seenImageSources[src.ID] {
return fmt.Errorf("duplicate image source id %q", src.ID)
}
seenImageSources[src.ID] = true
if !src.Title.HasAny() {
return fmt.Errorf("image source %q is missing a localized title", src.ID)
}
if strings.TrimSpace(src.Native) == "" {
if strings.TrimSpace(m.Entry.PanelDir) == "" {
return fmt.Errorf("image source %q requires entry.panelDir", src.ID)
}
entry := strings.TrimSpace(src.Entry)
if entry == "" {
entry = "index.html"
}
if err := validateSafeManifestAsset(entry, ""); err != nil {
return fmt.Errorf("invalid image source %q entry %q: %w", src.ID, src.Entry, err)
}
}
}
seenAutoInstallers := map[string]bool{}
validFamilies := map[string]bool{"macos": true, "linux": true, "windows": true, "android": true}
for _, ai := range m.Contributes.AutoInstallers {
if !reContributionID.MatchString(ai.ID) {
return fmt.Errorf("invalid autoInstaller id %q", ai.ID)
}
if seenAutoInstallers[ai.ID] {
return fmt.Errorf("duplicate autoInstaller id %q", ai.ID)
}
seenAutoInstallers[ai.ID] = true
if !ai.Title.HasAny() {
return fmt.Errorf("autoInstaller %q is missing a localized title", ai.ID)
}
if len(ai.GuestFamilies) == 0 {
return fmt.Errorf("autoInstaller %q must declare at least one guest family", ai.ID)
}
for _, fam := range ai.GuestFamilies {
if !validFamilies[strings.ToLower(strings.TrimSpace(fam))] {
return fmt.Errorf("autoInstaller %q has unknown guest family %q", ai.ID, fam)
}
}
if strings.TrimSpace(m.Entry.Sidecar) == "" {
return fmt.Errorf("autoInstaller %q requires entry.sidecar", ai.ID)
}
}
perLocation := map[string]int{}
seenViews := map[string]bool{}
for _, v := range m.Contributes.Views {
if !reContributionID.MatchString(v.ID) {
return fmt.Errorf("invalid view id %q", v.ID)
}
if seenViews[v.ID] {
return fmt.Errorf("duplicate view id %q", v.ID)
}
seenViews[v.ID] = true
if !v.Title.HasAny() {
return fmt.Errorf("view %q is missing a localized title", v.ID)
}
spec, ok := ViewLocationCatalog[v.Location]
if !ok {
return fmt.Errorf("view %q has unknown location %q", v.ID, v.Location)
}
perLocation[v.Location]++
if perLocation[v.Location] > spec.PerPlugin {
return fmt.Errorf("too many views at location %q (at most %d per plugin)", v.Location, spec.PerPlugin)
}
if strings.TrimSpace(m.Entry.PanelDir) == "" {
return fmt.Errorf("view %q requires entry.panelDir", v.ID)
}
if err := validateSafeManifestAsset(strings.TrimSpace(v.Entry), ""); err != nil {
return fmt.Errorf("invalid view %q entry %q: %w", v.ID, v.Entry, err)
}
if icon := strings.TrimSpace(v.Icon); icon != "" {
if err := validateSafeManifestAsset(icon, ""); err != nil {
return fmt.Errorf("invalid view %q icon %q: %w", v.ID, v.Icon, err)
}
}
}
icons := map[string]bool{}
for _, n := range ThemeIconNames {
icons[n] = true
}
for _, th := range m.Contributes.Themes {
for _, d := range th.Decorations {
_, slot := UISlotCatalog[d.Slot]
_, layer := UILayerCatalog[d.Slot]
if !slot && !layer {
return fmt.Errorf("theme %q decoration %q targets unknown slot or layer %q", th.ID, d.ID, d.Slot)
}
}
for name := range th.Icons {
if !icons[name] {
return fmt.Errorf("theme %q overrides unknown icon %q", th.ID, name)
}
}
if l := th.Layout; l != nil {
for opt, val := range map[string]string{
"sidebarPosition": l.SidebarPosition, "sidebarMode": l.SidebarMode,
"density": l.Density, "titlebar": l.Titlebar,
} {
if val != "" && !containsString(ThemeLayoutCatalog[opt], val) {
return fmt.Errorf("theme %q layout.%s has unknown value %q", th.ID, opt, val)
}
}
}
}
if req := strings.TrimSpace(m.Engines.BridgeAPI); req != "" && !MatchesRange(BridgeAPIVersion, req) {
return fmt.Errorf("incompatible bridgeApi: plugin requires %s, host provides %s", req, BridgeAPIVersion)
}
return nil
}
// ContractFindings reports non-blocking contract advisories for `plugin
// doctor` and the install-time scan: experimental entries the manifest relies
// on, fields this host does not know, and missing engines ranges. raw is the
// plugin.json text the manifest was decoded from.
func ContractFindings(m Manifest, raw []byte) []ScanFinding {
var out []ScanFinding
add := func(check, target, msg, zh, en string) {
out = append(out, ScanFinding{Severity: ScanSeverityPending, Check: check, Target: target, Message: msg,
Localized: LocalizedText{ZhCN: zh, EnUS: en}})
}
experimental := func(target, what string) {
add("contract-experimental", target, what+" is experimental: the host does not act on it yet and it carries no compatibility promise",
what+" 仍是实验性契约:宿主尚未实现,不受兼容承诺约束",
what+" is experimental: the host does not act on it yet and it carries no compatibility promise")
}
for _, key := range usedContributionKeys(m.Contributes) {
if ContributionCatalog[key] == ContractExperimental {
experimental("contributes."+key, "contributes."+key)
}
}
slotUse := func(what, id, slot, kind string) {
if spec, ok := UISlotCatalog[slot]; ok && spec.Accepts[kind] == ContractExperimental {
experimental(what+":"+id, fmt.Sprintf("%s in slot %s", what, slot))
}
}
for _, p := range m.Contributes.Panels {
slotUse("panel", p.ID, p.Slot, SlotPanel)
}
for _, mc := range m.Contributes.Menus {
slotUse("menu", mc.ID, mc.Slot, SlotMenu)
}
for _, v := range m.Contributes.Views {
if spec, ok := ViewLocationCatalog[v.Location]; ok && spec.Status == ContractExperimental && ContributionCatalog["views"] == ContractStable {
experimental("view:"+v.ID, "view location "+v.Location)
}
}
for _, th := range m.Contributes.Themes {
if len(th.Icons) > 0 && ThemeFieldCatalog["icons"] == ContractExperimental {
experimental("theme:"+th.ID, "theme icons")
}
if th.BrandMark != "" && ThemeFieldCatalog["brandMark"] == ContractExperimental {
experimental("theme:"+th.ID, "theme brandMark")
}
if th.Layout != nil && ThemeFieldCatalog["layout"] == ContractExperimental {
experimental("theme:"+th.ID, "theme layout")
}
for _, d := range th.Decorations {
if spec, ok := UISlotCatalog[d.Slot]; ok && spec.Status == ContractExperimental {
experimental("theme:"+th.ID, "decoration in slot "+d.Slot)
}
}
}
for _, gd := range m.Contributes.GuestDrivers {
if gd.ConsoleEndpoint != "" && GuestDriverFieldCatalog["consoleEndpoint"] == ContractExperimental {
experimental("guestDriver:"+gd.ID, "guestDrivers.consoleEndpoint")
}
}
if len(raw) > 0 {
dec := json.NewDecoder(bytes.NewReader(bytes.TrimPrefix(raw, []byte("\xef\xbb\xbf"))))
dec.DisallowUnknownFields()
var strict Manifest
if err := dec.Decode(&strict); err != nil && strings.Contains(err.Error(), "unknown field") {
add("contract-unknown-field", "plugin.json", err.Error(),
"清单含本宿主不认识的字段,会被忽略:"+err.Error(),
"plugin.json has a field this host does not know; it is ignored: "+err.Error())
}
}
hasIframeImageSource := false
for _, src := range m.Contributes.ImageSources {
if strings.TrimSpace(src.Native) == "" {
hasIframeImageSource = true
break
}
}
usesUI := len(m.Contributes.Themes) > 0 || len(m.Contributes.Panels) > 0 || hasIframeImageSource || len(m.Contributes.Views) > 0
if usesUI && strings.TrimSpace(m.Engines.UIAPI) == "" {
add("contract-engines", "engines.uiApi", "declare engines.uiApi so incompatible hosts refuse the plugin up front",
"建议声明 engines.uiApi,让不兼容的宿主在安装前就拒绝",
"Declare engines.uiApi so incompatible hosts refuse the plugin up front")
}
if (len(m.Contributes.Panels) > 0 || hasIframeImageSource || len(m.Contributes.Views) > 0) && strings.TrimSpace(m.Engines.BridgeAPI) == "" {
add("contract-engines", "engines.bridgeApi", "declare engines.bridgeApi for panels and views",
"面板与视图建议声明 engines.bridgeApi",
"Declare engines.bridgeApi for panels and views")
}
return out
}
// usedContributionKeys returns the JSON names of non-empty contributes lists.
func usedContributionKeys(c Contributes) []string {
var out []string
v := reflect.ValueOf(c)
t := v.Type()
for i := 0; i < t.NumField(); i++ {
name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
if f := v.Field(i); f.Kind() == reflect.Slice && f.Len() > 0 {
out = append(out, name)
}
}
return out
}
func containsString(list []string, s string) bool {
for _, x := range list {
if x == s {
return true
}
}
return false
}