Merge pull request #163 from Nwflower/refactor/entropy-convergence

架构降熵:合并重复实现、拆分过大的文件、删除不再使用的代码,并用测试守护这些规则。
This commit is contained in:
千川白浪 authored and GitHub committed 2026-12-04 16:10:06 +08:00
commit 7b76330d28
312 files changed
+8188 -9026

No files matched your search

+1 -1
View File
@@ -125,7 +125,7 @@ func (a *AssetServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ct = "image/svg+xml; charset=utf-8"
data = SanitizeSVG(data)
} else {
if err := ValidateThemeCSSSafetyInDir(string(data), filepath.Dir(fullPath)); err != nil {
if err := ValidateThemeCSSSafety(string(data), filepath.Dir(fullPath)); err != nil {
http.Error(w, "unsafe stylesheet blocked", http.StatusForbidden)
return
}
+3 -3
View File
@@ -191,7 +191,7 @@ func TestValidateThemeCSSAndContributionBlocksBypasses(t *testing.T) {
{"traversal-url", `.rg-p-shell { background: url("../../secret.png"); }`},
}
for _, tc := range badCSS {
if err := ValidateThemeCSSSafety(tc.css); err == nil {
if err := ValidateThemeCSSSafety(tc.css, ""); err == nil {
t.Errorf("ValidateThemeCSSSafety(%s) expected error, got nil", tc.name)
}
}
@@ -204,10 +204,10 @@ func TestValidateThemeCSSAndContributionBlocksBypasses(t *testing.T) {
if err := os.WriteFile(filepath.Join(dir, "assets", "bg.png"), []byte("png"), 0o644); err != nil {
t.Fatal(err)
}
if err := ValidateThemeCSSSafetyInDir(`.rg-p-shell { background: url("assets/bg.png"); }`, dir); err != nil {
if err := ValidateThemeCSSSafety(`.rg-p-shell { background: url("assets/bg.png"); }`, dir); err != nil {
t.Errorf("valid local asset rejected: %v", err)
}
if err := ValidateThemeCSSSafetyInDir(`.rg-p-shell { background: url("assets/missing.png"); }`, dir); err == nil {
if err := ValidateThemeCSSSafety(`.rg-p-shell { background: url("assets/missing.png"); }`, dir); err == nil {
t.Error("missing local asset should be rejected")
}
+12 -9
View File
@@ -44,10 +44,10 @@ type Broker struct {
procs map[int]*ManagedProcess
procsByRef map[string]*ManagedProcess
// VMs being spawned right now, so two requests cannot both start one.
spawning map[string]bool
onNotify func(pluginID, title, body string)
onVMExit func(driverID, vmName string)
onVMState func(pluginID string, rep ReportedVMState) error
spawning map[string]bool
onNotify func(pluginID, title, body string)
onVMExit func(driverID, vmName string)
onVMState func(pluginID string, rep ReportedVMState) error
}
type rateWindow struct {
@@ -181,7 +181,7 @@ func (b *Broker) AuthorizeNetOrigin(pluginID, rawURL string) error {
}
for _, p := range info.Permissions {
if netPermissionMatches(p.Name, u) {
if !b.allowRate(pluginID, 120) {
if !b.allowRate(pluginID) {
b.Audit(pluginID, "RATE_LIMIT", "net:"+u.Host)
return fmt.Errorf("plugin %q exceeded Host API rate limit", pluginID)
}
@@ -242,7 +242,7 @@ func (b *Broker) Authorize(pluginID, perm string) error {
}
}
// Rate limit: max 120 Host API calls / second per plugin.
if !b.allowRate(pluginID, 120) {
if !b.allowRate(pluginID) {
b.Audit(pluginID, "RATE_LIMIT", perm)
return fmt.Errorf("plugin %q exceeded Host API rate limit", pluginID)
}
@@ -261,14 +261,17 @@ func (b *Broker) AllowRate(pluginID string) error {
if st := b.reg.StateOf(pluginID); st != StateActive && st != StateDegraded {
return fmt.Errorf("plugin %q is not active (state=%s)", pluginID, st)
}
if !b.allowRate(pluginID, 120) {
if !b.allowRate(pluginID) {
b.Audit(pluginID, "RATE_LIMIT", "i18n.getBundle")
return fmt.Errorf("plugin %q exceeded Host API rate limit", pluginID)
}
return nil
}
func (b *Broker) allowRate(pluginID string, limitPerSec int) bool {
// hostCallsPerSecond is how many Host API calls one plugin may make per second.
const hostCallsPerSecond = 120
func (b *Broker) allowRate(pluginID string) bool {
b.mu.Lock()
defer b.mu.Unlock()
now := time.Now()
@@ -277,7 +280,7 @@ func (b *Broker) allowRate(pluginID string, limitPerSec int) bool {
b.rates[pluginID] = &rateWindow{windowStart: now, count: 1}
return true
}
if rw.count >= limitPerSec {
if rw.count >= hostCallsPerSecond {
return false
}
rw.count++
+6 -14
View File
@@ -19,6 +19,7 @@ import (
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/networkmsg"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/qmp"
"github.com/Nwflower/reims-go/internal/version"
)
@@ -69,15 +70,6 @@ type HostCallbacks struct {
GetSetting func(pluginID, vmName, key string) (any, bool)
}
func hasCap(caps []string, want string) bool {
for _, cap := range caps {
if strings.EqualFold(cap, want) {
return true
}
}
return false
}
func appVersion() string {
v := strings.TrimPrefix(strings.TrimSpace(version.Version), "v")
if v == "" || v == "dev" {
@@ -96,7 +88,7 @@ func RegisterAll(reg *plugin.Registry, cb HostCallbacks, desiredFn func(id strin
defs := []plugin.PluginDef{
defCore(ver),
defGuestTools(ver, cb, desiredFn),
defClipboard(ver, cb, desiredFn),
defClipboard(ver, desiredFn),
defInput(ver, cb, desiredFn),
defNpcapBridge(ver, cb, desiredFn),
defComputerUse(ver, desiredFn),
@@ -195,20 +187,20 @@ func defGuestTools(ver string, cb HostCallbacks, desiredFn func(string, bool) bo
s.StopManagementNetwork(p.VMName)
intent.ClearKeys = append(intent.ClearKeys, "guest-tools-network")
}
if hasCap(p.RuntimeCaps, "window-file-drop") {
if plugin.HasCap(p.RuntimeCaps, "window-file-drop") {
if token := s.HostDropToken(gtCfg.DriverID, p.VMName); token != "" {
intent.Env["REIMS_GO_DROP_URL"] = fmt.Sprintf("http://127.0.0.1:%d/v1/host-drop", port)
intent.Env["REIMS_GO_DROP_TOKEN"] = token
}
}
if sc.Registry().IsActive(IDInput) && hasCap(p.RuntimeCaps, "win32-unicode-input") {
if sc.Registry().IsActive(IDInput) && plugin.HasCap(p.RuntimeCaps, "win32-unicode-input") {
intent.Env["REIMS_GO_INPUT_URL"] = fmt.Sprintf("http://127.0.0.1:%d/v1/host-text", port)
intent.Env["REIMS_GO_INPUT_TOKEN"] = gtCfg.Token
}
}
if reims.HasGuestToolsArgs(p.ExtraArgs) && cb.GuestToolsImg != nil && err == nil {
imgPath := cb.GuestToolsImg(p.VMName)
tokens := plugin.SplitShellTokens(reims.MergeGuestToolsArgs("", imgPath))
tokens := qmp.SplitArgs(reims.MergeGuestToolsArgs("", imgPath))
intent.Args = append(intent.Args, plugin.ArgFragment{
PluginID: IDGuestTools,
Key: "reimstools",
@@ -227,7 +219,7 @@ func defGuestTools(ver string, cb HostCallbacks, desiredFn func(string, bool) bo
}
}
func defClipboard(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
func defClipboard(ver string, desiredFn func(string, bool) bool) plugin.PluginDef {
minMB := 1.0
maxMB := 16.0
minFileMB := float64(guesttools.MinClipboardMaxFileMB)
+7 -1
View File
@@ -3,7 +3,9 @@ package plugin
import (
"context"
"fmt"
"slices"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
@@ -61,6 +63,11 @@ type BeforeCreateResult struct {
Patches map[string]any `json:"patches,omitempty"`
}
// HasCap reports whether a runtime declares the capability want.
func HasCap(caps []string, want string) bool {
return slices.ContainsFunc(caps, func(c string) bool { return strings.EqualFold(c, want) })
}
// BeforeStartPayload is passed to vm.beforeStart handlers.
type BeforeStartPayload struct {
VMName string `json:"vm_name"`
@@ -102,7 +109,6 @@ type HookBus struct {
mu sync.RWMutex
handlers map[string][]*HookRegistration
seq uint64
// Zero-overhead counter for log.onLine (§8.1): checked with atomic load
// before constructing LogLineEvent objects.
+3 -3
View File
@@ -14,9 +14,9 @@ import (
)
const (
createNoWindow = 0x08000000
createBreakawayFromJob = 0x01000000
createNewProcessGroup = 0x00000200
createNoWindow = 0x08000000
createBreakawayFromJob = 0x01000000
createNewProcessGroup = 0x00000200
)
func configureSidecarCmd(cmd *exec.Cmd) {
+4 -2
View File
@@ -445,10 +445,12 @@ func TestArgLedgerReconcilePreserveUserArgsAndStripOnDisable(t *testing.T) {
}
// Disable thirdparty.tweak -> its fragment is stripped cleanly, user + builtin remain.
stripped, changed := StripPluginFromArgs(res.ExtraArgs, reloaded, "thirdparty.tweak")
if !changed {
delete(active, "thirdparty.tweak")
after := ReconcileStartIntents(res.ExtraArgs, reloaded, active, intents[:1])
if !after.Changed {
t.Fatal("expected change on strip")
}
stripped := after.ExtraArgs
if strings.Contains(stripped, "usb-tablet") {
t.Fatalf("plugin fragment not stripped: %q", stripped)
}
+7 -79
View File
@@ -9,6 +9,9 @@ import (
"sort"
"strconv"
"strings"
"github.com/Nwflower/reims-go/internal/atomicfile"
"github.com/Nwflower/reims-go/internal/qmp"
)
const ArgLedgerFileName = ".reims-go-arg-ledger.json"
@@ -195,35 +198,7 @@ func SaveArgLedger(vmDir string, ledger *ArgLedger) error {
return err
}
ledger.Version = 1
raw, err := json.MarshalIndent(ledger, "", " ")
if err != nil {
return err
}
target := filepath.Join(vmDir, ArgLedgerFileName)
f, err := os.CreateTemp(vmDir, ArgLedgerFileName+".*.tmp")
if err != nil {
return err
}
tmp := f.Name()
if _, err := f.Write(append(raw, '\n')); err != nil {
_ = f.Close()
_ = os.Remove(tmp)
return err
}
if err := f.Sync(); err != nil {
_ = f.Close()
_ = os.Remove(tmp)
return err
}
if err := f.Close(); err != nil {
_ = os.Remove(tmp)
return err
}
if err := os.Rename(tmp, target); err != nil {
_ = os.Remove(tmp)
return err
}
return nil
return atomicfile.WriteJSON(filepath.Join(vmDir, ArgLedgerFileName), ledger, 0o600)
}
// ReconcileResult holds the merged extra-args, env vars, warnings, and post-start actions.
@@ -278,7 +253,7 @@ func validateSingleShellToken(tok string) error {
return fmt.Errorf("QEMU argument token %q contains unquoted whitespace or quotes", tok)
}
}
resplit := SplitShellTokens(tok)
resplit := qmp.SplitArgs(tok)
if len(resplit) != 1 || resplit[0] != tok {
return fmt.Errorf("QEMU argument token %q does not round-trip as a single token", tok)
}
@@ -412,7 +387,7 @@ func sanitizeEnvPrefix(pluginID string) string {
// UserExtraArgs returns the portion of currentExtraArgs that is NOT owned by
// any fragment currently recorded in ledger.
func UserExtraArgs(currentExtraArgs string, ledger *ArgLedger) string {
return strings.Join(stripOwnedTokens(SplitShellTokens(currentExtraArgs), ledger), " ")
return strings.Join(stripOwnedTokens(qmp.SplitArgs(currentExtraArgs), ledger), " ")
}
// ReconcileStartIntents strips previously owned fragments from currentExtraArgs
@@ -437,7 +412,7 @@ func reconcileStartIntents(currentExtraArgs string, ledger *ArgLedger, activePlu
ledger.Owners = map[string][]ArgFragment{}
}
userTokens := stripOwnedTokens(SplitShellTokens(currentExtraArgs), ledger)
userTokens := stripOwnedTokens(qmp.SplitArgs(currentExtraArgs), ledger)
if activePlugins != nil {
for pid := range ledger.Owners {
@@ -596,19 +571,6 @@ func reconcileStartIntents(currentExtraArgs string, ledger *ArgLedger, activePlu
return res
}
// StripPluginFromArgs removes all fragments owned by pluginID from currentExtraArgs
// and updates ledger, leaving user args and other plugins' args intact.
func StripPluginFromArgs(currentExtraArgs string, ledger *ArgLedger, pluginID string) (string, bool) {
if ledger == nil || len(ledger.Owners[pluginID]) == 0 {
return strings.TrimSpace(currentExtraArgs), false
}
sub := &ArgLedger{Owners: map[string][]ArgFragment{pluginID: ledger.Owners[pluginID]}}
tokens := stripOwnedTokens(SplitShellTokens(currentExtraArgs), sub)
delete(ledger.Owners, pluginID)
next := strings.TrimSpace(strings.Join(tokens, " "))
return next, next != strings.TrimSpace(currentExtraArgs)
}
func fragWins(candidate, existing ArgFragment) bool {
if candidate.Builtin != existing.Builtin {
return candidate.Builtin
@@ -695,37 +657,3 @@ func unquoteShellToken(token string) string {
}
return token
}
// SplitShellTokens splits a QEMU extra-args string preserving quoted tokens.
func SplitShellTokens(s string) []string {
var out []string
var cur strings.Builder
var quote byte
for i := 0; i < len(s); i++ {
c := s[i]
if quote != 0 {
cur.WriteByte(c)
if c == quote {
quote = 0
}
continue
}
if c == '\'' || c == '"' {
quote = c
cur.WriteByte(c)
continue
}
if c == ' ' || c == '\t' || c == '\n' || c == '\r' {
if cur.Len() > 0 {
out = append(out, cur.String())
cur.Reset()
}
continue
}
cur.WriteByte(c)
}
if cur.Len() > 0 {
out = append(out, cur.String())
}
return out
}
-1
View File
@@ -548,4 +548,3 @@ func TestCommunityLocaleTrustBoundaryAndNoInUseWakeup(t *testing.T) {
t.Fatalf("community pack failed to fill missing fr-FR name: %+v", localized[0].Name)
}
}
+1 -973
View File
@@ -1327,7 +1327,7 @@ func (m *Manager) ActiveThemePayload() ActiveThemePayload {
if installDir != "" && th.Stylesheet != "" {
if full, err := safeJoin(installDir, th.Stylesheet); err == nil {
if raw, err := os.ReadFile(full); err == nil {
if ValidateThemeCSSSafetyInDir(string(raw), filepath.Dir(full)) == nil {
if ValidateThemeCSSSafety(string(raw), filepath.Dir(full)) == nil {
payload.CSS = string(raw)
}
}
@@ -1377,978 +1377,6 @@ func (m *Manager) ActiveThemePayload() ActiveThemePayload {
return payload
}
// ResolvedLocalePacks loads and merges all active plugin locale contributions
// and per-plugin l10n bundles into frontend UI packs and backend/CLI catalogs.
// Returns nil in safe mode.
func (m *Manager) ResolvedLocalePacks() ([]ResolvedLocalePack, map[i18n.Locale]i18n.PluginCatalog) {
if m.safeMode {
return nil, nil
}
contribs := m.registry.Locales()
m.mu.RLock()
dirs := make(map[string]string, len(m.installDirs))
for k, v := range m.installDirs {
dirs[k] = v
}
m.mu.RUnlock()
type mergedPack struct {
pack ResolvedLocalePack
seenPID map[string]bool
backend map[string]string
}
byLocale := make(map[string]*mergedPack)
ensurePack := func(canon i18n.Locale) *mergedPack {
key := string(canon)
mp := byLocale[key]
if mp == nil {
mp = &mergedPack{
pack: ResolvedLocalePack{
Locale: key,
Fallback: string(i18n.DefaultFallback(canon)),
Messages: make(map[string]string),
},
seenPID: make(map[string]bool),
backend: make(map[string]string),
}
byLocale[key] = mp
}
return mp
}
setPluginMsg := func(mp *mergedPack, targetPID, k, v string, overwrite bool) {
if targetPID == "" || k == "" || v == "" {
return
}
if mp.pack.PluginMessages == nil {
mp.pack.PluginMessages = make(map[string]map[string]string)
}
pm := mp.pack.PluginMessages[targetPID]
if pm == nil {
pm = make(map[string]string)
mp.pack.PluginMessages[targetPID] = pm
}
if !overwrite {
if _, exists := pm[k]; exists {
return
}
}
pm[k] = v
}
// 1. Collect private `<l10n>/<locale>.json` bundles from active/degraded functional plugins (underlay).
// Use ActivePluginIDs() rather than List() so we never trigger inUseChecker / Sidecar wake-ups
// while Registry.Reconcile holds reconcileMu.
activeIDs := m.registry.ActivePluginIDs()
sortedActiveIDs := make([]string, 0, len(activeIDs))
for pid := range activeIDs {
sortedActiveIDs = append(sortedActiveIDs, pid)
}
sort.Strings(sortedActiveIDs)
for _, pid := range sortedActiveIDs {
man, ok := m.registry.ManifestOf(pid)
if !ok || strings.TrimSpace(man.L10n) == "" {
continue
}
selfDir := dirs[pid]
if selfDir == "" {
continue
}
l10nClean := strings.Trim(strings.TrimSpace(man.L10n), "/")
fullL10n, err := safeJoin(selfDir, l10nClean)
if err != nil {
continue
}
entries, err := os.ReadDir(fullL10n)
if err != nil {
continue
}
for _, ent := range entries {
if ent.IsDir() || !strings.HasSuffix(strings.ToLower(ent.Name()), ".json") {
continue
}
tagRaw := strings.TrimSuffix(ent.Name(), filepath.Ext(ent.Name()))
canon, ok := i18n.ParseLocale(tagRaw)
if !ok {
continue
}
loaded, err := loadLocaleJSONFile(selfDir, l10nClean+"/"+ent.Name())
if err != nil || len(loaded) == 0 {
continue
}
mp := ensurePack(canon)
for k, v := range loaded {
setPluginMsg(mp, pid, k, v, true)
}
}
}
// 2. Layer active Language Pack contributions (sorted deterministically by TrustRank -> Priority -> PluginID).
uiDomains := []string{"core", "vm", "wizard", "settings", "plugins", "macosGlossary", "macos-glossary"}
backendDomains := []string{"native", "macosGlossary", "macos-glossary", "core"}
for _, lc := range contribs {
canon, ok := i18n.ParseLocale(lc.Locale)
if !ok {
continue
}
privileged := isPrivilegedLocaleTrustRank(lc.TrustRank)
if !privileged && (canon == i18n.ZhCN || canon == i18n.EnUS) {
// Community/unprivileged language packs may not hijack built-in host catalogs.
continue
}
mp := ensurePack(canon)
if lbl := strings.TrimSpace(lc.Label); lbl != "" {
mp.pack.Label = lbl
}
if fb := strings.TrimSpace(lc.Fallback); fb != "" {
if cfb, ok := i18n.ParseLocale(fb); ok {
mp.pack.Fallback = string(cfb)
}
}
installDir := dirs[lc.PluginID]
if installDir != "" && strings.TrimSpace(lc.File) != "" {
if loaded, err := loadLocaleJSONFile(installDir, lc.File); err == nil {
for k, v := range loaded {
if k != "" && v != "" {
mp.pack.Messages[k] = v
}
}
}
}
if installDir != "" && len(lc.Files) > 0 {
for _, dom := range uiDomains {
if rel := strings.TrimSpace(lc.Files[dom]); rel != "" {
if loaded, err := loadLocaleJSONFile(installDir, rel); err == nil {
for k, v := range loaded {
if k != "" && v != "" {
mp.pack.Messages[k] = v
}
}
}
}
}
for _, dom := range backendDomains {
if rel := strings.TrimSpace(lc.Files[dom]); rel != "" {
if loaded, err := loadLocaleJSONFile(installDir, rel); err == nil {
for k, v := range loaded {
if k != "" && v != "" {
mp.backend[k] = v
}
}
}
}
}
}
for k, v := range lc.Messages {
if k != "" && v != "" {
mp.pack.Messages[k] = v
}
}
if installDir != "" && strings.TrimSpace(lc.BackendFile) != "" {
if loaded, err := loadLocaleJSONFile(installDir, lc.BackendFile); err == nil {
for k, v := range loaded {
if k != "" && v != "" {
mp.backend[k] = v
}
}
}
}
for k, v := range lc.Backend {
if k != "" && v != "" {
mp.backend[k] = v
}
}
// Resolve bundled WOFF2 WebFonts via AssetServer.
if installDir != "" && m.assets != nil && len(lc.Fonts) > 0 {
for _, f := range lc.Fonts {
if strings.TrimSpace(f.Family) == "" || !strings.EqualFold(filepath.Ext(strings.TrimSpace(f.File)), ".woff2") {
continue
}
if full, err := safeJoin(installDir, f.File); err == nil && verifyWOFF2Header(full) == nil {
mp.pack.Fonts = append(mp.pack.Fonts, ResolvedLocaleFont{
Family: f.Family,
URL: m.assets.AssetURL(lc.PluginID, f.File),
Weight: f.Weight,
Style: f.Style,
UnicodeRange: f.UnicodeRange,
})
}
}
}
// Layer cross-plugin message overrides onto PluginMessages[targetID].
// Unprivileged community packs may only fill in missing keys, never overwrite
// a target plugin's own messages.
for targetID, ov := range lc.PluginOverrides {
if installDir != "" && strings.TrimSpace(ov.MessagesFile) != "" {
if loaded, err := loadLocaleJSONFile(installDir, ov.MessagesFile); err == nil {
for k, v := range loaded {
setPluginMsg(mp, targetID, k, v, privileged)
}
}
}
for k, v := range ov.Messages {
setPluginMsg(mp, targetID, k, v, privileged)
}
}
if lc.PluginID != "" && !mp.seenPID[lc.PluginID] {
mp.seenPID[lc.PluginID] = true
mp.pack.PluginIDs = append(mp.pack.PluginIDs, lc.PluginID)
}
}
if len(byLocale) == 0 {
return nil, nil
}
uiPacks := make([]ResolvedLocalePack, 0, len(byLocale))
backendPacks := make(map[i18n.Locale]i18n.PluginCatalog, len(byLocale))
for key, mp := range byLocale {
if mp.pack.Label == "" {
mp.pack.Label = defaultLocaleLabel(key)
}
sort.Strings(mp.pack.PluginIDs)
if len(mp.pack.Messages) > 0 {
mp.pack.HasUIMessages = true
} else {
mp.pack.Messages = nil
}
uiPacks = append(uiPacks, mp.pack)
if len(mp.backend) > 0 {
backendPacks[i18n.Locale(key)] = i18n.PluginCatalog{
Fallback: i18n.Locale(mp.pack.Fallback),
Messages: mp.backend,
}
}
}
sort.Slice(uiPacks, func(i, j int) bool {
return uiPacks[i].Locale < uiPacks[j].Locale
})
if len(backendPacks) == 0 {
backendPacks = nil
}
return uiPacks, backendPacks
}
type resolvedManifestOverride struct {
locale string
privileged bool
ov PluginManifestOverride
}
func applyLocalizedOverride(lt *LocalizedText, locale, val string, privileged bool) {
if privileged {
lt.Set(locale, val)
} else {
lt.SetIfEmpty(locale, val)
}
}
func (m *Manager) activeManifestOverrides() map[string][]resolvedManifestOverride {
if m == nil || m.safeMode {
return nil
}
contribs := m.registry.Locales()
if len(contribs) == 0 {
return nil
}
m.mu.RLock()
dirs := make(map[string]string, len(m.installDirs))
for k, v := range m.installDirs {
dirs[k] = v
}
m.mu.RUnlock()
var out map[string][]resolvedManifestOverride
for _, lc := range contribs {
if len(lc.PluginOverrides) == 0 {
continue
}
canon, ok := i18n.ParseLocale(lc.Locale)
if !ok {
continue
}
privileged := isPrivilegedLocaleTrustRank(lc.TrustRank)
if !privileged && (canon == i18n.ZhCN || canon == i18n.EnUS) {
continue
}
packDir := dirs[lc.PluginID]
for targetID, po := range lc.PluginOverrides {
var merged PluginManifestOverride
hasAny := false
if packDir != "" && strings.TrimSpace(po.ManifestFile) != "" {
if loaded, err := loadPluginManifestOverrideFile(packDir, po.ManifestFile); err == nil && loaded != nil {
merged = *loaded
hasAny = true
}
}
if po.Manifest != nil {
if po.Manifest.Name != "" {
merged.Name = po.Manifest.Name
}
if po.Manifest.Description != "" {
merged.Description = po.Manifest.Description
}
if len(po.Manifest.Fields) > 0 {
if merged.Fields == nil {
merged.Fields = make(map[string]string, len(po.Manifest.Fields))
}
for fk, fv := range po.Manifest.Fields {
merged.Fields[fk] = fv
}
}
hasAny = true
}
if !hasAny {
continue
}
if out == nil {
out = make(map[string][]resolvedManifestOverride)
}
out[targetID] = append(out[targetID], resolvedManifestOverride{
locale: string(canon),
privileged: privileged,
ov: merged,
})
}
}
return out
}
func cloneLocalizedText(lt LocalizedText) LocalizedText {
out := LocalizedText{ZhCN: lt.ZhCN, EnUS: lt.EnUS}
if len(lt.Extra) > 0 {
out.Extra = make(map[string]string, len(lt.Extra))
for k, v := range lt.Extra {
out.Extra[k] = v
}
}
return out
}
func cloneSettingsSchemaWithOverrides(sc *SettingsSchema, list []resolvedManifestOverride) *SettingsSchema {
if sc == nil {
return nil
}
cp := *sc
cp.Title = cloneLocalizedText(sc.Title)
if len(sc.Properties) > 0 {
cp.Properties = make(map[string]SettingProperty, len(sc.Properties))
for pk, prop := range sc.Properties {
pcp := prop
pcp.Title = cloneLocalizedText(prop.Title)
pcp.Description = cloneLocalizedText(prop.Description)
cp.Properties[pk] = pcp
}
}
for _, r := range list {
if v := r.ov.Fields["settings.title"]; v != "" {
applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged)
}
for pk, prop := range cp.Properties {
changed := false
if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".title", pk+".title"); v != "" {
applyLocalizedOverride(&prop.Title, r.locale, v, r.privileged)
changed = true
}
if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".description", pk+".description"); v != "" {
applyLocalizedOverride(&prop.Description, r.locale, v, r.privileged)
changed = true
}
if changed {
cp.Properties[pk] = prop
}
}
}
return &cp
}
func firstNonEmptyField(fields map[string]string, keys ...string) string {
if len(fields) == 0 {
return ""
}
for _, k := range keys {
if v := strings.TrimSpace(fields[k]); v != "" {
return v
}
}
return ""
}
// LocalizePluginInfos returns a copy of infos enriched with any active Language Pack
// `pluginOverrides` translations for plugin Name, Description, and SettingsSchema.
func (m *Manager) LocalizePluginInfos(infos []PluginInfo) []PluginInfo {
ovs := m.activeManifestOverrides()
if len(ovs) == 0 || len(infos) == 0 {
return infos
}
out := make([]PluginInfo, len(infos))
for i, info := range infos {
cp := info
if list := ovs[info.ID]; len(list) > 0 {
cp.Name = cloneLocalizedText(info.Name)
cp.Description = cloneLocalizedText(info.Description)
for _, r := range list {
if r.ov.Name != "" {
applyLocalizedOverride(&cp.Name, r.locale, r.ov.Name, r.privileged)
}
if r.ov.Description != "" {
applyLocalizedOverride(&cp.Description, r.locale, r.ov.Description, r.privileged)
}
}
cp.Settings = cloneSettingsSchemaWithOverrides(info.Settings, list)
}
out[i] = cp
}
return out
}
// LocalizeMenus applies active Language Pack manifest overrides onto MenuContribution titles.
func (m *Manager) LocalizeMenus(items []MenuContribution) []MenuContribution {
ovs := m.activeManifestOverrides()
if len(ovs) == 0 || len(items) == 0 {
return items
}
out := make([]MenuContribution, len(items))
for i, it := range items {
cp := it
if list := ovs[it.PluginID]; len(list) > 0 {
cp.Title = cloneLocalizedText(it.Title)
for _, r := range list {
if v := firstNonEmptyField(r.ov.Fields, "menu."+it.ID+".title", "command."+it.Command+".title"); v != "" {
applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged)
}
}
}
out[i] = cp
}
return out
}
// LocalizePanels applies active Language Pack manifest overrides onto PanelContribution titles.
func (m *Manager) LocalizePanels(items []PanelContribution) []PanelContribution {
ovs := m.activeManifestOverrides()
if len(ovs) == 0 || len(items) == 0 {
return items
}
out := make([]PanelContribution, len(items))
for i, it := range items {
cp := it
if list := ovs[it.PluginID]; len(list) > 0 {
cp.Title = cloneLocalizedText(it.Title)
for _, r := range list {
if v := firstNonEmptyField(r.ov.Fields, "panel."+it.ID+".title"); v != "" {
applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged)
}
}
}
out[i] = cp
}
return out
}
// LocalizeViews applies active Language Pack manifest overrides onto ViewContribution titles.
func (m *Manager) LocalizeViews(items []ViewContribution) []ViewContribution {
ovs := m.activeManifestOverrides()
if len(ovs) == 0 || len(items) == 0 {
return items
}
out := make([]ViewContribution, len(items))
for i, it := range items {
cp := it
if list := ovs[it.PluginID]; len(list) > 0 {
cp.Title = cloneLocalizedText(it.Title)
for _, r := range list {
if v := firstNonEmptyField(r.ov.Fields, "view."+it.ID+".title"); v != "" {
applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged)
}
}
}
out[i] = cp
}
return out
}
// LocalizeImageSources applies active Language Pack manifest overrides onto ImageSourceContribution labels.
func (m *Manager) LocalizeImageSources(items []ImageSourceContribution) []ImageSourceContribution {
ovs := m.activeManifestOverrides()
if len(ovs) == 0 || len(items) == 0 {
return items
}
out := make([]ImageSourceContribution, len(items))
for i, it := range items {
cp := it
if list := ovs[it.PluginID]; len(list) > 0 {
cp.Title = cloneLocalizedText(it.Title)
cp.Description = cloneLocalizedText(it.Description)
for _, r := range list {
if v := firstNonEmptyField(r.ov.Fields, "imageSource."+it.ID+".title"); v != "" {
applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged)
}
if v := firstNonEmptyField(r.ov.Fields, "imageSource."+it.ID+".description"); v != "" {
applyLocalizedOverride(&cp.Description, r.locale, v, r.privileged)
}
}
}
out[i] = cp
}
return out
}
// LocalizeVMCards applies active Language Pack manifest overrides onto VMCardContribution labels.
func (m *Manager) LocalizeVMCards(items []VMCardContribution) []VMCardContribution {
ovs := m.activeManifestOverrides()
if len(ovs) == 0 || len(items) == 0 {
return items
}
out := make([]VMCardContribution, len(items))
for i, it := range items {
cp := it
if list := ovs[it.PluginID]; len(list) > 0 {
cp.Title = cloneLocalizedText(it.Title)
cp.Value = cloneLocalizedText(it.Value)
for _, r := range list {
if v := firstNonEmptyField(r.ov.Fields, "vmCard."+it.ID+".title"); v != "" {
applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged)
}
if v := firstNonEmptyField(r.ov.Fields, "vmCard."+it.ID+".value"); v != "" {
applyLocalizedOverride(&cp.Value, r.locale, v, r.privileged)
}
}
}
out[i] = cp
}
return out
}
// LocalizeSettingsPages applies active Language Pack manifest overrides onto SettingsPageContribution titles.
func (m *Manager) LocalizeSettingsPages(items []SettingsPageContribution) []SettingsPageContribution {
ovs := m.activeManifestOverrides()
if len(ovs) == 0 || len(items) == 0 {
return items
}
out := make([]SettingsPageContribution, len(items))
for i, it := range items {
cp := it
if list := ovs[it.PluginID]; len(list) > 0 {
cp.Title = cloneLocalizedText(it.Title)
for _, r := range list {
if v := firstNonEmptyField(r.ov.Fields, "settingsPage."+it.ID+".title"); v != "" {
applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged)
}
}
}
out[i] = cp
}
return out
}
// LocalizeStatusItems applies active Language Pack manifest overrides onto StatusItemContribution labels.
func (m *Manager) LocalizeStatusItems(items []StatusItemContribution) []StatusItemContribution {
ovs := m.activeManifestOverrides()
if len(ovs) == 0 || len(items) == 0 {
return items
}
out := make([]StatusItemContribution, len(items))
for i, it := range items {
cp := it
if list := ovs[it.PluginID]; len(list) > 0 {
cp.Text = cloneLocalizedText(it.Text)
cp.Tooltip = cloneLocalizedText(it.Tooltip)
for _, r := range list {
if v := firstNonEmptyField(r.ov.Fields, "statusItem."+it.ID+".text"); v != "" {
applyLocalizedOverride(&cp.Text, r.locale, v, r.privileged)
}
if v := firstNonEmptyField(r.ov.Fields, "statusItem."+it.ID+".tooltip"); v != "" {
applyLocalizedOverride(&cp.Tooltip, r.locale, v, r.privileged)
}
}
}
out[i] = cp
}
return out
}
// CurrentLocale returns the active effective host locale for plugin operations.
func (m *Manager) CurrentLocale() i18n.Locale {
if m != nil && m.opts.LocaleFn != nil {
return i18n.EffectiveLocale(m.opts.LocaleFn())
}
return i18n.Detect()
}
// PluginL10nBundle builds the merged private localization dictionary for pluginID
// in loc, layering the plugin's own `<l10n>/<tag>.json` files underneath any
// active Language Pack `pluginOverrides[pluginID]` entries along FallbackChain(loc).
func (m *Manager) PluginL10nBundle(pluginID string, loc i18n.Locale) map[string]string {
if m == nil || pluginID == "" || m.safeMode {
return nil
}
cacheKey := pluginID + "\x00" + string(loc)
m.mu.RLock()
gen := m.l10nGen
if cached, ok := m.l10nCache[cacheKey]; ok {
m.mu.RUnlock()
if len(cached) == 0 {
return nil
}
cp := make(map[string]string, len(cached))
for k, v := range cached {
cp[k] = v
}
return cp
}
selfDir := m.installDirs[pluginID]
dirs := make(map[string]string, len(m.installDirs))
for k, v := range m.installDirs {
dirs[k] = v
}
m.mu.RUnlock()
chain := i18n.FallbackChain(loc)
out := make(map[string]string)
var l10nRel string
selfLocaleFiles := make(map[string]string)
if man, ok := m.registry.ManifestOf(pluginID); ok && strings.TrimSpace(man.L10n) != "" {
l10nRel = strings.Trim(strings.TrimSpace(man.L10n), "/")
if selfDir != "" && l10nRel != "" {
if fullL10n, err := safeJoin(selfDir, l10nRel); err == nil {
if entries, err := os.ReadDir(fullL10n); err == nil {
for _, ent := range entries {
if ent.IsDir() || !strings.HasSuffix(strings.ToLower(ent.Name()), ".json") {
continue
}
tagRaw := strings.TrimSuffix(ent.Name(), filepath.Ext(ent.Name()))
if canon, ok := i18n.ParseLocale(tagRaw); ok {
if _, exists := selfLocaleFiles[string(canon)]; !exists {
selfLocaleFiles[string(canon)] = l10nRel + "/" + ent.Name()
}
}
}
}
}
}
}
contribs := m.registry.Locales()
// Walk fallback chain from least specific to most specific so higher-priority hops win.
for idx := len(chain) - 1; idx >= 0; idx-- {
step := string(chain[idx])
selfKeysThisStep := make(map[string]bool)
if rel, ok := selfLocaleFiles[step]; ok {
if loaded, err := loadLocaleJSONFile(selfDir, rel); err == nil {
for k, v := range loaded {
if k != "" && v != "" {
out[k] = v
selfKeysThisStep[k] = true
}
}
}
}
for _, lc := range contribs {
if lc.Locale != step {
continue
}
privileged := isPrivilegedLocaleTrustRank(lc.TrustRank)
if !privileged && (step == string(i18n.ZhCN) || step == string(i18n.EnUS)) {
continue
}
ov, ok := lc.PluginOverrides[pluginID]
if !ok {
continue
}
applyMsg := func(k, v string) {
if k == "" || v == "" {
return
}
if !privileged && selfKeysThisStep[k] {
return
}
out[k] = v
}
packDir := dirs[lc.PluginID]
if packDir != "" && strings.TrimSpace(ov.MessagesFile) != "" {
if loaded, err := loadLocaleJSONFile(packDir, ov.MessagesFile); err == nil {
for k, v := range loaded {
applyMsg(k, v)
}
}
}
for k, v := range ov.Messages {
applyMsg(k, v)
}
}
}
m.mu.Lock()
if m.l10nGen == gen {
if len(m.l10nCache) >= 512 {
clear(m.l10nCache)
}
if len(out) == 0 {
m.l10nCache[cacheKey] = nil
} else {
stored := make(map[string]string, len(out))
for k, v := range out {
stored[k] = v
}
m.l10nCache[cacheKey] = stored
}
}
m.mu.Unlock()
if len(out) == 0 {
return nil
}
return out
}
// NotifyLocaleChanged broadcasts `plugin/localeChanged` to all currently running
// L3 Sidecar processes without waking sleeping Sidecars.
func (m *Manager) NotifyLocaleChanged(eff i18n.Locale) {
if m == nil {
return
}
m.mu.RLock()
sups := make(map[string]*SidecarSupervisor, len(m.supervisors))
for pid, s := range m.supervisors {
sups[pid] = s
}
m.mu.RUnlock()
if len(sups) == 0 {
return
}
chain := i18n.FallbackChain(eff)
strChain := make([]string, len(chain))
for i, c := range chain {
strChain[i] = string(c)
}
for pid, sup := range sups {
if sup.PID() == 0 {
continue
}
sup.NotifyIfRunning("plugin/localeChanged", map[string]any{
"locale": string(eff),
"fallbackChain": strChain,
"l10nBundle": m.PluginL10nBundle(pid, eff),
})
}
}
func defaultLocaleLabel(code string) string {
switch code {
case string(i18n.ZhCN):
return "简体中文"
case string(i18n.EnUS):
return "English"
default:
return code
}
}
func isPrivilegedLocaleTrustRank(rank int) bool {
return rank == 10 || rank == 20 || rank >= 50
}
func localeTrustRank(source SourceKind, trust TrustLevel) int {
switch {
case source == SourceBuiltin:
return 10
case source == SourceBundled:
return 20
case trust == TrustCommunity:
return 30
case trust == TrustVerified:
return 40
case trust == TrustOfficial:
return 50
case source == SourceDevLink || trust == TrustDev:
return 60
default:
return 30
}
}
// LoadStaticLocalePacks performs an ultra-fast (< 2ms), side-effect-free scan of
// enabled plugins under dataRoot to populate backend/CLI language packs without
// starting any L3 Sidecars, AssetServer, or service dependency reconciliation.
func LoadStaticLocalePacks(dataRoot string) map[i18n.Locale]i18n.PluginCatalog {
if strings.TrimSpace(dataRoot) == "" {
i18n.SetPluginCatalogs(nil)
return nil
}
layout := NewPluginsLayout(dataRoot)
if DidLastStartupCrash(layout.Root) {
i18n.SetPluginCatalogs(nil)
return nil
}
st, err := NewStateStore(layout.Root).Load()
if err != nil || st == nil || len(st.Plugins) == 0 {
i18n.SetPluginCatalogs(nil)
return nil
}
type staticCandidate struct {
id string
dir string
rec *PluginRecord
rank int
}
var candidates []staticCandidate
for id, rec := range st.Plugins {
if rec == nil || !rec.Enabled || rec.Source == SourceBuiltin || rec.Source == SourceBundled {
continue
}
var dir string
if rec.Source == SourceDevLink {
if !st.DeveloperMode || strings.TrimSpace(rec.DevPath) == "" {
continue
}
dir = rec.DevPath
} else {
if rec.Version == "" || !reReverseDomainID.MatchString(id) {
continue
}
if _, err := ParseSemVer(rec.Version); err != nil {
continue
}
safeDir, err := safeJoin(layout.PkgsDir(), id+"/"+rec.Version)
if err != nil {
continue
}
dir = safeDir
}
candidates = append(candidates, staticCandidate{
id: id,
dir: dir,
rec: rec,
rank: localeTrustRank(rec.Source, rec.Trust),
})
}
sort.Slice(candidates, func(i, j int) bool {
if candidates[i].rank != candidates[j].rank {
return candidates[i].rank < candidates[j].rank
}
return candidates[i].id < candidates[j].id
})
type staticLocaleItem struct {
canon i18n.Locale
rank int
id string
dir string
lc LocaleContribution
}
var items []staticLocaleItem
for _, c := range candidates {
raw, err := os.ReadFile(filepath.Join(c.dir, "plugin.json"))
if err != nil {
continue
}
var man Manifest
if json.Unmarshal(raw, &man) != nil || len(man.Contributes.Locales) == 0 {
continue
}
if c.id != "" && man.ID != c.id {
continue
}
trust := c.rec.Trust
if trust == "" {
trust = TrustCommunity
}
if c.rec.Source == SourceDevLink {
trust = TrustDev
}
_, _, entryHash, err := resolveManifestEntry(man, c.dir, false)
if err != nil {
continue
}
if computeNeedsApproval(man, trust, c.rec.ApprovedPermissions, c.rec.ApprovedEntryHash, entryHash) {
continue
}
for _, lc := range man.Contributes.Locales {
canon, ok := i18n.ParseLocale(lc.Locale)
if !ok {
continue
}
items = append(items, staticLocaleItem{
canon: canon,
rank: c.rank,
id: c.id,
dir: c.dir,
lc: lc,
})
}
}
sort.Slice(items, func(i, j int) bool {
if items[i].canon != items[j].canon {
return items[i].canon < items[j].canon
}
if items[i].rank != items[j].rank {
return items[i].rank < items[j].rank
}
if items[i].lc.Priority != items[j].lc.Priority {
return items[i].lc.Priority < items[j].lc.Priority
}
return items[i].id < items[j].id
})
packs := make(map[i18n.Locale]i18n.PluginCatalog)
for _, it := range items {
canon := it.canon
if !isPrivilegedLocaleTrustRank(it.rank) && (canon == i18n.ZhCN || canon == i18n.EnUS) {
continue
}
lc := it.lc
cur, exists := packs[canon]
if !exists {
cur = i18n.PluginCatalog{
Fallback: i18n.DefaultFallback(canon),
Messages: make(map[string]string),
}
}
if fb, ok := i18n.ParseLocale(lc.Fallback); ok {
cur.Fallback = fb
}
// Match ResolvedLocalePacks precedence: Files first, then BackendFile, then inline Backend.
for _, domKey := range []string{"native", "macosGlossary", "macos-glossary", "core"} {
if rel := strings.TrimSpace(lc.Files[domKey]); rel != "" {
if loaded, err := loadLocaleJSONFile(it.dir, rel); err == nil {
for k, v := range loaded {
if k != "" && v != "" {
cur.Messages[k] = v
}
}
}
}
}
if strings.TrimSpace(lc.BackendFile) != "" {
if loaded, err := loadLocaleJSONFile(it.dir, lc.BackendFile); err == nil {
for k, v := range loaded {
if k != "" && v != "" {
cur.Messages[k] = v
}
}
}
}
for k, v := range lc.Backend {
if k != "" && v != "" {
cur.Messages[k] = v
}
}
if len(cur.Messages) > 0 {
packs[canon] = cur
}
}
i18n.SetPluginCatalogs(packs)
return packs
}
// ActiveVMNamesWithSetting scans saved VM settings for pluginID where key==true.
func (m *Manager) ActiveVMNamesWithSetting(pluginID, key string) []string {
m.mu.RLock()
+844
View File
@@ -0,0 +1,844 @@
package plugin
import (
"encoding/json"
"maps"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"github.com/Nwflower/reims-go/internal/i18n"
)
// ResolvedLocalePacks loads and merges all active plugin locale contributions
// and per-plugin l10n bundles into frontend UI packs and backend/CLI catalogs.
// Returns nil in safe mode.
func (m *Manager) ResolvedLocalePacks() ([]ResolvedLocalePack, map[i18n.Locale]i18n.PluginCatalog) {
if m.safeMode {
return nil, nil
}
contribs := m.registry.Locales()
m.mu.RLock()
dirs := maps.Clone(m.installDirs)
m.mu.RUnlock()
type mergedPack struct {
pack ResolvedLocalePack
seenPID map[string]bool
backend map[string]string
}
byLocale := make(map[string]*mergedPack)
ensurePack := func(canon i18n.Locale) *mergedPack {
key := string(canon)
mp := byLocale[key]
if mp == nil {
mp = &mergedPack{
pack: ResolvedLocalePack{
Locale: key,
Fallback: string(i18n.DefaultFallback(canon)),
Messages: make(map[string]string),
},
seenPID: make(map[string]bool),
backend: make(map[string]string),
}
byLocale[key] = mp
}
return mp
}
setPluginMsg := func(mp *mergedPack, targetPID, k, v string, overwrite bool) {
if targetPID == "" || k == "" || v == "" {
return
}
if mp.pack.PluginMessages == nil {
mp.pack.PluginMessages = make(map[string]map[string]string)
}
pm := mp.pack.PluginMessages[targetPID]
if pm == nil {
pm = make(map[string]string)
mp.pack.PluginMessages[targetPID] = pm
}
if !overwrite {
if _, exists := pm[k]; exists {
return
}
}
pm[k] = v
}
// 1. Collect private `<l10n>/<locale>.json` bundles from active/degraded functional plugins (underlay).
// Use ActivePluginIDs() rather than List() so we never trigger inUseChecker / Sidecar wake-ups
// while Registry.Reconcile holds reconcileMu.
activeIDs := m.registry.ActivePluginIDs()
sortedActiveIDs := make([]string, 0, len(activeIDs))
for pid := range activeIDs {
sortedActiveIDs = append(sortedActiveIDs, pid)
}
sort.Strings(sortedActiveIDs)
for _, pid := range sortedActiveIDs {
man, ok := m.registry.ManifestOf(pid)
if !ok {
continue
}
for _, file := range l10nFiles(dirs[pid], man.L10n) {
loaded, err := loadLocaleJSONFile(dirs[pid], file.rel)
if err != nil || len(loaded) == 0 {
continue
}
mp := ensurePack(file.locale)
for k, v := range loaded {
setPluginMsg(mp, pid, k, v, true)
}
}
}
// 2. Layer active Language Pack contributions (sorted deterministically by TrustRank -> Priority -> PluginID).
uiDomains := []string{"core", "vm", "wizard", "settings", "plugins", "macosGlossary", "macos-glossary"}
for _, lc := range contribs {
canon, ok := i18n.ParseLocale(lc.Locale)
if !ok {
continue
}
privileged := isPrivilegedLocaleTrustRank(lc.TrustRank)
if !privileged && (canon == i18n.ZhCN || canon == i18n.EnUS) {
// Community/unprivileged language packs may not hijack built-in host catalogs.
continue
}
mp := ensurePack(canon)
if lbl := strings.TrimSpace(lc.Label); lbl != "" {
mp.pack.Label = lbl
}
if fb := strings.TrimSpace(lc.Fallback); fb != "" {
if cfb, ok := i18n.ParseLocale(fb); ok {
mp.pack.Fallback = string(cfb)
}
}
installDir := dirs[lc.PluginID]
mergeLocaleFile(mp.pack.Messages, installDir, lc.File)
for _, dom := range uiDomains {
mergeLocaleFile(mp.pack.Messages, installDir, lc.Files[dom])
}
mergeMessages(mp.pack.Messages, lc.Messages)
mergeBackendMessages(mp.backend, installDir, lc)
// Resolve bundled WOFF2 WebFonts via AssetServer.
if installDir != "" && m.assets != nil && len(lc.Fonts) > 0 {
for _, f := range lc.Fonts {
if strings.TrimSpace(f.Family) == "" || !strings.EqualFold(filepath.Ext(strings.TrimSpace(f.File)), ".woff2") {
continue
}
if full, err := safeJoin(installDir, f.File); err == nil && verifyWOFF2Header(full) == nil {
mp.pack.Fonts = append(mp.pack.Fonts, ResolvedLocaleFont{
Family: f.Family,
URL: m.assets.AssetURL(lc.PluginID, f.File),
Weight: f.Weight,
Style: f.Style,
UnicodeRange: f.UnicodeRange,
})
}
}
}
// Layer cross-plugin message overrides onto PluginMessages[targetID].
// Unprivileged community packs may only fill in missing keys, never overwrite
// a target plugin's own messages.
for targetID, ov := range lc.PluginOverrides {
if installDir != "" && strings.TrimSpace(ov.MessagesFile) != "" {
if loaded, err := loadLocaleJSONFile(installDir, ov.MessagesFile); err == nil {
for k, v := range loaded {
setPluginMsg(mp, targetID, k, v, privileged)
}
}
}
for k, v := range ov.Messages {
setPluginMsg(mp, targetID, k, v, privileged)
}
}
if lc.PluginID != "" && !mp.seenPID[lc.PluginID] {
mp.seenPID[lc.PluginID] = true
mp.pack.PluginIDs = append(mp.pack.PluginIDs, lc.PluginID)
}
}
if len(byLocale) == 0 {
return nil, nil
}
uiPacks := make([]ResolvedLocalePack, 0, len(byLocale))
backendPacks := make(map[i18n.Locale]i18n.PluginCatalog, len(byLocale))
for key, mp := range byLocale {
if mp.pack.Label == "" {
mp.pack.Label = defaultLocaleLabel(key)
}
sort.Strings(mp.pack.PluginIDs)
if len(mp.pack.Messages) > 0 {
mp.pack.HasUIMessages = true
} else {
mp.pack.Messages = nil
}
uiPacks = append(uiPacks, mp.pack)
if len(mp.backend) > 0 {
backendPacks[i18n.Locale(key)] = i18n.PluginCatalog{
Fallback: i18n.Locale(mp.pack.Fallback),
Messages: mp.backend,
}
}
}
sort.Slice(uiPacks, func(i, j int) bool {
return uiPacks[i].Locale < uiPacks[j].Locale
})
if len(backendPacks) == 0 {
backendPacks = nil
}
return uiPacks, backendPacks
}
type resolvedManifestOverride struct {
locale string
privileged bool
ov PluginManifestOverride
}
func applyLocalizedOverride(lt *LocalizedText, locale, val string, privileged bool) {
if privileged {
lt.Set(locale, val)
} else {
lt.SetIfEmpty(locale, val)
}
}
func (m *Manager) activeManifestOverrides() map[string][]resolvedManifestOverride {
if m == nil || m.safeMode {
return nil
}
contribs := m.registry.Locales()
if len(contribs) == 0 {
return nil
}
m.mu.RLock()
dirs := maps.Clone(m.installDirs)
m.mu.RUnlock()
var out map[string][]resolvedManifestOverride
for _, lc := range contribs {
if len(lc.PluginOverrides) == 0 {
continue
}
canon, ok := i18n.ParseLocale(lc.Locale)
if !ok {
continue
}
privileged := isPrivilegedLocaleTrustRank(lc.TrustRank)
if !privileged && (canon == i18n.ZhCN || canon == i18n.EnUS) {
continue
}
packDir := dirs[lc.PluginID]
for targetID, po := range lc.PluginOverrides {
var merged PluginManifestOverride
hasAny := false
if packDir != "" && strings.TrimSpace(po.ManifestFile) != "" {
if loaded, err := loadPluginManifestOverrideFile(packDir, po.ManifestFile); err == nil && loaded != nil {
merged = *loaded
hasAny = true
}
}
if po.Manifest != nil {
if po.Manifest.Name != "" {
merged.Name = po.Manifest.Name
}
if po.Manifest.Description != "" {
merged.Description = po.Manifest.Description
}
if len(po.Manifest.Fields) > 0 {
if merged.Fields == nil {
merged.Fields = make(map[string]string, len(po.Manifest.Fields))
}
for fk, fv := range po.Manifest.Fields {
merged.Fields[fk] = fv
}
}
hasAny = true
}
if !hasAny {
continue
}
if out == nil {
out = make(map[string][]resolvedManifestOverride)
}
out[targetID] = append(out[targetID], resolvedManifestOverride{
locale: string(canon),
privileged: privileged,
ov: merged,
})
}
}
return out
}
func cloneLocalizedText(lt LocalizedText) LocalizedText {
out := LocalizedText{ZhCN: lt.ZhCN, EnUS: lt.EnUS}
if len(lt.Extra) > 0 {
out.Extra = make(map[string]string, len(lt.Extra))
for k, v := range lt.Extra {
out.Extra[k] = v
}
}
return out
}
func cloneSettingsSchemaWithOverrides(sc *SettingsSchema, list []resolvedManifestOverride) *SettingsSchema {
if sc == nil {
return nil
}
cp := *sc
cp.Title = cloneLocalizedText(sc.Title)
if len(sc.Properties) > 0 {
cp.Properties = make(map[string]SettingProperty, len(sc.Properties))
for pk, prop := range sc.Properties {
pcp := prop
pcp.Title = cloneLocalizedText(prop.Title)
pcp.Description = cloneLocalizedText(prop.Description)
cp.Properties[pk] = pcp
}
}
for _, r := range list {
if v := r.ov.Fields["settings.title"]; v != "" {
applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged)
}
for pk, prop := range cp.Properties {
changed := false
if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".title", pk+".title"); v != "" {
applyLocalizedOverride(&prop.Title, r.locale, v, r.privileged)
changed = true
}
if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".description", pk+".description"); v != "" {
applyLocalizedOverride(&prop.Description, r.locale, v, r.privileged)
changed = true
}
if changed {
cp.Properties[pk] = prop
}
}
}
return &cp
}
func firstNonEmptyField(fields map[string]string, keys ...string) string {
if len(fields) == 0 {
return ""
}
for _, k := range keys {
if v := strings.TrimSpace(fields[k]); v != "" {
return v
}
}
return ""
}
// LocalizePluginInfos returns a copy of infos enriched with any active Language Pack
// `pluginOverrides` translations for plugin Name, Description, and SettingsSchema.
func (m *Manager) LocalizePluginInfos(infos []PluginInfo) []PluginInfo {
ovs := m.activeManifestOverrides()
if len(ovs) == 0 || len(infos) == 0 {
return infos
}
out := make([]PluginInfo, len(infos))
for i, info := range infos {
cp := info
if list := ovs[info.ID]; len(list) > 0 {
cp.Name = cloneLocalizedText(info.Name)
cp.Description = cloneLocalizedText(info.Description)
for _, r := range list {
if r.ov.Name != "" {
applyLocalizedOverride(&cp.Name, r.locale, r.ov.Name, r.privileged)
}
if r.ov.Description != "" {
applyLocalizedOverride(&cp.Description, r.locale, r.ov.Description, r.privileged)
}
}
cp.Settings = cloneSettingsSchemaWithOverrides(info.Settings, list)
}
out[i] = cp
}
return out
}
// overridableText is a contribution text that a Language Pack may replace, and
// the override fields that do so, in order of preference.
type overridableText struct {
text *LocalizedText
keys []string
}
// localizeContributions returns a copy of items with the active Language Pack
// overrides applied to the texts that texts lists for each item.
func localizeContributions[T any](m *Manager, items []T, texts func(*T) (pluginID string, list []overridableText)) []T {
ovs := m.activeManifestOverrides()
if len(ovs) == 0 || len(items) == 0 {
return items
}
out := slices.Clone(items)
for i := range out {
pluginID, list := texts(&out[i])
for _, t := range list {
if len(ovs[pluginID]) > 0 {
*t.text = cloneLocalizedText(*t.text)
}
for _, r := range ovs[pluginID] {
if v := firstNonEmptyField(r.ov.Fields, t.keys...); v != "" {
applyLocalizedOverride(t.text, r.locale, v, r.privileged)
}
}
}
}
return out
}
// LocalizeMenus applies Language Pack overrides to menu titles.
func (m *Manager) LocalizeMenus(items []MenuContribution) []MenuContribution {
return localizeContributions(m, items, func(c *MenuContribution) (string, []overridableText) {
return c.PluginID, []overridableText{{&c.Title, []string{"menu." + c.ID + ".title", "command." + c.Command + ".title"}}}
})
}
// LocalizePanels applies Language Pack overrides to panel titles.
func (m *Manager) LocalizePanels(items []PanelContribution) []PanelContribution {
return localizeContributions(m, items, func(c *PanelContribution) (string, []overridableText) {
return c.PluginID, []overridableText{{&c.Title, []string{"panel." + c.ID + ".title"}}}
})
}
// LocalizeViews applies Language Pack overrides to view titles.
func (m *Manager) LocalizeViews(items []ViewContribution) []ViewContribution {
return localizeContributions(m, items, func(c *ViewContribution) (string, []overridableText) {
return c.PluginID, []overridableText{{&c.Title, []string{"view." + c.ID + ".title"}}}
})
}
// LocalizeImageSources applies Language Pack overrides to image source titles and descriptions.
func (m *Manager) LocalizeImageSources(items []ImageSourceContribution) []ImageSourceContribution {
return localizeContributions(m, items, func(c *ImageSourceContribution) (string, []overridableText) {
return c.PluginID, []overridableText{
{&c.Title, []string{"imageSource." + c.ID + ".title"}},
{&c.Description, []string{"imageSource." + c.ID + ".description"}},
}
})
}
// LocalizeVMCards applies Language Pack overrides to VM card titles and values.
func (m *Manager) LocalizeVMCards(items []VMCardContribution) []VMCardContribution {
return localizeContributions(m, items, func(c *VMCardContribution) (string, []overridableText) {
return c.PluginID, []overridableText{
{&c.Title, []string{"vmCard." + c.ID + ".title"}},
{&c.Value, []string{"vmCard." + c.ID + ".value"}},
}
})
}
// LocalizeSettingsPages applies Language Pack overrides to settings page titles.
func (m *Manager) LocalizeSettingsPages(items []SettingsPageContribution) []SettingsPageContribution {
return localizeContributions(m, items, func(c *SettingsPageContribution) (string, []overridableText) {
return c.PluginID, []overridableText{{&c.Title, []string{"settingsPage." + c.ID + ".title"}}}
})
}
// LocalizeStatusItems applies Language Pack overrides to status item texts and tooltips.
func (m *Manager) LocalizeStatusItems(items []StatusItemContribution) []StatusItemContribution {
return localizeContributions(m, items, func(c *StatusItemContribution) (string, []overridableText) {
return c.PluginID, []overridableText{
{&c.Text, []string{"statusItem." + c.ID + ".text"}},
{&c.Tooltip, []string{"statusItem." + c.ID + ".tooltip"}},
}
})
}
// CurrentLocale returns the active effective host locale for plugin operations.
func (m *Manager) CurrentLocale() i18n.Locale {
if m != nil && m.opts.LocaleFn != nil {
return i18n.EffectiveLocale(m.opts.LocaleFn())
}
return i18n.Detect()
}
// PluginL10nBundle builds the merged private localization dictionary for pluginID
// in loc, layering the plugin's own `<l10n>/<tag>.json` files underneath any
// active Language Pack `pluginOverrides[pluginID]` entries along FallbackChain(loc).
func (m *Manager) PluginL10nBundle(pluginID string, loc i18n.Locale) map[string]string {
if m == nil || pluginID == "" || m.safeMode {
return nil
}
cacheKey := pluginID + "\x00" + string(loc)
m.mu.RLock()
gen := m.l10nGen
if cached, ok := m.l10nCache[cacheKey]; ok {
m.mu.RUnlock()
if len(cached) == 0 {
return nil
}
return maps.Clone(cached)
}
selfDir := m.installDirs[pluginID]
dirs := maps.Clone(m.installDirs)
m.mu.RUnlock()
chain := i18n.FallbackChain(loc)
out := make(map[string]string)
selfLocaleFiles := make(map[string]string)
if man, ok := m.registry.ManifestOf(pluginID); ok {
for _, file := range l10nFiles(selfDir, man.L10n) {
if _, exists := selfLocaleFiles[string(file.locale)]; !exists {
selfLocaleFiles[string(file.locale)] = file.rel
}
}
}
contribs := m.registry.Locales()
// Walk fallback chain from least specific to most specific so higher-priority hops win.
for idx := len(chain) - 1; idx >= 0; idx-- {
step := string(chain[idx])
selfKeysThisStep := make(map[string]bool)
if rel, ok := selfLocaleFiles[step]; ok {
if loaded, err := loadLocaleJSONFile(selfDir, rel); err == nil {
for k, v := range loaded {
if k != "" && v != "" {
out[k] = v
selfKeysThisStep[k] = true
}
}
}
}
for _, lc := range contribs {
if lc.Locale != step {
continue
}
privileged := isPrivilegedLocaleTrustRank(lc.TrustRank)
if !privileged && (step == string(i18n.ZhCN) || step == string(i18n.EnUS)) {
continue
}
ov, ok := lc.PluginOverrides[pluginID]
if !ok {
continue
}
applyMsg := func(k, v string) {
if k == "" || v == "" {
return
}
if !privileged && selfKeysThisStep[k] {
return
}
out[k] = v
}
packDir := dirs[lc.PluginID]
if packDir != "" && strings.TrimSpace(ov.MessagesFile) != "" {
if loaded, err := loadLocaleJSONFile(packDir, ov.MessagesFile); err == nil {
for k, v := range loaded {
applyMsg(k, v)
}
}
}
for k, v := range ov.Messages {
applyMsg(k, v)
}
}
}
m.mu.Lock()
if m.l10nGen == gen {
if len(m.l10nCache) >= 512 {
clear(m.l10nCache)
}
if len(out) == 0 {
m.l10nCache[cacheKey] = nil
} else {
m.l10nCache[cacheKey] = maps.Clone(out)
}
}
m.mu.Unlock()
if len(out) == 0 {
return nil
}
return out
}
// NotifyLocaleChanged broadcasts `plugin/localeChanged` to all currently running
// L3 Sidecar processes without waking sleeping Sidecars.
func (m *Manager) NotifyLocaleChanged(eff i18n.Locale) {
if m == nil {
return
}
m.mu.RLock()
sups := maps.Clone(m.supervisors)
m.mu.RUnlock()
if len(sups) == 0 {
return
}
chain := i18n.FallbackChain(eff)
strChain := make([]string, len(chain))
for i, c := range chain {
strChain[i] = string(c)
}
for pid, sup := range sups {
if sup.PID() == 0 {
continue
}
sup.NotifyIfRunning("plugin/localeChanged", map[string]any{
"locale": string(eff),
"fallbackChain": strChain,
"l10nBundle": m.PluginL10nBundle(pid, eff),
})
}
}
func defaultLocaleLabel(code string) string {
switch code {
case string(i18n.ZhCN):
return "简体中文"
case string(i18n.EnUS):
return "English"
default:
return code
}
}
func isPrivilegedLocaleTrustRank(rank int) bool {
return rank == 10 || rank == 20 || rank >= 50
}
func localeTrustRank(source SourceKind, trust TrustLevel) int {
switch {
case source == SourceBuiltin:
return 10
case source == SourceBundled:
return 20
case trust == TrustCommunity:
return 30
case trust == TrustVerified:
return 40
case trust == TrustOfficial:
return 50
case source == SourceDevLink || trust == TrustDev:
return 60
default:
return 30
}
}
func mergeMessages(dst, src map[string]string) {
for k, v := range src {
if k != "" && v != "" {
dst[k] = v
}
}
}
// mergeLocaleFile merges the messages in dir/rel into dst. A missing or
// invalid file adds nothing; the plugin scanner reports those.
func mergeLocaleFile(dst map[string]string, dir, rel string) {
rel = strings.TrimSpace(rel)
if dir == "" || rel == "" {
return
}
if loaded, err := loadLocaleJSONFile(dir, rel); err == nil {
mergeMessages(dst, loaded)
}
}
// mergeBackendMessages merges the Go-side messages of one language pack.
// Later sources win: domain files, the backend file, then inline messages.
func mergeBackendMessages(dst map[string]string, dir string, lc LocaleContribution) {
for _, dom := range []string{"native", "macosGlossary", "macos-glossary", "core"} {
mergeLocaleFile(dst, dir, lc.Files[dom])
}
mergeLocaleFile(dst, dir, lc.BackendFile)
mergeMessages(dst, lc.Backend)
}
// l10nFile is one `<l10n>/<locale>.json` message file of a plugin.
type l10nFile struct {
locale i18n.Locale
rel string
}
// l10nFiles lists the private message files a plugin ships in its l10n folder.
func l10nFiles(pluginDir, l10n string) []l10nFile {
l10n = strings.Trim(strings.TrimSpace(l10n), "/")
if pluginDir == "" || l10n == "" {
return nil
}
full, err := safeJoin(pluginDir, l10n)
if err != nil {
return nil
}
entries, err := os.ReadDir(full)
if err != nil {
return nil
}
var files []l10nFile
for _, ent := range entries {
if ent.IsDir() || !strings.HasSuffix(strings.ToLower(ent.Name()), ".json") {
continue
}
tag := strings.TrimSuffix(ent.Name(), filepath.Ext(ent.Name()))
if canon, ok := i18n.ParseLocale(tag); ok {
files = append(files, l10nFile{locale: canon, rel: l10n + "/" + ent.Name()})
}
}
return files
}
// LoadStaticLocalePacks performs an ultra-fast (< 2ms), side-effect-free scan of
// enabled plugins under dataRoot to populate backend/CLI language packs without
// starting any L3 Sidecars, AssetServer, or service dependency reconciliation.
func LoadStaticLocalePacks(dataRoot string) map[i18n.Locale]i18n.PluginCatalog {
if strings.TrimSpace(dataRoot) == "" {
i18n.SetPluginCatalogs(nil)
return nil
}
layout := NewPluginsLayout(dataRoot)
if DidLastStartupCrash(layout.Root) {
i18n.SetPluginCatalogs(nil)
return nil
}
st, err := NewStateStore(layout.Root).Load()
if err != nil || st == nil || len(st.Plugins) == 0 {
i18n.SetPluginCatalogs(nil)
return nil
}
type staticCandidate struct {
id string
dir string
rec *PluginRecord
rank int
}
var candidates []staticCandidate
for id, rec := range st.Plugins {
if rec == nil || !rec.Enabled || rec.Source == SourceBuiltin || rec.Source == SourceBundled {
continue
}
var dir string
if rec.Source == SourceDevLink {
if !st.DeveloperMode || strings.TrimSpace(rec.DevPath) == "" {
continue
}
dir = rec.DevPath
} else {
if rec.Version == "" || !reReverseDomainID.MatchString(id) {
continue
}
if _, err := ParseSemVer(rec.Version); err != nil {
continue
}
safeDir, err := safeJoin(layout.PkgsDir(), id+"/"+rec.Version)
if err != nil {
continue
}
dir = safeDir
}
candidates = append(candidates, staticCandidate{
id: id,
dir: dir,
rec: rec,
rank: localeTrustRank(rec.Source, rec.Trust),
})
}
sort.Slice(candidates, func(i, j int) bool {
if candidates[i].rank != candidates[j].rank {
return candidates[i].rank < candidates[j].rank
}
return candidates[i].id < candidates[j].id
})
type staticLocaleItem struct {
canon i18n.Locale
rank int
id string
dir string
lc LocaleContribution
}
var items []staticLocaleItem
for _, c := range candidates {
raw, err := os.ReadFile(filepath.Join(c.dir, "plugin.json"))
if err != nil {
continue
}
var man Manifest
if json.Unmarshal(raw, &man) != nil || len(man.Contributes.Locales) == 0 {
continue
}
if c.id != "" && man.ID != c.id {
continue
}
trust := c.rec.Trust
if trust == "" {
trust = TrustCommunity
}
if c.rec.Source == SourceDevLink {
trust = TrustDev
}
_, _, entryHash, err := resolveManifestEntry(man, c.dir, false)
if err != nil {
continue
}
if computeNeedsApproval(man, trust, c.rec.ApprovedPermissions, c.rec.ApprovedEntryHash, entryHash) {
continue
}
for _, lc := range man.Contributes.Locales {
canon, ok := i18n.ParseLocale(lc.Locale)
if !ok {
continue
}
items = append(items, staticLocaleItem{
canon: canon,
rank: c.rank,
id: c.id,
dir: c.dir,
lc: lc,
})
}
}
sort.Slice(items, func(i, j int) bool {
if items[i].canon != items[j].canon {
return items[i].canon < items[j].canon
}
if items[i].rank != items[j].rank {
return items[i].rank < items[j].rank
}
if items[i].lc.Priority != items[j].lc.Priority {
return items[i].lc.Priority < items[j].lc.Priority
}
return items[i].id < items[j].id
})
packs := make(map[i18n.Locale]i18n.PluginCatalog)
for _, it := range items {
canon := it.canon
if !isPrivilegedLocaleTrustRank(it.rank) && (canon == i18n.ZhCN || canon == i18n.EnUS) {
continue
}
lc := it.lc
cur, exists := packs[canon]
if !exists {
cur = i18n.PluginCatalog{
Fallback: i18n.DefaultFallback(canon),
Messages: make(map[string]string),
}
}
if fb, ok := i18n.ParseLocale(lc.Fallback); ok {
cur.Fallback = fb
}
mergeBackendMessages(cur.Messages, it.dir, lc)
if len(cur.Messages) > 0 {
packs[canon] = cur
}
}
i18n.SetPluginCatalogs(packs)
return packs
}
+6 -6
View File
@@ -19,7 +19,7 @@ import (
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginsdk"
)
@@ -148,7 +148,7 @@ func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) {
Trust: plugin.TrustOfficial,
PublicKey: pub,
}},
RedactFn: reims.RedactText,
RedactFn: host.RedactText,
})
if err != nil {
t.Fatal(err)
@@ -222,7 +222,7 @@ func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) {
Parts: []string{"rg-p-sidebar"},
Tokens: []string{"--surface-sidebar"},
}
findings := plugin.DoctorDirectory(info.InstallDir, "0.2.6", contract)
findings := plugin.ScanDirectory(info.InstallDir, "0.2.6", plugin.ScanOptions{Contract: contract}).ToDoctorFindings()
for _, f := range findings {
if f.Severity == "error" || f.Severity == "warn" {
t.Fatalf("unexpected doctor finding on valid theme: %+v", f)
@@ -268,7 +268,7 @@ func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) {
// 4. Market redline: reject Apple .ipsw inside zip.
redlineZip := makePluginZip(t, map[string][]byte{
"plugin.json": manifestJSON,
"plugin.json": manifestJSON,
"Universal.ipsw": []byte("nope"),
}, nil, false)
if _, err := mgr.InstallLocalArchive(context.Background(), redlineZip, plugin.PackageInstallOptions{}); err == nil {
@@ -289,7 +289,7 @@ func TestSidecarSupervisionReverseHostAPIDriverAndCrashIsolation(t *testing.T) {
dataRoot := t.TempDir()
layout := plugin.NewPluginsLayout(dataRoot)
reg := plugin.NewRegistry(nil)
broker := plugin.NewBroker(layout, reg, reims.RedactText)
broker := plugin.NewBroker(layout, reg, host.RedactText)
notified := make(chan string, 1)
broker.SetNotifier(func(pid, title, body string) {
@@ -361,7 +361,7 @@ func TestSidecarSupervisionReverseHostAPIDriverAndCrashIsolation(t *testing.T) {
}
// 3. Diagnostics collection enforces host redaction of MAC & serial (§4.2, §7.1).
diags := reg.CollectDiagnostics(context.Background(), "ubuntu-24", reims.RedactText)
diags := reg.CollectDiagnostics(context.Background(), "ubuntu-24", host.RedactText)
if len(diags) != 1 {
t.Fatalf("expected 1 diag entry, got %d", len(diags))
}
+3 -25
View File
@@ -17,6 +17,7 @@ import (
"sync"
"time"
"github.com/Nwflower/reims-go/internal/atomicfile"
"github.com/Nwflower/reims-go/internal/fetch"
"github.com/Nwflower/reims-go/internal/netproxy"
)
@@ -699,33 +700,10 @@ func (c *MarketClient) writeDiskCache(idx MarketIndex) error {
c.diskCacheMu.Lock()
defer c.diskCacheMu.Unlock()
cachePath := c.layout.IndexCachePath()
dir := filepath.Dir(cachePath)
if err := os.MkdirAll(dir, 0o755); err != nil {
if err := os.MkdirAll(filepath.Dir(cachePath), 0o755); err != nil {
return err
}
raw, err := json.MarshalIndent(idx, "", " ")
if err != nil {
return err
}
tmpFile, err := os.CreateTemp(dir, "index-cache-*.tmp")
if err != nil {
return err
}
tmpPath := tmpFile.Name()
if _, err := tmpFile.Write(raw); err != nil {
_ = tmpFile.Close()
_ = os.Remove(tmpPath)
return err
}
if err := tmpFile.Close(); err != nil {
_ = os.Remove(tmpPath)
return err
}
if err := os.Rename(tmpPath, cachePath); err != nil {
_ = os.Remove(tmpPath)
return err
}
return nil
return atomicfile.WriteJSON(cachePath, idx, 0o600)
}
func selectChannelEntries(entries []MarketEntry, includeAlpha bool) map[string]MarketEntry {
-10
View File
@@ -684,16 +684,6 @@ func InstallArchive(layout PluginsLayout, archivePath string, opts PackageInstal
}, 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_-]+)`)
+63 -230
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"slices"
"sort"
"strings"
"sync"
@@ -765,6 +766,42 @@ func (r *Registry) LookupService(name string) (any, bool) {
// --- Extension point registration (all reversible via Scope.OnDispose) ---
// addScoped appends item to list until sc is disposed. admit, when set, decides
// under the lock whether the list still takes it; same finds the item again.
func addScoped[T any](r *Registry, sc *Scope, list *[]T, item T, same func(T) bool, admit func() bool) {
r.mu.Lock()
ok := admit == nil || admit()
if ok {
*list = append(*list, item)
}
r.mu.Unlock()
if !ok {
return
}
sc.OnDispose(func() {
r.mu.Lock()
*list = slices.DeleteFunc(*list, same)
r.mu.Unlock()
})
}
// listScoped copies a list for a reader; the copy is never nil.
func listScoped[T any](r *Registry, list *[]T) []T {
r.mu.RLock()
defer r.mu.RUnlock()
return append([]T{}, *list...)
}
func countFunc[T any](list []T, match func(T) bool) int {
n := 0
for _, item := range list {
if match(item) {
n++
}
}
return n
}
func (r *Registry) RegisterTheme(sc *Scope, th ThemeContribution) {
if th.ID == "" {
return
@@ -970,86 +1007,31 @@ func (r *Registry) RegisterInputFilter(sc *Scope, flt InputFilterContribution) {
return
}
flt.PluginID = sc.PluginID()
r.mu.Lock()
r.inputFilters = append(r.inputFilters, flt)
r.mu.Unlock()
sc.OnDispose(func() {
r.mu.Lock()
kept := r.inputFilters[:0]
for _, item := range r.inputFilters {
if !(item.PluginID == sc.PluginID() && item.ID == flt.ID) {
kept = append(kept, item)
}
}
r.inputFilters = kept
r.mu.Unlock()
})
addScoped(r, sc, &r.inputFilters, flt, func(x InputFilterContribution) bool { return x.PluginID == flt.PluginID && x.ID == flt.ID }, nil)
}
func (r *Registry) InputFilters() []InputFilterContribution {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]InputFilterContribution, len(r.inputFilters))
copy(out, r.inputFilters)
return out
}
func (r *Registry) InputFilters() []InputFilterContribution { return listScoped(r, &r.inputFilters) }
func (r *Registry) RegisterVMTemplate(sc *Scope, tpl VMTemplateContribution) {
if tpl.ID == "" {
return
}
tpl.PluginID = sc.PluginID()
r.mu.Lock()
r.vmTemplates = append(r.vmTemplates, tpl)
r.mu.Unlock()
sc.OnDispose(func() {
r.mu.Lock()
kept := r.vmTemplates[:0]
for _, item := range r.vmTemplates {
if !(item.PluginID == sc.PluginID() && item.ID == tpl.ID) {
kept = append(kept, item)
}
}
r.vmTemplates = kept
r.mu.Unlock()
})
addScoped(r, sc, &r.vmTemplates, tpl, func(x VMTemplateContribution) bool { return x.PluginID == tpl.PluginID && x.ID == tpl.ID }, nil)
}
func (r *Registry) VMTemplates() []VMTemplateContribution {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]VMTemplateContribution, len(r.vmTemplates))
copy(out, r.vmTemplates)
return out
}
func (r *Registry) VMTemplates() []VMTemplateContribution { return listScoped(r, &r.vmTemplates) }
func (r *Registry) RegisterRuntimeSource(sc *Scope, rs RuntimeSourceContribution) {
if rs.ID == "" || rs.IndexURL == "" {
return
}
rs.PluginID = sc.PluginID()
r.mu.Lock()
r.runtimeSources = append(r.runtimeSources, rs)
r.mu.Unlock()
sc.OnDispose(func() {
r.mu.Lock()
kept := r.runtimeSources[:0]
for _, item := range r.runtimeSources {
if !(item.PluginID == sc.PluginID() && item.ID == rs.ID) {
kept = append(kept, item)
}
}
r.runtimeSources = kept
r.mu.Unlock()
})
addScoped(r, sc, &r.runtimeSources, rs, func(x RuntimeSourceContribution) bool { return x.PluginID == rs.PluginID && x.ID == rs.ID }, nil)
}
func (r *Registry) RuntimeSources() []RuntimeSourceContribution {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]RuntimeSourceContribution, len(r.runtimeSources))
copy(out, r.runtimeSources)
return out
return listScoped(r, &r.runtimeSources)
}
func (r *Registry) RegisterRuntimeKind(sc *Scope, rk RuntimeKindContribution) {
@@ -1259,29 +1241,8 @@ func (r *Registry) RegisterMenu(sc *Scope, m MenuContribution) {
return
}
m.PluginID = sc.PluginID()
r.mu.Lock()
count := 0
for _, existing := range r.menus {
if existing.Slot == m.Slot {
count++
}
}
if count >= DeclaredUISlots[m.Slot] {
r.mu.Unlock()
return
}
r.menus = append(r.menus, m)
r.mu.Unlock()
sc.OnDispose(func() {
r.mu.Lock()
kept := r.menus[:0]
for _, item := range r.menus {
if !(item.PluginID == sc.PluginID() && item.ID == m.ID) {
kept = append(kept, item)
}
}
r.menus = kept
r.mu.Unlock()
addScoped(r, sc, &r.menus, m, func(x MenuContribution) bool { return x.PluginID == m.PluginID && x.ID == m.ID }, func() bool {
return countFunc(r.menus, func(x MenuContribution) bool { return x.Slot == m.Slot }) < DeclaredUISlots[m.Slot]
})
}
@@ -1299,63 +1260,17 @@ func (r *Registry) Menus(slot string) []MenuContribution {
func (r *Registry) RegisterVMCard(sc *Scope, c VMCardContribution) {
c.PluginID = sc.PluginID()
r.mu.Lock()
if len(r.vmCards) >= DeclaredUISlots["vm.card"] {
r.mu.Unlock()
return
}
r.vmCards = append(r.vmCards, c)
r.mu.Unlock()
sc.OnDispose(func() {
r.mu.Lock()
kept := r.vmCards[:0]
for _, item := range r.vmCards {
if !(item.PluginID == sc.PluginID() && item.ID == c.ID) {
kept = append(kept, item)
}
}
r.vmCards = kept
r.mu.Unlock()
})
addScoped(r, sc, &r.vmCards, c, func(x VMCardContribution) bool { return x.PluginID == c.PluginID && x.ID == c.ID }, func() bool { return len(r.vmCards) < DeclaredUISlots["vm.card"] })
}
func (r *Registry) VMCards() []VMCardContribution {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]VMCardContribution, len(r.vmCards))
copy(out, r.vmCards)
return out
}
func (r *Registry) VMCards() []VMCardContribution { return listScoped(r, &r.vmCards) }
func (r *Registry) RegisterSettingsPage(sc *Scope, sp SettingsPageContribution) {
sp.PluginID = sc.PluginID()
r.mu.Lock()
if len(r.settingsPages) >= DeclaredUISlots["settings.plugin"] {
r.mu.Unlock()
return
}
r.settingsPages = append(r.settingsPages, sp)
r.mu.Unlock()
sc.OnDispose(func() {
r.mu.Lock()
kept := r.settingsPages[:0]
for _, item := range r.settingsPages {
if !(item.PluginID == sc.PluginID() && item.ID == sp.ID) {
kept = append(kept, item)
}
}
r.settingsPages = kept
r.mu.Unlock()
})
addScoped(r, sc, &r.settingsPages, sp, func(x SettingsPageContribution) bool { return x.PluginID == sp.PluginID && x.ID == sp.ID }, func() bool { return len(r.settingsPages) < DeclaredUISlots["settings.plugin"] })
}
func (r *Registry) SettingsPages() []SettingsPageContribution {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]SettingsPageContribution, len(r.settingsPages))
copy(out, r.settingsPages)
return out
}
func (r *Registry) SettingsPages() []SettingsPageContribution { return listScoped(r, &r.settingsPages) }
func (r *Registry) RegisterStatusItem(sc *Scope, si StatusItemContribution) {
if si.Slot == "" {
@@ -1365,62 +1280,18 @@ func (r *Registry) RegisterStatusItem(sc *Scope, si StatusItemContribution) {
return
}
si.PluginID = sc.PluginID()
r.mu.Lock()
if len(r.statusItems) >= DeclaredUISlots[si.Slot] {
r.mu.Unlock()
return
}
r.statusItems = append(r.statusItems, si)
r.mu.Unlock()
sc.OnDispose(func() {
r.mu.Lock()
kept := r.statusItems[:0]
for _, item := range r.statusItems {
if !(item.PluginID == sc.PluginID() && item.ID == si.ID) {
kept = append(kept, item)
}
}
r.statusItems = kept
r.mu.Unlock()
})
addScoped(r, sc, &r.statusItems, si, func(x StatusItemContribution) bool { return x.PluginID == si.PluginID && x.ID == si.ID }, func() bool { return len(r.statusItems) < DeclaredUISlots[si.Slot] })
}
func (r *Registry) StatusItems() []StatusItemContribution {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]StatusItemContribution, len(r.statusItems))
copy(out, r.statusItems)
return out
}
func (r *Registry) StatusItems() []StatusItemContribution { return listScoped(r, &r.statusItems) }
func (r *Registry) RegisterPanel(sc *Scope, p PanelContribution) {
if !IsDeclaredSlot(p.Slot) {
return
}
p.PluginID = sc.PluginID()
r.mu.Lock()
count := 0
for _, existing := range r.panels {
if existing.Slot == p.Slot {
count++
}
}
if count >= DeclaredUISlots[p.Slot] {
r.mu.Unlock()
return
}
r.panels = append(r.panels, p)
r.mu.Unlock()
sc.OnDispose(func() {
r.mu.Lock()
kept := r.panels[:0]
for _, item := range r.panels {
if !(item.PluginID == sc.PluginID() && item.ID == p.ID) {
kept = append(kept, item)
}
}
r.panels = kept
r.mu.Unlock()
addScoped(r, sc, &r.panels, p, func(x PanelContribution) bool { return x.PluginID == p.PluginID && x.ID == p.ID }, func() bool {
return countFunc(r.panels, func(x PanelContribution) bool { return x.Slot == p.Slot }) < DeclaredUISlots[p.Slot]
})
}
@@ -1438,44 +1309,17 @@ func (r *Registry) Panels(slot string) []PanelContribution {
func (r *Registry) RegisterView(sc *Scope, view ViewContribution) {
view.ID = strings.TrimSpace(view.ID)
if view.ID == "" {
return
}
location, ok := ViewLocationCatalog[view.Location]
if !ok {
if view.ID == "" || !ok {
return
}
view.PluginID = sc.PluginID()
r.mu.Lock()
count := 0
for _, existing := range r.views {
if existing.PluginID != view.PluginID {
continue
}
if existing.ID == view.ID {
r.mu.Unlock()
return
}
if existing.Location == view.Location {
count++
}
}
if location.PerPlugin > 0 && count >= location.PerPlugin {
r.mu.Unlock()
return
}
r.views = append(r.views, view)
r.mu.Unlock()
sc.OnDispose(func() {
r.mu.Lock()
kept := r.views[:0]
for _, item := range r.views {
if !(item.PluginID == sc.PluginID() && item.ID == view.ID) {
kept = append(kept, item)
}
}
r.views = kept
r.mu.Unlock()
same := func(x ViewContribution) bool { return x.PluginID == view.PluginID && x.ID == view.ID }
addScoped(r, sc, &r.views, view, same, func() bool {
atLocation := countFunc(r.views, func(x ViewContribution) bool {
return x.PluginID == view.PluginID && x.Location == view.Location
})
return !slices.ContainsFunc(r.views, same) && (location.PerPlugin <= 0 || atLocation < location.PerPlugin)
})
}
@@ -1570,20 +1414,9 @@ func (r *Registry) RegisterDiagnostics(sc *Scope, contrib DiagnosticsContributio
return
}
contrib.PluginID = sc.PluginID()
r.mu.Lock()
r.diagnostics = append(r.diagnostics, RegisteredDiagnostics{Contribution: contrib, Collector: collector})
r.mu.Unlock()
sc.OnDispose(func() {
r.mu.Lock()
kept := r.diagnostics[:0]
for _, item := range r.diagnostics {
if !(item.Contribution.PluginID == sc.PluginID() && item.Contribution.ID == contrib.ID) {
kept = append(kept, item)
}
}
r.diagnostics = kept
r.mu.Unlock()
})
addScoped(r, sc, &r.diagnostics, RegisteredDiagnostics{Contribution: contrib, Collector: collector}, func(x RegisteredDiagnostics) bool {
return x.Contribution.PluginID == contrib.PluginID && x.Contribution.ID == contrib.ID
}, nil)
}
// CollectDiagnostics invokes all registered diagnostics collectors, skipping
+4 -4
View File
@@ -44,10 +44,10 @@ type RPCRequestHandler func(ctx context.Context, params json.RawMessage) (any, e
// RPCConn implements bidirectional Content-Length framed JSON-RPC 2.0 over
// stdio pipes with a single writer goroutine and bounded queue (§8).
type RPCConn struct {
r *bufio.Reader
w io.Writer
writeCh chan []byte
closeCh chan struct{}
r *bufio.Reader
w io.Writer
writeCh chan []byte
closeCh chan struct{}
closeOnce sync.Once
nextID atomic.Uint64
+263 -238
View File
@@ -173,137 +173,170 @@ func ScanArchive(archivePath, tmpParentDir, hostVersion string, opts ScanOptions
return ScanDirectory(stageDir, hostVersion, opts), nil
}
// packageScan is one ScanDirectory run.
type packageScan struct {
dir string
opts ScanOptions
m Manifest
rep ScanReport
sidecar string // declared entries, normalized
panelDir string
runtimeDirs []string
hasNetPerm bool
themeCSS map[string]bool // stylesheets checked with their theme
netScripts []string // scripts that use a declared net permission
}
func (s *packageScan) hard(check, target, msg string, zh, en string) {
s.rep.HardFindings = append(s.rep.HardFindings, ScanFinding{
Severity: ScanSeverityHard,
Check: check,
Target: target,
Message: msg,
Localized: LocalizedText{ZhCN: zh, EnUS: en},
})
}
func (s *packageScan) pending(check, target, msg string, zh, en string) {
s.rep.PendingFindings = append(s.rep.PendingFindings, ScanFinding{
Severity: ScanSeverityPending,
Check: check,
Target: target,
Message: msg,
Localized: LocalizedText{ZhCN: zh, EnUS: en},
})
}
// ScanDirectory performs a comprehensive static risk and policy scan on a plugin
// directory (unpacked archive, installed package, or dev-linked directory).
func ScanDirectory(dir, hostVersion string, opts ScanOptions) ScanReport {
rep := ScanReport{
Trust: TrustCommunity,
}
addHard := func(check, target, msg string, zh, en string) {
rep.HardFindings = append(rep.HardFindings, ScanFinding{
Severity: ScanSeverityHard,
Check: check,
Target: target,
Message: msg,
Localized: LocalizedText{ZhCN: zh, EnUS: en},
})
}
addPending := func(check, target, msg string, zh, en string) {
rep.PendingFindings = append(rep.PendingFindings, ScanFinding{
Severity: ScanSeverityPending,
Check: check,
Target: target,
Message: msg,
Localized: LocalizedText{ZhCN: zh, EnUS: en},
})
}
raw, err := os.ReadFile(filepath.Join(dir, "plugin.json"))
s := &packageScan{dir: dir, opts: opts, rep: ScanReport{Trust: TrustCommunity}, themeCSS: map[string]bool{}}
raw, err := os.ReadFile(filepath.Join(s.dir, "plugin.json"))
if err != nil {
addHard("manifest", "plugin.json", "cannot read plugin.json: "+err.Error(),
s.hard("manifest", "plugin.json", "cannot read plugin.json: "+err.Error(),
"缺少或无法读取 plugin.json 清单文件",
"Cannot read plugin.json manifest")
finalizeScanReport(&rep)
return rep
finalizeScanReport(&s.rep)
return s.rep
}
var m Manifest
if err := json.Unmarshal(raw, &m); err != nil {
addHard("manifest", "plugin.json", "invalid plugin.json JSON: "+err.Error(),
if err := json.Unmarshal(raw, &s.m); err != nil {
s.hard("manifest", "plugin.json", "invalid plugin.json JSON: "+err.Error(),
"plugin.json 格式无效:"+err.Error(),
"Invalid plugin.json JSON: "+err.Error())
finalizeScanReport(&rep)
return rep
finalizeScanReport(&s.rep)
return s.rep
}
rep.PluginID = m.ID
rep.Version = m.Version
rep.Name = m.Name
rep.Tier = m.InferTier(false)
rep.Publisher = m.Publisher
rep.License = m.License
s.rep.PluginID = s.m.ID
s.rep.Version = s.m.Version
s.rep.Name = s.m.Name
s.rep.Tier = s.m.InferTier(false)
s.rep.Publisher = s.m.Publisher
s.rep.License = s.m.License
if err := ValidateManifest(m, hostVersion, false); err != nil {
addHard("manifest", "plugin.json", err.Error(),
if err := ValidateManifest(s.m, hostVersion, false); err != nil {
s.hard("manifest", "plugin.json", err.Error(),
"清单校验未通过:"+err.Error(),
"Manifest validation failed: "+err.Error())
}
rep.PendingFindings = append(rep.PendingFindings, ContractFindings(m, raw)...)
s.rep.PendingFindings = append(s.rep.PendingFindings, ContractFindings(s.m, raw)...)
// Build normalized sets of declared entries & runtime directories.
declaredSidecar := normalizeRel(m.Entry.Sidecar)
declaredPanelDir := normalizeRel(m.Entry.PanelDir)
runtimeDirs := make([]string, 0, len(m.Contributes.Runtimes))
for _, rtPack := range m.Contributes.Runtimes {
s.sidecar = normalizeRel(s.m.Entry.Sidecar)
s.panelDir = normalizeRel(s.m.Entry.PanelDir)
for _, rtPack := range s.m.Contributes.Runtimes {
if d := normalizeRel(rtPack.Dir); d != "" {
runtimeDirs = append(runtimeDirs, d)
s.runtimeDirs = append(s.runtimeDirs, d)
}
}
hasNetPerm := false
for _, p := range m.Permissions {
for _, p := range s.m.Permissions {
if strings.HasPrefix(strings.TrimSpace(p), "net:") {
hasNetPerm = true
s.hasNetPerm = true
break
}
}
// Verify declared entries exist on disk.
s.checkEntries()
s.checkThemes()
s.checkFiles()
s.checkChecksums()
s.checkLocales()
// Build plain-language capability explanations & L3 native boundary notice (§7.2).
s.rep.Capabilities = buildCapabilityItems(s.m, s.rep.Tier, s.rep.Executables, s.netScripts)
if s.rep.Tier == TierL3 {
s.rep.NativeExecNotice = LocalizedText{
ZhCN: "此插件包含原生可执行程序(L3 Sidecar),启动后将以当前 Windows 账户完整权限运行。静态扫描只能核对清单完整性与哈希,无法证明原生二进制内部行为安全,请务必核对作者来源与 SHA-256。",
EnUS: "This plugin ships a native executable (L3 Sidecar) that runs with full current Windows user privileges. Static scanning verifies manifest integrity and hashes only and cannot prove native binary safety; verify publisher provenance and SHA-256 before enabling.",
}
}
_, _, entryHash, _ := resolveManifestEntry(s.m, s.dir, false)
s.rep.NeedsApproval = computeNeedsApproval(s.m, s.rep.Trust, nil, "", entryHash)
finalizeScanReport(&s.rep)
return s.rep
}
// checkEntries verifies that the declared entries exist on disk.
func (s *packageScan) checkEntries() {
checkEntryFile := func(label, rel string, expectDir bool) {
if strings.TrimSpace(rel) == "" {
return
}
full, jErr := safeJoin(dir, rel)
full, jErr := safeJoin(s.dir, rel)
if jErr != nil {
addHard("missing-entry", rel, fmt.Sprintf("invalid %s path %q: %v", label, rel, jErr),
s.hard("missing-entry", rel, fmt.Sprintf("invalid %s path %q: %v", label, rel, jErr),
fmt.Sprintf("声明的入口路径 %s 非法:%v", rel, jErr),
fmt.Sprintf("Declared %s path %q is invalid: %v", label, rel, jErr))
return
}
st, sErr := os.Stat(full)
if sErr != nil {
addHard("missing-entry", rel, fmt.Sprintf("declared %s %q is missing", label, rel),
s.hard("missing-entry", rel, fmt.Sprintf("declared %s %q is missing", label, rel),
fmt.Sprintf("清单声明的入口 %s 不存在", rel),
fmt.Sprintf("Declared %s %q is missing from package", label, rel))
return
}
if expectDir && !st.IsDir() {
addHard("missing-entry", rel, fmt.Sprintf("declared %s %q is not a directory", label, rel),
s.hard("missing-entry", rel, fmt.Sprintf("declared %s %q is not a directory", label, rel),
fmt.Sprintf("清单声明的目录入口 %s 不是目录", rel),
fmt.Sprintf("Declared %s %q is not a directory", label, rel))
} else if !expectDir && st.IsDir() {
addHard("missing-entry", rel, fmt.Sprintf("declared %s %q is a directory, expected file", label, rel),
s.hard("missing-entry", rel, fmt.Sprintf("declared %s %q is a directory, expected file", label, rel),
fmt.Sprintf("清单声明的文件入口 %s 是目录而非文件", rel),
fmt.Sprintf("Declared %s %q is a directory, expected a file", label, rel))
}
}
checkEntryFile("entry.sidecar", m.Entry.Sidecar, false)
checkEntryFile("entry.script", m.Entry.Script, false)
checkEntryFile("entry.uiScript", m.Entry.UIScript, false)
checkEntryFile("entry.panelDir", m.Entry.PanelDir, true)
for _, us := range m.Contributes.UIScripts {
checkEntryFile("entry.sidecar", s.m.Entry.Sidecar, false)
checkEntryFile("entry.script", s.m.Entry.Script, false)
checkEntryFile("entry.uiScript", s.m.Entry.UIScript, false)
checkEntryFile("entry.panelDir", s.m.Entry.PanelDir, true)
for _, us := range s.m.Contributes.UIScripts {
checkEntryFile("contributes.uiScripts", us.Script, false)
}
for _, panel := range m.Contributes.Panels {
if declaredPanelDir != "" && panel.Entry != "" {
checkEntryFile("panel entry", declaredPanelDir+"/"+strings.TrimPrefix(panel.Entry, "/"), false)
for _, panel := range s.m.Contributes.Panels {
if s.panelDir != "" && panel.Entry != "" {
checkEntryFile("panel entry", s.panelDir+"/"+strings.TrimPrefix(panel.Entry, "/"), false)
}
}
}
// Track theme stylesheets so we don't duplicate CSS checks in the directory walk.
declaredThemeCSS := map[string]bool{}
for _, th := range m.Contributes.Themes {
func (s *packageScan) checkThemes() {
for _, th := range s.m.Contributes.Themes {
if th.Stylesheet != "" {
declaredThemeCSS[normalizeRel(th.Stylesheet)] = true
s.themeCSS[normalizeRel(th.Stylesheet)] = true
}
if err := ValidateThemeContribution(th, dir); err != nil {
addHard("theme-css", th.Stylesheet, err.Error(),
if err := ValidateThemeContribution(th, s.dir); err != nil {
s.hard("theme-css", th.Stylesheet, err.Error(),
"主题样式或资源未通过安全校验:"+err.Error(),
"Theme stylesheet or asset failed safety validation: "+err.Error())
}
if th.Stylesheet != "" && opts.Contract != nil {
if cssPath, jErr := safeJoin(dir, th.Stylesheet); jErr == nil {
if th.Stylesheet != "" && s.opts.Contract != nil {
if cssPath, jErr := safeJoin(s.dir, th.Stylesheet); jErr == nil {
if cssBytes, rErr := os.ReadFile(cssPath); rErr == nil {
for _, issue := range CheckCSSAgainstContract(string(cssBytes), *opts.Contract) {
addPending("ui-contract", th.Stylesheet, issue,
for _, issue := range CheckCSSAgainstContract(string(cssBytes), *s.opts.Contract) {
s.pending("ui-contract", th.Stylesheet, issue,
fmt.Sprintf("主题样式 %s 存在 UI 契约提示:%s", th.Stylesheet, issue),
fmt.Sprintf("Theme CSS %s UI contract advisory: %s", th.Stylesheet, issue))
}
@@ -311,15 +344,15 @@ func ScanDirectory(dir, hostVersion string, opts ScanOptions) ScanReport {
}
}
}
}
// Walk all files in the package for redlines, executables, SVG scripts, CSS, and JS safety.
var netScriptHits []string
func (s *packageScan) checkFiles() {
var walkFiles []string
_ = filepath.Walk(dir, func(p string, info os.FileInfo, wErr error) error {
_ = filepath.Walk(s.dir, func(p string, info os.FileInfo, wErr error) error {
if wErr != nil || info == nil || info.IsDir() {
return nil
}
rel, rErr := filepath.Rel(dir, p)
rel, rErr := filepath.Rel(s.dir, p)
if rErr != nil {
return nil
}
@@ -327,202 +360,195 @@ func ScanDirectory(dir, hostVersion string, opts ScanOptions) ScanReport {
return nil
})
sort.Strings(walkFiles)
for _, rel := range walkFiles {
full := filepath.Join(dir, filepath.FromSlash(rel))
info, sErr := os.Stat(full)
if sErr != nil || info.IsDir() {
continue
}
lowName := strings.ToLower(info.Name())
ext := strings.ToLower(filepath.Ext(lowName))
s.checkFile(rel)
}
}
for _, pat := range ForbiddenMarketPatterns {
if strings.Contains(lowName, pat) {
addHard("redline", rel, fmt.Sprintf("forbidden proprietary file detected (%s)", rel),
fmt.Sprintf("检测到禁止分发的专有系统文件:%s", rel),
fmt.Sprintf("Forbidden proprietary file detected: %s", rel))
}
}
if info.Size() <= 256*1024 && isRedlineTextExt(ext) {
if b, rErr := os.ReadFile(full); rErr == nil {
if containsForbiddenSMCKey(strings.ToLower(string(b))) {
addHard("redline", rel, fmt.Sprintf("forbidden Apple SMC OSK detected in %s", rel),
fmt.Sprintf("在 %s 中检测到禁止分发的 Apple SMC OSK 密钥", rel),
fmt.Sprintf("Forbidden Apple SMC OSK detected in %s", rel))
}
}
}
// checkFile looks for redlines, executables, SVG scripts, and unsafe CSS and JS.
func (s *packageScan) checkFile(rel string) {
full := filepath.Join(s.dir, filepath.FromSlash(rel))
info, sErr := os.Stat(full)
if sErr != nil || info.IsDir() {
return
}
lowName := strings.ToLower(info.Name())
ext := strings.ToLower(filepath.Ext(lowName))
if ForbiddenBinaryExtensions[ext] {
sum, _ := fileSHA256Hex(full)
declared := false
switch rep.Tier {
case TierL3:
if declaredSidecar != "" && strings.EqualFold(rel, declaredSidecar) {
declared = true
}
case TierRuntime:
for _, rd := range runtimeDirs {
if rel == rd || strings.HasPrefix(strings.ToLower(rel), strings.ToLower(rd)+"/") {
declared = true
break
}
}
}
rep.Executables = append(rep.Executables, ExecutableFile{
Path: rel,
SHA256: sum,
Declared: declared,
SizeBytes: info.Size(),
})
if !declared {
if rep.Tier == TierL3 || rep.Tier == TierRuntime {
addHard("unlisted-executable", rel,
fmt.Sprintf("unlisted executable or script %q not declared in manifest", rel),
fmt.Sprintf("包含未在清单中声明的可执行文件或脚本:%s", rel),
fmt.Sprintf("Unlisted executable or script not declared in manifest: %s", rel))
} else {
addHard("forbidden-binary", rel,
fmt.Sprintf("executable or OS script %q is forbidden in %s plugin packages", rel, rep.Tier),
fmt.Sprintf("%s 类型插件禁止夹带可执行文件或系统脚本:%s", rep.Tier, rel),
fmt.Sprintf("Executable or OS script %q is forbidden in %s packages", rel, rep.Tier))
}
}
for _, pat := range ForbiddenMarketPatterns {
if strings.Contains(lowName, pat) {
s.hard("redline", rel, fmt.Sprintf("forbidden proprietary file detected (%s)", rel),
fmt.Sprintf("检测到禁止分发的专有系统文件:%s", rel),
fmt.Sprintf("Forbidden proprietary file detected: %s", rel))
}
if ext == ".svg" && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
if reason := scanSVGActiveContent(string(b)); reason != "" {
addHard("svg-script", rel, fmt.Sprintf("unsafe active content in SVG %s: %s", rel, reason),
fmt.Sprintf("SVG 文件 %s 包含被禁止的脚本或事件属性(%s)", rel, reason),
fmt.Sprintf("SVG file %s contains forbidden active content (%s)", rel, reason))
}
}
}
if ext == ".css" && !declaredThemeCSS[rel] && !inRelDir(rel, declaredPanelDir) && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
if err := ValidateThemeCSSSafetyInDir(string(b), filepath.Dir(full)); err != nil {
addHard("theme-css", rel, fmt.Sprintf("unsafe CSS %s: %v", rel, err),
fmt.Sprintf("样式文件 %s 未通过安全校验:%v", rel, err),
fmt.Sprintf("Stylesheet %s failed safety check: %v", rel, err))
}
}
}
if (ext == ".js" || ext == ".mjs" || ext == ".cjs") && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
hits, hasNet := scanScriptContent(string(b), false)
for _, hit := range hits {
addHard("ui-script", rel, fmt.Sprintf("forbidden JS pattern (%s) in %s", hit, rel),
fmt.Sprintf("脚本 %s 包含被禁止的宿主逃逸或动态执行语句(%s)", rel, hit),
fmt.Sprintf("Script %s contains forbidden host-escape or dynamic-eval pattern (%s)", rel, hit))
}
if hasNet {
if !hasNetPerm {
addHard("ui-script-undeclared-net", rel,
fmt.Sprintf("script %s calls network APIs without declaring any net:<host> permission", rel),
fmt.Sprintf("脚本 %s 调用了网络接口,但清单未声明 net:<host> 权限", rel),
fmt.Sprintf("Script %s calls network APIs without declaring any net:<host> permission", rel))
} else {
netScriptHits = append(netScriptHits, rel)
}
}
}
}
if (ext == ".html" || ext == ".htm") && inRelDir(rel, declaredPanelDir) && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
hits, _ := scanScriptContent(string(b), true)
for _, hit := range hits {
addHard("panel-html", rel, fmt.Sprintf("forbidden host-escape pattern (%s) in panel %s", hit, rel),
fmt.Sprintf("面板页面 %s 包含被禁止的宿主逃逸语句(%s)", rel, hit),
fmt.Sprintf("Panel HTML %s contains forbidden host-escape pattern (%s)", rel, hit))
}
}
if info.Size() <= 256*1024 && isRedlineTextExt(ext) {
if b, rErr := os.ReadFile(full); rErr == nil {
if containsForbiddenSMCKey(strings.ToLower(string(b))) {
s.hard("redline", rel, fmt.Sprintf("forbidden Apple SMC OSK detected in %s", rel),
fmt.Sprintf("在 %s 中检测到禁止分发的 Apple SMC OSK 密钥", rel),
fmt.Sprintf("Forbidden Apple SMC OSK detected in %s", rel))
}
}
}
sumsPath := filepath.Join(dir, "SHA256SUMS")
if sumsRaw, sErr := os.ReadFile(sumsPath); sErr == nil {
if err := verifyDirSHA256Sums(dir, sumsRaw); err != nil {
addHard("checksum", "SHA256SUMS", err.Error(),
"SHA256SUMS 完整性校验失败:"+err.Error(),
"SHA256SUMS integrity verification failed: "+err.Error())
}
if sigRaw, sigErr := os.ReadFile(filepath.Join(dir, "SHA256SUMS.sig")); sigErr == nil {
if len(opts.Keyring) > 0 {
t, vErr := verifyEd25519Signature(sumsRaw, sigRaw, opts.Keyring)
if vErr != nil {
addHard("signature", "SHA256SUMS.sig", "invalid package signature: "+vErr.Error(),
"插件签名验证失败:"+vErr.Error(),
"Plugin signature verification failed: "+vErr.Error())
} else {
rep.Trust = t
if ForbiddenBinaryExtensions[ext] {
sum, _ := fileSHA256Hex(full)
declared := false
switch s.rep.Tier {
case TierL3:
if s.sidecar != "" && strings.EqualFold(rel, s.sidecar) {
declared = true
}
case TierRuntime:
for _, rd := range s.runtimeDirs {
if rel == rd || strings.HasPrefix(strings.ToLower(rel), strings.ToLower(rd)+"/") {
declared = true
break
}
}
}
} else if opts.RequireChecksums {
addHard("checksum", "SHA256SUMS", "package missing SHA256SUMS",
s.rep.Executables = append(s.rep.Executables, ExecutableFile{
Path: rel,
SHA256: sum,
Declared: declared,
SizeBytes: info.Size(),
})
if !declared {
if s.rep.Tier == TierL3 || s.rep.Tier == TierRuntime {
s.hard("unlisted-executable", rel,
fmt.Sprintf("unlisted executable or script %q not declared in manifest", rel),
fmt.Sprintf("包含未在清单中声明的可执行文件或脚本:%s", rel),
fmt.Sprintf("Unlisted executable or script not declared in manifest: %s", rel))
} else {
s.hard("forbidden-binary", rel,
fmt.Sprintf("executable or OS script %q is forbidden in %s plugin packages", rel, s.rep.Tier),
fmt.Sprintf("%s 类型插件禁止夹带可执行文件或系统脚本:%s", s.rep.Tier, rel),
fmt.Sprintf("Executable or OS script %q is forbidden in %s packages", rel, s.rep.Tier))
}
}
}
if ext == ".svg" && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
if reason := scanSVGActiveContent(string(b)); reason != "" {
s.hard("svg-script", rel, fmt.Sprintf("unsafe active content in SVG %s: %s", rel, reason),
fmt.Sprintf("SVG 文件 %s 包含被禁止的脚本或事件属性(%s)", rel, reason),
fmt.Sprintf("SVG file %s contains forbidden active content (%s)", rel, reason))
}
}
}
if ext == ".css" && !s.themeCSS[rel] && !inRelDir(rel, s.panelDir) && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
if err := ValidateThemeCSSSafety(string(b), filepath.Dir(full)); err != nil {
s.hard("theme-css", rel, fmt.Sprintf("unsafe CSS %s: %v", rel, err),
fmt.Sprintf("样式文件 %s 未通过安全校验:%v", rel, err),
fmt.Sprintf("Stylesheet %s failed safety check: %v", rel, err))
}
}
}
if (ext == ".js" || ext == ".mjs" || ext == ".cjs") && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
hits, hasNet := scanScriptContent(string(b), false)
for _, hit := range hits {
s.hard("ui-script", rel, fmt.Sprintf("forbidden JS pattern (%s) in %s", hit, rel),
fmt.Sprintf("脚本 %s 包含被禁止的宿主逃逸或动态执行语句(%s)", rel, hit),
fmt.Sprintf("Script %s contains forbidden host-escape or dynamic-eval pattern (%s)", rel, hit))
}
if hasNet {
if !s.hasNetPerm {
s.hard("ui-script-undeclared-net", rel,
fmt.Sprintf("script %s calls network APIs without declaring any net:<host> permission", rel),
fmt.Sprintf("脚本 %s 调用了网络接口,但清单未声明 net:<host> 权限", rel),
fmt.Sprintf("Script %s calls network APIs without declaring any net:<host> permission", rel))
} else {
s.netScripts = append(s.netScripts, rel)
}
}
}
}
if (ext == ".html" || ext == ".htm") && inRelDir(rel, s.panelDir) && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
hits, _ := scanScriptContent(string(b), true)
for _, hit := range hits {
s.hard("panel-html", rel, fmt.Sprintf("forbidden host-escape pattern (%s) in panel %s", hit, rel),
fmt.Sprintf("面板页面 %s 包含被禁止的宿主逃逸语句(%s)", rel, hit),
fmt.Sprintf("Panel HTML %s contains forbidden host-escape pattern (%s)", rel, hit))
}
}
}
}
func (s *packageScan) checkChecksums() {
sumsPath := filepath.Join(s.dir, "SHA256SUMS")
if sumsRaw, sErr := os.ReadFile(sumsPath); sErr == nil {
if err := verifyDirSHA256Sums(s.dir, sumsRaw); err != nil {
s.hard("checksum", "SHA256SUMS", err.Error(),
"SHA256SUMS 完整性校验失败:"+err.Error(),
"SHA256SUMS integrity verification failed: "+err.Error())
}
if sigRaw, sigErr := os.ReadFile(filepath.Join(s.dir, "SHA256SUMS.sig")); sigErr == nil {
if len(s.opts.Keyring) > 0 {
t, vErr := verifyEd25519Signature(sumsRaw, sigRaw, s.opts.Keyring)
if vErr != nil {
s.hard("signature", "SHA256SUMS.sig", "invalid package signature: "+vErr.Error(),
"插件签名验证失败:"+vErr.Error(),
"Plugin signature verification failed: "+vErr.Error())
} else {
s.rep.Trust = t
}
}
}
} else if s.opts.RequireChecksums {
s.hard("checksum", "SHA256SUMS", "package missing SHA256SUMS",
"分发压缩包缺少必需的 SHA256SUMS 校验文件",
"Distribution package is missing required SHA256SUMS file")
} else {
addPending("checksum", "SHA256SUMS", "SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)",
s.pending("checksum", "SHA256SUMS", "SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)",
"未包含 SHA256SUMS(本地开发链接可忽略,打包分发 .zip 时必需)",
"SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)")
}
if rep.Trust == TrustCommunity {
addPending("trust-unsigned", "", "community package is not signed by an official or verified market key",
if s.rep.Trust == TrustCommunity {
s.pending("trust-unsigned", "", "community package is not signed by an official or verified market key",
"社区插件未携带官方或已审核签名,请仅安装来自可信作者的插件包",
"Community package is not signed by an official or verified key; install only from authors you trust")
}
}
// 7. L10n & Locale contributions.
if strings.TrimSpace(m.L10n) != "" {
if err := validatePluginL10nDir(m.L10n, dir); err != nil {
addHard("l10n", m.L10n, err.Error(),
func (s *packageScan) checkLocales() {
if strings.TrimSpace(s.m.L10n) != "" {
if err := validatePluginL10nDir(s.m.L10n, s.dir); err != nil {
s.hard("l10n", s.m.L10n, err.Error(),
"插件本地化目录校验失败:"+err.Error(),
"Plugin l10n directory validation failed: "+err.Error())
}
}
if len(m.Contributes.Locales) > 0 {
if _, locFindings, cErr := CheckLocalePack(dir); cErr == nil && len(locFindings) > 0 {
if len(s.m.Contributes.Locales) > 0 {
if _, locFindings, cErr := CheckLocalePack(s.dir); cErr == nil && len(locFindings) > 0 {
for _, lf := range locFindings {
if lf.Severity == "error" {
addHard("locale", lf.Check, lf.Message,
s.hard("locale", lf.Check, lf.Message,
"语言包校验错误:"+lf.Message,
"Language pack validation error: "+lf.Message)
} else if lf.Severity == "warn" {
addPending("locale", lf.Check, lf.Message,
s.pending("locale", lf.Check, lf.Message,
"语言包提示:"+lf.Message,
"Language pack advisory: "+lf.Message)
}
}
} else {
for _, lc := range m.Contributes.Locales {
if err := ValidateLocaleContribution(lc, dir); err != nil {
addHard("locale", lc.Locale, err.Error(),
for _, lc := range s.m.Contributes.Locales {
if err := ValidateLocaleContribution(lc, s.dir); err != nil {
s.hard("locale", lc.Locale, err.Error(),
fmt.Sprintf("语言包 %s 校验失败:%v", lc.Locale, err),
fmt.Sprintf("Locale %s validation failed: %v", lc.Locale, err))
}
}
}
}
// 8. Build plain-language capability explanations & L3 native boundary notice (§7.2).
rep.Capabilities = buildCapabilityItems(m, rep.Tier, rep.Executables, netScriptHits)
if rep.Tier == TierL3 {
rep.NativeExecNotice = LocalizedText{
ZhCN: "此插件包含原生可执行程序(L3 Sidecar),启动后将以当前 Windows 账户完整权限运行。静态扫描只能核对清单完整性与哈希,无法证明原生二进制内部行为安全,请务必核对作者来源与 SHA-256。",
EnUS: "This plugin ships a native executable (L3 Sidecar) that runs with full current Windows user privileges. Static scanning verifies manifest integrity and hashes only and cannot prove native binary safety; verify publisher provenance and SHA-256 before enabling.",
}
}
_, _, entryHash, _ := resolveManifestEntry(m, dir, false)
rep.NeedsApproval = computeNeedsApproval(m, rep.Trust, nil, "", entryHash)
finalizeScanReport(&rep)
return rep
}
func finalizeScanReport(rep *ScanReport) {
@@ -561,8 +587,7 @@ func finalizeScanReport(rep *ScanReport) {
}
}
// ToDoctorFindings converts a ScanReport into backward-compatible DoctorFinding
// entries so `DoctorDirectory` and existing callers/tests share one engine.
// ToDoctorFindings lists a ScanReport's results the way `plugin doctor` prints them.
func (r ScanReport) ToDoctorFindings() []DoctorFinding {
var out []DoctorFinding
hasManifestErr := false
@@ -843,12 +868,12 @@ func describePermission(perm string) (LocalizedText, LocalizedText) {
if strings.HasPrefix(perm, "net:") {
host := strings.TrimPrefix(perm, "net:")
return LocalizedText{
ZhCN: "访问指定网络主机",
EnUS: "Access declared network host",
}, LocalizedText{
ZhCN: fmt.Sprintf("允许向 %s 发起网络请求。", host),
EnUS: fmt.Sprintf("Allows outbound network requests to %s.", host),
}
ZhCN: "访问指定网络主机",
EnUS: "Access declared network host",
}, LocalizedText{
ZhCN: fmt.Sprintf("允许向 %s 发起网络请求。", host),
EnUS: fmt.Sprintf("Allows outbound network requests to %s.", host),
}
}
switch perm {
case "ui:script":
+2 -2
View File
@@ -11,9 +11,9 @@ type Scope struct {
pluginID string
registry *Registry
mu sync.Mutex
mu sync.Mutex
disposers []func()
disposed bool
disposed bool
}
func newScope(pluginID string, reg *Registry) *Scope {
+1 -1
View File
@@ -314,7 +314,7 @@ func (s *SidecarSupervisor) registerReverseHostAPI(conn *RPCConn) {
conn.Handle("host/audit", func(_ context.Context, raw json.RawMessage) (any, error) {
if broker != nil {
if !broker.allowRate(pid, 120) {
if !broker.allowRate(pid) {
return nil, fmt.Errorf("plugin %q exceeded audit rate limit", pid)
}
var req struct {
+4 -26
View File
@@ -9,6 +9,8 @@ import (
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/atomicfile"
)
const (
@@ -116,47 +118,23 @@ func (s *StateStore) Save(st *StateFile) error {
if err := os.MkdirAll(s.dir, 0o755); err != nil {
return err
}
raw, err := json.MarshalIndent(st, "", " ")
if err != nil {
return err
}
raw = append(raw, '\n')
target := s.Path()
tmp := target + ".tmp"
if err := os.WriteFile(tmp, raw, 0o644); err != nil {
return err
}
// Preserve previous valid file as .bak before atomic swap. A failed backup
// Preserve the previous valid file as .bak before the swap. A failed backup
// aborts the migration/save instead of silently destroying the only fallback.
if prev, err := os.ReadFile(target); err == nil {
if err := os.WriteFile(target+".bak", prev, 0o644); err != nil {
_ = os.Remove(tmp)
return fmt.Errorf("backup plugin state: %w", err)
}
} else if !errors.Is(err, os.ErrNotExist) {
_ = os.Remove(tmp)
return fmt.Errorf("read plugin state before backup: %w", err)
}
if err := os.Rename(tmp, target); err != nil {
_ = os.Remove(tmp)
if err := atomicfile.WriteJSON(target, st, 0o644); err != nil {
return err
}
s.data = st
return nil
}
// ReadState reads `<dataRoot>/plugins/state.json` without starting a Manager,
// for processes such as `vm start` that only need a setting or two. It returns
// nil when the file is unreadable; callers then use their defaults, as the
// GUI's Manager does.
func ReadState(dataRoot string) *StateFile {
st, err := NewStateStore(NewPluginsLayout(dataRoot).Root).Load()
if err != nil {
return nil
}
return st
}
// --- Safe-mode startup sentinel (§9) ---
// SentinelPath returns `<DataRoot>/plugins/.startup-sentinel`.
+11 -22
View File
@@ -12,26 +12,20 @@ import (
)
var (
reTokenKey = regexp.MustCompile(`^--[a-z0-9][a-z0-9-]*$`)
reSafeFontFamily = regexp.MustCompile(`^[\p{L}\p{N} _-]{1,80}$`)
reFontWeight = regexp.MustCompile(`^[0-9a-zA-Z\s-]+$`)
reFontStyle = regexp.MustCompile(`^(normal|italic|oblique(\s+-?[0-9]+(\.[0-9]+)?deg)?)$`)
reUnicodeRange = regexp.MustCompile(`^[U+0-9a-fA-F?,\s-]+$`)
reSafeAssetRel = regexp.MustCompile(`^[a-zA-Z0-9._/@ -]+$`)
reSchemePrefix = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9+.-]*:`)
reTokenKey = regexp.MustCompile(`^--[a-z0-9][a-z0-9-]*$`)
reSafeFontFamily = regexp.MustCompile(`^[\p{L}\p{N} _-]{1,80}$`)
reFontWeight = regexp.MustCompile(`^[0-9a-zA-Z\s-]+$`)
reFontStyle = regexp.MustCompile(`^(normal|italic|oblique(\s+-?[0-9]+(\.[0-9]+)?deg)?)$`)
reUnicodeRange = regexp.MustCompile(`^[U+0-9a-fA-F?,\s-]+$`)
reSafeAssetRel = regexp.MustCompile(`^[a-zA-Z0-9._/@ -]+$`)
reSchemePrefix = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9+.-]*:`)
)
// ValidateThemeCSSSafety rejects unbalanced braces, unclosed strings/comments,
// CSS-escaped url()/image-set()/expression() bypasses, remote @import, and
// external or unsafe data: URLs.
func ValidateThemeCSSSafety(css string) error {
return ValidateThemeCSSSafetyInDir(css, "")
}
// ValidateThemeCSSSafetyInDir performs ValidateThemeCSSSafety and, when rootDir
// is non-empty, also verifies that every relative url()/@import resolves to an
// existing file inside rootDir.
func ValidateThemeCSSSafetyInDir(css, rootDir string) error {
// external or unsafe data: URLs. When rootDir is non-empty, every relative
// url()/@import must also resolve to an existing file inside rootDir.
func ValidateThemeCSSSafety(css, rootDir string) error {
if strings.Contains(strings.ToLower(css), "</style") {
return errors.New("theme stylesheet cannot contain </style")
}
@@ -459,11 +453,6 @@ func ValidateThemeContribution(th ThemeContribution, rootDir string) error {
return fmt.Errorf("theme icon %q (%q): %w", k, asset, err)
}
}
for k, asset := range th.Sounds {
if err := validateSafeManifestAsset(asset, rootDir); err != nil {
return fmt.Errorf("theme sound %q (%q): %w", k, asset, err)
}
}
for _, dec := range th.Decorations {
for _, st := range dec.States {
if st.Asset != "" {
@@ -507,7 +496,7 @@ func ValidateThemeContribution(th ThemeContribution, rootDir string) error {
}
// Relative url() inside stylesheet resolves relative to stylesheet's dir;
// verify inside package rootDir as well.
if err := ValidateThemeCSSSafetyInDir(string(cssRaw), filepath.Dir(cssPath)); err != nil {
if err := ValidateThemeCSSSafety(string(cssRaw), filepath.Dir(cssPath)); err != nil {
return fmt.Errorf("unsafe theme CSS %q: %w", th.Stylesheet, err)
}
}
-1
View File
@@ -358,7 +358,6 @@ type ThemeContribution struct {
Icons map[string]string `json:"icons,omitempty"`
BrandMark string `json:"brandMark,omitempty"`
Background string `json:"background,omitempty"`
Sounds map[string]string `json:"sounds,omitempty"`
Stylesheet string `json:"stylesheet,omitempty"` // relative path inside package
Decorations []ThemeDecoration `json:"decorations,omitempty"`
UIScript string `json:"uiScript,omitempty"` // requires ui:script
+3 -10
View File
@@ -10,6 +10,8 @@ import (
"strings"
"unicode"
"unicode/utf8"
"github.com/Nwflower/reims-go/internal/atomicfile"
)
const (
@@ -79,16 +81,7 @@ func (m *Manager) saveViewStorage(pluginID string, st *viewStorageFile) error {
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
target := m.viewStoragePath(pluginID)
tmp := target + ".tmp"
if err := os.WriteFile(tmp, raw, 0o600); err != nil {
return err
}
if err := os.Rename(tmp, target); err != nil {
_ = os.Remove(tmp)
return err
}
return nil
return atomicfile.Write(m.viewStoragePath(pluginID), raw, 0o600)
}
// ViewStorageGet returns one value from a plugin's persistent private view store.