Files
Reims-Go/internal/plugin/uiassets/assets.go
T
千川白浪 e0ff794b0e feat: add experimental macOS desktop support on Apple Silicon (#207)
* feat: add experimental Apple Silicon support with Nivfold

Integrate the standalone Nivfold protocol 1 runner; tested against Nivfold f436fb6. The Windows Reims vGPU runtime remains independent.

* fix: open QQ invites and VM SSH on macOS

* fix: move VM, View and Help to the macOS menu bar

* feat(macos): add resumable Apple restore image downloads

Expose the compatible restore image in the VM wizard and Images page, validate downloads before caching, and fix macOS memory reporting and plugin SVG rendering.

* fix(macos): localize the native application menu

* fix(macos): address native desktop review findings
2026-12-06 00:47:07 +08:00

228 lines
6.7 KiB
Go

package uiassets
import (
"bytes"
"crypto/rand"
"crypto/subtle"
"encoding/hex"
"encoding/xml"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"strings"
)
// AssetServer serves static assets for installed/linked plugins over a
// per-run random token prefix: `/plugin-assets/<runToken>/<pluginID>/<relPath>`
// with path-traversal protection, nosniff, strict CSP, and SVG script blocking (§7.3).
type AssetServer struct {
token string
lookup func(pluginID string) (installDir string, ok bool)
}
// NewAssetServer constructs a plugin static asset handler with a fresh 128-bit run token.
func NewAssetServer(lookup func(pluginID string) (string, bool)) *AssetServer {
var raw [16]byte
_, _ = rand.Read(raw[:])
return &AssetServer{
token: hex.EncodeToString(raw[:]),
lookup: lookup,
}
}
// Token returns the per-run random URL token.
func (a *AssetServer) Token() string { return a.token }
// AssetURL returns the safe URL for relPath inside pluginID.
func (a *AssetServer) AssetURL(pluginID, relPath string) string {
rel := strings.TrimPrefix(filepath.ToSlash(filepath.Clean(relPath)), "/")
return "/plugin-assets/" + a.token + "/" + pluginID + "/" + rel
}
// Prefix returns the route prefix handled by this AssetServer.
func (a *AssetServer) Prefix() string { return "/plugin-assets/" }
// ServeHTTP serves `/plugin-assets/<token>/<pluginID>/<relPath>` with strict security headers.
func (a *AssetServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
trimmed := strings.TrimPrefix(r.URL.Path, "/plugin-assets/")
parts := strings.SplitN(trimmed, "/", 3)
if len(parts) < 3 || subtle.ConstantTimeCompare([]byte(parts[0]), []byte(a.token)) != 1 {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
pluginID, relPath := parts[1], parts[2]
if strings.Contains(relPath, "..") || strings.ContainsRune(relPath, '\\') {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
if a.lookup == nil {
http.NotFound(w, r)
return
}
rootDir, ok := a.lookup(pluginID)
if !ok || rootDir == "" {
http.NotFound(w, r)
return
}
fullPath, err := SafeJoin(rootDir, relPath)
if err != nil {
http.Error(w, "forbidden path", http.StatusForbidden)
return
}
info, err := os.Stat(fullPath)
if err != nil || info.IsDir() {
http.NotFound(w, r)
return
}
ext := strings.ToLower(filepath.Ext(fullPath))
const (
maxSanitizedTextBytes = 2 << 20 // 2 MiB for SVG / CSS buffered sanitization
maxStaticAssetBytes = 16 << 20 // 16 MiB cap for WOFF2 / images / HTML / scripts
)
if (ext == ".svg" || ext == ".css") && info.Size() > maxSanitizedTextBytes {
http.Error(w, "asset exceeds size limit", http.StatusRequestEntityTooLarge)
return
}
if info.Size() > maxStaticAssetBytes {
http.Error(w, "asset exceeds size limit", http.StatusRequestEntityTooLarge)
return
}
ct := mime.TypeByExtension(ext)
switch ext {
case ".woff2":
ct = "font/woff2"
case ".woff":
ct = "font/woff"
}
if ct == "" {
ct = "application/octet-stream"
}
// Hardening headers (§7.3).
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "no-store")
if ext == ".html" || ext == ".htm" {
// Sandboxed L4 iframe panel CSP: no external network connections (§7.3).
w.Header().Set("Content-Security-Policy", "default-src 'self' 'unsafe-inline'; connect-src 'none'; img-src 'self' data:; font-src 'self'; object-src 'none'; base-uri 'none'")
} else {
w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; font-src 'self'; sandbox")
}
if ext == ".svg" || ext == ".css" {
data, err := os.ReadFile(fullPath)
if err != nil {
http.Error(w, "read error", http.StatusInternalServerError)
return
}
if ext == ".svg" {
ct = "image/svg+xml; charset=utf-8"
data = SanitizeSVG(data)
} else {
if err := ValidateThemeCSSSafety(string(data), filepath.Dir(fullPath)); err != nil {
http.Error(w, "unsafe stylesheet blocked", http.StatusForbidden)
return
}
}
w.Header().Set("Content-Type", ct)
w.WriteHeader(http.StatusOK)
if r.Method == http.MethodGet {
_, _ = w.Write(data)
}
return
}
fh, err := os.Open(fullPath)
if err != nil {
http.Error(w, "read error", http.StatusInternalServerError)
return
}
defer fh.Close()
w.Header().Set("Content-Type", ct)
w.WriteHeader(http.StatusOK)
if r.Method == http.MethodGet {
_, _ = io.CopyN(w, fh, info.Size())
}
}
// SanitizeSVG parses SVG XML and strips <script>/<foreignObject> subtrees,
// inline on* event attributes, and dangerous URI schemes (javascript:/vbscript:/data:text/html) (§7.3).
func SanitizeSVG(raw []byte) []byte {
dec := xml.NewDecoder(bytes.NewReader(raw))
var out bytes.Buffer
enc := xml.NewEncoder(&out)
skipDepth := 0
var namespaces []string
for {
tok, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
// Malformed XML: fail closed rather than passing raw markup through.
return nil
}
switch t := tok.(type) {
case xml.StartElement:
local := strings.ToLower(t.Name.Local)
if skipDepth > 0 || local == "script" || local == "foreignobject" {
skipDepth++
continue
}
filtered := make([]xml.Attr, 0, len(t.Attr))
// The decoder resolves namespace URIs and the encoder emits their
// declarations. Forwarding the original xmlns would duplicate it.
if n := len(namespaces); n > 0 && namespaces[n-1] != "" && t.Name.Space == "" {
filtered = append(filtered, xml.Attr{Name: xml.Name{Local: "xmlns"}})
}
namespaces = append(namespaces, t.Name.Space)
for _, attr := range t.Attr {
if attr.Name.Space == "xmlns" || (attr.Name.Space == "" && attr.Name.Local == "xmlns") {
continue
}
name := strings.ToLower(attr.Name.Local)
if strings.HasPrefix(name, "on") {
continue
}
val := strings.ToLower(strings.TrimSpace(attr.Value))
if name == "href" || name == "values" || name == "from" || name == "to" || name == "by" {
if strings.HasPrefix(val, "javascript:") || strings.HasPrefix(val, "vbscript:") || strings.HasPrefix(val, "data:text/html") || strings.Contains(val, "javascript:") {
continue
}
}
filtered = append(filtered, attr)
}
t.Attr = filtered
if err := enc.EncodeToken(t); err != nil {
return nil
}
case xml.EndElement:
if skipDepth > 0 {
skipDepth--
continue
}
namespaces = namespaces[:len(namespaces)-1]
if err := enc.EncodeToken(t); err != nil {
return nil
}
default:
if skipDepth > 0 {
continue
}
if err := enc.EncodeToken(tok); err != nil {
return nil
}
}
}
if err := enc.Flush(); err != nil {
return nil
}
return out.Bytes()
}