Files
Reims-Go/internal/app/plugin_bridge_files.go

241 lines
6.4 KiB
Go

package app
import (
"crypto/rand"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"unicode/utf8"
"github.com/Nwflower/reims-go/internal/atomicfile"
"github.com/Nwflower/reims-go/internal/plugin"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
const (
maxPanelFileBytes = 8 << 20
maxPluginFileGrants = 32
pluginFileGrantTTL = 15 * time.Minute
)
type pluginFileGrant struct {
PluginID string
Path string
Write bool
Expires time.Time
}
func (a *App) issuePluginFileGrant(pluginID, path string, write bool) (map[string]any, error) {
if strings.TrimSpace(path) == "" {
return map[string]any{"canceled": true}, nil
}
clean, err := filepath.Abs(path)
if err != nil {
return nil, err
}
var token [16]byte
if _, err := rand.Read(token[:]); err != nil {
return nil, err
}
id := hex.EncodeToString(token[:])
result := map[string]any{"id": id, "name": filepath.Base(clean), "write": write}
if info, err := os.Stat(clean); err == nil {
result["size"] = info.Size()
} else if !write {
return nil, err
}
h := a.hostAPISvc()
h.filesMu.Lock()
defer h.filesMu.Unlock()
now := time.Now()
count := 0
for key, grant := range h.pluginFiles {
if !now.Before(grant.Expires) {
delete(h.pluginFiles, key)
} else if grant.PluginID == pluginID {
count++
}
}
if count >= maxPluginFileGrants {
return nil, errors.New("too many open file handles for this plugin")
}
if h.pluginFiles == nil {
h.pluginFiles = make(map[string]pluginFileGrant)
}
h.pluginFiles[id] = pluginFileGrant{PluginID: pluginID, Path: clean, Write: write, Expires: now.Add(pluginFileGrantTTL)}
return result, nil
}
func (a *App) revokePluginFiles(pluginID string) {
h := a.hostAPISvc()
h.filesMu.Lock()
defer h.filesMu.Unlock()
for id, grant := range h.pluginFiles {
if grant.PluginID == pluginID {
delete(h.pluginFiles, id)
}
}
}
func (a *App) pluginFilePath(pluginID, id string, write bool) (string, error) {
h := a.hostAPISvc()
h.filesMu.Lock()
defer h.filesMu.Unlock()
grant, ok := h.pluginFiles[id]
if ok && !time.Now().Before(grant.Expires) {
delete(h.pluginFiles, id)
ok = false
}
if !ok || grant.PluginID != pluginID || (write && !grant.Write) {
return "", errors.New("file handle is not available to this plugin")
}
return grant.Path, nil
}
func panelFileEncoding(params map[string]any) (string, error) {
encoding, err := panelTextParam(params, "encoding", false, 16, false)
if err != nil {
return "", err
}
switch encoding {
case "", "utf8", "base64":
return encoding, nil
default:
return "", fmt.Errorf("unsupported encoding %q", encoding)
}
}
func (a *App) panelFileCall(mgr *plugin.Manager, pluginID, method string, params map[string]any) (any, error) {
if err := mgr.Broker().Authorize(pluginID, "fs:pick"); err != nil {
return nil, err
}
switch method {
case "file.pick", "file.save":
if a.ctx == nil {
return nil, errors.New("window context not ready")
}
title, err := panelTextParam(params, "title", false, 200, false)
if err != nil {
return nil, err
}
pattern, err := panelTextParam(params, "pattern", false, 200, false)
if err != nil {
return nil, err
}
if method == "file.pick" {
path, err := a.PickFile(title, pattern)
if err != nil {
return nil, err
}
return a.issuePluginFileGrant(pluginID, path, false)
}
defaultFilename, err := panelTextParam(params, "defaultFilename", false, 255, false)
if err != nil {
return nil, err
}
if defaultFilename != "" && (filepath.Base(defaultFilename) != defaultFilename || defaultFilename == "." || defaultFilename == "..") {
return nil, errors.New("defaultFilename must be a file name")
}
opts := wailsRuntime.SaveDialogOptions{Title: title, DefaultFilename: defaultFilename, CanCreateDirectories: true}
if pattern != "" {
opts.Filters = []wailsRuntime.FileFilter{{DisplayName: pattern, Pattern: pattern}}
}
path, err := wailsRuntime.SaveFileDialog(a.ctx, opts)
if err != nil {
return nil, err
}
return a.issuePluginFileGrant(pluginID, path, true)
case "file.read":
id, err := panelTextParam(params, "id", true, 64, false)
if err != nil {
return nil, err
}
path, err := a.pluginFilePath(pluginID, id, false)
if err != nil {
return nil, err
}
encoding, err := panelFileEncoding(params)
if err != nil {
return nil, err
}
info, err := os.Stat(path)
if err != nil {
return nil, err
}
if info.Size() > maxPanelFileBytes {
return nil, fmt.Errorf("file exceeds %d bytes", maxPanelFileBytes)
}
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
data, err := io.ReadAll(io.LimitReader(file, maxPanelFileBytes+1))
if err != nil {
return nil, err
}
if len(data) > maxPanelFileBytes {
return nil, fmt.Errorf("file exceeds %d bytes", maxPanelFileBytes)
}
result := map[string]any{"name": filepath.Base(path), "size": len(data)}
if encoding == "base64" {
result["encoding"] = "base64"
result["data"] = base64.StdEncoding.EncodeToString(data)
} else {
if !utf8.Valid(data) {
return nil, errors.New("file is not valid UTF-8")
}
result["encoding"] = "utf8"
result["data"] = string(data)
}
return result, nil
case "file.write":
id, err := panelTextParam(params, "id", true, 64, false)
if err != nil {
return nil, err
}
path, err := a.pluginFilePath(pluginID, id, true)
if err != nil {
return nil, err
}
encoding, err := panelFileEncoding(params)
if err != nil {
return nil, err
}
rawData, ok := params["data"].(string)
if !ok {
return nil, errors.New("data must be a string")
}
if encoding == "base64" && len(rawData) > (maxPanelFileBytes+2)/3*4 {
return nil, fmt.Errorf("encoded data exceeds %d bytes", maxPanelFileBytes)
}
if encoding != "base64" && len(rawData) > maxPanelFileBytes {
return nil, fmt.Errorf("data exceeds %d bytes", maxPanelFileBytes)
}
var data []byte
if encoding == "base64" {
data, err = base64.StdEncoding.DecodeString(rawData)
if err != nil {
return nil, fmt.Errorf("decode base64 data: %w", err)
}
} else {
data = []byte(rawData)
}
if len(data) > maxPanelFileBytes {
return nil, fmt.Errorf("data exceeds %d bytes", maxPanelFileBytes)
}
if err := atomicfile.Write(path, data, 0o600); err != nil {
return nil, err
}
return map[string]any{"ok": true, "name": filepath.Base(path), "size": len(data)}, nil
default:
return nil, fmt.Errorf("unsupported plugin file method %q", method)
}
}