Files
Reims-Go/internal/app/plugin_bridge_net.go
千川白浪andClaude Opus 5.5 fa3e1e2889 feat: add plugin views and expand the sandboxed page bridge
Plugins can add pages to the sidebar, VM tabs, Settings and dialogs. Their
pages can now use host forms and navigation, VM and settings access,
authorized file I/O, task progress, controlled HTTP requests, events and
private storage.

Plugin pages cannot change allow_ai_access, which stays the user's per-VM
consent. Closing a page cancels its unfinished tasks, and running plugin
tasks no longer block changing the data folder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:11:23 -07:00

166 lines
4.8 KiB
Go

package app
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"unicode/utf8"
"github.com/Nwflower/reims-go/internal/netproxy"
"github.com/Nwflower/reims-go/internal/plugin"
)
const (
maxPanelNetRequestBytes = 1 << 20
maxPanelNetResponseBytes = 4 << 20
)
func authorizePanelNetURL(mgr *plugin.Manager, pluginID, rawURL string) error {
clean, err := validateExternalHTTPSURL(rawURL)
if err != nil {
return err
}
u, err := url.Parse(clean)
if err != nil {
return err
}
info, ok := mgr.Registry().Info(pluginID)
if !ok {
return fmt.Errorf("unknown plugin %q", pluginID)
}
for _, permission := range info.Permissions {
if !strings.HasPrefix(permission.Name, "net:") {
continue
}
host := strings.TrimPrefix(permission.Name, "net:")
if strings.EqualFold(host, u.Host) || strings.EqualFold(host, u.Hostname()) {
return mgr.Broker().Authorize(pluginID, permission.Name)
}
}
return fmt.Errorf("plugin %q has not declared net:%s", pluginID, u.Host)
}
func panelNetFetch(mgr *plugin.Manager, pluginID string, params map[string]any) (any, error) {
client := netproxy.NewClient()
client.Timeout = 30 * time.Second
return panelNetFetchWithClient(mgr, pluginID, params, client)
}
func panelNetFetchWithClient(mgr *plugin.Manager, pluginID string, params map[string]any, client *http.Client) (any, error) {
rawURL, err := panelTextParam(params, "url", true, 2048, false)
if err != nil {
return nil, err
}
if err := authorizePanelNetURL(mgr, pluginID, rawURL); err != nil {
return nil, err
}
rawURL = strings.TrimSpace(rawURL)
previousRedirect := client.CheckRedirect
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if err := authorizePanelNetURL(mgr, pluginID, req.URL.String()); err != nil {
return err
}
if previousRedirect != nil {
return previousRedirect(req, via)
}
if len(via) >= 10 {
return fmt.Errorf("stopped after 10 redirects")
}
return nil
}
method, err := panelTextParam(params, "method", false, 16, false)
if err != nil {
return nil, err
}
if method == "" {
method = http.MethodGet
}
switch method {
case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodHead:
default:
return nil, fmt.Errorf("unsupported HTTP method %q", method)
}
bodyText, err := panelTextParam(params, "body", false, maxPanelNetRequestBytes, true)
if err != nil {
return nil, err
}
responseType, err := panelTextParam(params, "responseType", false, 16, false)
if err != nil {
return nil, err
}
switch responseType {
case "", "text", "json", "base64":
default:
return nil, fmt.Errorf("unsupported responseType %q", responseType)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, method, rawURL, strings.NewReader(bodyText))
if err != nil {
return nil, err
}
if rawHeaders, ok := params["headers"]; ok && rawHeaders != nil {
headers, ok := rawHeaders.(map[string]any)
if !ok || len(headers) > 32 {
return nil, fmt.Errorf("invalid headers")
}
for name, raw := range headers {
value, ok := raw.(string)
lowerName := strings.ToLower(strings.TrimSpace(name))
if lowerName == "host" || lowerName == "content-length" || strings.HasPrefix(lowerName, "proxy-") {
return nil, fmt.Errorf("header %q is managed by the host", name)
}
if !ok || strings.TrimSpace(name) == "" || strings.ContainsAny(name, "\r\n:") || strings.ContainsAny(value, "\r\n") {
return nil, fmt.Errorf("invalid header %q", name)
}
req.Header.Set(name, value)
}
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, maxPanelNetResponseBytes+1))
if err != nil {
return nil, err
}
if len(body) > maxPanelNetResponseBytes {
return nil, fmt.Errorf("response exceeds %d bytes", maxPanelNetResponseBytes)
}
headers := make(map[string]string, len(resp.Header))
for key, values := range resp.Header {
if strings.EqualFold(key, "Set-Cookie") {
continue
}
headers[key] = strings.Join(values, ", ")
}
result := map[string]any{"status": resp.StatusCode, "headers": headers, "url": resp.Request.URL.String()}
switch responseType {
case "", "text":
if !utf8.Valid(body) {
return nil, fmt.Errorf("response is not valid UTF-8")
}
result["body"] = string(body)
result["encoding"] = "utf8"
case "base64":
result["body"] = base64.StdEncoding.EncodeToString(body)
result["encoding"] = "base64"
case "json":
var value any
if err := json.Unmarshal(body, &value); err != nil {
return nil, fmt.Errorf("decode JSON response: %w", err)
}
result["json"] = value
default:
return nil, fmt.Errorf("unsupported responseType %q", responseType)
}
return result, nil
}