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) } // SigningKey maps key IDs / publishers to ed25519 public keys and trust level. type SigningKey struct { KeyID string Publisher string Trust TrustLevel PublicKey ed25519.PublicKey } // PackageInstallOptions controls optional expectations during transactional install. type PackageInstallOptions struct { ExpectedID string ExpectedVersion string HostVersion string Keyring []SigningKey AllowUnsigned bool // IndexTrust is the trust a first-party market index vouches for. The // caller sets it only after the archive matched that index's SHA-256, so // it stands in for a signature. A valid signature still takes precedence // when it ranks higher, and a bad one still fails the install. IndexTrust TrustLevel } // 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"` Layers []string `json:"layers,omitempty"` Experimental UIContractExperimental `json:"experimental,omitempty"` } // UIContractExperimental lists published but not yet emitted contract entries // (frontend/ui-contract.json "experimental"). type UIContractExperimental struct { Parts []string `json:"parts,omitempty"` StateAttrs []string `json:"stateAttrs,omitempty"` ItemStates []string `json:"itemStates,omitempty"` Slots []string `json:"slots,omitempty"` Layers []string `json:"layers,omitempty"` LayoutOptions []string `json:"layoutOptions,omitempty"` Icons []string `json:"icons,omitempty"` ViewLocations []string `json:"viewLocations,omitempty"` SDKEvents []string `json:"sdkEvents,omitempty"` } // PluginsLayout returns the standard directories under `/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 m.Version == "" || strings.TrimSpace(m.Version) != m.Version { return fmt.Errorf("invalid plugin version %q: must not contain surrounding whitespace", m.Version) } 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 compat, reason := checkHostCompatibility(m.Platforms, m.Engines, hostVersion); !compat { return errors.New(reason) } 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\"") } if len(m.Contributes.ImageSources) > 0 { if !permSet["ui:slot"] { return errors.New("plugin declaring imageSources must request permission \"ui:slot\"") } for _, src := range m.Contributes.ImageSources { if strings.TrimSpace(src.Native) != "" { return fmt.Errorf("external image source %q may not declare native renderer", src.ID) } } } } for _, d := range m.Contributes.GuestDrivers { for _, root := range d.VMRoots { root = strings.TrimSpace(root) clean := path.Clean(root) if root == "" || strings.Contains(root, `\`) || path.IsAbs(root) || filepath.IsAbs(root) || filepath.VolumeName(root) != "" || clean == "." || clean == ".." || strings.HasPrefix(clean, "../") { return fmt.Errorf("guest driver %q has invalid VM root %q: must be a relative path inside DataRoot", d.ID, root) } } } 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 } } if err := validateUIContract(m); err != nil { return err } if strings.TrimSpace(m.L10n) != "" { if err := validatePluginL10nDir(m.L10n, ""); 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 per JSON catalog maxLocaleTotalFontBytes = 8 << 20 // 8 MiB cumulative WOFF2 fonts per locale contribution ) var allowedLocaleDomainKeys = map[string]bool{ "core": true, "vm": true, "wizard": true, "settings": true, "plugins": true, "native": true, "macosGlossary": true, "macos-glossary": true, } func validatePluginL10nDir(relDir, rootDir string) error { clean := strings.Trim(strings.TrimSpace(relDir), "/") if clean == "" { return errors.New("l10n directory cannot be empty") } if strings.ContainsAny(clean, "\"'\\;{}()\r\n\x00") || !reSafeAssetRel.MatchString(clean) || reSchemePrefix.MatchString(clean) { return fmt.Errorf("invalid l10n directory %q", relDir) } for _, seg := range strings.Split(clean, "/") { if seg == "" || seg == "." || seg == ".." { return fmt.Errorf("invalid l10n directory segment in %q", relDir) } } if rootDir != "" { full, err := safeJoin(rootDir, clean) if err != nil { return fmt.Errorf("invalid l10n directory %q: %w", relDir, err) } entries, err := os.ReadDir(full) if err != nil { if errors.Is(err, os.ErrNotExist) { return nil } return fmt.Errorf("read l10n directory %q: %w", relDir, err) } for _, ent := range entries { if ent.IsDir() || !strings.HasSuffix(strings.ToLower(ent.Name()), ".json") { continue } msgs, err := loadLocaleJSONFile(rootDir, clean+"/"+ent.Name()) if err != nil { return fmt.Errorf("l10n file %s/%s: %w", clean, ent.Name(), err) } if err := validateICUMap(msgs, clean+"/"+ent.Name()); err != nil { return err } } } return nil } func validateICUMap(msgs map[string]string, ctxLabel string) error { for k, v := range msgs { if _, _, err := i18n.ParseICU(v); err != nil { return fmt.Errorf("%s key %q has invalid ICU template: %w", ctxLabel, k, err) } } return nil } // ValidateLocaleContribution checks a declarative locale pack contribution. // When rootDir is non-empty, referenced JSON files and WOFF2 fonts are also read and verified. 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.Files) == 0 && len(lc.Messages) == 0 && len(lc.Backend) == 0 && len(lc.PluginOverrides) == 0 && len(lc.Fonts) == 0 { return fmt.Errorf("locale %q must declare files, file, backendFile, messages, backend, fonts, or pluginOverrides", 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 != "" { msgs, err := loadLocaleJSONFile(rootDir, rel) if err != nil { return fmt.Errorf("locale %q invalid %s %q: %w", lc.Locale, field, rel, err) } if err := validateICUMap(msgs, fmt.Sprintf("locale %q %s (%s)", lc.Locale, field, rel)); err != nil { return err } } return nil } if err := checkFile(lc.File, "file"); err != nil { return err } if err := checkFile(lc.BackendFile, "backendFile"); err != nil { return err } for dom, rel := range lc.Files { if !allowedLocaleDomainKeys[dom] { return fmt.Errorf("locale %q unknown domain key %q in files", lc.Locale, dom) } if err := checkFile(rel, "files."+dom); err != nil { return err } } if err := validateICUMap(lc.Messages, fmt.Sprintf("locale %q messages", lc.Locale)); err != nil { return err } if err := validateICUMap(lc.Backend, fmt.Sprintf("locale %q backend", lc.Locale)); err != nil { return err } var totalFontBytes int64 for _, f := range lc.Fonts { if !reSafeFontFamily.MatchString(strings.TrimSpace(f.Family)) || strings.Contains(strings.ToLower(f.Family), " maxLocaleTotalFontBytes { return fmt.Errorf("locale %q bundled fonts exceed %d MiB limit", lc.Locale, maxLocaleTotalFontBytes>>20) } if err := verifyWOFF2Header(full); err != nil { return fmt.Errorf("locale %q font %q: %w", lc.Locale, f.File, err) } } } for targetID, ov := range lc.PluginOverrides { if !reReverseDomainID.MatchString(targetID) { return fmt.Errorf("locale %q pluginOverrides has invalid target plugin id %q", lc.Locale, targetID) } if err := checkFile(ov.MessagesFile, "pluginOverrides."+targetID+".messagesFile"); err != nil { return err } if err := validateICUMap(ov.Messages, fmt.Sprintf("locale %q pluginOverrides.%s.messages", lc.Locale, targetID)); err != nil { return err } if strings.TrimSpace(ov.ManifestFile) != "" { if err := validateSafeManifestAsset(ov.ManifestFile, rootDir); err != nil { return fmt.Errorf("locale %q pluginOverrides.%s.manifestFile: %w", lc.Locale, targetID, err) } if !strings.EqualFold(path.Ext(strings.TrimSpace(ov.ManifestFile)), ".json") { return fmt.Errorf("locale %q pluginOverrides.%s.manifestFile %q must be a .json file", lc.Locale, targetID, ov.ManifestFile) } if rootDir != "" { if _, err := loadPluginManifestOverrideFile(rootDir, ov.ManifestFile); err != nil { return fmt.Errorf("locale %q pluginOverrides.%s.manifestFile %q: %w", lc.Locale, targetID, ov.ManifestFile, err) } } } } return nil } func verifyWOFF2Header(fullPath string) error { fh, err := os.Open(fullPath) if err != nil { return err } defer fh.Close() var magic [4]byte if _, err := io.ReadFull(fh, magic[:]); err != nil { return errors.New("file too short to be a valid WOFF2 font") } if string(magic[:]) != "wOF2" { return errors.New("invalid WOFF2 magic header (expected wOF2)") } return nil } func loadPluginManifestOverrideFile(rootDir, rel string) (*PluginManifestOverride, 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() || st.Size() > maxLocaleFileBytes { return nil, errors.New("invalid manifest override file") } raw, err := os.ReadFile(full) if err != nil { return nil, err } var out PluginManifestOverride if err := json.Unmarshal(raw, &out); err != nil { return nil, err } return &out, 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 } return parseLocaleMessagesJSON(raw) } func parseLocaleMessagesJSON(raw []byte) (map[string]string, error) { var entries map[string]json.RawMessage if err := json.Unmarshal(raw, &entries); err != nil { return nil, fmt.Errorf("must be a JSON object: %w", err) } out := make(map[string]string, len(entries)) for k, v := range entries { if strings.HasPrefix(k, "$") { continue } var plain string if err := json.Unmarshal(v, &plain); err == nil { out[k] = plain continue } var structured struct { Message *string `json:"message"` } if err := json.Unmarshal(v, &structured); err == nil && structured.Message != nil { out[k] = *structured.Message continue } return nil, fmt.Errorf("key %q must be a string or an object with a string \"message\" field", k) } return out, nil } func currentPlatformTag() string { if override := strings.TrimSpace(os.Getenv("REIMS_GO_PLATFORM")); override != "" { return strings.ToLower(strings.ReplaceAll(override, "/", "-")) } arch := runtime.GOARCH if arch == "amd64" { arch = "x64" } return runtime.GOOS + "-" + arch } // InstallArchive transactionally validates, verifies checksums/signatures, and // atomically installs a plugin .zip archive into plugins/pkgs//. // Any failure removes the staging directory without altering existing state. 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 } 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 } 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 } 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") } if (opts.IndexTrust == TrustOfficial || opts.IndexTrust == TrustVerified) && trustSortRank(opts.IndexTrust) > trustSortRank(trust) { trust = opts.IndexTrust } // Validate entry file(s) existence and compute entry hash for high-risk display and approval pinning. entryRel, _, entryHash, err := resolveManifestEntry(m, stageDir, true) if err != nil { return nil, err } if err := validateDiskContributions(m, stageDir); err != nil { return nil, err } // Enforce unified static security & packaging hard-gate before activation. scanRep := ScanDirectory(stageDir, opts.HostVersion, ScanOptions{ Keyring: opts.Keyring, RequireChecksums: true, }) if scanRep.HardBlocked { reasons := make([]string, 0, len(scanRep.HardFindings)) for _, f := range scanRep.HardFindings { if f.Target != "" { reasons = append(reasons, fmt.Sprintf("[%s] %s: %s", f.Check, f.Target, f.Message)) } else { reasons = append(reasons, fmt.Sprintf("[%s] %s", f.Check, f.Message)) } } return nil, fmt.Errorf("plugin package blocked by static security gate: %s", strings.Join(reasons, "; ")) } // Atomically activate into pkgs// after path-traversal validation. 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), static risk rules, CSS safety, // and UI contract compliance (§5.1, §10). func DoctorDirectory(dir string, hostVersion string, contract *UIContract) []DoctorFinding { return ScanDirectory(dir, hostVersion, ScanOptions{ Contract: contract, RequireChecksums: false, }).ToDoctorFindings() } var ( reCSSClass = regexp.MustCompile(`\.([a-zA-Z_-][a-zA-Z0-9_-]*)`) reCSSVar = regexp.MustCompile(`var\(\s*(--[a-zA-Z0-9_-]+)`) ) // matchesCurrentPlatform reports whether platforms includes the current host // platform (accepting both "windows-x64" and "windows/amd64" forms as well as // "*" and "any", case-insensitively). An empty slice matches all platforms. func matchesCurrentPlatform(platforms []string) bool { if len(platforms) == 0 { return true } curTag := currentPlatformTag() curPair := runtime.GOOS + "/" + runtime.GOARCH if override := strings.TrimSpace(os.Getenv("REIMS_GO_PLATFORM")); override != "" { curPair = strings.ToLower(strings.ReplaceAll(override, "-", "/")) if curPair == "windows/x64" { curPair = "windows/amd64" } } for _, p := range platforms { p = strings.TrimSpace(p) if p == "*" || strings.EqualFold(p, "any") || strings.EqualFold(p, curTag) || strings.EqualFold(p, curPair) { return true } } return false } // checkHostCompatibility is the shared platform and engines gate used by both // market pre-download checks and manifest installation validation. func checkHostCompatibility(platforms []string, engines Engines, hostVersion string) (bool, string) { if !matchesCurrentPlatform(platforms) { return false, fmt.Sprintf("platform %s not supported (requires %s)", currentPlatformTag(), strings.Join(platforms, ", ")) } if reqAPI := strings.TrimSpace(engines.PluginAPI); reqAPI != "" && !MatchesRange(PluginAPIVersion, reqAPI) { return false, fmt.Sprintf("incompatible pluginApi: requires %s (host has %s)", reqAPI, PluginAPIVersion) } if reqUI := strings.TrimSpace(engines.UIAPI); reqUI != "" && !MatchesRange(UIAPIVersion, reqUI) { return false, fmt.Sprintf("incompatible uiApi: requires %s (host has %s)", reqUI, UIAPIVersion) } if reqBridge := strings.TrimSpace(engines.BridgeAPI); reqBridge != "" && !MatchesRange(BridgeAPIVersion, reqBridge) { return false, fmt.Sprintf("incompatible bridgeApi: requires %s (host has %s)", reqBridge, BridgeAPIVersion) } if reqHost := strings.TrimSpace(engines.ReimsGo); reqHost != "" && hostVersion != "" && hostVersion != "dev" && !MatchesRange(hostVersion, reqHost) { return false, fmt.Sprintf("incompatible reims-go: requires %s (host has %s)", reqHost, hostVersion) } return true, "" } // collectApprovalEntryPaths returns the primary executable/script entry path // (preserving Sidecar first for L3 activation) and all deduplicated executable // or UI script entry paths that must be covered by approval hash pinning. func collectApprovalEntryPaths(m Manifest) (primary string, all []string) { seen := map[string]bool{} add := func(rel string) { rel = normalizeRel(rel) if rel == "" || seen[rel] { return } seen[rel] = true if primary == "" { primary = rel } all = append(all, rel) } add(m.Entry.Sidecar) add(m.Entry.Script) for _, p := range collectUIScriptPaths(m) { add(p) } return primary, all } // resolveManifestEntry resolves the primary entry file path and computes the // approval SHA-256 digest covering all executable / UI script entries. // For a single entry file, the digest is the raw file SHA-256 (matching L3 // sidecar hashes and sha256sum output). For multiple entries, it computes a // deterministic composite SHA-256 over sorted ":\n" lines. func resolveManifestEntry(m Manifest, rootDir string, requireFiles bool) (primaryRel, primaryAbs, entryHash string, err error) { primaryRel, allRels := collectApprovalEntryPaths(m) if len(allRels) == 0 { return "", "", "", nil } primaryAbs, err = safeJoin(rootDir, primaryRel) if err != nil { return "", "", "", fmt.Errorf("invalid entry path %q: %w", primaryRel, err) } if len(allRels) == 1 { h, hErr := fileSHA256Hex(primaryAbs) if hErr != nil { if requireFiles { return "", "", "", fmt.Errorf("entry file %q missing: %w", primaryRel, hErr) } return primaryRel, primaryAbs, "", nil } return primaryRel, primaryAbs, h, nil } sorted := append([]string(nil), allRels...) sort.Strings(sorted) agg := sha256.New() for _, rel := range sorted { full, jErr := safeJoin(rootDir, rel) if jErr != nil { return "", "", "", fmt.Errorf("invalid entry path %q: %w", rel, jErr) } h, hErr := fileSHA256Hex(full) if hErr != nil { if requireFiles { return "", "", "", fmt.Errorf("entry file %q missing: %w", rel, hErr) } return primaryRel, primaryAbs, "", nil } _, _ = fmt.Fprintf(agg, "%s:%s\n", rel, h) } return primaryRel, primaryAbs, hex.EncodeToString(agg.Sum(nil)), nil } // stripCSSNonCode replaces CSS comments, quoted strings, and url(...) arguments // with spaces so contract selector/variable regexes never match inside comments // or asset filenames (such as /* studio.js */ or url(assets/bg.png)). func stripCSSNonCode(css string) string { var b strings.Builder b.Grow(len(css)) n := len(css) i := 0 skipComment := func() bool { if i+1 >= n || css[i] != '/' || css[i+1] != '*' { return false } end := strings.Index(css[i+2:], "*/") if end < 0 { i = n return true } i += 2 + end + 2 return true } skipQuoted := func() bool { if i >= n || (css[i] != '"' && css[i] != '\'') { return false } q := css[i] i++ for i < n { if css[i] == '\\' && i+1 < n { if css[i+1] == '\r' && i+2 < n && css[i+2] == '\n' { i += 3 continue } i += 2 continue } if css[i] == q || css[i] == '\n' || css[i] == '\r' { i++ break } i++ } return true } for i < n { if skipComment() || skipQuoted() { b.WriteByte(' ') continue } // url(...) function (case-insensitive, not part of a longer identifier) if i+4 <= n && strings.EqualFold(css[i:i+4], "url(") && (i == 0 || !isCSSIdentChar(css[i-1])) { b.WriteString("url()") i += 4 for i < n { if skipComment() || skipQuoted() { continue } if css[i] == '\\' && i+1 < n { i += 2 continue } if css[i] == ')' { i++ break } i++ } continue } b.WriteByte(css[i]) i++ } return b.String() } // 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 { cleaned := stripCSSNonCode(css) partSet := make(map[string]bool, len(contract.Parts)) for _, p := range contract.Parts { partSet[p] = true } experimentalParts := make(map[string]bool, len(contract.Experimental.Parts)) for _, p := range contract.Experimental.Parts { experimentalParts[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(cleaned, -1) { cls := m[1] if !partSet[cls] && !seen["cls:"+cls] { seen["cls:"+cls] = true if experimentalParts[cls] { issues = append(issues, fmt.Sprintf("selector class .%s is an experimental ui-contract part the host does not emit yet", cls)) } else { issues = append(issues, fmt.Sprintf("selector class .%s is not in ui-contract parts", cls)) } } } for _, m := range reCSSVar.FindAllStringSubmatch(cleaned, -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 } const maxPluginArchiveBytes = int64(512 << 20) 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 = maxPluginArchiveBytes ) 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 _, rawLine := range strings.Split(string(sumsRaw), "\n") { line := strings.TrimRight(rawLine, "\r") trimmed := strings.TrimLeft(line, " \t") if trimmed == "" || strings.HasPrefix(trimmed, "#") { continue } if len(trimmed) < 66 { return fmt.Errorf("malformed SHA256SUMS line: %q", strings.TrimSpace(line)) } hashHex := strings.ToLower(trimmed[:64]) if _, err := hex.DecodeString(hashHex); err != nil { return fmt.Errorf("malformed SHA256SUMS line: %q", strings.TrimSpace(line)) } rest := trimmed[64:] switch { case strings.HasPrefix(rest, " "), strings.HasPrefix(rest, " *"): rest = rest[2:] case strings.HasPrefix(rest, " "), strings.HasPrefix(rest, "\t"): rest = rest[1:] default: return fmt.Errorf("malformed SHA256SUMS line: %q", strings.TrimSpace(line)) } if rest == "" || strings.ContainsRune(rest, '\\') { return fmt.Errorf("malformed SHA256SUMS line: %q", strings.TrimSpace(line)) } rel := strings.TrimPrefix(rest, "./") if _, dup := expected[rel]; dup { return fmt.Errorf("duplicate SHA256SUMS entry: %s", rel) } expected[rel] = hashHex } 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 validateDiskContributions(m Manifest, rootDir string) error { for _, th := range m.Contributes.Themes { if err := ValidateThemeContribution(th, rootDir); err != nil { return err } } if strings.TrimSpace(m.L10n) != "" { if err := validatePluginL10nDir(m.L10n, rootDir); err != nil { return err } } for _, lc := range m.Contributes.Locales { if err := ValidateLocaleContribution(lc, rootDir); err != nil { return err } } return nil } func safeJoin(root, rel string) (string, error) { absRoot, err := filepath.Abs(root) if err != nil { return "", fmt.Errorf("resolve root path: %w", err) } cleanRoot := filepath.Clean(absRoot) 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, including when // the leaf path does not exist yet (check nearest existing ancestor). evalRoot := cleanRoot if r, err := filepath.EvalSymlinks(cleanRoot); err == nil { evalRoot = filepath.Clean(r) } else if !errors.Is(err, os.ErrNotExist) { return "", fmt.Errorf("evaluate root path: %w", err) } evalJoined, err := filepath.EvalSymlinks(joined) if err == nil { evalJoined = filepath.Clean(evalJoined) if !pathWithinRoot(evalRoot, evalJoined) { return "", fmt.Errorf("symlink traversal blocked: %q", rel) } return evalJoined, nil } if !errors.Is(err, os.ErrNotExist) { return "", fmt.Errorf("evaluate path %q: %w", rel, err) } // Walk upward to the nearest existing ancestor directory and verify it resolves within evalRoot. cur := joined var tail []string for cur != cleanRoot { parent := filepath.Dir(cur) if parent == cur { break } tail = append(tail, filepath.Base(cur)) cur = parent if evalAnc, aErr := filepath.EvalSymlinks(cur); aErr == nil { evalAnc = filepath.Clean(evalAnc) if !pathWithinRoot(evalRoot, evalAnc) { return "", fmt.Errorf("symlink ancestor traversal blocked: %q", rel) } for i := len(tail) - 1; i >= 0; i-- { evalAnc = filepath.Join(evalAnc, tail[i]) } return evalAnc, nil } else if !errors.Is(aErr, os.ErrNotExist) { return "", fmt.Errorf("evaluate ancestor path %q: %w", rel, aErr) } } 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 }