Delete functions that no product code calls, and fold "simple plus WithOptions" pairs into the one signature callers actually use. Rename the live macOS lifecycle functions that were labelled Legacy. The architecture tests now share one source loader and reject functions without a product caller and catalog messages nobody reads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
217 lines
6.2 KiB
Go
217 lines
6.2 KiB
Go
package plugin
|
|
|
|
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
|
|
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))
|
|
for _, attr := range t.Attr {
|
|
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
|
|
}
|
|
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()
|
|
}
|