refactor: 抽离 HostAPIService 并将 internal/plugin 拆分为四层无环子包 (#202)
This commit is contained in:
44 files changed
+1218
-969
No files matched your search
+7
-19
@@ -21,6 +21,7 @@ import (
|
||||
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/packetbridge"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/tray"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
@@ -136,8 +137,7 @@ type App struct {
|
||||
trayIcon []byte // embedded PNG passed in from package main
|
||||
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
|
||||
pluginMgr *plugin.Manager
|
||||
pluginFiles map[string]pluginFileGrant
|
||||
pluginMarket *plugin.MarketClient
|
||||
pluginMarket *market.MarketClient
|
||||
controlServer *control.Server
|
||||
driverRouter *driver.Router
|
||||
vmStateTable *driver.StateTable
|
||||
@@ -151,25 +151,12 @@ type App struct {
|
||||
displayPlacements sync.Map
|
||||
|
||||
inputShuttingDown bool
|
||||
// computerUseOwnedVMs caches ownership markers for MCP-created temporary VMs.
|
||||
computerUseOwnedVMs map[string]map[string]bool
|
||||
computerUseCloneMu sync.Mutex
|
||||
// computerUseHeld records the keys and pointer buttons each plugin left
|
||||
// held in a guest, so the host can release them when the plugin goes away.
|
||||
computerUseHeld map[string]map[string]*heldInputs
|
||||
computerUseHeldMu sync.Mutex
|
||||
fullscreenHotkey host.FullscreenHotkeyService
|
||||
fullscreenSyncMu sync.Mutex
|
||||
fullscreenTargets fullscreenHotkeyTargetCache
|
||||
|
||||
// Plugin elevation requests (elevate_flow.go).
|
||||
elevatePromptMu sync.Mutex
|
||||
elevateMu sync.Mutex
|
||||
elevatePending map[string]chan bool
|
||||
elevateSeq uint64
|
||||
elevateEmit func(ElevationPrompt)
|
||||
elevateDismiss func(string)
|
||||
elevateRunner elevationRunner
|
||||
// Host-side plugin API service (computer-use, secrets, downloads, elevation, file grants).
|
||||
hostAPI HostAPIService
|
||||
}
|
||||
|
||||
// Lifecycle exposes Wails lifecycle callbacks without exporting them as
|
||||
@@ -211,10 +198,11 @@ func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
|
||||
pollWake: make(chan struct{}, 1),
|
||||
diskPaths: make(map[string]cachedDiskPath),
|
||||
procSamples: make(map[string]host.ProcessSample),
|
||||
pluginFiles: make(map[string]pluginFileGrant),
|
||||
uiHealth: uiHealthState{windowHidden: launch.Background},
|
||||
displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay},
|
||||
}
|
||||
a.hostAPI.app = a
|
||||
a.hostAPI.pluginFiles = make(map[string]pluginFileGrant)
|
||||
return a, Lifecycle{
|
||||
OnStartup: a.startup,
|
||||
OnBeforeClose: a.beforeClose,
|
||||
@@ -617,8 +605,8 @@ func (a *App) resetDataRootCaches() {
|
||||
a.lastVMListErr = nil
|
||||
a.diskPaths = make(map[string]cachedDiskPath)
|
||||
a.procSamples = make(map[string]host.ProcessSample)
|
||||
a.pluginFiles = make(map[string]pluginFileGrant)
|
||||
a.mu.Unlock()
|
||||
a.hostAPISvc().ResetPluginFiles()
|
||||
cancelPluginTasks("")
|
||||
}
|
||||
|
||||
|
||||
@@ -44,8 +44,8 @@ type heldInputs struct {
|
||||
// noteHeldKey records or forgets one key transition. code must already be a
|
||||
// QKeyCode.
|
||||
func (a *App) noteHeldKey(pluginID, vmKey, code string, down bool) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
held := a.heldLocked(pluginID, vmKey)
|
||||
if down {
|
||||
held.keys[code] = true
|
||||
@@ -57,8 +57,8 @@ func (a *App) noteHeldKey(pluginID, vmKey, code string, down bool) {
|
||||
|
||||
// noteHeldButton records or forgets one pointer button transition.
|
||||
func (a *App) noteHeldButton(pluginID, vmKey, button string, down bool) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
held := a.heldLocked(pluginID, vmKey)
|
||||
if down {
|
||||
held.buttons[button] = true
|
||||
@@ -71,13 +71,13 @@ func (a *App) noteHeldButton(pluginID, vmKey, button string, down bool) {
|
||||
// heldLocked returns the record for one plugin and VM, creating it when
|
||||
// needed. The caller holds computerUseHeldMu.
|
||||
func (a *App) heldLocked(pluginID, vmKey string) *heldInputs {
|
||||
if a.computerUseHeld == nil {
|
||||
a.computerUseHeld = map[string]map[string]*heldInputs{}
|
||||
if a.hostAPI.computerUseHeld == nil {
|
||||
a.hostAPI.computerUseHeld = map[string]map[string]*heldInputs{}
|
||||
}
|
||||
byVM := a.computerUseHeld[pluginID]
|
||||
byVM := a.hostAPI.computerUseHeld[pluginID]
|
||||
if byVM == nil {
|
||||
byVM = map[string]*heldInputs{}
|
||||
a.computerUseHeld[pluginID] = byVM
|
||||
a.hostAPI.computerUseHeld[pluginID] = byVM
|
||||
}
|
||||
held := byVM[vmKey]
|
||||
if held == nil {
|
||||
@@ -113,7 +113,7 @@ func (a *App) armHeldTimerLocked(pluginID, vmKey string, held *heldInputs, d tim
|
||||
// pruneHeldLocked drops a record that holds nothing, so an idle plugin leaves
|
||||
// no state behind. The caller holds computerUseHeldMu.
|
||||
func (a *App) pruneHeldLocked(pluginID, vmKey string) {
|
||||
byVM := a.computerUseHeld[pluginID]
|
||||
byVM := a.hostAPI.computerUseHeld[pluginID]
|
||||
if byVM == nil {
|
||||
return
|
||||
}
|
||||
@@ -125,16 +125,16 @@ func (a *App) pruneHeldLocked(pluginID, vmKey string) {
|
||||
delete(byVM, vmKey)
|
||||
}
|
||||
if len(byVM) == 0 {
|
||||
delete(a.computerUseHeld, pluginID)
|
||||
delete(a.hostAPI.computerUseHeld, pluginID)
|
||||
}
|
||||
}
|
||||
|
||||
// heldSnapshot returns what one plugin holds in one VM, sorted, with the
|
||||
// generation it was read at.
|
||||
func (a *App) heldSnapshot(pluginID, vmKey string) (keys, buttons []string, generation uint64) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
byVM := a.computerUseHeld[pluginID]
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
byVM := a.hostAPI.computerUseHeld[pluginID]
|
||||
if byVM == nil {
|
||||
return nil, nil, 0
|
||||
}
|
||||
@@ -156,9 +156,9 @@ func (a *App) heldSnapshot(pluginID, vmKey string) (keys, buttons []string, gene
|
||||
// heldGeneration returns the record's current generation, or 0 when there is
|
||||
// no record.
|
||||
func (a *App) heldGeneration(pluginID, vmKey string) uint64 {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
if held := a.computerUseHeld[pluginID][vmKey]; held != nil {
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
if held := a.hostAPI.computerUseHeld[pluginID][vmKey]; held != nil {
|
||||
return held.generation
|
||||
}
|
||||
return 0
|
||||
@@ -166,10 +166,10 @@ func (a *App) heldGeneration(pluginID, vmKey string) uint64 {
|
||||
|
||||
// heldVMs lists the VMs one plugin currently holds input in.
|
||||
func (a *App) heldVMs(pluginID string) map[string]bool {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
out := map[string]bool{}
|
||||
for vmKey := range a.computerUseHeld[pluginID] {
|
||||
for vmKey := range a.hostAPI.computerUseHeld[pluginID] {
|
||||
out[vmKey] = true
|
||||
}
|
||||
return out
|
||||
@@ -179,9 +179,9 @@ func (a *App) heldVMs(pluginID string) map[string]bool {
|
||||
// when the caller itself named what it lifted, so there is no snapshot to
|
||||
// compare with.
|
||||
func (a *App) dropHeld(pluginID, vmKey string, keys, buttons []string) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
held := a.computerUseHeld[pluginID][vmKey]
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
held := a.hostAPI.computerUseHeld[pluginID][vmKey]
|
||||
if held == nil {
|
||||
return
|
||||
}
|
||||
@@ -199,9 +199,9 @@ func (a *App) dropHeld(pluginID, vmKey string, keys, buttons []string) {
|
||||
// meantime may hold a press this release did not lift, so it keeps everything
|
||||
// and its timer releases it later.
|
||||
func (a *App) dropHeldIfGeneration(pluginID, vmKey string, keys, buttons []string, generation uint64) bool {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
held := a.computerUseHeld[pluginID][vmKey]
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
held := a.hostAPI.computerUseHeld[pluginID][vmKey]
|
||||
if held == nil {
|
||||
return false
|
||||
}
|
||||
@@ -221,9 +221,9 @@ func (a *App) dropHeldIfGeneration(pluginID, vmKey string, keys, buttons []strin
|
||||
// rearmHeld schedules another fallback release for a record whose release
|
||||
// failed while the VM is still running.
|
||||
func (a *App) rearmHeld(pluginID, vmKey string) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
held := a.computerUseHeld[pluginID][vmKey]
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
held := a.hostAPI.computerUseHeld[pluginID][vmKey]
|
||||
if held == nil || len(held.keys)+len(held.buttons) == 0 {
|
||||
return
|
||||
}
|
||||
@@ -235,8 +235,8 @@ func (a *App) rearmHeld(pluginID, vmKey string) {
|
||||
// can still be held, and a release sent later could lift a key the user is
|
||||
// pressing after the VM starts again.
|
||||
func (a *App) forgetHeld(pluginID, vmKey string) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
a.hostAPI.heldMu.Lock()
|
||||
defer a.hostAPI.heldMu.Unlock()
|
||||
a.pruneHeldLocked(pluginID, vmKey)
|
||||
}
|
||||
|
||||
|
||||
@@ -48,23 +48,23 @@ func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[
|
||||
return nil
|
||||
}
|
||||
return map[string]plugin.RPCRequestHandler{
|
||||
"host/vm.list": a.hostVMMethod(mgr, pluginID, "host/vm.list", a.handleComputerUseVMList),
|
||||
"host/vm.get": a.hostVMMethod(mgr, pluginID, "host/vm.get", a.handleComputerUseVMGet),
|
||||
"host/vm.start": a.hostVMMethod(mgr, pluginID, "host/vm.start", a.handleComputerUseVMStart),
|
||||
"host/vm.shutdown": a.hostVMMethod(mgr, pluginID, "host/vm.shutdown", a.handleComputerUseVMShutdown),
|
||||
"host/vm.suspend": a.hostVMMethod(mgr, pluginID, "host/vm.suspend", a.handleComputerUseVMStateChange("host/vm.suspend", a.SuspendVM)),
|
||||
"host/vm.resume": a.hostVMMethod(mgr, pluginID, "host/vm.resume", a.handleComputerUseVMStateChange("host/vm.resume", a.ResumeVM)),
|
||||
"host/vm.clone": a.hostVMMethod(mgr, pluginID, "host/vm.clone", a.handleComputerUseVMClone),
|
||||
"host/vm.delete": a.hostVMMethod(mgr, pluginID, "host/vm.delete", a.handleComputerUseVMDelete),
|
||||
"host/vm.snapshot.list": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
|
||||
"host/vm.snapshot.create": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
|
||||
"host/vm.snapshot.restore": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
|
||||
"host/console.screenshot": a.hostVMMethod(mgr, pluginID, "host/console.screenshot", a.handleComputerUseScreenshot),
|
||||
"host/console.pointer": a.hostVMMethod(mgr, pluginID, "host/console.pointer", a.handleComputerUsePointer),
|
||||
"host/console.key": a.hostVMMethod(mgr, pluginID, "host/console.key", a.handleComputerUseKey),
|
||||
"host/console.type": a.hostVMMethod(mgr, pluginID, "host/console.type", a.handleComputerUseType),
|
||||
"host/console.typeSecret": a.hostVMMethod(mgr, pluginID, "host/console.typeSecret", a.handleComputerUseTypeSecret),
|
||||
"host/console.release": a.hostVMMethod(mgr, pluginID, "host/console.release", a.handleComputerUseRelease),
|
||||
"host/vm.list": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.list", a.handleComputerUseVMList),
|
||||
"host/vm.get": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.get", a.handleComputerUseVMGet),
|
||||
"host/vm.start": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.start", a.handleComputerUseVMStart),
|
||||
"host/vm.shutdown": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.shutdown", a.handleComputerUseVMShutdown),
|
||||
"host/vm.suspend": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.suspend", a.handleComputerUseVMStateChange("host/vm.suspend", a.SuspendVM)),
|
||||
"host/vm.resume": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.resume", a.handleComputerUseVMStateChange("host/vm.resume", a.ResumeVM)),
|
||||
"host/vm.clone": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.clone", a.handleComputerUseVMClone),
|
||||
"host/vm.delete": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.delete", a.handleComputerUseVMDelete),
|
||||
"host/vm.snapshot.list": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
|
||||
"host/vm.snapshot.create": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
|
||||
"host/vm.snapshot.restore": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
|
||||
"host/console.screenshot": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.screenshot", a.handleComputerUseScreenshot),
|
||||
"host/console.pointer": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.pointer", a.handleComputerUsePointer),
|
||||
"host/console.key": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.key", a.handleComputerUseKey),
|
||||
"host/console.type": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.type", a.handleComputerUseType),
|
||||
"host/console.typeSecret": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.typeSecret", a.handleComputerUseTypeSecret),
|
||||
"host/console.release": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.release", a.handleComputerUseRelease),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -243,8 +243,8 @@ func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.computerUseCloneMu.Lock()
|
||||
defer a.computerUseCloneMu.Unlock()
|
||||
a.hostAPI.computerUseCloneMu.Lock()
|
||||
defer a.hostAPI.computerUseCloneMu.Unlock()
|
||||
if existing, listErr := a.listVMsInternal(ctx); listErr != nil {
|
||||
return nil, listErr
|
||||
} else if slices.ContainsFunc(existing, func(item driver.VMListItem) bool {
|
||||
@@ -446,24 +446,26 @@ func (a *App) computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey st
|
||||
}
|
||||
|
||||
func (a *App) computerUseOwned(pluginID, vmKey string) bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.computerUseOwnedVMs != nil && a.computerUseOwnedVMs[pluginID] != nil && a.computerUseOwnedVMs[pluginID][vmKey]
|
||||
h := a.hostAPISvc()
|
||||
h.ownedMu.Lock()
|
||||
defer h.ownedMu.Unlock()
|
||||
return h.computerUseOwnedVMs != nil && h.computerUseOwnedVMs[pluginID] != nil && h.computerUseOwnedVMs[pluginID][vmKey]
|
||||
}
|
||||
|
||||
func (a *App) markComputerUseOwnedVM(pluginID, vmKey string, owned bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.computerUseOwnedVMs == nil {
|
||||
a.computerUseOwnedVMs = make(map[string]map[string]bool)
|
||||
h := a.hostAPISvc()
|
||||
h.ownedMu.Lock()
|
||||
defer h.ownedMu.Unlock()
|
||||
if h.computerUseOwnedVMs == nil {
|
||||
h.computerUseOwnedVMs = make(map[string]map[string]bool)
|
||||
}
|
||||
if a.computerUseOwnedVMs[pluginID] == nil {
|
||||
a.computerUseOwnedVMs[pluginID] = make(map[string]bool)
|
||||
if h.computerUseOwnedVMs[pluginID] == nil {
|
||||
h.computerUseOwnedVMs[pluginID] = make(map[string]bool)
|
||||
}
|
||||
if owned {
|
||||
a.computerUseOwnedVMs[pluginID][vmKey] = true
|
||||
h.computerUseOwnedVMs[pluginID][vmKey] = true
|
||||
} else {
|
||||
delete(a.computerUseOwnedVMs[pluginID], vmKey)
|
||||
delete(h.computerUseOwnedVMs[pluginID], vmKey)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -472,12 +474,13 @@ func (a *App) forgetComputerUseOwnedVM(vmKey string) {
|
||||
if vmKey == "" {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for pluginID, owned := range a.computerUseOwnedVMs {
|
||||
h := a.hostAPISvc()
|
||||
h.ownedMu.Lock()
|
||||
defer h.ownedMu.Unlock()
|
||||
for pluginID, owned := range h.computerUseOwnedVMs {
|
||||
delete(owned, vmKey)
|
||||
if len(owned) == 0 {
|
||||
delete(a.computerUseOwnedVMs, pluginID)
|
||||
delete(h.computerUseOwnedVMs, pluginID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -611,14 +614,15 @@ func (a *App) syncComputerUseOwnership(vms []driver.VMListItem) {
|
||||
continue
|
||||
}
|
||||
key := vm.Ref().Key()
|
||||
a.mu.Lock()
|
||||
h := a.hostAPISvc()
|
||||
h.ownedMu.Lock()
|
||||
var pluginIDs []string
|
||||
for pluginID, owned := range a.computerUseOwnedVMs {
|
||||
for pluginID, owned := range h.computerUseOwnedVMs {
|
||||
if owned[key] {
|
||||
pluginIDs = append(pluginIDs, pluginID)
|
||||
}
|
||||
}
|
||||
a.mu.Unlock()
|
||||
h.ownedMu.Unlock()
|
||||
for _, pluginID := range pluginIDs {
|
||||
// The source VM is no longer known on this repair path (the marker
|
||||
// was lost), so write an empty source: no fallback, same as before.
|
||||
|
||||
@@ -51,7 +51,7 @@ func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[str
|
||||
}
|
||||
broker := mgr.Broker()
|
||||
return map[string]plugin.RPCRequestHandler{
|
||||
"host/download.start": a.hostMethod(mgr, pluginID, "host/download.start", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
"host/download.start": a.hostAPISvc().hostMethod(mgr, pluginID, "host/download.start", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
a.mu.Lock()
|
||||
dataRoot := ""
|
||||
if a.cfg != nil {
|
||||
@@ -62,7 +62,7 @@ func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[str
|
||||
notify := func(method string, params any) { mgr.NotifySidecar(pluginID, method, params) }
|
||||
return a.startPluginDownload(mgr, broker, notify, pluginID, roots, raw)
|
||||
}),
|
||||
"host/download.cancel": a.hostMethod(mgr, pluginID, "host/download.cancel", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
"host/download.cancel": a.hostAPISvc().hostMethod(mgr, pluginID, "host/download.cancel", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
return cancelPluginDownload(mgr, pluginID, raw)
|
||||
}),
|
||||
}
|
||||
|
||||
@@ -33,14 +33,14 @@ type ElevationPrompt struct {
|
||||
|
||||
type elevationRunner func(ctx context.Context, action, targetUser string) (host.ElevationResult, error)
|
||||
|
||||
func (a *App) elevateHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
|
||||
func (h *HostAPIService) elevateHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
|
||||
if mgr == nil || mgr.Broker() == nil {
|
||||
return nil
|
||||
}
|
||||
broker := mgr.Broker()
|
||||
return map[string]plugin.RPCRequestHandler{
|
||||
"host/elevate.request": a.hostMethod(mgr, pluginID, "host/elevate.request", func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
return a.requestElevation(ctx, mgr, broker, mgr.Registry(), pluginID, raw)
|
||||
"host/elevate.request": h.hostMethod(mgr, pluginID, "host/elevate.request", func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
return h.app.requestElevation(ctx, mgr, broker, mgr.Registry(), pluginID, raw)
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -60,9 +60,6 @@ func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broke
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
emit := a.elevateEmit
|
||||
dismiss := a.elevateDismiss
|
||||
runner := a.elevateRunner
|
||||
winCtx := a.ctx
|
||||
hasWindow := winCtx != nil
|
||||
locale := i18n.EffectiveLocale(i18n.Auto)
|
||||
@@ -70,14 +67,20 @@ func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broke
|
||||
locale = i18n.EffectiveLocale(a.cfg.Locale)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
h := a.hostAPISvc()
|
||||
h.elevateMu.Lock()
|
||||
emit := h.elevateEmit
|
||||
dismiss := h.elevateDismiss
|
||||
runner := h.elevateRunner
|
||||
h.elevateMu.Unlock()
|
||||
if emit == nil && !hasWindow {
|
||||
broker.Audit(pluginID, "ELEVATE_UNAVAILABLE", spec.Action)
|
||||
return nil, errors.New("elevation_unavailable: the desktop window is required to confirm elevation")
|
||||
}
|
||||
|
||||
// One confirmation and one servicing run at a time.
|
||||
a.elevatePromptMu.Lock()
|
||||
defer a.elevatePromptMu.Unlock()
|
||||
h.elevatePromptMu.Lock()
|
||||
defer h.elevatePromptMu.Unlock()
|
||||
|
||||
prompt := ElevationPrompt{
|
||||
PluginID: pluginID, PluginName: pluginID, Action: spec.Action,
|
||||
@@ -92,19 +95,19 @@ func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broke
|
||||
}
|
||||
|
||||
ch := make(chan bool, 1)
|
||||
a.elevateMu.Lock()
|
||||
if a.elevatePending == nil {
|
||||
a.elevatePending = map[string]chan bool{}
|
||||
h.elevateMu.Lock()
|
||||
if h.elevatePending == nil {
|
||||
h.elevatePending = map[string]chan bool{}
|
||||
}
|
||||
a.elevateSeq++
|
||||
prompt.ID = fmt.Sprintf("elevate-%d", a.elevateSeq)
|
||||
a.elevatePending[prompt.ID] = ch
|
||||
a.elevateMu.Unlock()
|
||||
h.elevateSeq++
|
||||
prompt.ID = fmt.Sprintf("elevate-%d", h.elevateSeq)
|
||||
h.elevatePending[prompt.ID] = ch
|
||||
h.elevateMu.Unlock()
|
||||
dismissed := false
|
||||
clearPrompt := func() {
|
||||
a.elevateMu.Lock()
|
||||
delete(a.elevatePending, prompt.ID)
|
||||
a.elevateMu.Unlock()
|
||||
h.elevateMu.Lock()
|
||||
delete(h.elevatePending, prompt.ID)
|
||||
h.elevateMu.Unlock()
|
||||
if dismissed {
|
||||
return
|
||||
}
|
||||
@@ -178,10 +181,11 @@ func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broke
|
||||
// ResolveElevationRequest delivers the person's answer to a pending plugin
|
||||
// elevation request. An expired or answered request is ignored.
|
||||
func (a *App) ResolveElevationRequest(id string, approved bool) error {
|
||||
a.elevateMu.Lock()
|
||||
ch, ok := a.elevatePending[id]
|
||||
delete(a.elevatePending, id)
|
||||
a.elevateMu.Unlock()
|
||||
h := a.hostAPISvc()
|
||||
h.elevateMu.Lock()
|
||||
ch, ok := h.elevatePending[id]
|
||||
delete(h.elevatePending, id)
|
||||
h.elevateMu.Unlock()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
@@ -195,10 +199,11 @@ func (a *App) ResolveElevationRequest(id string, approved bool) error {
|
||||
// cancelPendingElevations answers every waiting request with a no, so
|
||||
// shutting down never leaves a plugin waiting on a dialog.
|
||||
func (a *App) cancelPendingElevations() {
|
||||
a.elevateMu.Lock()
|
||||
pending := a.elevatePending
|
||||
a.elevatePending = nil
|
||||
a.elevateMu.Unlock()
|
||||
h := a.hostAPISvc()
|
||||
h.elevateMu.Lock()
|
||||
pending := h.elevatePending
|
||||
h.elevatePending = nil
|
||||
h.elevateMu.Unlock()
|
||||
for _, ch := range pending {
|
||||
close(ch)
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ func newElevateTestEnv(t *testing.T) *elevateTestEnv {
|
||||
e := &elevateTestEnv{h: h, plugin: "test.fake.elev"}
|
||||
h.Add("hosted", e.plugin, "test.driver.elev")
|
||||
e.app = &App{cfg: &config.Config{DataRoot: h.DataRoot}}
|
||||
e.app.elevateEmit = func(p ElevationPrompt) {
|
||||
e.app.hostAPI.elevateEmit = func(p ElevationPrompt) {
|
||||
e.mu.Lock()
|
||||
e.prompts = append(e.prompts, p)
|
||||
answer := e.onPrompt
|
||||
@@ -49,12 +49,12 @@ func newElevateTestEnv(t *testing.T) *elevateTestEnv {
|
||||
go answer(p)
|
||||
}
|
||||
}
|
||||
e.app.elevateDismiss = func(id string) {
|
||||
e.app.hostAPI.elevateDismiss = func(id string) {
|
||||
e.mu.Lock()
|
||||
e.dismissed = append(e.dismissed, id)
|
||||
e.mu.Unlock()
|
||||
}
|
||||
e.app.elevateRunner = func(_ context.Context, action, targetUser string) (host.ElevationResult, error) {
|
||||
e.app.hostAPI.elevateRunner = func(_ context.Context, action, targetUser string) (host.ElevationResult, error) {
|
||||
e.runs.Add(1)
|
||||
e.mu.Lock()
|
||||
e.runArgs = []string{action, targetUser}
|
||||
@@ -83,7 +83,7 @@ func (e *elevateTestEnv) kernel() testHostMethodHost {
|
||||
|
||||
func (e *elevateTestEnv) request(ctx context.Context, pluginID, action string) (any, error) {
|
||||
raw, _ := json.Marshal(map[string]any{"action": action})
|
||||
handler := e.app.hostMethod(e.kernel(), pluginID, "host/elevate.request", func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
handler := e.app.hostAPISvc().hostMethod(e.kernel(), pluginID, "host/elevate.request", func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
return e.app.requestElevation(ctx, e.kernel(), e.h.Broker, e.h.Registry, pluginID, raw)
|
||||
})
|
||||
return handler(ctx, raw)
|
||||
@@ -138,7 +138,7 @@ func TestElevationRejectsActionsOutsideTheWhitelist(t *testing.T) {
|
||||
|
||||
func TestElevationIsRefusedWithoutADesktopWindow(t *testing.T) {
|
||||
e := newElevateTestEnv(t)
|
||||
e.app.elevateEmit = nil
|
||||
e.app.hostAPI.elevateEmit = nil
|
||||
_, err := e.request(context.Background(), e.plugin, host.ElevateHyperVEnable)
|
||||
if err == nil || !strings.Contains(err.Error(), "elevation_unavailable") {
|
||||
t.Fatalf("err = %v, want elevation_unavailable", err)
|
||||
|
||||
@@ -77,7 +77,7 @@ func decodeHostParams[T any](host hostMethodHost, pluginID, method string, raw j
|
||||
// audits the call under the method name, and hands the request to run. No
|
||||
// handler states its own permission, so a permission cannot drift from the
|
||||
// method it guards.
|
||||
func (a *App) hostMethod(host hostMethodHost, pluginID, method string, run hostMethodHandler) plugin.RPCRequestHandler {
|
||||
func (h *HostAPIService) hostMethod(host hostMethodHost, pluginID, method string, run hostMethodHandler) plugin.RPCRequestHandler {
|
||||
return func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
if err := authorizeHostMethod(host, pluginID, method); err != nil {
|
||||
return nil, err
|
||||
@@ -94,8 +94,8 @@ func (a *App) hostMethod(host hostMethodHost, pluginID, method string, run hostM
|
||||
}
|
||||
|
||||
// hostVMMethod wraps a handler that needs the manager and the calling plugin.
|
||||
func (a *App) hostVMMethod(mgr *plugin.Manager, pluginID, method string, run computerUseVMHandler) plugin.RPCRequestHandler {
|
||||
return a.hostMethod(mgr, pluginID, method, func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
func (h *HostAPIService) hostVMMethod(mgr *plugin.Manager, pluginID, method string, run computerUseVMHandler) plugin.RPCRequestHandler {
|
||||
return h.hostMethod(mgr, pluginID, method, func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
return run(ctx, raw, mgr, pluginID)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package app
|
||||
|
||||
import "sync"
|
||||
|
||||
// HostAPIService owns the state and RPC handlers for all host-side plugin
|
||||
// capabilities: computer-use VM control & held inputs, secret materialization,
|
||||
// host downloads, plugin elevation prompts, and panel file grants.
|
||||
// Keeping this state off *App isolates lock domains and keeps *App focused on
|
||||
// Wails IPC bindings and desktop lifecycle coordination.
|
||||
type HostAPIService struct {
|
||||
app *App
|
||||
|
||||
// Plugin panel file grants (plugin_bridge_files.go).
|
||||
filesMu sync.Mutex
|
||||
pluginFiles map[string]pluginFileGrant
|
||||
|
||||
// Computer-use VM ownership & held console inputs (computer_use_host.go, computer_use_held.go).
|
||||
ownedMu sync.Mutex
|
||||
computerUseOwnedVMs map[string]map[string]bool
|
||||
computerUseCloneMu sync.Mutex
|
||||
heldMu sync.Mutex
|
||||
computerUseHeld map[string]map[string]*heldInputs
|
||||
|
||||
// Plugin elevation requests (elevate_flow.go).
|
||||
elevatePromptMu sync.Mutex
|
||||
elevateMu sync.Mutex
|
||||
elevatePending map[string]chan bool
|
||||
elevateSeq uint64
|
||||
elevateEmit func(ElevationPrompt)
|
||||
elevateDismiss func(string)
|
||||
elevateRunner elevationRunner
|
||||
}
|
||||
|
||||
func (h *HostAPIService) ResetPluginFiles() {
|
||||
h.filesMu.Lock()
|
||||
h.pluginFiles = make(map[string]pluginFileGrant)
|
||||
h.filesMu.Unlock()
|
||||
}
|
||||
|
||||
func (a *App) hostAPISvc() *HostAPIService {
|
||||
a.mu.Lock()
|
||||
if a.hostAPI.app == nil {
|
||||
a.hostAPI.app = a
|
||||
}
|
||||
svc := &a.hostAPI
|
||||
a.mu.Unlock()
|
||||
return svc
|
||||
}
|
||||
@@ -51,7 +51,7 @@ func TestEveryStableHostMethodIsServed(t *testing.T) {
|
||||
for _, method := range plugin.ReverseHostAPIMethods() {
|
||||
served[method] = true
|
||||
}
|
||||
for method := range app.hostHandlers(mgr, hostContractPlugin) {
|
||||
for method := range app.hostAPISvc().Handlers(mgr, hostContractPlugin) {
|
||||
if _, ok := pluginproto.Lookup(method); !ok {
|
||||
t.Errorf("%s is served but not in the contract catalog", method)
|
||||
}
|
||||
|
||||
@@ -2,15 +2,15 @@ package app
|
||||
|
||||
import "github.com/Nwflower/reims-go/internal/plugin"
|
||||
|
||||
// hostHandlers returns every host-owned RPC a Sidecar may call, each guarded
|
||||
// Handlers returns every host-owned RPC a Sidecar may call, each guarded
|
||||
// by its own permission check.
|
||||
func (a *App) hostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
|
||||
func (h *HostAPIService) Handlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
|
||||
out := map[string]plugin.RPCRequestHandler{}
|
||||
for _, set := range []map[string]plugin.RPCRequestHandler{
|
||||
a.computerUseHostHandlers(mgr, pluginID),
|
||||
a.secretHostHandlers(mgr, pluginID),
|
||||
a.downloadHostHandlers(mgr, pluginID),
|
||||
a.elevateHostHandlers(mgr, pluginID),
|
||||
h.app.computerUseHostHandlers(mgr, pluginID),
|
||||
h.app.secretHostHandlers(mgr, pluginID),
|
||||
h.app.downloadHostHandlers(mgr, pluginID),
|
||||
h.elevateHostHandlers(mgr, pluginID),
|
||||
} {
|
||||
for method, handler := range set {
|
||||
out[method] = handler
|
||||
|
||||
@@ -219,9 +219,9 @@ func TestPluginFileGrantsExpireAndAreCapped(t *testing.T) {
|
||||
if _, err := a.issuePluginFileGrant("vendor.panel", path, true); err == nil {
|
||||
t.Fatal("plugin exceeded its file grant limit")
|
||||
}
|
||||
grant := a.pluginFiles[first]
|
||||
grant := a.hostAPI.pluginFiles[first]
|
||||
grant.Expires = time.Now().Add(-time.Minute)
|
||||
a.pluginFiles[first] = grant
|
||||
a.hostAPI.pluginFiles[first] = grant
|
||||
if _, err := a.pluginFilePath("vendor.panel", first, true); err == nil {
|
||||
t.Fatal("expired file grant was accepted")
|
||||
}
|
||||
|
||||
@@ -50,13 +50,14 @@ func (a *App) issuePluginFileGrant(pluginID, path string, write bool) (map[strin
|
||||
} else if !write {
|
||||
return nil, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
h := a.hostAPISvc()
|
||||
h.filesMu.Lock()
|
||||
defer h.filesMu.Unlock()
|
||||
now := time.Now()
|
||||
count := 0
|
||||
for key, grant := range a.pluginFiles {
|
||||
for key, grant := range h.pluginFiles {
|
||||
if !now.Before(grant.Expires) {
|
||||
delete(a.pluginFiles, key)
|
||||
delete(h.pluginFiles, key)
|
||||
} else if grant.PluginID == pluginID {
|
||||
count++
|
||||
}
|
||||
@@ -64,29 +65,31 @@ func (a *App) issuePluginFileGrant(pluginID, path string, write bool) (map[strin
|
||||
if count >= maxPluginFileGrants {
|
||||
return nil, errors.New("too many open file handles for this plugin")
|
||||
}
|
||||
if a.pluginFiles == nil {
|
||||
a.pluginFiles = make(map[string]pluginFileGrant)
|
||||
if h.pluginFiles == nil {
|
||||
h.pluginFiles = make(map[string]pluginFileGrant)
|
||||
}
|
||||
a.pluginFiles[id] = pluginFileGrant{PluginID: pluginID, Path: clean, Write: write, Expires: now.Add(pluginFileGrantTTL)}
|
||||
h.pluginFiles[id] = pluginFileGrant{PluginID: pluginID, Path: clean, Write: write, Expires: now.Add(pluginFileGrantTTL)}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (a *App) revokePluginFiles(pluginID string) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for id, grant := range a.pluginFiles {
|
||||
h := a.hostAPISvc()
|
||||
h.filesMu.Lock()
|
||||
defer h.filesMu.Unlock()
|
||||
for id, grant := range h.pluginFiles {
|
||||
if grant.PluginID == pluginID {
|
||||
delete(a.pluginFiles, id)
|
||||
delete(h.pluginFiles, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) pluginFilePath(pluginID, id string, write bool) (string, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
grant, ok := a.pluginFiles[id]
|
||||
h := a.hostAPISvc()
|
||||
h.filesMu.Lock()
|
||||
defer h.filesMu.Unlock()
|
||||
grant, ok := h.pluginFiles[id]
|
||||
if ok && !time.Now().Before(grant.Expires) {
|
||||
delete(a.pluginFiles, id)
|
||||
delete(h.pluginFiles, id)
|
||||
ok = false
|
||||
}
|
||||
if !ok || grant.PluginID != pluginID || (write && !grant.Write) {
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
@@ -87,7 +88,7 @@ func (a *App) initPlugins() {
|
||||
a.mu.Lock()
|
||||
current := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
return a.hostHandlers(current, pluginID)
|
||||
return a.hostAPISvc().Handlers(current, pluginID)
|
||||
},
|
||||
OnSettingsChanged: func(pluginID, vmName string) {
|
||||
a.onPluginSettingsChanged(pluginID, vmName)
|
||||
@@ -265,7 +266,7 @@ func (a *App) shutdownPlugins() {
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) getPluginMarket() *plugin.MarketClient {
|
||||
func (a *App) getPluginMarket() *market.MarketClient {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.needsSetup {
|
||||
@@ -273,7 +274,7 @@ func (a *App) getPluginMarket() *plugin.MarketClient {
|
||||
// only the default suggestion), so nothing may be cached or
|
||||
// downloaded into it. A throwaway client keeps the index in memory;
|
||||
// the first call after setup builds the real one.
|
||||
return plugin.NewMarketClient(plugin.MarketClientOptions{HostVersion: version.Version})
|
||||
return market.NewMarketClient(market.MarketClientOptions{HostVersion: version.Version})
|
||||
}
|
||||
if a.pluginMarket != nil {
|
||||
return a.pluginMarket
|
||||
@@ -282,7 +283,7 @@ func (a *App) getPluginMarket() *plugin.MarketClient {
|
||||
if a.cfg != nil {
|
||||
dataRoot = a.cfg.DataRoot
|
||||
}
|
||||
a.pluginMarket = plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
a.pluginMarket = market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: plugin.NewPluginsLayout(dataRoot),
|
||||
HostVersion: version.Version,
|
||||
})
|
||||
@@ -948,7 +949,7 @@ func (a *App) ScanInstalledPlugin(pluginID string) (plugin.ScanReport, error) {
|
||||
|
||||
// BrowsePluginMarket lazily queries the remote/cached/fallback plugin market
|
||||
// index (never called at app startup, §8.1, §9).
|
||||
func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh bool) plugin.MarketBrowseResult {
|
||||
func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh bool) market.MarketBrowseResult {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
@@ -956,7 +957,7 @@ func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh
|
||||
if mgr != nil {
|
||||
installed = mgr.Registry().List()
|
||||
}
|
||||
return a.getPluginMarket().Browse(context.Background(), installed, plugin.MarketBrowseOptions{
|
||||
return a.getPluginMarket().Browse(context.Background(), installed, market.MarketBrowseOptions{
|
||||
Query: query,
|
||||
Kind: kind,
|
||||
IncludeAlpha: includeAlpha,
|
||||
@@ -967,7 +968,7 @@ func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh
|
||||
// PeekPluginMarket returns the market from memory, disk cache or the embedded
|
||||
// fallback with no network I/O, so the page can paint before
|
||||
// BrowsePluginMarket revalidates.
|
||||
func (a *App) PeekPluginMarket(query, kind string) plugin.MarketBrowseResult {
|
||||
func (a *App) PeekPluginMarket(query, kind string) market.MarketBrowseResult {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
@@ -975,7 +976,7 @@ func (a *App) PeekPluginMarket(query, kind string) plugin.MarketBrowseResult {
|
||||
if mgr != nil {
|
||||
installed = mgr.Registry().List()
|
||||
}
|
||||
return a.getPluginMarket().Peek(installed, plugin.MarketBrowseOptions{Query: query, Kind: kind, IncludeAlpha: true})
|
||||
return a.getPluginMarket().Peek(installed, market.MarketBrowseOptions{Query: query, Kind: kind, IncludeAlpha: true})
|
||||
}
|
||||
|
||||
// SuggestLanguagePack looks up the market once for a language pack matching
|
||||
@@ -983,7 +984,7 @@ func (a *App) PeekPluginMarket(query, kind string) plugin.MarketBrowseResult {
|
||||
// request made without the user opening the market (§8.1), and returns nil
|
||||
// when a built-in language already covers the OS language, the market is
|
||||
// unreachable or turned off, or nothing matches.
|
||||
func (a *App) SuggestLanguagePack() *plugin.MarketCatalogItem {
|
||||
func (a *App) SuggestLanguagePack() *market.MarketCatalogItem {
|
||||
tag := i18n.DetectOSLocaleTag()
|
||||
if builtinCoversLocale(string(tag)) {
|
||||
return nil
|
||||
@@ -1044,13 +1045,13 @@ func (a *App) installMarketPlugin(pluginID, ver string, includeAlpha bool) (*plu
|
||||
}
|
||||
var (
|
||||
progMu sync.Mutex
|
||||
phase = plugin.MarketPhaseDownload
|
||||
phase = market.MarketPhaseDownload
|
||||
lastEmit time.Time
|
||||
)
|
||||
emit := func(p MarketInstallProgress) {
|
||||
a.emit("reims:plugin-install", p)
|
||||
}
|
||||
info, err := a.getPluginMarket().InstallFromMarket(context.Background(), mgr, pluginID, plugin.MarketInstallOptions{
|
||||
info, err := a.getPluginMarket().InstallFromMarket(context.Background(), mgr, pluginID, market.MarketInstallOptions{
|
||||
Version: ver,
|
||||
IncludeAlpha: includeAlpha,
|
||||
OnPhase: func(ph string) {
|
||||
|
||||
@@ -62,10 +62,10 @@ func (a *App) secretHostHandlers(mgr *plugin.Manager, pluginID string) map[strin
|
||||
return value, err
|
||||
}
|
||||
return map[string]plugin.RPCRequestHandler{
|
||||
"host/secret.materialize": a.hostMethod(mgr, pluginID, "host/secret.materialize", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
"host/secret.materialize": a.hostAPISvc().hostMethod(mgr, pluginID, "host/secret.materialize", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
return a.materializeSecret(mgr, broker, source, pluginID, raw)
|
||||
}),
|
||||
"host/secret.discard": a.hostMethod(mgr, pluginID, "host/secret.discard", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
"host/secret.discard": a.hostAPISvc().hostMethod(mgr, pluginID, "host/secret.discard", func(_ context.Context, raw json.RawMessage) (any, error) {
|
||||
return a.discardSecret(mgr, broker, pluginID, raw)
|
||||
}),
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ var renameOwners = map[string]bool{
|
||||
"internal/macos/reims/suspend_fileops_other.go": true, // state and metadata commit together
|
||||
"internal/macos/reims/suspend_fileops_windows.go": true, // state and metadata commit together
|
||||
"internal/plugin/broker.go": true, // log rotation
|
||||
"internal/plugin/pack.go": true, // archive
|
||||
"internal/plugin/market/pack.go": true, // archive
|
||||
"internal/plugin/package_rename_other.go": true, // plugin directory
|
||||
"internal/plugin/package_rename_windows.go": true, // plugin directory
|
||||
"internal/runtime/runtime.go": true, // runtime directory
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
@@ -51,8 +52,8 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
|
||||
return mgr, router, nil
|
||||
}
|
||||
|
||||
func openCLIMarketClient(cfg *config.Config) *plugin.MarketClient {
|
||||
return plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
func openCLIMarketClient(cfg *config.Config) *market.MarketClient {
|
||||
return market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: plugin.NewPluginsLayout(cfg.DataRoot),
|
||||
HostVersion: version.Version,
|
||||
})
|
||||
@@ -113,7 +114,7 @@ func pluginSearch(ctx context.Context, cfg *config.Config, loc i18n.Locale, args
|
||||
defer mgr.Close()
|
||||
mc := openCLIMarketClient(cfg)
|
||||
query := strings.TrimSpace(strings.Join(fs.Args(), " "))
|
||||
res := mc.Browse(ctx, mgr.Registry().List(), plugin.MarketBrowseOptions{
|
||||
res := mc.Browse(ctx, mgr.Registry().List(), market.MarketBrowseOptions{
|
||||
Query: query,
|
||||
Kind: *kind,
|
||||
IncludeAlpha: *includeAlpha,
|
||||
@@ -219,7 +220,7 @@ func pluginInstall(ctx context.Context, cfg *config.Config, loc i18n.Locale, arg
|
||||
info, err = mgr.InstallLocalArchive(ctx, target, plugin.PackageInstallOptions{})
|
||||
} else {
|
||||
mc := openCLIMarketClient(cfg)
|
||||
info, err = mc.InstallFromMarket(ctx, mgr, target, plugin.MarketInstallOptions{
|
||||
info, err = mc.InstallFromMarket(ctx, mgr, target, market.MarketInstallOptions{
|
||||
IncludeAlpha: *includeAlpha,
|
||||
ForceRefresh: *refresh,
|
||||
})
|
||||
@@ -249,7 +250,7 @@ func pluginUpdate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args
|
||||
if _, ok := mgr.Registry().Info(id); !ok {
|
||||
return fmt.Errorf("%s", i18n.T(loc, "plugin.not_found", id))
|
||||
}
|
||||
info, uErr := mc.InstallFromMarket(ctx, mgr, id, plugin.MarketInstallOptions{
|
||||
info, uErr := mc.InstallFromMarket(ctx, mgr, id, market.MarketInstallOptions{
|
||||
IncludeAlpha: *includeAlpha,
|
||||
ForceRefresh: *refresh,
|
||||
})
|
||||
@@ -268,7 +269,7 @@ func pluginUpdate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args
|
||||
return nil
|
||||
}
|
||||
for _, up := range updates {
|
||||
info, uErr := mc.InstallFromMarket(ctx, mgr, up.Entry.ID, plugin.MarketInstallOptions{
|
||||
info, uErr := mc.InstallFromMarket(ctx, mgr, up.Entry.ID, market.MarketInstallOptions{
|
||||
IncludeAlpha: *includeAlpha,
|
||||
ForceRefresh: false,
|
||||
})
|
||||
@@ -296,7 +297,7 @@ func pluginPack(loc i18n.Locale, args []string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
packOpts := plugin.PackOptions{
|
||||
packOpts := market.PackOptions{
|
||||
HostVersion: version.Version,
|
||||
Contract: contract,
|
||||
OutputPath: *outPath,
|
||||
@@ -308,7 +309,7 @@ func pluginPack(loc i18n.Locale, args []string) error {
|
||||
}
|
||||
packOpts.SignKey = pk
|
||||
}
|
||||
res, pErr := plugin.PackDirectory(fs.Arg(0), packOpts)
|
||||
res, pErr := market.PackDirectory(fs.Arg(0), packOpts)
|
||||
if pErr != nil {
|
||||
if res.Report.HardBlocked && !*asJSON {
|
||||
fmt.Fprintln(os.Stderr, res.Report.SummaryText(string(loc)))
|
||||
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin/sidecarproc"
|
||||
)
|
||||
|
||||
const maxPluginLogBytes = 2 << 20 // 2 MiB log rotation threshold (§6.1)
|
||||
@@ -26,7 +28,7 @@ type ManagedProcess struct {
|
||||
// DriverID is empty only for legacy spawns that named no driver.
|
||||
DriverID string
|
||||
cmd *exec.Cmd
|
||||
job *vmJob
|
||||
job *sidecarproc.VMJob
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
@@ -479,15 +481,15 @@ func (b *Broker) SpawnManagedVMProcessWithRef(ctx context.Context, pluginID stri
|
||||
cmd.Env = append(os.Environ(), env...)
|
||||
}
|
||||
if breakaway {
|
||||
configureDetachedVMProcess(cmd)
|
||||
sidecarproc.ConfigureDetachedVMProcess(cmd)
|
||||
} else {
|
||||
configureNestedVMProcess(cmd)
|
||||
sidecarproc.ConfigureNestedVMProcess(cmd)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
cmd := build(true)
|
||||
startErr := cmd.Start()
|
||||
if startErr != nil && isBreakawayDenied(startErr) {
|
||||
if startErr != nil && sidecarproc.IsBreakawayDenied(startErr) {
|
||||
// The host itself runs in a job that forbids breakaway (some launchers
|
||||
// and CI sandboxes do). Start the VM inside that job instead; it is
|
||||
// still moved into its own per-VM job below.
|
||||
@@ -500,7 +502,7 @@ func (b *Broker) SpawnManagedVMProcessWithRef(ctx context.Context, pluginID stri
|
||||
return 0, startErr
|
||||
}
|
||||
pid := cmd.Process.Pid
|
||||
job, jobErr := newVMJob()
|
||||
job, jobErr := sidecarproc.NewVMJob()
|
||||
if jobErr == nil {
|
||||
if jobErr = job.Assign(pid); jobErr != nil {
|
||||
job.Close()
|
||||
@@ -512,7 +514,7 @@ func (b *Broker) SpawnManagedVMProcessWithRef(ctx context.Context, pluginID stri
|
||||
if jobErr != nil {
|
||||
b.Audit(pluginID, "JOB_ERR", fmt.Sprintf("vm=%s pid=%d: %v (only the launcher process is tracked)", vmName, pid, jobErr))
|
||||
}
|
||||
if err := resumeVMProcess(pid); err != nil {
|
||||
if err := sidecarproc.ResumeVMProcess(pid); err != nil {
|
||||
_ = cmd.Process.Kill()
|
||||
_ = cmd.Wait()
|
||||
job.Close()
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin/sidecarproc"
|
||||
"github.com/Nwflower/reims-go/pkg/pluginproto"
|
||||
)
|
||||
|
||||
@@ -33,8 +34,8 @@ func TestSupervisorHostMethodsAreCatalogued(t *testing.T) {
|
||||
func TestHandlerErrorKeepsItsCode(t *testing.T) {
|
||||
hostRead, pluginWrite := net.Pipe()
|
||||
pluginRead, hostWrite := net.Pipe()
|
||||
host := NewRPCConn(hostRead, hostWrite)
|
||||
plugin := NewRPCConn(pluginRead, pluginWrite)
|
||||
host := sidecarproc.NewRPCConn(hostRead, hostWrite)
|
||||
plugin := sidecarproc.NewRPCConn(pluginRead, pluginWrite)
|
||||
t.Cleanup(func() {
|
||||
host.Close()
|
||||
plugin.Close()
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"sync"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func configureSidecarCmd(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
}
|
||||
|
||||
func configureDetachedVMProcess(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
}
|
||||
|
||||
func configureNestedVMProcess(cmd *exec.Cmd) { configureDetachedVMProcess(cmd) }
|
||||
|
||||
func resumeVMProcess(int) error { return nil }
|
||||
|
||||
func isBreakawayDenied(error) bool { return false }
|
||||
|
||||
type sidecarJob struct {
|
||||
pgid int
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
func newSidecarJob(_ uintptr) (*sidecarJob, error) {
|
||||
return &sidecarJob{}, nil
|
||||
}
|
||||
|
||||
func (j *sidecarJob) Assign(pid int) error {
|
||||
if j != nil {
|
||||
j.pgid = pid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *sidecarJob) Close() {
|
||||
if j == nil {
|
||||
return
|
||||
}
|
||||
j.closeOnce.Do(func() {
|
||||
if j.pgid > 0 {
|
||||
_ = syscall.Kill(-j.pgid, syscall.SIGKILL)
|
||||
j.pgid = 0
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
package plugin
|
||||
package market
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
// MarketEntryLocales returns the canonical UI language tags a locale pack
|
||||
@@ -60,7 +61,7 @@ func primaryLanguage(tag string) string {
|
||||
// installable (compatible, not withdrawn, not installed), exact language
|
||||
// first, then the most trusted. It returns nil when there is none or the
|
||||
// market is unreachable.
|
||||
func (c *MarketClient) SuggestLocalePack(ctx context.Context, installed []PluginInfo, tag string) *MarketCatalogItem {
|
||||
func (c *MarketClient) SuggestLocalePack(ctx context.Context, installed []plugin.PluginInfo, tag string) *MarketCatalogItem {
|
||||
want, ok := i18n.ParseLocale(tag)
|
||||
if !ok {
|
||||
return nil
|
||||
+6
-5
@@ -1,4 +1,4 @@
|
||||
package plugin_test
|
||||
package market_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
)
|
||||
|
||||
// Entries shaped like the live index: no explicit locales, the language shows
|
||||
@@ -38,18 +39,18 @@ const localeIndexJSON = `{
|
||||
}`
|
||||
|
||||
func TestMarketEntryLocales(t *testing.T) {
|
||||
var idx plugin.MarketIndex
|
||||
var idx market.MarketIndex
|
||||
if err := json.Unmarshal([]byte(strings.ReplaceAll(localeIndexJSON, "SUM", strings.Repeat("a", 64))), &idx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := plugin.MarketEntryLocales(idx.Plugins[0])
|
||||
got := market.MarketEntryLocales(idx.Plugins[0])
|
||||
sort.Strings(got)
|
||||
// Non-language tags such as "locale" and "i18n" are dropped.
|
||||
want := []string{"zh-HK", "zh-TW"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("zh-TW pack locales = %v, want %v", got, want)
|
||||
}
|
||||
if got := plugin.MarketEntryLocales(idx.Plugins[2]); !reflect.DeepEqual(got, []string{"ja-JP"}) {
|
||||
if got := market.MarketEntryLocales(idx.Plugins[2]); !reflect.DeepEqual(got, []string{"ja-JP"}) {
|
||||
t.Fatalf("explicit locales = %v, want [ja-JP]", got)
|
||||
}
|
||||
}
|
||||
@@ -60,7 +61,7 @@ func TestSuggestLocalePack(t *testing.T) {
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
defer srv.Close()
|
||||
mc := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
mc := market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: plugin.PluginsLayout{}, HostVersion: "0.2.10",
|
||||
URLs: []string{srv.URL + "/index.json"}, CacheTTL: time.Minute, AllowInsecureLocalhost: true,
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
package plugin
|
||||
package market
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -20,8 +20,15 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/atomicfile"
|
||||
"github.com/Nwflower/reims-go/internal/fetch"
|
||||
"github.com/Nwflower/reims-go/internal/netproxy"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
// MarketEntryRisks estimates risk categories for a market listing from its
|
||||
// declared kind, tier and permissions before anything is downloaded.
|
||||
func MarketEntryRisks(e MarketEntry) []string {
|
||||
return plugin.EstimateMarketRisks(e.Tier, e.Kind, e.Permissions)
|
||||
}
|
||||
|
||||
//go:embed market_fallback.json
|
||||
var embeddedMarketFallbackJSON []byte
|
||||
|
||||
@@ -52,32 +59,32 @@ type MarketRelease struct {
|
||||
SHA256 string `json:"sha256"`
|
||||
SizeBytes int64 `json:"size_bytes,omitempty"`
|
||||
PublishedAt string `json:"published_at,omitempty"`
|
||||
Changelog LocalizedText `json:"changelog,omitempty"`
|
||||
Changelog plugin.LocalizedText `json:"changelog,omitempty"`
|
||||
}
|
||||
|
||||
// MarketEntry describes one plugin published in the remote/embedded market index (§9).
|
||||
type MarketEntry struct {
|
||||
ID string `json:"id"`
|
||||
Version string `json:"version"`
|
||||
Name LocalizedText `json:"name"`
|
||||
Description LocalizedText `json:"description"`
|
||||
Name plugin.LocalizedText `json:"name"`
|
||||
Description plugin.LocalizedText `json:"description"`
|
||||
Publisher string `json:"publisher"`
|
||||
License string `json:"license"`
|
||||
Channel string `json:"channel"` // "stable" | "alpha"
|
||||
Trust TrustLevel `json:"trust"`
|
||||
Trust plugin.TrustLevel `json:"trust"`
|
||||
Kind string `json:"kind,omitempty"` // "theme" | "locale" | "driver" | "tool" | "template" | "runtime"
|
||||
Tier Tier `json:"tier,omitempty"`
|
||||
Icon *PluginIcon `json:"icon,omitempty"`
|
||||
Tier plugin.Tier `json:"tier,omitempty"`
|
||||
Icon *plugin.PluginIcon `json:"icon,omitempty"`
|
||||
Homepage string `json:"homepage,omitempty"`
|
||||
ReadmeURL string `json:"readme_url,omitempty"`
|
||||
Engines Engines `json:"engines"`
|
||||
Engines plugin.Engines `json:"engines"`
|
||||
Platforms []string `json:"platforms,omitempty"`
|
||||
Permissions []string `json:"permissions,omitempty"`
|
||||
DownloadURL string `json:"download_url"`
|
||||
SHA256 string `json:"sha256"`
|
||||
SizeBytes int64 `json:"size_bytes,omitempty"`
|
||||
Signer string `json:"signer,omitempty"`
|
||||
Changelog LocalizedText `json:"changelog,omitempty"`
|
||||
Changelog plugin.LocalizedText `json:"changelog,omitempty"`
|
||||
Releases []MarketRelease `json:"releases,omitempty"`
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
// Locales lists the UI languages a locale pack provides. When absent,
|
||||
@@ -92,7 +99,7 @@ type MarketEntry struct {
|
||||
// while already-installed users keep running with a replacement advisory.
|
||||
type MarketWithdrawal struct {
|
||||
ID string `json:"id"`
|
||||
Reason LocalizedText `json:"reason"`
|
||||
Reason plugin.LocalizedText `json:"reason"`
|
||||
InsteadID string `json:"instead_id,omitempty"`
|
||||
InsteadName string `json:"instead_name,omitempty"`
|
||||
WithdrawnAt string `json:"withdrawn_at,omitempty"`
|
||||
@@ -169,7 +176,7 @@ type MarketInstallOptions struct {
|
||||
Version string
|
||||
IncludeAlpha bool
|
||||
ForceRefresh bool
|
||||
Keyring []SigningKey
|
||||
Keyring []plugin.SigningKey
|
||||
OnProgress fetch.Progress
|
||||
// OnPhase is called when the install moves to a new phase.
|
||||
OnPhase func(phase string)
|
||||
@@ -177,7 +184,7 @@ type MarketInstallOptions struct {
|
||||
|
||||
// MarketClientOptions configures MarketClient.
|
||||
type MarketClientOptions struct {
|
||||
Layout PluginsLayout
|
||||
Layout plugin.PluginsLayout
|
||||
HostVersion string
|
||||
URLs []string
|
||||
HTTPClient *http.Client
|
||||
@@ -193,7 +200,7 @@ type MarketClientOptions struct {
|
||||
// MarketClient lazily fetches, caches, searches, and installs plugins from the
|
||||
// static remote market index with disk-cache + embedded fallback (§9).
|
||||
type MarketClient struct {
|
||||
layout PluginsLayout
|
||||
layout plugin.PluginsLayout
|
||||
hostVersion string
|
||||
urls []string
|
||||
httpClient *http.Client
|
||||
@@ -379,19 +386,19 @@ func (c *MarketClient) cachedSnapshot() (idx MarketIndex, source string, stale b
|
||||
}
|
||||
|
||||
// Peek is Browse over CachedIndex: no network I/O.
|
||||
func (c *MarketClient) Peek(installed []PluginInfo, opts MarketBrowseOptions) MarketBrowseResult {
|
||||
func (c *MarketClient) Peek(installed []plugin.PluginInfo, opts MarketBrowseOptions) MarketBrowseResult {
|
||||
idx, source, stale, fetchErr := c.cachedSnapshot()
|
||||
return c.browseIndex(idx, source, stale, fetchErr, installed, opts, c.vouches(source, stale))
|
||||
}
|
||||
|
||||
// Browse filters the market index and annotates compatibility, local install
|
||||
// state, available updates, and soft-withdrawal advisories.
|
||||
func (c *MarketClient) Browse(ctx context.Context, installed []PluginInfo, opts MarketBrowseOptions) MarketBrowseResult {
|
||||
func (c *MarketClient) Browse(ctx context.Context, installed []plugin.PluginInfo, opts MarketBrowseOptions) MarketBrowseResult {
|
||||
idx, source, stale, fetchErr := c.LoadIndex(ctx, opts.ForceRefresh)
|
||||
return c.browseIndex(idx, source, stale, fetchErr, installed, opts, c.vouches(source, stale))
|
||||
}
|
||||
|
||||
func (c *MarketClient) browseIndex(idx MarketIndex, source string, stale bool, fetchErr error, installed []PluginInfo, opts MarketBrowseOptions, vouched bool) MarketBrowseResult {
|
||||
func (c *MarketClient) browseIndex(idx MarketIndex, source string, stale bool, fetchErr error, installed []plugin.PluginInfo, opts MarketBrowseOptions, vouched bool) MarketBrowseResult {
|
||||
res := MarketBrowseResult{
|
||||
Source: source,
|
||||
Stale: stale,
|
||||
@@ -403,7 +410,7 @@ func (c *MarketClient) browseIndex(idx MarketIndex, source string, stale bool, f
|
||||
res.FetchError = fetchErr.Error()
|
||||
}
|
||||
|
||||
instMap := make(map[string]PluginInfo, len(installed))
|
||||
instMap := make(map[string]plugin.PluginInfo, len(installed))
|
||||
for _, info := range installed {
|
||||
instMap[info.ID] = info
|
||||
}
|
||||
@@ -435,17 +442,17 @@ func (c *MarketClient) browseIndex(idx MarketIndex, source string, stale bool, f
|
||||
if kindFilter != "" && !strings.EqualFold(entry.Kind, kindFilter) {
|
||||
continue
|
||||
}
|
||||
if !vouched && entry.Trust != TrustCommunity {
|
||||
if !vouched && entry.Trust != plugin.TrustCommunity {
|
||||
// An index that cannot vouch (third-party or stale cache) must show
|
||||
// the trust its packages will actually install with.
|
||||
entry.Trust = TrustCommunity
|
||||
entry.Trust = plugin.TrustCommunity
|
||||
}
|
||||
compat, incompatReason := CheckMarketCompatibility(entry, c.hostVersion)
|
||||
item := MarketCatalogItem{
|
||||
Entry: entry,
|
||||
Compatible: compat,
|
||||
IncompatibleReason: incompatReason,
|
||||
HighRiskPermissions: HighRiskPermissions(entry.Permissions),
|
||||
HighRiskPermissions: plugin.HighRiskPermissions(entry.Permissions),
|
||||
Risks: MarketEntryRisks(entry),
|
||||
}
|
||||
if w, ok := withdrawnMap[entry.ID]; ok {
|
||||
@@ -467,7 +474,7 @@ func (c *MarketClient) browseIndex(idx MarketIndex, source string, stale bool, f
|
||||
if a.UpdateAvailable != b.UpdateAvailable {
|
||||
return a.UpdateAvailable
|
||||
}
|
||||
ra, rb := trustSortRank(a.Entry.Trust), trustSortRank(b.Entry.Trust)
|
||||
ra, rb := plugin.TrustSortRank(a.Entry.Trust), plugin.TrustSortRank(b.Entry.Trust)
|
||||
if ra != rb {
|
||||
return ra > rb
|
||||
}
|
||||
@@ -488,7 +495,7 @@ func (c *MarketClient) browseIndex(idx MarketIndex, source string, stale bool, f
|
||||
|
||||
// CheckUpdates returns installed plugins that have a compatible, non-withdrawn
|
||||
// newer version available in the market.
|
||||
func (c *MarketClient) CheckUpdates(ctx context.Context, installed []PluginInfo, includeAlpha, forceRefresh bool) ([]MarketCatalogItem, MarketBrowseResult) {
|
||||
func (c *MarketClient) CheckUpdates(ctx context.Context, installed []plugin.PluginInfo, includeAlpha, forceRefresh bool) ([]MarketCatalogItem, MarketBrowseResult) {
|
||||
browse := c.Browse(ctx, installed, MarketBrowseOptions{
|
||||
IncludeAlpha: includeAlpha,
|
||||
ForceRefresh: forceRefresh,
|
||||
@@ -504,12 +511,12 @@ func (c *MarketClient) CheckUpdates(ctx context.Context, installed []PluginInfo,
|
||||
|
||||
// InstallFromMarket downloads, verifies SHA-256, static-scans, and
|
||||
// transactionally installs pluginID from the market index.
|
||||
func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, pluginID string, opts MarketInstallOptions) (*PluginInfo, error) {
|
||||
func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *plugin.Manager, pluginID string, opts MarketInstallOptions) (*plugin.PluginInfo, error) {
|
||||
if mgr == nil {
|
||||
return nil, errors.New("plugin manager is nil")
|
||||
}
|
||||
pluginID = strings.TrimSpace(pluginID)
|
||||
if !reReverseDomainID.MatchString(pluginID) {
|
||||
if !plugin.IsValidReverseDomainID(pluginID) {
|
||||
return nil, fmt.Errorf("invalid plugin id %q", pluginID)
|
||||
}
|
||||
|
||||
@@ -582,10 +589,10 @@ func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, plug
|
||||
strings.ContainsAny(entry.Version, `/\`) || strings.Contains(entry.Version, "..") {
|
||||
return nil, fmt.Errorf("market entry %s has invalid version %q", entry.ID, entry.Version)
|
||||
}
|
||||
if _, err := ParseSemVer(entry.Version); err != nil {
|
||||
if _, err := plugin.ParseSemVer(entry.Version); err != nil {
|
||||
return nil, fmt.Errorf("market entry %s has invalid version %q: %w", entry.ID, entry.Version, err)
|
||||
}
|
||||
if entry.SizeBytes < 0 || entry.SizeBytes > maxPluginArchiveBytes {
|
||||
if entry.SizeBytes < 0 || entry.SizeBytes > plugin.MaxPluginArchiveBytes {
|
||||
return nil, fmt.Errorf("market entry %s@%s declares invalid archive size %d", entry.ID, entry.Version, entry.SizeBytes)
|
||||
}
|
||||
wantSum := strings.ToLower(strings.TrimSpace(entry.SHA256))
|
||||
@@ -603,7 +610,7 @@ func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, plug
|
||||
return nil, err
|
||||
}
|
||||
archiveName := fmt.Sprintf("market-%s-%s.zip", entry.ID, entry.Version)
|
||||
archivePath, err := safeJoin(c.layout.TmpDir(), archiveName)
|
||||
archivePath, err := plugin.SafeJoin(c.layout.TmpDir(), archiveName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid market archive path for %s@%s: %w", entry.ID, entry.Version, err)
|
||||
}
|
||||
@@ -615,7 +622,7 @@ func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, plug
|
||||
if opts.OnPhase != nil {
|
||||
opts.OnPhase(MarketPhaseDownload)
|
||||
}
|
||||
maxBytes := maxPluginArchiveBytes
|
||||
maxBytes := plugin.MaxPluginArchiveBytes
|
||||
if entry.SizeBytes > 0 && entry.SizeBytes < maxBytes {
|
||||
maxBytes = entry.SizeBytes
|
||||
}
|
||||
@@ -630,7 +637,7 @@ func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, plug
|
||||
opts.OnPhase(MarketPhaseInstall)
|
||||
}
|
||||
|
||||
return mgr.InstallArchiveWithSource(ctx, archivePath, SourceMarket, PackageInstallOptions{
|
||||
return mgr.InstallArchiveWithSource(ctx, archivePath, plugin.SourceMarket, plugin.PackageInstallOptions{
|
||||
ExpectedID: entry.ID,
|
||||
ExpectedVersion: entry.Version,
|
||||
HostVersion: c.hostVersion,
|
||||
@@ -642,7 +649,7 @@ func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, plug
|
||||
|
||||
// CheckMarketCompatibility verifies platform and engines constraints before downloading.
|
||||
func CheckMarketCompatibility(entry MarketEntry, hostVersion string) (bool, string) {
|
||||
return checkHostCompatibility(entry.Platforms, entry.Engines, hostVersion)
|
||||
return plugin.CheckHostCompatibility(entry.Platforms, entry.Engines, hostVersion)
|
||||
}
|
||||
|
||||
func (c *MarketClient) fetchRemoteIndex(ctx context.Context, rawURL string) (MarketIndex, error) {
|
||||
@@ -828,8 +835,8 @@ func selectChannelEntries(entries []MarketEntry, includeAlpha bool) map[string]M
|
||||
}
|
||||
|
||||
func isVersionNewer(candidate, current string) bool {
|
||||
vc, err1 := ParseSemVer(candidate)
|
||||
vcur, err2 := ParseSemVer(current)
|
||||
vc, err1 := plugin.ParseSemVer(candidate)
|
||||
vcur, err2 := plugin.ParseSemVer(current)
|
||||
if err1 != nil || err2 != nil {
|
||||
return candidate != current && candidate > current
|
||||
}
|
||||
@@ -864,19 +871,6 @@ func marketEntryMatchesQuery(e MarketEntry, q string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func trustSortRank(t TrustLevel) int {
|
||||
switch t {
|
||||
case TrustOfficial:
|
||||
return 3
|
||||
case TrustVerified:
|
||||
return 2
|
||||
case TrustCommunity:
|
||||
return 1
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func cloneMarketIndex(idx MarketIndex) MarketIndex {
|
||||
cp := MarketIndex{
|
||||
Schema: idx.Schema,
|
||||
@@ -910,11 +904,11 @@ func (c *MarketClient) vouches(source string, stale bool) bool {
|
||||
}
|
||||
|
||||
// indexTrust is the trust an install inherits from a vouching index.
|
||||
func indexTrust(entry MarketEntry, vouched bool) TrustLevel {
|
||||
func indexTrust(entry MarketEntry, vouched bool) plugin.TrustLevel {
|
||||
if !vouched {
|
||||
return ""
|
||||
}
|
||||
if entry.Trust == TrustOfficial || entry.Trust == TrustVerified {
|
||||
if entry.Trust == plugin.TrustOfficial || entry.Trust == plugin.TrustVerified {
|
||||
return entry.Trust
|
||||
}
|
||||
return ""
|
||||
File renamed without changes.
@@ -1,4 +1,4 @@
|
||||
package plugin_test
|
||||
package market_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/downloader"
|
||||
"github.com/Nwflower/reims-go/internal/fetch"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
)
|
||||
|
||||
func TestMarketFetchCacheAndFallback(t *testing.T) {
|
||||
@@ -23,10 +24,10 @@ func TestMarketFetchCacheAndFallback(t *testing.T) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
idx := plugin.MarketIndex{
|
||||
idx := market.MarketIndex{
|
||||
Schema: 1,
|
||||
UpdatedAt: "2026-11-30T00:00:00Z",
|
||||
Plugins: []plugin.MarketEntry{{
|
||||
Plugins: []market.MarketEntry{{
|
||||
ID: "community.theme.nord",
|
||||
Version: "1.2.0",
|
||||
Name: plugin.LocalizedText{ZhCN: "北欧主题", EnUS: "Nord Theme"},
|
||||
@@ -46,7 +47,7 @@ func TestMarketFetchCacheAndFallback(t *testing.T) {
|
||||
|
||||
dataRoot := t.TempDir()
|
||||
layout := plugin.NewPluginsLayout(dataRoot)
|
||||
mc := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
mc := market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: layout,
|
||||
HostVersion: "0.2.8",
|
||||
URLs: []string{srv.URL + "/index.json"},
|
||||
@@ -71,7 +72,7 @@ func TestMarketFetchCacheAndFallback(t *testing.T) {
|
||||
|
||||
// 3. Server goes down + forceRefresh: must retain valid disk/mem cache with stale=true.
|
||||
fail.Store(true)
|
||||
mcFresh := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
mcFresh := market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: layout,
|
||||
HostVersion: "0.2.8",
|
||||
URLs: []string{srv.URL + "/index.json"},
|
||||
@@ -132,10 +133,10 @@ func TestMarketBrowseAndInstallGates(t *testing.T) {
|
||||
w.Header().Set("Content-Type", "application/zip")
|
||||
_, _ = w.Write(evilBytes)
|
||||
case "/index.json":
|
||||
idx := plugin.MarketIndex{
|
||||
idx := market.MarketIndex{
|
||||
Schema: 1,
|
||||
UpdatedAt: "2026-11-30T00:00:00Z",
|
||||
Plugins: []plugin.MarketEntry{
|
||||
Plugins: []market.MarketEntry{
|
||||
{
|
||||
ID: "community.theme.mist",
|
||||
Version: "1.1.0",
|
||||
@@ -194,7 +195,7 @@ func TestMarketBrowseAndInstallGates(t *testing.T) {
|
||||
SHA256: evilSum,
|
||||
},
|
||||
},
|
||||
Withdrawn: []plugin.MarketWithdrawal{{
|
||||
Withdrawn: []market.MarketWithdrawal{{
|
||||
ID: "community.old.tool",
|
||||
Reason: plugin.LocalizedText{ZhCN: "已合并进新插件", EnUS: "Merged into new plugin"},
|
||||
InsteadID: "community.theme.mist",
|
||||
@@ -219,7 +220,7 @@ func TestMarketBrowseAndInstallGates(t *testing.T) {
|
||||
}
|
||||
defer mgr.Close()
|
||||
|
||||
mc := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
mc := market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: mgr.Layout(),
|
||||
HostVersion: "0.2.8",
|
||||
URLs: []string{srvURL + "/index.json"},
|
||||
@@ -230,11 +231,11 @@ func TestMarketBrowseAndInstallGates(t *testing.T) {
|
||||
res := mc.Browse(context.Background(), []plugin.PluginInfo{
|
||||
{ID: "community.old.tool", Version: "0.9.0"},
|
||||
{ID: "community.theme.mist", Version: "1.0.0"},
|
||||
}, plugin.MarketBrowseOptions{})
|
||||
}, market.MarketBrowseOptions{})
|
||||
if len(res.WithdrawnInstalled) != 1 || res.WithdrawnInstalled[0].InsteadID != "community.theme.mist" {
|
||||
t.Fatalf("expected withdrawn installed advisory, got %+v", res.WithdrawnInstalled)
|
||||
}
|
||||
var mistItem *plugin.MarketCatalogItem
|
||||
var mistItem *market.MarketCatalogItem
|
||||
for i := range res.Items {
|
||||
if res.Items[i].Entry.ID == "community.theme.mist" {
|
||||
mistItem = &res.Items[i]
|
||||
@@ -245,27 +246,27 @@ func TestMarketBrowseAndInstallGates(t *testing.T) {
|
||||
}
|
||||
|
||||
// Withdrawn plugin install refused with replacement hint.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.old.tool", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "withdrawn") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.old.tool", market.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "withdrawn") {
|
||||
t.Fatalf("expected withdrawn refusal, got: %v", err)
|
||||
}
|
||||
|
||||
// Incompatible plugin refused BEFORE download.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.incompat", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "incompatible") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.incompat", market.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "incompatible") {
|
||||
t.Fatalf("expected incompatible refusal, got: %v", err)
|
||||
}
|
||||
|
||||
// SHA-256 mismatch refused.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.badhash", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "SHA256 mismatch") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.badhash", market.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "SHA256 mismatch") {
|
||||
t.Fatalf("expected SHA256 mismatch refusal, got: %v", err)
|
||||
}
|
||||
|
||||
// Smuggled .ps1 in L1 zip refused by static security gate even when archive SHA-256 matches.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.evil", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "static security gate") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.evil", market.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "static security gate") {
|
||||
t.Fatalf("expected static gate refusal for smuggled .ps1, got: %v", err)
|
||||
}
|
||||
|
||||
// Valid market plugin installs cleanly with SourceMarket.
|
||||
info, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.mist", plugin.MarketInstallOptions{})
|
||||
info, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.mist", market.MarketInstallOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("InstallFromMarket valid plugin: %v", err)
|
||||
}
|
||||
@@ -275,7 +276,7 @@ func TestMarketBrowseAndInstallGates(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCheckMarketCompatibilityUnified(t *testing.T) {
|
||||
base := plugin.MarketEntry{
|
||||
base := market.MarketEntry{
|
||||
ID: "community.theme.compat",
|
||||
Version: "1.0.0",
|
||||
Engines: plugin.Engines{PluginAPI: "^1.0.0", UIAPI: "^2.0.0", BridgeAPI: "^1.0.0", ReimsGo: ">=0.2.10"},
|
||||
@@ -283,24 +284,24 @@ func TestCheckMarketCompatibilityUnified(t *testing.T) {
|
||||
for _, plats := range [][]string{nil, {"*"}, {"any"}, {"ANY"}, {"windows-x64", "linux-x64", "darwin-arm64", "darwin-x64"}, {"windows/amd64", "linux/amd64", "darwin/arm64", "darwin/amd64"}} {
|
||||
e := base
|
||||
e.Platforms = plats
|
||||
if ok, reason := plugin.CheckMarketCompatibility(e, "0.2.11"); !ok {
|
||||
if ok, reason := market.CheckMarketCompatibility(e, "0.2.11"); !ok {
|
||||
t.Fatalf("platforms=%v expected compatible, got: %s", plats, reason)
|
||||
}
|
||||
}
|
||||
// Dev host builds skip engines.reims-go just like ValidateManifest.
|
||||
if ok, reason := plugin.CheckMarketCompatibility(base, "dev"); !ok {
|
||||
if ok, reason := market.CheckMarketCompatibility(base, "dev"); !ok {
|
||||
t.Fatalf("dev host expected compatible, got: %s", reason)
|
||||
}
|
||||
// Unsupported platform rejected.
|
||||
badPlat := base
|
||||
badPlat.Platforms = []string{"solaris-sparc"}
|
||||
if ok, _ := plugin.CheckMarketCompatibility(badPlat, "0.2.11"); ok {
|
||||
if ok, _ := market.CheckMarketCompatibility(badPlat, "0.2.11"); ok {
|
||||
t.Fatal("expected unsupported platform to be incompatible")
|
||||
}
|
||||
// Incompatible bridgeApi rejected before download.
|
||||
badBridge := base
|
||||
badBridge.Engines.BridgeAPI = "^9.0.0"
|
||||
if ok, reason := plugin.CheckMarketCompatibility(badBridge, "0.2.11"); ok || !strings.Contains(reason, "bridgeApi") {
|
||||
if ok, reason := market.CheckMarketCompatibility(badBridge, "0.2.11"); ok || !strings.Contains(reason, "bridgeApi") {
|
||||
t.Fatalf("expected bridgeApi incompatibility, got ok=%v reason=%q", ok, reason)
|
||||
}
|
||||
}
|
||||
@@ -310,10 +311,10 @@ func TestMarketSecurityGatesSearchExtraAndConcurrentCache(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/index.json":
|
||||
idx := plugin.MarketIndex{
|
||||
idx := market.MarketIndex{
|
||||
Schema: 1,
|
||||
UpdatedAt: "2026-12-02T00:00:00Z",
|
||||
Plugins: []plugin.MarketEntry{
|
||||
Plugins: []market.MarketEntry{
|
||||
{
|
||||
ID: "evil.theme.traversal",
|
||||
Version: "../../escape",
|
||||
@@ -423,7 +424,7 @@ func TestMarketSecurityGatesSearchExtraAndConcurrentCache(t *testing.T) {
|
||||
}
|
||||
defer mgr.Close()
|
||||
|
||||
mc := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
mc := market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: mgr.Layout(),
|
||||
HostVersion: "0.2.11",
|
||||
URLs: []string{srvURL + "/index.json"},
|
||||
@@ -440,37 +441,37 @@ func TestMarketSecurityGatesSearchExtraAndConcurrentCache(t *testing.T) {
|
||||
t.Cleanup(func() { fetch.SetDefaultDownloader(nil) })
|
||||
|
||||
// 1. Path traversal or surrounding whitespace in entry.Version must be rejected.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.traversal", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "invalid version") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.traversal", market.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "invalid version") {
|
||||
t.Fatalf("expected invalid version error for traversal, got: %v", err)
|
||||
}
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.spacesver", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "invalid version") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.spacesver", market.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "invalid version") {
|
||||
t.Fatalf("expected invalid version error for whitespace version, got: %v", err)
|
||||
}
|
||||
|
||||
// 2. Oversized declared SizeBytes and oversized actual stream must both be rejected.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.huge", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "invalid archive size") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.huge", market.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "invalid archive size") {
|
||||
t.Fatalf("expected invalid archive size error, got: %v", err)
|
||||
}
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.oversize-body", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "exceeds 64 byte limit") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.oversize-body", market.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "exceeds 64 byte limit") {
|
||||
t.Fatalf("expected actual stream byte limit error, got: %v", err)
|
||||
}
|
||||
|
||||
// 3. Stalled market stream aborts via DownloadStallTimeout.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.stall", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "stalled") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.stall", market.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "stalled") {
|
||||
t.Fatalf("expected stalled error, got: %v", err)
|
||||
}
|
||||
|
||||
// 4. Redirect to non-localhost plain HTTP must still be blocked even with ParallelDownloader active.
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.downgrade", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "only HTTPS") {
|
||||
if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.downgrade", market.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "only HTTPS") {
|
||||
t.Fatalf("expected HTTPS-only redirect refusal with active ParallelDownloader, got: %v", err)
|
||||
}
|
||||
|
||||
// 4. Market search matches localized Name.Extra and Description.Extra.
|
||||
resName := mc.Browse(context.Background(), nil, plugin.MarketBrowseOptions{Query: "日本語"})
|
||||
resName := mc.Browse(context.Background(), nil, market.MarketBrowseOptions{Query: "日本語"})
|
||||
if len(resName.Items) != 1 || resName.Items[0].Entry.ID != "community.locale.ja" {
|
||||
t.Fatalf("expected Name.Extra search match, got %+v", resName.Items)
|
||||
}
|
||||
resDesc := mc.Browse(context.Background(), nil, plugin.MarketBrowseOptions{Query: "한국어"})
|
||||
resDesc := mc.Browse(context.Background(), nil, market.MarketBrowseOptions{Query: "한국어"})
|
||||
if len(resDesc.Items) != 1 || resDesc.Items[0].Entry.ID != "community.locale.ja" {
|
||||
t.Fatalf("expected Description.Extra search match, got %+v", resDesc.Items)
|
||||
}
|
||||
@@ -496,7 +497,7 @@ func TestMarketSecurityGatesSearchExtraAndConcurrentCache(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("read disk cache: %v", err)
|
||||
}
|
||||
var cached plugin.MarketIndex
|
||||
var cached market.MarketIndex
|
||||
if err := json.Unmarshal(raw, &cached); err != nil || len(cached.Plugins) != 7 {
|
||||
t.Fatalf("corrupted disk cache after concurrent writes: err=%v len=%d", err, len(cached.Plugins))
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package plugin
|
||||
package market
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
@@ -12,12 +12,14 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
// PackOptions configures PackDirectory.
|
||||
type PackOptions struct {
|
||||
HostVersion string
|
||||
Contract *UIContract
|
||||
Contract *plugin.UIContract
|
||||
OutputPath string // optional; defaults to "<cwd>/<id>-<version>.zip"
|
||||
SignKey ed25519.PrivateKey
|
||||
}
|
||||
@@ -25,15 +27,15 @@ type PackOptions struct {
|
||||
// PackResult describes a freshly packed plugin archive ready for distribution
|
||||
// or market submission.
|
||||
type PackResult struct {
|
||||
PluginID string `json:"plugin_id"`
|
||||
Version string `json:"version"`
|
||||
Tier Tier `json:"tier"`
|
||||
OutputPath string `json:"output_path"`
|
||||
SHA256 string `json:"sha256"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
FileCount int `json:"file_count"`
|
||||
Signed bool `json:"signed"`
|
||||
Report ScanReport `json:"report"`
|
||||
PluginID string `json:"plugin_id"`
|
||||
Version string `json:"version"`
|
||||
Tier plugin.Tier `json:"tier"`
|
||||
OutputPath string `json:"output_path"`
|
||||
SHA256 string `json:"sha256"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
FileCount int `json:"file_count"`
|
||||
Signed bool `json:"signed"`
|
||||
Report plugin.ScanReport `json:"report"`
|
||||
}
|
||||
|
||||
// PackDirectory validates dir through the unified static security gate, generates
|
||||
@@ -56,13 +58,13 @@ func PackDirectory(dir string, opts PackOptions) (PackResult, error) {
|
||||
if err != nil {
|
||||
return PackResult{}, fmt.Errorf("read plugin.json: %w", err)
|
||||
}
|
||||
var m Manifest
|
||||
var m plugin.Manifest
|
||||
if err := json.Unmarshal(rawMan, &m); err != nil {
|
||||
return PackResult{}, fmt.Errorf("parse plugin.json: %w", err)
|
||||
}
|
||||
|
||||
// Run static security gate before creating any output archive.
|
||||
report := ScanDirectory(absDir, opts.HostVersion, ScanOptions{
|
||||
report := plugin.ScanDirectory(absDir, opts.HostVersion, plugin.ScanOptions{
|
||||
Contract: opts.Contract,
|
||||
RequireChecksums: false,
|
||||
})
|
||||
@@ -116,7 +118,7 @@ func PackDirectory(dir string, opts PackOptions) (PackResult, error) {
|
||||
if slash == "SHA256SUMS" || slash == "SHA256SUMS.sig" || info.Name() == ".DS_Store" || info.Name() == "Thumbs.db" {
|
||||
return nil
|
||||
}
|
||||
h, hErr := fileSHA256Hex(p)
|
||||
h, hErr := plugin.FileSHA256Hex(p)
|
||||
if hErr != nil {
|
||||
return hErr
|
||||
}
|
||||
@@ -232,7 +234,7 @@ func PackDirectory(dir string, opts PackOptions) (PackResult, error) {
|
||||
return PackResult{}, err
|
||||
}
|
||||
|
||||
zipHash, err := fileSHA256Hex(absOut)
|
||||
zipHash, err := plugin.FileSHA256Hex(absOut)
|
||||
if err != nil {
|
||||
return PackResult{}, err
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package plugin_test
|
||||
package market_test
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
)
|
||||
|
||||
func TestPackDirectorySignAndInstallRoundTrip(t *testing.T) {
|
||||
@@ -42,7 +43,7 @@ func TestPackDirectorySignAndInstallRoundTrip(t *testing.T) {
|
||||
_ = os.WriteFile(filepath.Join(srcDir, ".DS_Store"), []byte("junk"), 0o644)
|
||||
|
||||
outZip := filepath.Join(t.TempDir(), "official.theme.packtest-1.0.0.zip")
|
||||
res, err := plugin.PackDirectory(srcDir, plugin.PackOptions{
|
||||
res, err := market.PackDirectory(srcDir, market.PackOptions{
|
||||
HostVersion: "0.2.8",
|
||||
OutputPath: outZip,
|
||||
SignKey: priv,
|
||||
@@ -94,7 +95,7 @@ func TestPackDirectoryRefusesBlockedPackage(t *testing.T) {
|
||||
_ = os.WriteFile(filepath.Join(srcDir, "sneak.ps1"), []byte(`Write-Host "nope"`), 0o644)
|
||||
|
||||
outZip := filepath.Join(t.TempDir(), "should-not-exist.zip")
|
||||
res, err := plugin.PackDirectory(srcDir, plugin.PackOptions{
|
||||
res, err := market.PackDirectory(srcDir, market.PackOptions{
|
||||
HostVersion: "0.2.8",
|
||||
OutputPath: outZip,
|
||||
})
|
||||
@@ -107,16 +108,16 @@ func TestPackDirectoryRefusesBlockedPackage(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestDefaultMarketURLsPointToReimsGoOrg(t *testing.T) {
|
||||
t.Setenv(plugin.EnvPluginMarketURL, "")
|
||||
urls := plugin.DefaultMarketURLs()
|
||||
t.Setenv(market.EnvPluginMarketURL, "")
|
||||
urls := market.DefaultMarketURLs()
|
||||
if len(urls) < 2 {
|
||||
t.Fatalf("expected primary + mirror URLs, got %v", urls)
|
||||
}
|
||||
if !strings.Contains(urls[0], "reims-go/plugins") || !strings.Contains(urls[1], "reims-go/plugins") {
|
||||
t.Fatalf("expected reims-go/plugins URLs, got %v", urls)
|
||||
}
|
||||
t.Setenv(plugin.EnvPluginMarketURL, "off")
|
||||
if got := plugin.DefaultMarketURLs(); got != nil {
|
||||
t.Setenv(market.EnvPluginMarketURL, "off")
|
||||
if got := market.DefaultMarketURLs(); got != nil {
|
||||
t.Fatalf("expected nil URLs in offline mode, got %v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package market_test
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"crypto/ed25519"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func makePluginZip(t *testing.T, files map[string][]byte, priv ed25519.PrivateKey, corruptSum bool) string {
|
||||
t.Helper()
|
||||
zipPath := filepath.Join(t.TempDir(), "plugin.zip")
|
||||
f, err := os.Create(zipPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zw := zip.NewWriter(f)
|
||||
|
||||
var sumLines []string
|
||||
for rel, content := range files {
|
||||
w, err := zw.Create(rel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = w.Write(content)
|
||||
h := sha256.Sum256(content)
|
||||
hexSum := hex.EncodeToString(h[:])
|
||||
if corruptSum {
|
||||
hexSum = strings.Repeat("0", 64)
|
||||
}
|
||||
sumLines = append(sumLines, fmt.Sprintf("%s %s", hexSum, rel))
|
||||
}
|
||||
sumsBytes := []byte(strings.Join(sumLines, "\n") + "\n")
|
||||
w, _ := zw.Create("SHA256SUMS")
|
||||
_, _ = w.Write(sumsBytes)
|
||||
|
||||
if len(priv) > 0 {
|
||||
sig := ed25519.Sign(priv, sumsBytes)
|
||||
sw, _ := zw.Create("SHA256SUMS.sig")
|
||||
_, _ = sw.Write([]byte(base64.StdEncoding.EncodeToString(sig)))
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = f.Close()
|
||||
return zipPath
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package plugin
|
||||
|
||||
import "github.com/Nwflower/reims-go/internal/plugin/uiassets"
|
||||
|
||||
// MaxPluginArchiveBytes is the maximum accepted size of a plugin archive.
|
||||
const MaxPluginArchiveBytes = maxPluginArchiveBytes
|
||||
|
||||
// IsValidReverseDomainID reports whether id matches the reverse-domain plugin ID format.
|
||||
func IsValidReverseDomainID(id string) bool {
|
||||
return reReverseDomainID.MatchString(id)
|
||||
}
|
||||
|
||||
// CheckHostCompatibility checks whether a plugin's platform list and engine
|
||||
// constraints are compatible with the running host version.
|
||||
func CheckHostCompatibility(platforms []string, engines Engines, hostVersion string) (bool, string) {
|
||||
return checkHostCompatibility(platforms, engines, hostVersion)
|
||||
}
|
||||
|
||||
// FileSHA256Hex returns the lowercase hex SHA-256 digest of the file at path.
|
||||
func FileSHA256Hex(path string) (string, error) {
|
||||
return fileSHA256Hex(path)
|
||||
}
|
||||
|
||||
// SafeJoin joins rel under root and blocks lexical and symlink traversal.
|
||||
func SafeJoin(root, rel string) (string, error) {
|
||||
return uiassets.SafeJoin(root, rel)
|
||||
}
|
||||
|
||||
// TrustSortRank orders trust levels with higher numbers being more trusted.
|
||||
func TrustSortRank(t TrustLevel) int {
|
||||
switch t {
|
||||
case TrustOfficial:
|
||||
return 3
|
||||
case TrustVerified:
|
||||
return 2
|
||||
case TrustCommunity:
|
||||
return 1
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func trustSortRank(t TrustLevel) int {
|
||||
return TrustSortRank(t)
|
||||
}
|
||||
@@ -1123,15 +1123,6 @@ func verifyEd25519Signature(message, sigRaw []byte, keyring []SigningKey) (Trust
|
||||
return TrustCommunity, errors.New("signature did not match any trusted signing key")
|
||||
}
|
||||
|
||||
func pathWithinRoot(root, candidate string) bool {
|
||||
if runtime.GOOS == "windows" {
|
||||
r := strings.ToLower(root)
|
||||
c := strings.ToLower(candidate)
|
||||
return c == r || strings.HasPrefix(c, r+string(os.PathSeparator))
|
||||
}
|
||||
return candidate == root || strings.HasPrefix(candidate, root+string(os.PathSeparator))
|
||||
}
|
||||
|
||||
func validateDiskContributions(m Manifest, rootDir string) error {
|
||||
for _, th := range m.Contributes.Themes {
|
||||
if err := ValidateThemeContribution(th, rootDir); err != nil {
|
||||
@@ -1151,63 +1142,6 @@ func validateDiskContributions(m Manifest, rootDir string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeJoin(root, rel string) (string, error) {
|
||||
absRoot, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve root path: %w", err)
|
||||
}
|
||||
cleanRoot := filepath.Clean(absRoot)
|
||||
joined := filepath.Clean(filepath.Join(cleanRoot, filepath.FromSlash(rel)))
|
||||
if !pathWithinRoot(cleanRoot, joined) {
|
||||
return "", fmt.Errorf("path traversal blocked: %q", rel)
|
||||
}
|
||||
// Guard against symlinks / NTFS junctions escaping rootDir, including when
|
||||
// the leaf path does not exist yet (check nearest existing ancestor).
|
||||
evalRoot := cleanRoot
|
||||
if r, err := filepath.EvalSymlinks(cleanRoot); err == nil {
|
||||
evalRoot = filepath.Clean(r)
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("evaluate root path: %w", err)
|
||||
}
|
||||
|
||||
evalJoined, err := filepath.EvalSymlinks(joined)
|
||||
if err == nil {
|
||||
evalJoined = filepath.Clean(evalJoined)
|
||||
if !pathWithinRoot(evalRoot, evalJoined) {
|
||||
return "", fmt.Errorf("symlink traversal blocked: %q", rel)
|
||||
}
|
||||
return evalJoined, nil
|
||||
}
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("evaluate path %q: %w", rel, err)
|
||||
}
|
||||
|
||||
// Walk upward to the nearest existing ancestor directory and verify it resolves within evalRoot.
|
||||
cur := joined
|
||||
var tail []string
|
||||
for cur != cleanRoot {
|
||||
parent := filepath.Dir(cur)
|
||||
if parent == cur {
|
||||
break
|
||||
}
|
||||
tail = append(tail, filepath.Base(cur))
|
||||
cur = parent
|
||||
if evalAnc, aErr := filepath.EvalSymlinks(cur); aErr == nil {
|
||||
evalAnc = filepath.Clean(evalAnc)
|
||||
if !pathWithinRoot(evalRoot, evalAnc) {
|
||||
return "", fmt.Errorf("symlink ancestor traversal blocked: %q", rel)
|
||||
}
|
||||
for i := len(tail) - 1; i >= 0; i-- {
|
||||
evalAnc = filepath.Join(evalAnc, tail[i])
|
||||
}
|
||||
return evalAnc, nil
|
||||
} else if !errors.Is(aErr, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("evaluate ancestor path %q: %w", rel, aErr)
|
||||
}
|
||||
}
|
||||
return joined, nil
|
||||
}
|
||||
|
||||
func fileSHA256Hex(p string) (string, error) {
|
||||
f, err := os.Open(p)
|
||||
if err != nil {
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
@@ -311,7 +314,40 @@ func packRenameTestPlugin(t *testing.T, id, version, entry, contents string) str
|
||||
t.Fatal(err)
|
||||
}
|
||||
archive := filepath.Join(t.TempDir(), "plugin.zip")
|
||||
if _, err := PackDirectory(source, PackOptions{HostVersion: "0.3.0", OutputPath: archive}); err != nil {
|
||||
f, err := os.Create(archive)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zw := zip.NewWriter(f)
|
||||
entryRel := filepath.ToSlash(entry)
|
||||
files := map[string][]byte{
|
||||
"plugin.json": []byte(manifest),
|
||||
entryRel: []byte(contents),
|
||||
}
|
||||
var sums strings.Builder
|
||||
for _, name := range []string{entryRel, "plugin.json"} {
|
||||
data := files[name]
|
||||
w, err := zw.Create(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := w.Write(data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := sha256.Sum256(data)
|
||||
fmt.Fprintf(&sums, "%s %s\n", hex.EncodeToString(h[:]), name)
|
||||
}
|
||||
sw, err := zw.Create("SHA256SUMS")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := sw.Write([]byte(sums.String())); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return archive
|
||||
|
||||
@@ -54,16 +54,16 @@ func ManifestRisks(m Manifest, tier Tier) []string {
|
||||
return orderedRisks(set)
|
||||
}
|
||||
|
||||
// MarketEntryRisks estimates risk categories for a market listing from its
|
||||
// EstimateMarketRisks estimates risk categories for a market listing from its
|
||||
// declared kind, tier and permissions, before anything is downloaded. The
|
||||
// installed manifest is authoritative once the package is on disk.
|
||||
func MarketEntryRisks(e MarketEntry) []string {
|
||||
func EstimateMarketRisks(tier Tier, kind string, permissions []string) []string {
|
||||
set := map[string]bool{}
|
||||
addTierRisks(set, e.Tier)
|
||||
for _, p := range e.Permissions {
|
||||
addTierRisks(set, tier)
|
||||
for _, p := range permissions {
|
||||
addPermissionRisks(set, p)
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(e.Kind)) {
|
||||
switch strings.ToLower(strings.TrimSpace(kind)) {
|
||||
case "theme", "locale":
|
||||
set[RiskUI] = true
|
||||
case "driver", "runtime":
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
)
|
||||
|
||||
func TestManifestRisks(t *testing.T) {
|
||||
@@ -48,11 +49,11 @@ func TestManifestRisks(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestMarketEntryRisks(t *testing.T) {
|
||||
got := plugin.MarketEntryRisks(plugin.MarketEntry{Kind: "locale", Tier: plugin.TierL1})
|
||||
got := market.MarketEntryRisks(market.MarketEntry{Kind: "locale", Tier: plugin.TierL1})
|
||||
if !reflect.DeepEqual(got, []string{plugin.RiskUI}) {
|
||||
t.Fatalf("locale entry risks = %v", got)
|
||||
}
|
||||
got = plugin.MarketEntryRisks(plugin.MarketEntry{Kind: "tool", Tier: plugin.TierL2, Permissions: []string{"net:x.example"}})
|
||||
got = market.MarketEntryRisks(market.MarketEntry{Kind: "tool", Tier: plugin.TierL2, Permissions: []string{"net:x.example"}})
|
||||
if !reflect.DeepEqual(got, []string{plugin.RiskBackground, plugin.RiskNetwork}) {
|
||||
t.Fatalf("script entry risks = %v", got)
|
||||
}
|
||||
@@ -60,8 +61,8 @@ func TestMarketEntryRisks(t *testing.T) {
|
||||
|
||||
func TestMarketKindFacetsAndPeek(t *testing.T) {
|
||||
var hits atomic.Int32
|
||||
entry := func(id, kind string) plugin.MarketEntry {
|
||||
return plugin.MarketEntry{
|
||||
entry := func(id, kind string) market.MarketEntry {
|
||||
return market.MarketEntry{
|
||||
ID: id, Version: "1.0.0", Kind: kind, Channel: "stable",
|
||||
Name: plugin.LocalizedText{EnUS: id},
|
||||
DownloadURL: "https://example.invalid/x.zip", SHA256: strings.Repeat("a", 64),
|
||||
@@ -69,9 +70,9 @@ func TestMarketKindFacetsAndPeek(t *testing.T) {
|
||||
}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
_ = json.NewEncoder(w).Encode(plugin.MarketIndex{
|
||||
_ = json.NewEncoder(w).Encode(market.MarketIndex{
|
||||
Schema: 1,
|
||||
Plugins: []plugin.MarketEntry{
|
||||
Plugins: []market.MarketEntry{
|
||||
entry("a.theme.one", "theme"), entry("a.theme.two", "theme"),
|
||||
entry("a.lang.one", "locale"), entry("a.tool.one", ""),
|
||||
},
|
||||
@@ -80,23 +81,23 @@ func TestMarketKindFacetsAndPeek(t *testing.T) {
|
||||
defer srv.Close()
|
||||
|
||||
layout := plugin.NewPluginsLayout(t.TempDir())
|
||||
opts := plugin.MarketClientOptions{
|
||||
opts := market.MarketClientOptions{
|
||||
Layout: layout, URLs: []string{srv.URL + "/index.json"},
|
||||
CacheTTL: time.Minute, AllowInsecureLocalhost: true,
|
||||
}
|
||||
mc := plugin.NewMarketClient(opts)
|
||||
mc := market.NewMarketClient(opts)
|
||||
|
||||
// Nothing cached yet: Peek serves the embedded fallback without a request.
|
||||
if res := mc.Peek(nil, plugin.MarketBrowseOptions{}); res.Source != "fallback" || hits.Load() != 0 {
|
||||
if res := mc.Peek(nil, market.MarketBrowseOptions{}); res.Source != "fallback" || hits.Load() != 0 {
|
||||
t.Fatalf("cold Peek = source %q, %d requests", res.Source, hits.Load())
|
||||
}
|
||||
|
||||
// Facets count the whole index even while a kind filter narrows items.
|
||||
res := mc.Browse(context.Background(), nil, plugin.MarketBrowseOptions{Kind: "theme"})
|
||||
res := mc.Browse(context.Background(), nil, market.MarketBrowseOptions{Kind: "theme"})
|
||||
if len(res.Items) != 2 {
|
||||
t.Fatalf("filtered items = %d, want 2", len(res.Items))
|
||||
}
|
||||
wantKinds := []plugin.MarketKindFacet{{Kind: "theme", Count: 2}, {Kind: "locale", Count: 1}}
|
||||
wantKinds := []market.MarketKindFacet{{Kind: "theme", Count: 2}, {Kind: "locale", Count: 1}}
|
||||
if !reflect.DeepEqual(res.Kinds, wantKinds) {
|
||||
t.Fatalf("kinds = %+v, want %+v", res.Kinds, wantKinds)
|
||||
}
|
||||
@@ -104,11 +105,11 @@ func TestMarketKindFacetsAndPeek(t *testing.T) {
|
||||
// A new client reads the disk cache in Peek, and its next Browse still
|
||||
// goes to the network because nothing was fetched in this session.
|
||||
before := hits.Load()
|
||||
mc2 := plugin.NewMarketClient(opts)
|
||||
if res := mc2.Peek(nil, plugin.MarketBrowseOptions{}); res.Source != "cache" || len(res.Items) != 4 || hits.Load() != before {
|
||||
mc2 := market.NewMarketClient(opts)
|
||||
if res := mc2.Peek(nil, market.MarketBrowseOptions{}); res.Source != "cache" || len(res.Items) != 4 || hits.Load() != before {
|
||||
t.Fatalf("warm Peek = source %q, %d items, %d new requests", res.Source, len(res.Items), hits.Load()-before)
|
||||
}
|
||||
if res := mc2.Browse(context.Background(), nil, plugin.MarketBrowseOptions{}); res.Source != "remote" {
|
||||
if res := mc2.Browse(context.Background(), nil, market.MarketBrowseOptions{}); res.Source != "remote" {
|
||||
t.Fatalf("Browse after Peek = source %q, want remote", res.Source)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin/sidecarproc"
|
||||
"github.com/Nwflower/reims-go/pkg/pluginproto"
|
||||
)
|
||||
|
||||
@@ -38,7 +39,7 @@ type SidecarOptions struct {
|
||||
|
||||
type sidecarInstance struct {
|
||||
cmd *exec.Cmd
|
||||
job *sidecarJob
|
||||
job *sidecarproc.SidecarJob
|
||||
rpc *RPCConn
|
||||
stdin io.WriteCloser
|
||||
exited chan struct{}
|
||||
@@ -163,7 +164,7 @@ func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance
|
||||
}
|
||||
cmd := exec.Command(s.opts.ExePath, s.opts.Args...)
|
||||
cmd.Dir = s.opts.DataDir
|
||||
configureSidecarCmd(cmd)
|
||||
sidecarproc.ConfigureSidecarCmd(cmd)
|
||||
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
@@ -181,7 +182,7 @@ func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
job, err := newSidecarJob(s.opts.MemLimitBytes)
|
||||
job, err := sidecarproc.NewSidecarJob(s.opts.MemLimitBytes)
|
||||
if err != nil {
|
||||
_ = stdin.Close()
|
||||
_ = stdout.Close()
|
||||
@@ -203,7 +204,7 @@ func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance
|
||||
return nil, nil, fmt.Errorf("assign sidecar %s to job: %w", s.opts.PluginID, err)
|
||||
}
|
||||
|
||||
rpcConn := NewRPCConn(stdout, stdin)
|
||||
rpcConn := sidecarproc.NewRPCConn(stdout, stdin)
|
||||
s.registerReverseHostAPI(rpcConn)
|
||||
|
||||
inst := &sidecarInstance{
|
||||
@@ -257,7 +258,7 @@ func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance
|
||||
|
||||
// StdoutPipe and StderrPipe must be drained before Wait closes their handles.
|
||||
go func() {
|
||||
<-rpcConn.doneCh
|
||||
<-rpcConn.Done()
|
||||
<-stderrDone
|
||||
err := cmd.Wait()
|
||||
rpcConn.Close()
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//go:build !windows
|
||||
|
||||
package sidecarproc
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"sync"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func ConfigureSidecarCmd(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
}
|
||||
|
||||
func ConfigureDetachedVMProcess(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
}
|
||||
|
||||
func ConfigureNestedVMProcess(cmd *exec.Cmd) { ConfigureDetachedVMProcess(cmd) }
|
||||
|
||||
func ResumeVMProcess(int) error { return nil }
|
||||
|
||||
func IsBreakawayDenied(error) bool { return false }
|
||||
|
||||
type SidecarJob struct {
|
||||
pgid int
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
func NewSidecarJob(_ uintptr) (*SidecarJob, error) {
|
||||
return &SidecarJob{}, nil
|
||||
}
|
||||
|
||||
func (j *SidecarJob) Assign(pid int) error {
|
||||
if j != nil {
|
||||
j.pgid = pid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *SidecarJob) Close() {
|
||||
if j == nil {
|
||||
return
|
||||
}
|
||||
j.closeOnce.Do(func() {
|
||||
if j.pgid > 0 {
|
||||
_ = syscall.Kill(-j.pgid, syscall.SIGKILL)
|
||||
j.pgid = 0
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//go:build windows
|
||||
|
||||
package plugin
|
||||
package sidecarproc
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -19,25 +19,25 @@ const (
|
||||
createNewProcessGroup = 0x00000200
|
||||
)
|
||||
|
||||
func configureSidecarCmd(cmd *exec.Cmd) {
|
||||
func ConfigureSidecarCmd(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||
HideWindow: true,
|
||||
CreationFlags: createNoWindow | createNewProcessGroup,
|
||||
}
|
||||
}
|
||||
|
||||
// configureDetachedVMProcess starts the VM suspended, so it joins its job before
|
||||
// it can start children; resumeVMProcess lets it run.
|
||||
func configureDetachedVMProcess(cmd *exec.Cmd) {
|
||||
// ConfigureDetachedVMProcess starts the VM suspended, so it joins its job before
|
||||
// it can start children; ResumeVMProcess lets it run.
|
||||
func ConfigureDetachedVMProcess(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||
HideWindow: true,
|
||||
CreationFlags: createNoWindow | createNewProcessGroup | createBreakawayFromJob | windows.CREATE_SUSPENDED,
|
||||
}
|
||||
}
|
||||
|
||||
// configureNestedVMProcess is the fallback when the host's own job forbids
|
||||
// ConfigureNestedVMProcess is the fallback when the host's own job forbids
|
||||
// breakaway: the VM starts inside that job and moves into its per-VM job.
|
||||
func configureNestedVMProcess(cmd *exec.Cmd) {
|
||||
func ConfigureNestedVMProcess(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||
HideWindow: true,
|
||||
CreationFlags: createNoWindow | createNewProcessGroup | windows.CREATE_SUSPENDED,
|
||||
@@ -46,7 +46,7 @@ func configureNestedVMProcess(cmd *exec.Cmd) {
|
||||
|
||||
var procNtResumeProcess = windows.NewLazySystemDLL("ntdll.dll").NewProc("NtResumeProcess")
|
||||
|
||||
func resumeVMProcess(pid int) error {
|
||||
func ResumeVMProcess(pid int) error {
|
||||
proc, err := windows.OpenProcess(windows.PROCESS_SUSPEND_RESUME, false, uint32(pid))
|
||||
if err != nil {
|
||||
return fmt.Errorf("OpenProcess(%d): %w", pid, err)
|
||||
@@ -58,20 +58,20 @@ func resumeVMProcess(pid int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// isBreakawayDenied reports a failed CREATE_BREAKAWAY_FROM_JOB start.
|
||||
func isBreakawayDenied(err error) bool {
|
||||
// IsBreakawayDenied reports a failed CREATE_BREAKAWAY_FROM_JOB start.
|
||||
func IsBreakawayDenied(err error) bool {
|
||||
return errors.Is(err, windows.ERROR_ACCESS_DENIED)
|
||||
}
|
||||
|
||||
type sidecarJob struct {
|
||||
type SidecarJob struct {
|
||||
handle windows.Handle
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
// newSidecarJob creates a Windows Job Object with KILL_ON_JOB_CLOSE so that
|
||||
// NewSidecarJob creates a Windows Job Object with KILL_ON_JOB_CLOSE so that
|
||||
// closing the job (or host exit/crash) reclaims the entire Sidecar process tree
|
||||
// with zero orphan processes (§8). Optional memLimitBytes caps process memory (L2).
|
||||
func newSidecarJob(memLimitBytes uintptr) (*sidecarJob, error) {
|
||||
func NewSidecarJob(memLimitBytes uintptr) (*SidecarJob, error) {
|
||||
h, err := windows.CreateJobObject(nil, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("CreateJobObject: %w", err)
|
||||
@@ -91,10 +91,10 @@ func newSidecarJob(memLimitBytes uintptr) (*sidecarJob, error) {
|
||||
_ = windows.CloseHandle(h)
|
||||
return nil, fmt.Errorf("SetInformationJobObject: %w", err)
|
||||
}
|
||||
return &sidecarJob{handle: h}, nil
|
||||
return &SidecarJob{handle: h}, nil
|
||||
}
|
||||
|
||||
func (j *sidecarJob) Assign(pid int) error {
|
||||
func (j *SidecarJob) Assign(pid int) error {
|
||||
if j == nil || j.handle == 0 || pid <= 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -106,7 +106,7 @@ func (j *sidecarJob) Assign(pid int) error {
|
||||
return windows.AssignProcessToJobObject(j.handle, proc)
|
||||
}
|
||||
|
||||
func (j *sidecarJob) Close() {
|
||||
func (j *SidecarJob) Close() {
|
||||
if j == nil {
|
||||
return
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package plugin
|
||||
package sidecarproc
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
const maxRPCFrameBytes = 8 << 20 // 8 MiB per JSON-RPC frame (large blobs go via file paths, §8)
|
||||
const MaxRPCFrameBytes = 8 << 20 // 8 MiB per JSON-RPC frame (large blobs go via file paths, §8)
|
||||
|
||||
// RPCMethodNotFound is the code a peer answers for a method it does not serve.
|
||||
const RPCMethodNotFound = -32601
|
||||
@@ -80,6 +80,11 @@ func NewRPCConn(r io.Reader, w io.Writer) *RPCConn {
|
||||
return c
|
||||
}
|
||||
|
||||
// Done returns a channel that is closed when the connection's read loop exits.
|
||||
func (c *RPCConn) Done() <-chan struct{} {
|
||||
return c.doneCh
|
||||
}
|
||||
|
||||
// Handle registers a handler for inbound peer requests of method.
|
||||
func (c *RPCConn) Handle(method string, h RPCRequestHandler) {
|
||||
c.mu.Lock()
|
||||
@@ -337,7 +342,7 @@ func readContentLengthFrame(r *bufio.Reader) ([]byte, error) {
|
||||
k, v, ok := strings.Cut(line, ":")
|
||||
if ok && strings.EqualFold(strings.TrimSpace(k), "Content-Length") {
|
||||
n, err := strconv.Atoi(strings.TrimSpace(v))
|
||||
if err != nil || n < 0 || n > maxRPCFrameBytes {
|
||||
if err != nil || n < 0 || n > MaxRPCFrameBytes {
|
||||
return nil, fmt.Errorf("invalid Content-Length %q", v)
|
||||
}
|
||||
contentLen = n
|
||||
@@ -1,37 +1,37 @@
|
||||
//go:build !windows
|
||||
|
||||
package plugin
|
||||
package sidecarproc
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// vmJob approximates the Windows per-VM job with a process group: it tracks
|
||||
// VMJob approximates the Windows per-VM job with a process group: it tracks
|
||||
// the root process and the group it leads. Reims-Go runs VMs on Windows; this
|
||||
// keeps the package compiling and testable elsewhere.
|
||||
type vmJob struct {
|
||||
type VMJob struct {
|
||||
mu sync.Mutex
|
||||
pgid int
|
||||
done chan struct{}
|
||||
doneOnce sync.Once
|
||||
}
|
||||
|
||||
func newVMJob() (*vmJob, error) { return &vmJob{done: make(chan struct{})}, nil }
|
||||
func NewVMJob() (*VMJob, error) { return &VMJob{done: make(chan struct{})}, nil }
|
||||
|
||||
func (j *vmJob) markDone() { j.doneOnce.Do(func() { close(j.done) }) }
|
||||
func (j *VMJob) markDone() { j.doneOnce.Do(func() { close(j.done) }) }
|
||||
|
||||
// Done is closed once the root process has exited.
|
||||
func (j *vmJob) Done() <-chan struct{} { return j.done }
|
||||
func (j *VMJob) Done() <-chan struct{} { return j.done }
|
||||
|
||||
// RootExited closes Done: without a job object the root is the whole tree.
|
||||
func (j *vmJob) RootExited() {
|
||||
func (j *VMJob) RootExited() {
|
||||
if j != nil {
|
||||
j.markDone()
|
||||
}
|
||||
}
|
||||
|
||||
func (j *vmJob) Assign(pid int) error {
|
||||
func (j *VMJob) Assign(pid int) error {
|
||||
if j == nil || pid <= 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -41,7 +41,7 @@ func (j *vmJob) Assign(pid int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *vmJob) PIDs() []uint32 {
|
||||
func (j *VMJob) PIDs() []uint32 {
|
||||
if j == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -59,9 +59,9 @@ func (j *vmJob) PIDs() []uint32 {
|
||||
}
|
||||
|
||||
// SetAffinity is a no-op off Windows.
|
||||
func (j *vmJob) SetAffinity(uint64) error { return nil }
|
||||
func (j *VMJob) SetAffinity(uint64) error { return nil }
|
||||
|
||||
func (j *vmJob) Terminate() error {
|
||||
func (j *VMJob) Terminate() error {
|
||||
if j == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -74,7 +74,7 @@ func (j *vmJob) Terminate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *vmJob) Close() {
|
||||
func (j *VMJob) Close() {
|
||||
if j != nil {
|
||||
j.markDone()
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//go:build windows
|
||||
|
||||
package plugin
|
||||
package sidecarproc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -15,18 +15,17 @@ const (
|
||||
vmJobCompletionKey = 0x5247564d // "RGVM"
|
||||
)
|
||||
|
||||
// vmJobAssociateCompletionPort mirrors JOBOBJECT_ASSOCIATE_COMPLETION_PORT.
|
||||
type vmJobAssociateCompletionPort struct {
|
||||
CompletionKey uintptr
|
||||
CompletionPort windows.Handle
|
||||
}
|
||||
|
||||
// vmJob holds the process tree of one driver-spawned VM. Unlike sidecarJob it
|
||||
// VMJob holds the process tree of one driver-spawned VM. Unlike SidecarJob it
|
||||
// does not kill its processes when the handle closes: a VM must survive a
|
||||
// restart of the desktop client (for example an in-app update). Only an
|
||||
// explicit Terminate stops it. A completion port reports when the last
|
||||
// process of the tree has exited.
|
||||
type vmJob struct {
|
||||
type VMJob struct {
|
||||
mu sync.Mutex
|
||||
job windows.Handle
|
||||
port windows.Handle
|
||||
@@ -34,7 +33,7 @@ type vmJob struct {
|
||||
doneOnce sync.Once
|
||||
}
|
||||
|
||||
func newVMJob() (*vmJob, error) {
|
||||
func NewVMJob() (*VMJob, error) {
|
||||
job, err := windows.CreateJobObject(nil, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("CreateJobObject: %w", err)
|
||||
@@ -51,18 +50,17 @@ func newVMJob() (*vmJob, error) {
|
||||
_ = windows.CloseHandle(job)
|
||||
return nil, fmt.Errorf("associate job completion port: %w", err)
|
||||
}
|
||||
j := &vmJob{job: job, port: port, done: make(chan struct{})}
|
||||
j := &VMJob{job: job, port: port, done: make(chan struct{})}
|
||||
go j.watch(port)
|
||||
return j, nil
|
||||
}
|
||||
|
||||
func (j *vmJob) watch(port windows.Handle) {
|
||||
func (j *VMJob) watch(port windows.Handle) {
|
||||
for {
|
||||
var qty uint32
|
||||
var key uintptr
|
||||
var ov *windows.Overlapped
|
||||
if err := windows.GetQueuedCompletionStatus(port, &qty, &key, &ov, windows.INFINITE); err != nil {
|
||||
// The port was closed.
|
||||
j.markDone()
|
||||
return
|
||||
}
|
||||
@@ -73,17 +71,17 @@ func (j *vmJob) watch(port windows.Handle) {
|
||||
}
|
||||
}
|
||||
|
||||
func (j *vmJob) markDone() { j.doneOnce.Do(func() { close(j.done) }) }
|
||||
func (j *VMJob) markDone() { j.doneOnce.Do(func() { close(j.done) }) }
|
||||
|
||||
// Done is closed once the job holds no process.
|
||||
func (j *vmJob) Done() <-chan struct{} { return j.done }
|
||||
func (j *VMJob) Done() <-chan struct{} { return j.done }
|
||||
|
||||
// RootExited tells the job the root process was reaped. On Windows the job
|
||||
// itself reports when the whole tree is gone, so there is nothing to do.
|
||||
func (j *vmJob) RootExited() {}
|
||||
func (j *VMJob) RootExited() {}
|
||||
|
||||
// Assign puts the process, and every child it starts afterwards, in the job.
|
||||
func (j *vmJob) Assign(pid int) error {
|
||||
func (j *VMJob) Assign(pid int) error {
|
||||
if j == nil || pid <= 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -101,7 +99,7 @@ func (j *vmJob) Assign(pid int) error {
|
||||
}
|
||||
|
||||
// PIDs lists the processes currently in the job.
|
||||
func (j *vmJob) PIDs() []uint32 {
|
||||
func (j *VMJob) PIDs() []uint32 {
|
||||
if j == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -138,7 +136,7 @@ func (j *vmJob) PIDs() []uint32 {
|
||||
|
||||
// SetAffinity limits every process of the job, present and future, to mask.
|
||||
// A zero mask removes the limit.
|
||||
func (j *vmJob) SetAffinity(mask uint64) error {
|
||||
func (j *VMJob) SetAffinity(mask uint64) error {
|
||||
if j == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -160,7 +158,7 @@ func (j *vmJob) SetAffinity(mask uint64) error {
|
||||
}
|
||||
|
||||
// Terminate kills every process of the job.
|
||||
func (j *vmJob) Terminate() error {
|
||||
func (j *VMJob) Terminate() error {
|
||||
if j == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -173,7 +171,7 @@ func (j *vmJob) Terminate() error {
|
||||
}
|
||||
|
||||
// Close releases the handles without touching the processes.
|
||||
func (j *vmJob) Close() {
|
||||
func (j *VMJob) Close() {
|
||||
if j == nil {
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package plugin
|
||||
|
||||
import "github.com/Nwflower/reims-go/internal/plugin/sidecarproc"
|
||||
|
||||
// Re-export JSON-RPC 2.0 transport types and error codes from sidecarproc so
|
||||
// callers outside internal/plugin keep their existing import paths.
|
||||
const (
|
||||
maxRPCFrameBytes = sidecarproc.MaxRPCFrameBytes
|
||||
RPCMethodNotFound = sidecarproc.RPCMethodNotFound
|
||||
RPCInvalidParams = sidecarproc.RPCInvalidParams
|
||||
)
|
||||
|
||||
type (
|
||||
RPCError = sidecarproc.RPCError
|
||||
RPCRequestHandler = sidecarproc.RPCRequestHandler
|
||||
RPCConn = sidecarproc.RPCConn
|
||||
)
|
||||
+20
-472
@@ -1,402 +1,35 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin/uiassets"
|
||||
)
|
||||
|
||||
// Re-export AssetServer and CSS/SVG safety primitives from internal/plugin/uiassets.
|
||||
type AssetServer = uiassets.AssetServer
|
||||
|
||||
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+.-]*:`)
|
||||
NewAssetServer = uiassets.NewAssetServer
|
||||
SanitizeSVG = uiassets.SanitizeSVG
|
||||
ValidateThemeCSSSafety = uiassets.ValidateThemeCSSSafety
|
||||
ValidateCSSTokenValue = uiassets.ValidateCSSTokenValue
|
||||
validateSafeManifestAsset = uiassets.ValidateSafeManifestAsset
|
||||
safeJoin = uiassets.SafeJoin
|
||||
|
||||
reTokenKey = uiassets.ReTokenKey
|
||||
reSafeFontFamily = uiassets.ReSafeFontFamily
|
||||
reFontWeight = uiassets.ReFontWeight
|
||||
reFontStyle = uiassets.ReFontStyle
|
||||
reUnicodeRange = uiassets.ReUnicodeRange
|
||||
reSafeAssetRel = uiassets.ReSafeAssetRel
|
||||
reSchemePrefix = uiassets.ReSchemePrefix
|
||||
isCSSIdentChar = uiassets.IsCSSIdentChar
|
||||
)
|
||||
|
||||
// ValidateThemeCSSSafety rejects unbalanced braces, unclosed strings/comments,
|
||||
// CSS-escaped url()/image-set()/expression() bypasses, remote @import, and
|
||||
// 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")
|
||||
}
|
||||
n := len(css)
|
||||
i := 0
|
||||
braceDepth := 0
|
||||
|
||||
skipWSAndComments := func() error {
|
||||
for i < n {
|
||||
if css[i] == ' ' || css[i] == '\t' || css[i] == '\r' || css[i] == '\n' || css[i] == '\f' {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if i+1 < n && css[i] == '/' && css[i+1] == '*' {
|
||||
end := strings.Index(css[i+2:], "*/")
|
||||
if end < 0 {
|
||||
return errors.New("unclosed CSS comment in theme stylesheet")
|
||||
}
|
||||
i += 2 + end + 2
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
readString := func(quote byte) (string, error) {
|
||||
i++ // consume opening quote
|
||||
var b strings.Builder
|
||||
for i < n {
|
||||
c := css[i]
|
||||
if c == '\n' || c == '\r' || c == '\f' {
|
||||
return "", errors.New("unclosed CSS string literal")
|
||||
}
|
||||
if c == quote {
|
||||
i++
|
||||
return b.String(), nil
|
||||
}
|
||||
if c == '\\' {
|
||||
i++
|
||||
if i >= n {
|
||||
return "", errors.New("dangling escape in CSS string")
|
||||
}
|
||||
if css[i] == '\n' || css[i] == '\r' || css[i] == '\f' {
|
||||
if css[i] == '\r' && i+1 < n && css[i+1] == '\n' {
|
||||
i += 2
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
continue
|
||||
}
|
||||
r, next := decodeCSSEscape(css, i)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
b.WriteByte(c)
|
||||
i++
|
||||
}
|
||||
return "", errors.New("unclosed CSS string literal")
|
||||
}
|
||||
|
||||
readIdent := func() string {
|
||||
var b strings.Builder
|
||||
for i < n {
|
||||
c := css[i]
|
||||
if c == '\\' && i+1 < n && css[i+1] != '\n' && css[i+1] != '\r' {
|
||||
r, next := decodeCSSEscape(css, i+1)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
if isCSSIdentChar(c) {
|
||||
b.WriteByte(c)
|
||||
i++
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
readURLArg := func() (string, error) {
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if i >= n {
|
||||
return "", errors.New("unclosed url() in theme stylesheet")
|
||||
}
|
||||
if css[i] == '"' || css[i] == '\'' {
|
||||
val, err := readString(css[i])
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if i >= n || css[i] != ')' {
|
||||
return "", errors.New("malformed url() in theme stylesheet")
|
||||
}
|
||||
i++ // consume ')'
|
||||
return val, nil
|
||||
}
|
||||
var b strings.Builder
|
||||
for i < n {
|
||||
c := css[i]
|
||||
if c == ')' {
|
||||
i++
|
||||
return strings.TrimSpace(b.String()), nil
|
||||
}
|
||||
if c == '(' || c == '"' || c == '\'' || c == '\n' || c == '\r' {
|
||||
return "", errors.New("malformed unquoted url() in theme stylesheet")
|
||||
}
|
||||
if c == '\\' {
|
||||
if i+1 >= n {
|
||||
return "", errors.New("dangling escape in url()")
|
||||
}
|
||||
r, next := decodeCSSEscape(css, i+1)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
b.WriteByte(c)
|
||||
i++
|
||||
}
|
||||
return "", errors.New("unclosed url() in theme stylesheet")
|
||||
}
|
||||
|
||||
for i < n {
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return err
|
||||
}
|
||||
if i >= n {
|
||||
break
|
||||
}
|
||||
c := css[i]
|
||||
switch {
|
||||
case c == '{':
|
||||
braceDepth++
|
||||
i++
|
||||
case c == '}':
|
||||
braceDepth--
|
||||
if braceDepth < 0 {
|
||||
return errors.New("unbalanced '}' in theme stylesheet (layer breakout blocked)")
|
||||
}
|
||||
i++
|
||||
case c == '"' || c == '\'':
|
||||
if _, err := readString(c); err != nil {
|
||||
return err
|
||||
}
|
||||
case c == '@':
|
||||
i++
|
||||
atName := strings.ToLower(readIdent())
|
||||
if atName == "import" {
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return err
|
||||
}
|
||||
var target string
|
||||
var err error
|
||||
if i < n && (css[i] == '"' || css[i] == '\'') {
|
||||
target, err = readString(css[i])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
fn := strings.ToLower(readIdent())
|
||||
if fn != "url" || i >= n || css[i] != '(' {
|
||||
return errors.New("@import syntax not allowed in theme stylesheet")
|
||||
}
|
||||
i++ // '('
|
||||
target, err = readURLArg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := validateCSSResourceURL(target, rootDir, true); err != nil {
|
||||
return fmt.Errorf("@import %q forbidden: %w", target, err)
|
||||
}
|
||||
}
|
||||
case isCSSIdentStart(c) || c == '\\':
|
||||
ident := strings.ToLower(readIdent())
|
||||
if i < n && css[i] == '(' {
|
||||
switch ident {
|
||||
case "expression":
|
||||
return errors.New("CSS expression() is forbidden in theme stylesheets")
|
||||
case "url", "src":
|
||||
i++ // consume '('
|
||||
u, err := readURLArg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateCSSResourceURL(u, rootDir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
case "image-set", "-webkit-image-set":
|
||||
i++ // consume '('
|
||||
if err := validateImageSetArgs(css, &i, rootDir, skipWSAndComments, readString, readIdent, readURLArg); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
i++ // consume '('
|
||||
}
|
||||
}
|
||||
default:
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
if braceDepth != 0 {
|
||||
return errors.New("unbalanced '{' in theme stylesheet")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateImageSetArgs(
|
||||
css string,
|
||||
idx *int,
|
||||
rootDir string,
|
||||
skipWS func() error,
|
||||
readString func(byte) (string, error),
|
||||
readIdent func() string,
|
||||
readURLArg func() (string, error),
|
||||
) error {
|
||||
depth := 1
|
||||
n := len(css)
|
||||
for *idx < n && depth > 0 {
|
||||
if err := skipWS(); err != nil {
|
||||
return err
|
||||
}
|
||||
if *idx >= n {
|
||||
break
|
||||
}
|
||||
c := css[*idx]
|
||||
switch {
|
||||
case c == ')':
|
||||
depth--
|
||||
*idx++
|
||||
case c == '(':
|
||||
depth++
|
||||
*idx++
|
||||
case c == '"' || c == '\'':
|
||||
s, err := readString(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Bare strings inside image-set() are URLs unless inside type("...").
|
||||
if depth == 1 {
|
||||
if err := validateCSSResourceURL(s, rootDir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case isCSSIdentStart(c) || c == '\\':
|
||||
fn := strings.ToLower(readIdent())
|
||||
if *idx < n && css[*idx] == '(' {
|
||||
switch fn {
|
||||
case "url", "src":
|
||||
*idx++
|
||||
u, err := readURLArg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateCSSResourceURL(u, rootDir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
case "image-set", "-webkit-image-set":
|
||||
*idx++
|
||||
if err := validateImageSetArgs(css, idx, rootDir, skipWS, readString, readIdent, readURLArg); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
depth++
|
||||
*idx++
|
||||
}
|
||||
}
|
||||
default:
|
||||
*idx++
|
||||
}
|
||||
}
|
||||
if depth != 0 {
|
||||
return errors.New("unclosed image-set() in theme stylesheet")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateCSSResourceURL(rawURL, rootDir string, isImport bool) error {
|
||||
u := strings.TrimSpace(rawURL)
|
||||
if u == "" {
|
||||
if isImport {
|
||||
return errors.New("empty @import URL")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if strings.ContainsAny(u, "\r\n\x00") {
|
||||
return errors.New("control characters in CSS URL")
|
||||
}
|
||||
lower := strings.ToLower(u)
|
||||
if strings.HasPrefix(lower, "//") {
|
||||
return fmt.Errorf("external protocol-relative URL %q is forbidden", u)
|
||||
}
|
||||
if strings.HasPrefix(lower, "data:") {
|
||||
if isImport {
|
||||
return errors.New("data: URL forbidden in @import")
|
||||
}
|
||||
allowedData := []string{
|
||||
"data:image/png;", "data:image/png,",
|
||||
"data:image/jpeg;", "data:image/jpeg,",
|
||||
"data:image/webp;", "data:image/webp,",
|
||||
"data:image/gif;", "data:image/gif,",
|
||||
"data:font/woff2;", "data:font/woff;",
|
||||
}
|
||||
for _, pfx := range allowedData {
|
||||
if strings.HasPrefix(lower, pfx) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("unsafe data: URL %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
if reSchemePrefix.MatchString(u) {
|
||||
return fmt.Errorf("external/scheme URL %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
// Strip query/fragment for path validation.
|
||||
pathOnly := u
|
||||
if q := strings.IndexAny(pathOnly, "?#"); q >= 0 {
|
||||
pathOnly = pathOnly[:q]
|
||||
}
|
||||
if pathOnly == "" {
|
||||
// Fragment-only URL like url(#clip) — allowed for SVG/local refs, not @import.
|
||||
if isImport {
|
||||
return errors.New("fragment URL forbidden in @import")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if strings.HasPrefix(pathOnly, "/") || strings.Contains(pathOnly, "\\") {
|
||||
return fmt.Errorf("absolute or backslash path %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
for _, seg := range strings.Split(pathOnly, "/") {
|
||||
if seg == ".." {
|
||||
return fmt.Errorf("path traversal %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
}
|
||||
if rootDir != "" {
|
||||
full, err := safeJoin(rootDir, pathOnly)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
st, err := os.Stat(full)
|
||||
if err != nil || st.IsDir() {
|
||||
return fmt.Errorf("theme CSS asset %q not found in package", pathOnly)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateCSSTokenValue checks a single CSS custom property or seed value to
|
||||
// ensure it cannot break out of a declaration, close @layer, or load external URLs.
|
||||
func ValidateCSSTokenValue(val string) error {
|
||||
if strings.ContainsAny(val, "\r\n\x00{};") || strings.HasSuffix(strings.TrimSpace(val), `\`) {
|
||||
return fmt.Errorf("CSS token value %q contains forbidden characters", val)
|
||||
}
|
||||
if strings.Contains(val, "/*") || strings.Contains(val, "*/") {
|
||||
return fmt.Errorf("CSS token value %q must not contain CSS comments", val)
|
||||
}
|
||||
decoded := strings.ToLower(decodeAllCSSEscapes(val))
|
||||
for _, bad := range []string{"</style", "url(", "src(", "image-set(", "-webkit-image-set(", "expression(", "@import", "javascript:", "data:", "http://", "https://", "//"} {
|
||||
if strings.Contains(decoded, bad) {
|
||||
return fmt.Errorf("CSS token value %q contains forbidden construct %q", val, bad)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateThemeContribution validates all theme manifest fields (tokens, seeds,
|
||||
// fonts, background, and stylesheet) so untrusted strings cannot inject CSS.
|
||||
func ValidateThemeContribution(th ThemeContribution, rootDir string) error {
|
||||
@@ -503,88 +136,3 @@ func ValidateThemeContribution(th ThemeContribution, rootDir string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateSafeManifestAsset(rel, rootDir string) error {
|
||||
if rel == "" {
|
||||
return errors.New("empty asset path")
|
||||
}
|
||||
if strings.ContainsAny(rel, "\"'\\;{}()\r\n\x00") || !reSafeAssetRel.MatchString(rel) {
|
||||
return errors.New("asset path contains forbidden characters")
|
||||
}
|
||||
if strings.HasPrefix(rel, "/") || reSchemePrefix.MatchString(rel) {
|
||||
return errors.New("asset path must be package-relative")
|
||||
}
|
||||
for _, seg := range strings.Split(rel, "/") {
|
||||
if seg == ".." {
|
||||
return errors.New("path traversal in asset path")
|
||||
}
|
||||
}
|
||||
if rootDir != "" {
|
||||
full, err := safeJoin(rootDir, rel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
st, err := os.Stat(full)
|
||||
if err != nil || st.IsDir() {
|
||||
return errors.New("asset file not found in package")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func decodeCSSEscape(s string, pos int) (rune, int) {
|
||||
n := len(s)
|
||||
if pos >= n {
|
||||
return 0xFFFD, pos
|
||||
}
|
||||
if isHexByte(s[pos]) {
|
||||
start := pos
|
||||
for pos < n && pos-start < 6 && isHexByte(s[pos]) {
|
||||
pos++
|
||||
}
|
||||
code, err := strconv.ParseInt(s[start:pos], 16, 32)
|
||||
// CSS spec: one optional whitespace char after hex escape is consumed.
|
||||
if pos < n {
|
||||
if s[pos] == '\r' && pos+1 < n && s[pos+1] == '\n' {
|
||||
pos += 2
|
||||
} else if s[pos] == ' ' || s[pos] == '\t' || s[pos] == '\n' || s[pos] == '\r' || s[pos] == '\f' {
|
||||
pos++
|
||||
}
|
||||
}
|
||||
if err != nil || code <= 0 || code > unicode.MaxRune {
|
||||
return 0xFFFD, pos
|
||||
}
|
||||
return rune(code), pos
|
||||
}
|
||||
return rune(s[pos]), pos + 1
|
||||
}
|
||||
|
||||
func decodeAllCSSEscapes(s string) string {
|
||||
if !strings.ContainsRune(s, '\\') {
|
||||
return s
|
||||
}
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(s); {
|
||||
if s[i] == '\\' && i+1 < len(s) {
|
||||
r, next := decodeCSSEscape(s, i+1)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
b.WriteByte(s[i])
|
||||
i++
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func isHexByte(c byte) bool {
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
|
||||
}
|
||||
|
||||
func isCSSIdentStart(c byte) bool {
|
||||
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '-' || c >= 0x80
|
||||
}
|
||||
|
||||
func isCSSIdentChar(c byte) bool {
|
||||
return isCSSIdentStart(c) || (c >= '0' && c <= '9')
|
||||
}
|
||||
@@ -11,11 +11,12 @@ import (
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/fetch"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/market"
|
||||
)
|
||||
|
||||
// marketFixture serves one plugin package and an index that lists it with the
|
||||
// given trust level and permissions.
|
||||
func marketFixture(t *testing.T, id string, trust plugin.TrustLevel, perms []string) (*httptest.Server, func() plugin.MarketIndex) {
|
||||
func marketFixture(t *testing.T, id string, trust plugin.TrustLevel, perms []string) (*httptest.Server, func() market.MarketIndex) {
|
||||
t.Helper()
|
||||
manifest, _ := json.Marshal(plugin.Manifest{
|
||||
Schema: 1,
|
||||
@@ -38,8 +39,8 @@ func marketFixture(t *testing.T, id string, trust plugin.TrustLevel, perms []str
|
||||
sum, _ := fetch.FileSHA256(zipPath)
|
||||
|
||||
var srv *httptest.Server
|
||||
index := func() plugin.MarketIndex {
|
||||
return plugin.MarketIndex{Schema: 1, Plugins: []plugin.MarketEntry{{
|
||||
index := func() market.MarketIndex {
|
||||
return market.MarketIndex{Schema: 1, Plugins: []market.MarketEntry{{
|
||||
ID: id, Version: "1.0.0", Channel: "stable", Trust: trust, Kind: "theme",
|
||||
Name: plugin.LocalizedText{EnUS: id}, Permissions: perms,
|
||||
DownloadURL: srv.URL + "/pkg.zip", SHA256: sum, SizeBytes: int64(len(zipBytes)),
|
||||
@@ -78,16 +79,16 @@ func TestFirstPartyIndexVouchesForInstalls(t *testing.T) {
|
||||
|
||||
install := func(firstParty bool) plugin.TrustLevel {
|
||||
mgr := newTrustTestManager(t)
|
||||
mc := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
mc := market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: mgr.Layout(), HostVersion: "0.2.10",
|
||||
URLs: []string{srv.URL + "/index.json"}, CacheTTL: time.Minute,
|
||||
AllowInsecureLocalhost: true, FirstParty: firstParty,
|
||||
})
|
||||
browse := mc.Browse(context.Background(), nil, plugin.MarketBrowseOptions{})
|
||||
browse := mc.Browse(context.Background(), nil, market.MarketBrowseOptions{})
|
||||
if len(browse.Items) != 1 {
|
||||
t.Fatalf("browse items = %d", len(browse.Items))
|
||||
}
|
||||
info, err := mc.InstallFromMarket(context.Background(), mgr, id, plugin.MarketInstallOptions{})
|
||||
info, err := mc.InstallFromMarket(context.Background(), mgr, id, market.MarketInstallOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("install: %v", err)
|
||||
}
|
||||
@@ -110,7 +111,7 @@ func TestStaleIndexDoesNotVouch(t *testing.T) {
|
||||
const id = "official.theme.stale"
|
||||
srv, _ := marketFixture(t, id, plugin.TrustOfficial, nil)
|
||||
mgr := newTrustTestManager(t)
|
||||
opts := plugin.MarketClientOptions{
|
||||
opts := market.MarketClientOptions{
|
||||
Layout: mgr.Layout(), HostVersion: "0.2.10",
|
||||
URLs: []string{srv.URL + "/index.json"}, CacheTTL: time.Minute,
|
||||
AllowInsecureLocalhost: true, FirstParty: true,
|
||||
@@ -118,28 +119,28 @@ func TestStaleIndexDoesNotVouch(t *testing.T) {
|
||||
// Seed the disk cache, then test cold disk-cache Peek and post-failure
|
||||
// stale consistency: neither cold disk cache nor a failed refresh may ever
|
||||
// claim official trust or silently rebound to fresh within the cache TTL.
|
||||
plugin.NewMarketClient(opts).Browse(context.Background(), nil, plugin.MarketBrowseOptions{})
|
||||
market.NewMarketClient(opts).Browse(context.Background(), nil, market.MarketBrowseOptions{})
|
||||
opts.URLs = []string{srv.URL + "/missing-index.json"}
|
||||
staleClient := plugin.NewMarketClient(opts)
|
||||
staleClient := market.NewMarketClient(opts)
|
||||
|
||||
// Cold disk cache Peek (before network fetch in this session) must not vouch.
|
||||
if coldPeek := staleClient.Peek(nil, plugin.MarketBrowseOptions{}); len(coldPeek.Items) != 1 || coldPeek.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
if coldPeek := staleClient.Peek(nil, market.MarketBrowseOptions{}); len(coldPeek.Items) != 1 || coldPeek.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
t.Fatalf("cold disk-cache Peek must show community trust, got items=%+v", coldPeek.Items)
|
||||
}
|
||||
|
||||
browse := staleClient.Browse(context.Background(), nil, plugin.MarketBrowseOptions{})
|
||||
browse := staleClient.Browse(context.Background(), nil, market.MarketBrowseOptions{})
|
||||
if !browse.Stale || browse.FetchError == "" || len(browse.Items) != 1 || browse.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
t.Fatalf("stale browse must show community trust, got stale=%v err=%q items=%+v", browse.Stale, browse.FetchError, browse.Items)
|
||||
}
|
||||
// Follow-up non-forced Browse within TTL (e.g. search/category filter) must stay stale + community.
|
||||
followUp := staleClient.Browse(context.Background(), nil, plugin.MarketBrowseOptions{Query: id})
|
||||
followUp := staleClient.Browse(context.Background(), nil, market.MarketBrowseOptions{Query: id})
|
||||
if !followUp.Stale || followUp.FetchError == "" || len(followUp.Items) != 1 || followUp.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
t.Fatalf("follow-up Browse after failure must stay stale/community, got stale=%v err=%q items=%+v", followUp.Stale, followUp.FetchError, followUp.Items)
|
||||
}
|
||||
if peek := staleClient.Peek(nil, plugin.MarketBrowseOptions{}); !peek.Stale || len(peek.Items) != 1 || peek.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
if peek := staleClient.Peek(nil, market.MarketBrowseOptions{}); !peek.Stale || len(peek.Items) != 1 || peek.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
t.Fatalf("peek after stale browse must keep community trust, got stale=%v items=%+v", peek.Stale, peek.Items)
|
||||
}
|
||||
info, err := staleClient.InstallFromMarket(context.Background(), mgr, id, plugin.MarketInstallOptions{})
|
||||
info, err := staleClient.InstallFromMarket(context.Background(), mgr, id, market.MarketInstallOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("install: %v", err)
|
||||
}
|
||||
@@ -159,24 +160,24 @@ func TestStaleIndexDoesNotVouch(t *testing.T) {
|
||||
_ = json.NewEncoder(w).Encode(indexFn())
|
||||
}))
|
||||
t.Cleanup(switchSrv.Close)
|
||||
liveClient := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
liveClient := market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: mgr.Layout(), HostVersion: "0.2.10",
|
||||
URLs: []string{switchSrv.URL + "/index.json"}, CacheTTL: time.Minute,
|
||||
AllowInsecureLocalhost: true, FirstParty: true,
|
||||
})
|
||||
if okRes := liveClient.Browse(context.Background(), nil, plugin.MarketBrowseOptions{}); okRes.Stale || okRes.Items[0].Entry.Trust != plugin.TrustOfficial {
|
||||
if okRes := liveClient.Browse(context.Background(), nil, market.MarketBrowseOptions{}); okRes.Stale || okRes.Items[0].Entry.Trust != plugin.TrustOfficial {
|
||||
t.Fatalf("initial live browse want official/fresh, got stale=%v trust=%q", okRes.Stale, okRes.Items[0].Entry.Trust)
|
||||
}
|
||||
failRemote = true
|
||||
if failRes := liveClient.Browse(context.Background(), nil, plugin.MarketBrowseOptions{ForceRefresh: true}); !failRes.Stale || failRes.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
if failRes := liveClient.Browse(context.Background(), nil, market.MarketBrowseOptions{ForceRefresh: true}); !failRes.Stale || failRes.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
t.Fatalf("failed force-refresh want stale/community, got stale=%v trust=%q", failRes.Stale, failRes.Items[0].Entry.Trust)
|
||||
}
|
||||
if afterFail := liveClient.Browse(context.Background(), nil, plugin.MarketBrowseOptions{}); !afterFail.Stale || afterFail.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
if afterFail := liveClient.Browse(context.Background(), nil, market.MarketBrowseOptions{}); !afterFail.Stale || afterFail.Items[0].Entry.Trust != plugin.TrustCommunity {
|
||||
t.Fatalf("non-forced Browse after failed refresh rebounded: stale=%v trust=%q", afterFail.Stale, afterFail.Items[0].Entry.Trust)
|
||||
}
|
||||
// Once remote recovers, the next non-forced Browse must retry and restore official trust immediately.
|
||||
failRemote = false
|
||||
if recovered := liveClient.Browse(context.Background(), nil, plugin.MarketBrowseOptions{}); recovered.Stale || recovered.Source != "remote" || recovered.Items[0].Entry.Trust != plugin.TrustOfficial {
|
||||
if recovered := liveClient.Browse(context.Background(), nil, market.MarketBrowseOptions{}); recovered.Stale || recovered.Source != "remote" || recovered.Items[0].Entry.Trust != plugin.TrustOfficial {
|
||||
t.Fatalf("non-forced Browse after recovery stayed stale: source=%q stale=%v trust=%q", recovered.Source, recovered.Stale, recovered.Items[0].Entry.Trust)
|
||||
}
|
||||
}
|
||||
@@ -185,12 +186,12 @@ func TestOfficialPluginsStillNeedApproval(t *testing.T) {
|
||||
const id = "official.theme.clip"
|
||||
srv, _ := marketFixture(t, id, plugin.TrustOfficial, []string{"host:clipboard"})
|
||||
mgr := newTrustTestManager(t)
|
||||
mc := plugin.NewMarketClient(plugin.MarketClientOptions{
|
||||
mc := market.NewMarketClient(market.MarketClientOptions{
|
||||
Layout: mgr.Layout(), HostVersion: "0.2.10",
|
||||
URLs: []string{srv.URL + "/index.json"}, CacheTTL: time.Minute,
|
||||
AllowInsecureLocalhost: true, FirstParty: true,
|
||||
})
|
||||
info, err := mc.InstallFromMarket(context.Background(), mgr, id, plugin.MarketInstallOptions{})
|
||||
info, err := mc.InstallFromMarket(context.Background(), mgr, id, market.MarketInstallOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("install: %v", err)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package plugin
|
||||
package uiassets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -70,7 +70,7 @@ func (a *AssetServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
fullPath, err := safeJoin(rootDir, relPath)
|
||||
fullPath, err := SafeJoin(rootDir, relPath)
|
||||
if err != nil {
|
||||
http.Error(w, "forbidden path", http.StatusForbidden)
|
||||
return
|
||||
@@ -0,0 +1,482 @@
|
||||
package uiassets
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
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+.-]*:`)
|
||||
)
|
||||
|
||||
// ValidateThemeCSSSafety rejects unbalanced braces, unclosed strings/comments,
|
||||
// CSS-escaped url()/image-set()/expression() bypasses, remote @import, and
|
||||
// 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")
|
||||
}
|
||||
n := len(css)
|
||||
i := 0
|
||||
braceDepth := 0
|
||||
|
||||
skipWSAndComments := func() error {
|
||||
for i < n {
|
||||
if css[i] == ' ' || css[i] == '\t' || css[i] == '\r' || css[i] == '\n' || css[i] == '\f' {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if i+1 < n && css[i] == '/' && css[i+1] == '*' {
|
||||
end := strings.Index(css[i+2:], "*/")
|
||||
if end < 0 {
|
||||
return errors.New("unclosed CSS comment in theme stylesheet")
|
||||
}
|
||||
i += 2 + end + 2
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
readString := func(quote byte) (string, error) {
|
||||
i++ // consume opening quote
|
||||
var b strings.Builder
|
||||
for i < n {
|
||||
c := css[i]
|
||||
if c == '\n' || c == '\r' || c == '\f' {
|
||||
return "", errors.New("unclosed CSS string literal")
|
||||
}
|
||||
if c == quote {
|
||||
i++
|
||||
return b.String(), nil
|
||||
}
|
||||
if c == '\\' {
|
||||
i++
|
||||
if i >= n {
|
||||
return "", errors.New("dangling escape in CSS string")
|
||||
}
|
||||
if css[i] == '\n' || css[i] == '\r' || css[i] == '\f' {
|
||||
if css[i] == '\r' && i+1 < n && css[i+1] == '\n' {
|
||||
i += 2
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
continue
|
||||
}
|
||||
r, next := decodeCSSEscape(css, i)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
b.WriteByte(c)
|
||||
i++
|
||||
}
|
||||
return "", errors.New("unclosed CSS string literal")
|
||||
}
|
||||
|
||||
readIdent := func() string {
|
||||
var b strings.Builder
|
||||
for i < n {
|
||||
c := css[i]
|
||||
if c == '\\' && i+1 < n && css[i+1] != '\n' && css[i+1] != '\r' {
|
||||
r, next := decodeCSSEscape(css, i+1)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
if IsCSSIdentChar(c) {
|
||||
b.WriteByte(c)
|
||||
i++
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
readURLArg := func() (string, error) {
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if i >= n {
|
||||
return "", errors.New("unclosed url() in theme stylesheet")
|
||||
}
|
||||
if css[i] == '"' || css[i] == '\'' {
|
||||
val, err := readString(css[i])
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if i >= n || css[i] != ')' {
|
||||
return "", errors.New("malformed url() in theme stylesheet")
|
||||
}
|
||||
i++ // consume ')'
|
||||
return val, nil
|
||||
}
|
||||
var b strings.Builder
|
||||
for i < n {
|
||||
c := css[i]
|
||||
if c == ')' {
|
||||
i++
|
||||
return strings.TrimSpace(b.String()), nil
|
||||
}
|
||||
if c == '(' || c == '"' || c == '\'' || c == '\n' || c == '\r' {
|
||||
return "", errors.New("malformed unquoted url() in theme stylesheet")
|
||||
}
|
||||
if c == '\\' {
|
||||
if i+1 >= n {
|
||||
return "", errors.New("dangling escape in url()")
|
||||
}
|
||||
r, next := decodeCSSEscape(css, i+1)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
b.WriteByte(c)
|
||||
i++
|
||||
}
|
||||
return "", errors.New("unclosed url() in theme stylesheet")
|
||||
}
|
||||
|
||||
for i < n {
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return err
|
||||
}
|
||||
if i >= n {
|
||||
break
|
||||
}
|
||||
c := css[i]
|
||||
switch {
|
||||
case c == '{':
|
||||
braceDepth++
|
||||
i++
|
||||
case c == '}':
|
||||
braceDepth--
|
||||
if braceDepth < 0 {
|
||||
return errors.New("unbalanced '}' in theme stylesheet (layer breakout blocked)")
|
||||
}
|
||||
i++
|
||||
case c == '"' || c == '\'':
|
||||
if _, err := readString(c); err != nil {
|
||||
return err
|
||||
}
|
||||
case c == '@':
|
||||
i++
|
||||
atName := strings.ToLower(readIdent())
|
||||
if atName == "import" {
|
||||
if err := skipWSAndComments(); err != nil {
|
||||
return err
|
||||
}
|
||||
var target string
|
||||
var err error
|
||||
if i < n && (css[i] == '"' || css[i] == '\'') {
|
||||
target, err = readString(css[i])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
fn := strings.ToLower(readIdent())
|
||||
if fn != "url" || i >= n || css[i] != '(' {
|
||||
return errors.New("@import syntax not allowed in theme stylesheet")
|
||||
}
|
||||
i++ // '('
|
||||
target, err = readURLArg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := validateCSSResourceURL(target, rootDir, true); err != nil {
|
||||
return fmt.Errorf("@import %q forbidden: %w", target, err)
|
||||
}
|
||||
}
|
||||
case isCSSIdentStart(c) || c == '\\':
|
||||
ident := strings.ToLower(readIdent())
|
||||
if i < n && css[i] == '(' {
|
||||
switch ident {
|
||||
case "expression":
|
||||
return errors.New("CSS expression() is forbidden in theme stylesheets")
|
||||
case "url", "src":
|
||||
i++ // consume '('
|
||||
u, err := readURLArg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateCSSResourceURL(u, rootDir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
case "image-set", "-webkit-image-set":
|
||||
i++ // consume '('
|
||||
if err := validateImageSetArgs(css, &i, rootDir, skipWSAndComments, readString, readIdent, readURLArg); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
i++ // consume '('
|
||||
}
|
||||
}
|
||||
default:
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
if braceDepth != 0 {
|
||||
return errors.New("unbalanced '{' in theme stylesheet")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateImageSetArgs(
|
||||
css string,
|
||||
idx *int,
|
||||
rootDir string,
|
||||
skipWS func() error,
|
||||
readString func(byte) (string, error),
|
||||
readIdent func() string,
|
||||
readURLArg func() (string, error),
|
||||
) error {
|
||||
depth := 1
|
||||
n := len(css)
|
||||
for *idx < n && depth > 0 {
|
||||
if err := skipWS(); err != nil {
|
||||
return err
|
||||
}
|
||||
if *idx >= n {
|
||||
break
|
||||
}
|
||||
c := css[*idx]
|
||||
switch {
|
||||
case c == ')':
|
||||
depth--
|
||||
*idx++
|
||||
case c == '(':
|
||||
depth++
|
||||
*idx++
|
||||
case c == '"' || c == '\'':
|
||||
s, err := readString(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Bare strings inside image-set() are URLs unless inside type("...").
|
||||
if depth == 1 {
|
||||
if err := validateCSSResourceURL(s, rootDir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case isCSSIdentStart(c) || c == '\\':
|
||||
fn := strings.ToLower(readIdent())
|
||||
if *idx < n && css[*idx] == '(' {
|
||||
switch fn {
|
||||
case "url", "src":
|
||||
*idx++
|
||||
u, err := readURLArg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateCSSResourceURL(u, rootDir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
case "image-set", "-webkit-image-set":
|
||||
*idx++
|
||||
if err := validateImageSetArgs(css, idx, rootDir, skipWS, readString, readIdent, readURLArg); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
depth++
|
||||
*idx++
|
||||
}
|
||||
}
|
||||
default:
|
||||
*idx++
|
||||
}
|
||||
}
|
||||
if depth != 0 {
|
||||
return errors.New("unclosed image-set() in theme stylesheet")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateCSSResourceURL(rawURL, rootDir string, isImport bool) error {
|
||||
u := strings.TrimSpace(rawURL)
|
||||
if u == "" {
|
||||
if isImport {
|
||||
return errors.New("empty @import URL")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if strings.ContainsAny(u, "\r\n\x00") {
|
||||
return errors.New("control characters in CSS URL")
|
||||
}
|
||||
lower := strings.ToLower(u)
|
||||
if strings.HasPrefix(lower, "//") {
|
||||
return fmt.Errorf("external protocol-relative URL %q is forbidden", u)
|
||||
}
|
||||
if strings.HasPrefix(lower, "data:") {
|
||||
if isImport {
|
||||
return errors.New("data: URL forbidden in @import")
|
||||
}
|
||||
allowedData := []string{
|
||||
"data:image/png;", "data:image/png,",
|
||||
"data:image/jpeg;", "data:image/jpeg,",
|
||||
"data:image/webp;", "data:image/webp,",
|
||||
"data:image/gif;", "data:image/gif,",
|
||||
"data:font/woff2;", "data:font/woff;",
|
||||
}
|
||||
for _, pfx := range allowedData {
|
||||
if strings.HasPrefix(lower, pfx) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("unsafe data: URL %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
if ReSchemePrefix.MatchString(u) {
|
||||
return fmt.Errorf("external/scheme URL %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
// Strip query/fragment for path validation.
|
||||
pathOnly := u
|
||||
if q := strings.IndexAny(pathOnly, "?#"); q >= 0 {
|
||||
pathOnly = pathOnly[:q]
|
||||
}
|
||||
if pathOnly == "" {
|
||||
// Fragment-only URL like url(#clip) — allowed for SVG/local refs, not @import.
|
||||
if isImport {
|
||||
return errors.New("fragment URL forbidden in @import")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if strings.HasPrefix(pathOnly, "/") || strings.Contains(pathOnly, "\\") {
|
||||
return fmt.Errorf("absolute or backslash path %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
for _, seg := range strings.Split(pathOnly, "/") {
|
||||
if seg == ".." {
|
||||
return fmt.Errorf("path traversal %q is forbidden in theme stylesheets", u)
|
||||
}
|
||||
}
|
||||
if rootDir != "" {
|
||||
full, err := SafeJoin(rootDir, pathOnly)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
st, err := os.Stat(full)
|
||||
if err != nil || st.IsDir() {
|
||||
return fmt.Errorf("theme CSS asset %q not found in package", pathOnly)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateCSSTokenValue checks a single CSS custom property or seed value to
|
||||
// ensure it cannot break out of a declaration, close @layer, or load external URLs.
|
||||
func ValidateCSSTokenValue(val string) error {
|
||||
if strings.ContainsAny(val, "\r\n\x00{};") || strings.HasSuffix(strings.TrimSpace(val), `\`) {
|
||||
return fmt.Errorf("CSS token value %q contains forbidden characters", val)
|
||||
}
|
||||
if strings.Contains(val, "/*") || strings.Contains(val, "*/") {
|
||||
return fmt.Errorf("CSS token value %q must not contain CSS comments", val)
|
||||
}
|
||||
decoded := strings.ToLower(decodeAllCSSEscapes(val))
|
||||
for _, bad := range []string{"</style", "url(", "src(", "image-set(", "-webkit-image-set(", "expression(", "@import", "javascript:", "data:", "http://", "https://", "//"} {
|
||||
if strings.Contains(decoded, bad) {
|
||||
return fmt.Errorf("CSS token value %q contains forbidden construct %q", val, bad)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateSafeManifestAsset(rel, rootDir string) error {
|
||||
if rel == "" {
|
||||
return errors.New("empty asset path")
|
||||
}
|
||||
if strings.ContainsAny(rel, "\"'\\;{}()\r\n\x00") || !ReSafeAssetRel.MatchString(rel) {
|
||||
return errors.New("asset path contains forbidden characters")
|
||||
}
|
||||
if strings.HasPrefix(rel, "/") || ReSchemePrefix.MatchString(rel) {
|
||||
return errors.New("asset path must be package-relative")
|
||||
}
|
||||
for _, seg := range strings.Split(rel, "/") {
|
||||
if seg == ".." {
|
||||
return errors.New("path traversal in asset path")
|
||||
}
|
||||
}
|
||||
if rootDir != "" {
|
||||
full, err := SafeJoin(rootDir, rel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
st, err := os.Stat(full)
|
||||
if err != nil || st.IsDir() {
|
||||
return errors.New("asset file not found in package")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func decodeCSSEscape(s string, pos int) (rune, int) {
|
||||
n := len(s)
|
||||
if pos >= n {
|
||||
return 0xFFFD, pos
|
||||
}
|
||||
if isHexByte(s[pos]) {
|
||||
start := pos
|
||||
for pos < n && pos-start < 6 && isHexByte(s[pos]) {
|
||||
pos++
|
||||
}
|
||||
code, err := strconv.ParseInt(s[start:pos], 16, 32)
|
||||
// CSS spec: one optional whitespace char after hex escape is consumed.
|
||||
if pos < n {
|
||||
if s[pos] == '\r' && pos+1 < n && s[pos+1] == '\n' {
|
||||
pos += 2
|
||||
} else if s[pos] == ' ' || s[pos] == '\t' || s[pos] == '\n' || s[pos] == '\r' || s[pos] == '\f' {
|
||||
pos++
|
||||
}
|
||||
}
|
||||
if err != nil || code <= 0 || code > unicode.MaxRune {
|
||||
return 0xFFFD, pos
|
||||
}
|
||||
return rune(code), pos
|
||||
}
|
||||
return rune(s[pos]), pos + 1
|
||||
}
|
||||
|
||||
func decodeAllCSSEscapes(s string) string {
|
||||
if !strings.ContainsRune(s, '\\') {
|
||||
return s
|
||||
}
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(s); {
|
||||
if s[i] == '\\' && i+1 < len(s) {
|
||||
r, next := decodeCSSEscape(s, i+1)
|
||||
b.WriteRune(r)
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
b.WriteByte(s[i])
|
||||
i++
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func isHexByte(c byte) bool {
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
|
||||
}
|
||||
|
||||
func isCSSIdentStart(c byte) bool {
|
||||
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '-' || c >= 0x80
|
||||
}
|
||||
|
||||
func IsCSSIdentChar(c byte) bool {
|
||||
return isCSSIdentStart(c) || (c >= '0' && c <= '9')
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package uiassets
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func pathWithinRoot(root, candidate string) bool {
|
||||
if runtime.GOOS == "windows" {
|
||||
r := strings.ToLower(root)
|
||||
c := strings.ToLower(candidate)
|
||||
return c == r || strings.HasPrefix(c, r+string(os.PathSeparator))
|
||||
}
|
||||
return candidate == root || strings.HasPrefix(candidate, root+string(os.PathSeparator))
|
||||
}
|
||||
|
||||
// SafeJoin joins rel under root and verifies that neither lexical traversal
|
||||
// nor symlinks / NTFS junctions escape root.
|
||||
func SafeJoin(root, rel string) (string, error) {
|
||||
absRoot, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve root path: %w", err)
|
||||
}
|
||||
cleanRoot := filepath.Clean(absRoot)
|
||||
joined := filepath.Clean(filepath.Join(cleanRoot, filepath.FromSlash(rel)))
|
||||
if !pathWithinRoot(cleanRoot, joined) {
|
||||
return "", fmt.Errorf("path traversal blocked: %q", rel)
|
||||
}
|
||||
evalRoot := cleanRoot
|
||||
if r, err := filepath.EvalSymlinks(cleanRoot); err == nil {
|
||||
evalRoot = filepath.Clean(r)
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("evaluate root path: %w", err)
|
||||
}
|
||||
|
||||
evalJoined, err := filepath.EvalSymlinks(joined)
|
||||
if err == nil {
|
||||
evalJoined = filepath.Clean(evalJoined)
|
||||
if !pathWithinRoot(evalRoot, evalJoined) {
|
||||
return "", fmt.Errorf("symlink traversal blocked: %q", rel)
|
||||
}
|
||||
return evalJoined, nil
|
||||
}
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("evaluate path %q: %w", rel, err)
|
||||
}
|
||||
|
||||
cur := joined
|
||||
var tail []string
|
||||
for cur != cleanRoot {
|
||||
parent := filepath.Dir(cur)
|
||||
if parent == cur {
|
||||
break
|
||||
}
|
||||
tail = append(tail, filepath.Base(cur))
|
||||
cur = parent
|
||||
if evalAnc, aErr := filepath.EvalSymlinks(cur); aErr == nil {
|
||||
evalAnc = filepath.Clean(evalAnc)
|
||||
if !pathWithinRoot(evalRoot, evalAnc) {
|
||||
return "", fmt.Errorf("symlink ancestor traversal blocked: %q", rel)
|
||||
}
|
||||
for i := len(tail) - 1; i >= 0; i-- {
|
||||
evalAnc = filepath.Join(evalAnc, tail[i])
|
||||
}
|
||||
return evalAnc, nil
|
||||
} else if !errors.Is(aErr, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("evaluate ancestor path %q: %w", rel, aErr)
|
||||
}
|
||||
}
|
||||
return joined, nil
|
||||
}
|
||||
Reference in new issue
Block a user