Files
Reims-Go/internal/app/elevate_flow.go
千川白浪 9006e6d9a7
CI / verify (push) Canceled after 0s
CI / rolling-release (push) Canceled after 0s
refactor: 抽离 HostAPIService 并将 internal/plugin 拆分为四层无环子包 (#202)
2026-12-05 06:05:41 -07:00

211 lines
6.2 KiB
Go

package app
import (
"context"
"encoding/json"
"errors"
"fmt"
"os/user"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
// elevatePromptTimeout is how long a confirmation waits for the person.
var elevatePromptTimeout = 2 * time.Minute
// ElevationPrompt is what the desktop window shows before a plugin's
// elevation request goes on to the Windows UAC prompt.
type ElevationPrompt struct {
ID string `json:"id"`
PluginID string `json:"plugin_id"`
PluginName string `json:"plugin_name"`
Publisher string `json:"publisher,omitempty"`
Trust string `json:"trust,omitempty"`
Action string `json:"action"`
NeedsReboot bool `json:"needs_reboot,omitempty"`
NeedsLogoff bool `json:"needs_logoff,omitempty"`
}
type elevationRunner func(ctx context.Context, action, targetUser string) (host.ElevationResult, error)
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": 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)
}),
}
}
// requestElevation runs one plugin elevation request: check the permission and
// the closed action list, ask the person in the desktop window, and only after
// a yes run the action (which raises the Windows UAC prompt). A no,
// a timeout or a missing window ends the request before anything runs.
func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broker *plugin.Broker, reg *plugin.Registry, pluginID string, raw json.RawMessage) (any, error) {
req, err := decodeHostParams[pluginproto.ElevateParams](kernel, pluginID, "host/elevate.request", raw)
if err != nil {
return nil, err
}
spec, ok := host.LookupElevationAction(req.Action)
if !ok {
return nil, fmt.Errorf("unsupported elevation action %q", req.Action)
}
a.mu.Lock()
winCtx := a.ctx
hasWindow := winCtx != nil
locale := i18n.EffectiveLocale(i18n.Auto)
if a.cfg != nil {
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.
h.elevatePromptMu.Lock()
defer h.elevatePromptMu.Unlock()
prompt := ElevationPrompt{
PluginID: pluginID, PluginName: pluginID, Action: spec.Action,
NeedsReboot: spec.NeedsReboot, NeedsLogoff: spec.NeedsLogoff,
}
if info, found := reg.Info(pluginID); found {
if name := strings.TrimSpace(info.Name.Get(string(locale))); name != "" {
prompt.PluginName = name
}
prompt.Publisher = info.Publisher
prompt.Trust = string(info.Trust)
}
ch := make(chan bool, 1)
h.elevateMu.Lock()
if h.elevatePending == nil {
h.elevatePending = map[string]chan bool{}
}
h.elevateSeq++
prompt.ID = fmt.Sprintf("elevate-%d", h.elevateSeq)
h.elevatePending[prompt.ID] = ch
h.elevateMu.Unlock()
dismissed := false
clearPrompt := func() {
h.elevateMu.Lock()
delete(h.elevatePending, prompt.ID)
h.elevateMu.Unlock()
if dismissed {
return
}
dismissed = true
if dismiss != nil {
dismiss(prompt.ID)
} else if emit == nil {
a.emit("reims:elevate-resolved", prompt.ID)
}
}
defer clearPrompt()
if emit != nil {
emit(prompt)
} else {
a.showMainWindow()
a.emit("reims:elevate-request", prompt)
}
timer := time.NewTimer(elevatePromptTimeout)
defer timer.Stop()
select {
case approved, open := <-ch:
clearPrompt()
if !open || !approved {
broker.Audit(pluginID, "ELEVATE_DENIED", spec.Action)
return nil, errors.New("elevation_denied: the user declined the elevation request")
}
case <-ctx.Done():
clearPrompt()
broker.Audit(pluginID, "ELEVATE_CANCELED", spec.Action)
return nil, fmt.Errorf("elevation_denied: %w", ctx.Err())
case <-timer.C:
clearPrompt()
broker.Audit(pluginID, "ELEVATE_TIMEOUT", spec.Action)
return nil, errors.New("elevation_denied: the confirmation timed out")
}
broker.Audit(pluginID, "ELEVATE_APPROVED", spec.Action)
targetUser := ""
if spec.Action == host.ElevateHyperVAddAdminGroup {
cur, err := user.Current()
if err != nil {
broker.Audit(pluginID, "ELEVATE_ERROR", spec.Action)
return nil, fmt.Errorf("find the current account: %w", err)
}
targetUser = cur.Username
}
if runner == nil {
runner = host.RunElevatedAction
}
res, err := runner(ctx, spec.Action, targetUser)
if err != nil {
if errors.Is(err, host.ErrElevationDeclined) {
broker.Audit(pluginID, "ELEVATE_UAC_DECLINED", spec.Action)
return nil, errors.New("elevation_denied: the Windows UAC prompt was declined")
}
broker.Audit(pluginID, "ELEVATE_ERROR", spec.Action)
return nil, err
}
broker.Audit(pluginID, "ELEVATE_OK", spec.Action)
return pluginproto.ElevateResult{
OK: res.OK,
Action: res.Action,
ExitCode: res.ExitCode,
RebootRequired: res.RebootRequired,
LogoffRequired: res.LogoffRequired,
}, nil
}
// 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 {
h := a.hostAPISvc()
h.elevateMu.Lock()
ch, ok := h.elevatePending[id]
delete(h.elevatePending, id)
h.elevateMu.Unlock()
if !ok {
return nil
}
select {
case ch <- approved:
default:
}
return nil
}
// cancelPendingElevations answers every waiting request with a no, so
// shutting down never leaves a plugin waiting on a dialog.
func (a *App) cancelPendingElevations() {
h := a.hostAPISvc()
h.elevateMu.Lock()
pending := h.elevatePending
h.elevatePending = nil
h.elevateMu.Unlock()
for _, ch := range pending {
close(ch)
}
}