- Add shared resumable + SHA256SUMS-verified downloader (internal/fetch) and Windows executable swap/relaunch flow (internal/selfupdate, internal/app/appupdate_flow.go, --wait-pid in main.go/cli). - Add dedicated About page and sidebar update capsule with background release checks, download progress, and restart confirmation when VMs are running. - Implement plugin-contributed UI and backend/CLI locale packs (contributes.locales, LocalizedText extra tags, validation, runtime overlay, and PopupSelect language picker). - Move kernel-irqchip and Windows processor scheduling controls into VM Compute > Performance settings, hide Plugins settings gear for VM-only schemas, and align locked system plugin switches.
782 lines
25 KiB
Go
782 lines
25 KiB
Go
package plugin
|
|
|
|
import (
|
|
"archive/zip"
|
|
"crypto/ed25519"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"regexp"
|
|
"runtime"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/i18n"
|
|
)
|
|
|
|
var (
|
|
reReverseDomainID = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]*(\.[a-z0-9][a-z0-9_-]*)+$`)
|
|
)
|
|
|
|
// ForbiddenMarketPatterns enforces §1.3 & §9 market redlines: reject Apple
|
|
// proprietary payloads, closed firmware, and SMBIOS literal secrets.
|
|
var ForbiddenMarketPatterns = []string{
|
|
".ipsw",
|
|
"basesystem.dmg",
|
|
"installesd.dmg",
|
|
"apple-osk",
|
|
}
|
|
|
|
var reOSKAssignment = regexp.MustCompile(`(?i)\bosk\s*=\s*[^\s,"']{32,}`)
|
|
|
|
func containsForbiddenSMCKey(low string) bool {
|
|
if strings.Contains(low, "isa-applesmc") && strings.Contains(low, "osk=") {
|
|
return true
|
|
}
|
|
return reOSKAssignment.MatchString(low)
|
|
}
|
|
|
|
// SigningKeyring maps key IDs / publishers to ed25519 public keys and trust level.
|
|
type SigningKey struct {
|
|
KeyID string
|
|
Publisher string
|
|
Trust TrustLevel
|
|
PublicKey ed25519.PublicKey
|
|
}
|
|
|
|
// MarketEntry describes one plugin published in the remote/embedded market index (§9).
|
|
type MarketEntry struct {
|
|
ID string `json:"id"`
|
|
Version string `json:"version"`
|
|
Name LocalizedText `json:"name"`
|
|
Description LocalizedText `json:"description"`
|
|
Publisher string `json:"publisher"`
|
|
License string `json:"license"`
|
|
Channel string `json:"channel"` // "stable" | "alpha"
|
|
Trust TrustLevel `json:"trust"`
|
|
Engines Engines `json:"engines"`
|
|
DownloadURL string `json:"download_url"`
|
|
SHA256 string `json:"sha256"`
|
|
Signer string `json:"signer,omitempty"`
|
|
}
|
|
|
|
// MarketIndex is the static index.json structure (§9).
|
|
type MarketIndex struct {
|
|
Schema int `json:"schema"`
|
|
UpdatedAt string `json:"updated_at"`
|
|
Plugins []MarketEntry `json:"plugins"`
|
|
}
|
|
|
|
// EmbeddedFallbackMarketIndex is shipped as a zero-network fallback (§9).
|
|
var EmbeddedFallbackMarketIndex = MarketIndex{
|
|
Schema: 1,
|
|
UpdatedAt: "2026-11-29T00:00:00Z",
|
|
Plugins: []MarketEntry{},
|
|
}
|
|
|
|
// PackageInstallOptions controls optional expectations during transactional install.
|
|
type PackageInstallOptions struct {
|
|
ExpectedID string
|
|
ExpectedVersion string
|
|
HostVersion string
|
|
Keyring []SigningKey
|
|
AllowUnsigned bool
|
|
}
|
|
|
|
// InstalledPackage describes the verified result of a transactional package install.
|
|
type InstalledPackage struct {
|
|
Manifest Manifest `json:"manifest"`
|
|
InstallDir string `json:"install_dir"`
|
|
Trust TrustLevel `json:"trust"`
|
|
EntryPath string `json:"entry_path,omitempty"`
|
|
EntryHash string `json:"entry_hash,omitempty"`
|
|
}
|
|
|
|
// DoctorFinding is one diagnostic item produced by `reims-go plugin doctor`.
|
|
type DoctorFinding struct {
|
|
Severity string `json:"severity"` // "error" | "warn" | "ok"
|
|
Check string `json:"check"`
|
|
Message string `json:"message"`
|
|
}
|
|
|
|
// UIContract describes the exported frontend UI contract (`ui-contract.json`)
|
|
// used by `plugin doctor` to validate theme CSS selectors (§5.1).
|
|
type UIContract struct {
|
|
UIAPI string `json:"uiApi"`
|
|
Tokens []string `json:"tokens"`
|
|
Parts []string `json:"parts"`
|
|
StateAttrs []string `json:"stateAttrs"`
|
|
Slots []string `json:"slots"`
|
|
}
|
|
|
|
// PluginsLayout returns the standard directories under `<DataRoot>/plugins/` (§6.1).
|
|
type PluginsLayout struct {
|
|
Root string
|
|
}
|
|
|
|
func NewPluginsLayout(dataRoot string) PluginsLayout {
|
|
return PluginsLayout{Root: filepath.Join(dataRoot, "plugins")}
|
|
}
|
|
|
|
func (l PluginsLayout) StatePath() string { return filepath.Join(l.Root, StateFileName) }
|
|
func (l PluginsLayout) PkgsDir() string { return filepath.Join(l.Root, "pkgs") }
|
|
func (l PluginsLayout) PkgDir(id, ver string) string {
|
|
return filepath.Join(l.Root, "pkgs", id, ver)
|
|
}
|
|
func (l PluginsLayout) DataDir(id string) string { return filepath.Join(l.Root, "data", id) }
|
|
func (l PluginsLayout) LogsDir() string { return filepath.Join(l.Root, "logs") }
|
|
func (l PluginsLayout) LogPath(id string) string { return filepath.Join(l.Root, "logs", id+".log") }
|
|
func (l PluginsLayout) TmpDir() string { return filepath.Join(l.Root, "tmp") }
|
|
func (l PluginsLayout) IndexCachePath() string { return filepath.Join(l.Root, "index-cache.json") }
|
|
|
|
// ValidateManifest validates plugin.json schema, ID, SemVer, engines, platforms,
|
|
// permissions, and runtime provenance (§6.2, §7.1, §9).
|
|
func ValidateManifest(m Manifest, hostVersion string, isBuiltinOrBundled bool) error {
|
|
if m.Schema != 0 && m.Schema != ManifestSchemaVersion {
|
|
return fmt.Errorf("unsupported plugin manifest schema %d (expected %d)", m.Schema, ManifestSchemaVersion)
|
|
}
|
|
if !reReverseDomainID.MatchString(m.ID) {
|
|
return fmt.Errorf("invalid plugin id %q (must be reverse-domain lowercase, e.g. vendor.feature)", m.ID)
|
|
}
|
|
if !isBuiltinOrBundled && strings.HasPrefix(m.ID, "builtin.") {
|
|
return fmt.Errorf("plugin id %q uses reserved builtin. namespace", m.ID)
|
|
}
|
|
if _, err := ParseSemVer(m.Version); err != nil {
|
|
return fmt.Errorf("invalid plugin version %q: %w", m.Version, err)
|
|
}
|
|
if !m.Name.HasAny() {
|
|
return errors.New("plugin manifest missing localized name")
|
|
}
|
|
if m.DefaultEnabled && !isBuiltinOrBundled {
|
|
return errors.New("only builtin or bundled plugins may set defaultEnabled=true")
|
|
}
|
|
if bad := ForbiddenPermissions(m.Permissions); len(bad) > 0 {
|
|
return fmt.Errorf("plugin requests forbidden or unknown permissions: %s", strings.Join(bad, ", "))
|
|
}
|
|
if reqAPI := strings.TrimSpace(m.Engines.PluginAPI); reqAPI != "" {
|
|
if !MatchesRange(PluginAPIVersion, reqAPI) {
|
|
return fmt.Errorf("incompatible pluginApi: plugin requires %s, host provides %s", reqAPI, PluginAPIVersion)
|
|
}
|
|
}
|
|
if reqUI := strings.TrimSpace(m.Engines.UIAPI); reqUI != "" {
|
|
if !MatchesRange(UIAPIVersion, reqUI) {
|
|
return fmt.Errorf("incompatible uiApi: plugin requires %s, host provides %s", reqUI, UIAPIVersion)
|
|
}
|
|
}
|
|
if reqHost := strings.TrimSpace(m.Engines.ReimsGo); reqHost != "" && hostVersion != "" && hostVersion != "dev" {
|
|
if !MatchesRange(hostVersion, reqHost) {
|
|
return fmt.Errorf("incompatible reims-go version: plugin requires %s, host is %s", reqHost, hostVersion)
|
|
}
|
|
}
|
|
if len(m.Platforms) > 0 {
|
|
curPlat := currentPlatformTag()
|
|
matched := false
|
|
for _, p := range m.Platforms {
|
|
if strings.EqualFold(p, curPlat) || p == "*" || strings.EqualFold(p, "any") {
|
|
matched = true
|
|
break
|
|
}
|
|
}
|
|
if !matched {
|
|
return fmt.Errorf("plugin does not support platform %s (supported: %s)", curPlat, strings.Join(m.Platforms, ", "))
|
|
}
|
|
}
|
|
if len(m.Contributes.Runtimes) > 0 {
|
|
if m.Provenance == nil || strings.TrimSpace(m.Provenance.SourcePackage) == "" || strings.TrimSpace(m.License) == "" {
|
|
return errors.New("runtime plugin packages must declare license and provenance.sourcePackage")
|
|
}
|
|
}
|
|
if !isBuiltinOrBundled {
|
|
permSet := make(map[string]bool, len(m.Permissions))
|
|
for _, p := range m.Permissions {
|
|
permSet[p] = true
|
|
}
|
|
hasThemeUIScript := false
|
|
for _, th := range m.Contributes.Themes {
|
|
if strings.TrimSpace(th.UIScript) != "" {
|
|
hasThemeUIScript = true
|
|
break
|
|
}
|
|
}
|
|
if (strings.TrimSpace(m.Entry.UIScript) != "" || len(m.Contributes.UIScripts) > 0 || hasThemeUIScript) && !permSet["ui:script"] {
|
|
return errors.New("plugin declaring uiScript must request permission \"ui:script\"")
|
|
}
|
|
if len(m.Contributes.RuleHooks) > 0 && !permSet["vm:intent"] {
|
|
return errors.New("plugin declaring ruleHooks must request permission \"vm:intent\"")
|
|
}
|
|
if len(m.Contributes.GuestDrivers) > 0 && !permSet["driver:vm"] {
|
|
return errors.New("plugin declaring guestDrivers must request permission \"driver:vm\"")
|
|
}
|
|
if len(m.Contributes.InputFilters) > 0 && !permSet["input:filter"] {
|
|
return errors.New("plugin declaring inputFilters must request permission \"input:filter\"")
|
|
}
|
|
if len(m.Contributes.Runtimes) > 0 && !permSet["runtime:provider"] {
|
|
return errors.New("plugin declaring runtimes must request permission \"runtime:provider\"")
|
|
}
|
|
}
|
|
for _, panel := range m.Contributes.Panels {
|
|
entry := strings.TrimSpace(panel.Entry)
|
|
if entry == "" {
|
|
entry = "index.html"
|
|
}
|
|
if err := validateSafeManifestAsset(entry, ""); err != nil {
|
|
return fmt.Errorf("invalid panel %q entry %q: %w", panel.ID, panel.Entry, err)
|
|
}
|
|
}
|
|
for _, th := range m.Contributes.Themes {
|
|
if err := ValidateThemeContribution(th, ""); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
for _, lc := range m.Contributes.Locales {
|
|
if err := ValidateLocaleContribution(lc, ""); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
const maxLocaleFileBytes = 2 << 20 // 2 MiB
|
|
|
|
// ValidateLocaleContribution checks a declarative locale pack contribution.
|
|
// When rootDir is non-empty, referenced JSON files are also read and parsed.
|
|
func ValidateLocaleContribution(lc LocaleContribution, rootDir string) error {
|
|
if _, ok := i18n.ParseLocale(lc.Locale); !ok {
|
|
return fmt.Errorf("invalid locale tag %q", lc.Locale)
|
|
}
|
|
if strings.TrimSpace(lc.Fallback) != "" {
|
|
if _, ok := i18n.ParseLocale(lc.Fallback); !ok {
|
|
return fmt.Errorf("locale %q has invalid fallback tag %q", lc.Locale, lc.Fallback)
|
|
}
|
|
}
|
|
hasFile := strings.TrimSpace(lc.File) != ""
|
|
hasBackendFile := strings.TrimSpace(lc.BackendFile) != ""
|
|
if !hasFile && !hasBackendFile && len(lc.Messages) == 0 && len(lc.Backend) == 0 {
|
|
return fmt.Errorf("locale %q must declare file, backendFile, messages, or backend", lc.Locale)
|
|
}
|
|
checkFile := func(rel, field string) error {
|
|
if strings.TrimSpace(rel) == "" {
|
|
return nil
|
|
}
|
|
if err := validateSafeManifestAsset(rel, rootDir); err != nil {
|
|
return fmt.Errorf("locale %q invalid %s %q: %w", lc.Locale, field, rel, err)
|
|
}
|
|
if !strings.EqualFold(path.Ext(strings.TrimSpace(rel)), ".json") {
|
|
return fmt.Errorf("locale %q %s %q must be a .json file", lc.Locale, field, rel)
|
|
}
|
|
if rootDir != "" {
|
|
if _, err := loadLocaleJSONFile(rootDir, rel); err != nil {
|
|
return fmt.Errorf("locale %q invalid %s %q: %w", lc.Locale, field, rel, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
if err := checkFile(lc.File, "file"); err != nil {
|
|
return err
|
|
}
|
|
if err := checkFile(lc.BackendFile, "backendFile"); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func loadLocaleJSONFile(rootDir, rel string) (map[string]string, error) {
|
|
full, err := safeJoin(rootDir, rel)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
st, err := os.Stat(full)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if st.IsDir() {
|
|
return nil, errors.New("path is a directory")
|
|
}
|
|
if st.Size() > maxLocaleFileBytes {
|
|
return nil, fmt.Errorf("file exceeds %d bytes", maxLocaleFileBytes)
|
|
}
|
|
raw, err := os.ReadFile(full)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var out map[string]string
|
|
if err := json.Unmarshal(raw, &out); err != nil {
|
|
return nil, fmt.Errorf("must be a JSON object mapping string keys to string values: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func currentPlatformTag() string {
|
|
arch := runtime.GOARCH
|
|
if arch == "amd64" {
|
|
arch = "x64"
|
|
}
|
|
return runtime.GOOS + "-" + arch
|
|
}
|
|
|
|
// InstallArchive transactionally verifies and installs a plugin .zip package (§9):
|
|
// 1. Extract into plugins/tmp/<stage> (rejecting zip-slip and market redline files)
|
|
// 2. Parse & validate plugin.json (engines, platforms, permissions, id/version anti-swap)
|
|
// 3. Verify SHA256SUMS covers every extracted file with matching hashes
|
|
// 4. Verify optional ed25519 signature over SHA256SUMS to derive TrustLevel
|
|
// 5. Atomically rename stage dir into plugins/pkgs/<id>/<version>
|
|
// Any error removes stage dir and leaves existing pkgs/ and state.json untouched.
|
|
func InstallArchive(layout PluginsLayout, archivePath string, opts PackageInstallOptions) (*InstalledPackage, error) {
|
|
if err := os.MkdirAll(layout.TmpDir(), 0o755); err != nil {
|
|
return nil, err
|
|
}
|
|
stageDir, err := os.MkdirTemp(layout.TmpDir(), "stage-*")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
cleanupStage := true
|
|
defer func() {
|
|
if cleanupStage {
|
|
_ = os.RemoveAll(stageDir)
|
|
}
|
|
}()
|
|
|
|
if err := extractPluginZip(archivePath, stageDir); err != nil {
|
|
return nil, err
|
|
}
|
|
// Enforce market redlines on extracted content.
|
|
if err := checkMarketRedlines(stageDir); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
manifestPath := filepath.Join(stageDir, "plugin.json")
|
|
rawManifest, err := os.ReadFile(manifestPath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("package missing plugin.json: %w", err)
|
|
}
|
|
var m Manifest
|
|
if err := json.Unmarshal(rawManifest, &m); err != nil {
|
|
return nil, fmt.Errorf("invalid plugin.json: %w", err)
|
|
}
|
|
if opts.ExpectedID != "" && m.ID != opts.ExpectedID {
|
|
return nil, fmt.Errorf("package id mismatch (anti-swap): expected %q, got %q", opts.ExpectedID, m.ID)
|
|
}
|
|
if opts.ExpectedVersion != "" && m.Version != opts.ExpectedVersion {
|
|
return nil, fmt.Errorf("package version mismatch (anti-swap): expected %q, got %q", opts.ExpectedVersion, m.Version)
|
|
}
|
|
if err := ValidateManifest(m, opts.HostVersion, false); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Verify SHA256SUMS.
|
|
sumsPath := filepath.Join(stageDir, "SHA256SUMS")
|
|
sumsRaw, err := os.ReadFile(sumsPath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("package missing SHA256SUMS: %w", err)
|
|
}
|
|
if err := verifyDirSHA256Sums(stageDir, sumsRaw); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Verify optional ed25519 signature over SHA256SUMS.
|
|
trust := TrustCommunity
|
|
sigPath := filepath.Join(stageDir, "SHA256SUMS.sig")
|
|
if sigRaw, sigErr := os.ReadFile(sigPath); sigErr == nil {
|
|
if len(opts.Keyring) > 0 {
|
|
t, vErr := verifyEd25519Signature(sumsRaw, sigRaw, opts.Keyring)
|
|
if vErr != nil {
|
|
return nil, fmt.Errorf("invalid package signature: %w", vErr)
|
|
}
|
|
trust = t
|
|
} else if !opts.AllowUnsigned {
|
|
return nil, errors.New("package signature present but no trusted keyring configured")
|
|
}
|
|
} else if !errors.Is(sigErr, os.ErrNotExist) {
|
|
return nil, sigErr
|
|
} else if !opts.AllowUnsigned && len(opts.Keyring) > 0 {
|
|
return nil, errors.New("unsigned plugin package rejected by policy")
|
|
}
|
|
|
|
// Validate entry file existence and compute entry hash for high-risk display.
|
|
entryRel := m.Entry.Sidecar
|
|
if entryRel == "" {
|
|
entryRel = m.Entry.UIScript
|
|
}
|
|
if entryRel == "" {
|
|
entryRel = m.Entry.Script
|
|
}
|
|
var entryHash string
|
|
if entryRel != "" {
|
|
entryFull, err := safeJoin(stageDir, entryRel)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid entry path %q: %w", entryRel, err)
|
|
}
|
|
h, err := fileSHA256Hex(entryFull)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("entry file %q missing: %w", entryRel, err)
|
|
}
|
|
entryHash = h
|
|
}
|
|
|
|
// Validate all theme fields (tokens, seeds, fonts, background, stylesheet & asset refs, B5).
|
|
for _, th := range m.Contributes.Themes {
|
|
if err := ValidateThemeContribution(th, stageDir); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
// Atomic activation into pkgs/<id>/<version> with path-traversal guard (B3).
|
|
finalDir, err := safeJoin(layout.PkgsDir(), m.ID+"/"+m.Version)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid plugin install target: %w", err)
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(finalDir), 0o755); err != nil {
|
|
return nil, err
|
|
}
|
|
// If same version already exists, replace atomically via backup swap.
|
|
backupDir := ""
|
|
if _, err := os.Stat(finalDir); err == nil {
|
|
backupDir = finalDir + ".prev-" + fmt.Sprintf("%d", time.Now().UnixNano())
|
|
if err := os.Rename(finalDir, backupDir); err != nil {
|
|
return nil, fmt.Errorf("prepare upgrade swap: %w", err)
|
|
}
|
|
}
|
|
if err := os.Rename(stageDir, finalDir); err != nil {
|
|
if backupDir != "" {
|
|
_ = os.Rename(backupDir, finalDir)
|
|
}
|
|
return nil, fmt.Errorf("activate plugin package: %w", err)
|
|
}
|
|
cleanupStage = false
|
|
if backupDir != "" {
|
|
_ = os.RemoveAll(backupDir)
|
|
}
|
|
|
|
entryAbs := ""
|
|
if entryRel != "" {
|
|
entryAbs = filepath.Join(finalDir, filepath.FromSlash(entryRel))
|
|
}
|
|
return &InstalledPackage{
|
|
Manifest: m,
|
|
InstallDir: finalDir,
|
|
Trust: trust,
|
|
EntryPath: entryAbs,
|
|
EntryHash: entryHash,
|
|
}, nil
|
|
}
|
|
|
|
// DoctorDirectory validates a plugin directory (installed or local dev link),
|
|
// checking manifest, SHA256SUMS (if present), CSS safety, and UI contract compliance (§5.1, §10).
|
|
func DoctorDirectory(dir string, hostVersion string, contract *UIContract) []DoctorFinding {
|
|
var out []DoctorFinding
|
|
add := func(sev, check, msg string) {
|
|
out = append(out, DoctorFinding{Severity: sev, Check: check, Message: msg})
|
|
}
|
|
raw, err := os.ReadFile(filepath.Join(dir, "plugin.json"))
|
|
if err != nil {
|
|
add("error", "manifest", "cannot read plugin.json: "+err.Error())
|
|
return out
|
|
}
|
|
var m Manifest
|
|
if err := json.Unmarshal(raw, &m); err != nil {
|
|
add("error", "manifest", "invalid plugin.json JSON: "+err.Error())
|
|
return out
|
|
}
|
|
if err := ValidateManifest(m, hostVersion, false); err != nil {
|
|
add("error", "manifest", err.Error())
|
|
} else {
|
|
add("ok", "manifest", fmt.Sprintf("valid manifest %s@%s (tier=%s)", m.ID, m.Version, m.InferTier(false)))
|
|
}
|
|
|
|
if err := checkMarketRedlines(dir); err != nil {
|
|
add("error", "redline", err.Error())
|
|
} else {
|
|
add("ok", "redline", "no forbidden proprietary or secret files detected")
|
|
}
|
|
|
|
if sumsRaw, err := os.ReadFile(filepath.Join(dir, "SHA256SUMS")); err == nil {
|
|
if err := verifyDirSHA256Sums(dir, sumsRaw); err != nil {
|
|
add("error", "checksum", err.Error())
|
|
} else {
|
|
add("ok", "checksum", "SHA256SUMS verified")
|
|
}
|
|
} else {
|
|
add("warn", "checksum", "SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)")
|
|
}
|
|
|
|
// Validate theme manifest fields and stylesheets against safety rules and UI Contract v1 (§5.1, B5).
|
|
for _, th := range m.Contributes.Themes {
|
|
if err := ValidateThemeContribution(th, dir); err != nil {
|
|
add("error", "theme-css", err.Error())
|
|
} else if th.Stylesheet != "" {
|
|
add("ok", "theme-css", th.Stylesheet+" passed CSS safety & asset check")
|
|
}
|
|
if th.Stylesheet == "" {
|
|
continue
|
|
}
|
|
cssPath, err := safeJoin(dir, th.Stylesheet)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
cssBytes, err := os.ReadFile(cssPath)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
cssText := string(cssBytes)
|
|
if contract != nil {
|
|
for _, issue := range CheckCSSAgainstContract(cssText, *contract) {
|
|
add("warn", "ui-contract", issue)
|
|
}
|
|
}
|
|
}
|
|
for _, lc := range m.Contributes.Locales {
|
|
if err := ValidateLocaleContribution(lc, dir); err != nil {
|
|
add("error", "locale", err.Error())
|
|
} else {
|
|
add("ok", "locale", fmt.Sprintf("locale %s validated", lc.Locale))
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
var (
|
|
reCSSClass = regexp.MustCompile(`\.([a-zA-Z_-][a-zA-Z0-9_-]*)`)
|
|
reCSSVar = regexp.MustCompile(`var\(\s*(--[a-zA-Z0-9_-]+)`)
|
|
)
|
|
|
|
// CheckCSSAgainstContract verifies that a theme stylesheet only references
|
|
// contract part classes (`rg-p-*`) and contract design tokens (§5.1).
|
|
func CheckCSSAgainstContract(css string, contract UIContract) []string {
|
|
partSet := make(map[string]bool, len(contract.Parts))
|
|
for _, p := range contract.Parts {
|
|
partSet[p] = true
|
|
}
|
|
tokenSet := make(map[string]bool, len(contract.Tokens))
|
|
for _, tk := range contract.Tokens {
|
|
tokenSet[tk] = true
|
|
}
|
|
var issues []string
|
|
seen := map[string]bool{}
|
|
for _, m := range reCSSClass.FindAllStringSubmatch(css, -1) {
|
|
cls := m[1]
|
|
if !partSet[cls] && !seen["cls:"+cls] {
|
|
seen["cls:"+cls] = true
|
|
issues = append(issues, fmt.Sprintf("selector class .%s is not in ui-contract parts", cls))
|
|
}
|
|
}
|
|
for _, m := range reCSSVar.FindAllStringSubmatch(css, -1) {
|
|
v := m[1]
|
|
if !tokenSet[v] && !strings.HasPrefix(v, "--theme-") && !seen["var:"+v] {
|
|
seen["var:"+v] = true
|
|
issues = append(issues, fmt.Sprintf("CSS variable %s is not in ui-contract tokens", v))
|
|
}
|
|
}
|
|
sort.Strings(issues)
|
|
return issues
|
|
}
|
|
|
|
func extractPluginZip(archivePath, destDir string) error {
|
|
r, err := zip.OpenReader(archivePath)
|
|
if err != nil {
|
|
return fmt.Errorf("open plugin zip: %w", err)
|
|
}
|
|
defer r.Close()
|
|
const (
|
|
maxZipFiles = 2048
|
|
maxZipFileBytes = int64(256 << 20)
|
|
maxZipTotalBytes = int64(512 << 20)
|
|
)
|
|
if len(r.File) > maxZipFiles {
|
|
return fmt.Errorf("plugin zip exceeds maximum file count (%d)", maxZipFiles)
|
|
}
|
|
var totalWritten int64
|
|
cleanDest := filepath.Clean(destDir) + string(os.PathSeparator)
|
|
for _, f := range r.File {
|
|
if f.Mode()&os.ModeSymlink != 0 {
|
|
return fmt.Errorf("symlink entries are forbidden in plugin zip: %s", f.Name)
|
|
}
|
|
target := filepath.Join(destDir, filepath.FromSlash(f.Name))
|
|
if !strings.HasPrefix(filepath.Clean(target), cleanDest) && filepath.Clean(target) != filepath.Clean(destDir) {
|
|
return fmt.Errorf("illegal path in plugin zip: %s", f.Name)
|
|
}
|
|
if f.FileInfo().IsDir() {
|
|
if err := os.MkdirAll(target, 0o755); err != nil {
|
|
return err
|
|
}
|
|
continue
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
|
|
return err
|
|
}
|
|
rc, err := f.Open()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
out, err := os.Create(target)
|
|
if err != nil {
|
|
_ = rc.Close()
|
|
return err
|
|
}
|
|
// Cap single extracted file and cumulative archive bytes to prevent zip bombs.
|
|
n, copyErr := io.Copy(out, io.LimitReader(rc, maxZipFileBytes+1))
|
|
_ = rc.Close()
|
|
closeErr := out.Close()
|
|
if copyErr != nil {
|
|
return copyErr
|
|
}
|
|
if closeErr != nil {
|
|
return closeErr
|
|
}
|
|
if n > maxZipFileBytes {
|
|
return fmt.Errorf("plugin zip entry %s exceeds max file size", f.Name)
|
|
}
|
|
totalWritten += n
|
|
if totalWritten > maxZipTotalBytes {
|
|
return errors.New("plugin zip exceeds maximum total extracted size")
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func checkMarketRedlines(root string) error {
|
|
return filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
|
|
if err != nil || info.IsDir() {
|
|
return err
|
|
}
|
|
lowName := strings.ToLower(info.Name())
|
|
for _, pat := range ForbiddenMarketPatterns {
|
|
if strings.Contains(lowName, pat) {
|
|
return fmt.Errorf("forbidden proprietary file detected (%s)", info.Name())
|
|
}
|
|
}
|
|
// Quick scan of small text/json manifests for Apple OSK patterns.
|
|
if info.Size() <= 256*1024 && (strings.HasSuffix(lowName, ".json") || strings.HasSuffix(lowName, ".toml") || strings.HasSuffix(lowName, ".txt")) {
|
|
if b, rErr := os.ReadFile(p); rErr == nil {
|
|
low := strings.ToLower(string(b))
|
|
if containsForbiddenSMCKey(low) {
|
|
return fmt.Errorf("forbidden Apple SMC OSK detected in %s", info.Name())
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
func verifyDirSHA256Sums(root string, sumsRaw []byte) error {
|
|
expected := make(map[string]string)
|
|
for _, line := range strings.Split(string(sumsRaw), "\n") {
|
|
line = strings.TrimSpace(line)
|
|
if line == "" || strings.HasPrefix(line, "#") {
|
|
continue
|
|
}
|
|
fields := strings.Fields(line)
|
|
if len(fields) < 2 {
|
|
return fmt.Errorf("malformed SHA256SUMS line: %q", line)
|
|
}
|
|
rel := filepath.ToSlash(strings.TrimPrefix(fields[1], "./"))
|
|
expected[rel] = strings.ToLower(fields[0])
|
|
}
|
|
if len(expected) == 0 {
|
|
return errors.New("SHA256SUMS is empty")
|
|
}
|
|
// Check every declared file matches its hash.
|
|
for rel, wantHash := range expected {
|
|
full, err := safeJoin(root, rel)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
got, err := fileSHA256Hex(full)
|
|
if err != nil {
|
|
return fmt.Errorf("SHA256SUMS file missing %s: %w", rel, err)
|
|
}
|
|
if got != wantHash {
|
|
return fmt.Errorf("SHA256 mismatch for %s: expected %s, got %s", rel, wantHash, got)
|
|
}
|
|
}
|
|
// Ensure no unhashed extra files exist (except SHA256SUMS and SHA256SUMS.sig).
|
|
return filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
|
|
if err != nil || info.IsDir() {
|
|
return err
|
|
}
|
|
rel, err := filepath.Rel(root, p)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
rel = filepath.ToSlash(rel)
|
|
if rel == "SHA256SUMS" || rel == "SHA256SUMS.sig" {
|
|
return nil
|
|
}
|
|
if _, ok := expected[rel]; !ok {
|
|
return fmt.Errorf("unverified file in package not listed in SHA256SUMS: %s", rel)
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
func verifyEd25519Signature(message, sigRaw []byte, keyring []SigningKey) (TrustLevel, error) {
|
|
sigBytes, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(sigRaw)))
|
|
if err != nil {
|
|
// Also accept raw 64-byte binary signature.
|
|
if len(sigRaw) == ed25519.SignatureSize {
|
|
sigBytes = sigRaw
|
|
} else {
|
|
return TrustCommunity, fmt.Errorf("decode signature: %w", err)
|
|
}
|
|
}
|
|
if len(sigBytes) != ed25519.SignatureSize {
|
|
return TrustCommunity, fmt.Errorf("unexpected ed25519 signature size %d", len(sigBytes))
|
|
}
|
|
for _, k := range keyring {
|
|
if len(k.PublicKey) == ed25519.PublicKeySize && ed25519.Verify(k.PublicKey, message, sigBytes) {
|
|
return k.Trust, nil
|
|
}
|
|
}
|
|
return TrustCommunity, errors.New("signature did not match any trusted signing key")
|
|
}
|
|
|
|
func pathWithinRoot(root, candidate string) bool {
|
|
if runtime.GOOS == "windows" {
|
|
r := strings.ToLower(root)
|
|
c := strings.ToLower(candidate)
|
|
return c == r || strings.HasPrefix(c, r+string(os.PathSeparator))
|
|
}
|
|
return candidate == root || strings.HasPrefix(candidate, root+string(os.PathSeparator))
|
|
}
|
|
|
|
func safeJoin(root, rel string) (string, error) {
|
|
cleanRoot := filepath.Clean(root)
|
|
joined := filepath.Clean(filepath.Join(cleanRoot, filepath.FromSlash(rel)))
|
|
if !pathWithinRoot(cleanRoot, joined) {
|
|
return "", fmt.Errorf("path traversal blocked: %q", rel)
|
|
}
|
|
// Guard against symlinks / NTFS junctions escaping rootDir.
|
|
evalRoot := cleanRoot
|
|
if r, err := filepath.EvalSymlinks(cleanRoot); err == nil {
|
|
evalRoot = filepath.Clean(r)
|
|
}
|
|
if evalJoined, err := filepath.EvalSymlinks(joined); err == nil {
|
|
evalJoined = filepath.Clean(evalJoined)
|
|
if !pathWithinRoot(evalRoot, evalJoined) {
|
|
return "", fmt.Errorf("symlink traversal blocked: %q", rel)
|
|
}
|
|
return evalJoined, nil
|
|
}
|
|
return joined, nil
|
|
}
|
|
|
|
func fileSHA256Hex(p string) (string, error) {
|
|
f, err := os.Open(p)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer f.Close()
|
|
h := sha256.New()
|
|
if _, err := io.Copy(h, f); err != nil {
|
|
return "", err
|
|
}
|
|
return hex.EncodeToString(h.Sum(nil)), nil
|
|
}
|