1package webutil
2
3import (
4 "bytes"
5 "errors"
6 "fmt"
7 "io"
8 "io/fs"
9 "net/url"
10 "path"
11 "strconv"
12 "strings"
13
14 "github.com/andybalholm/brotli"
15)
16
17// Shared system-view (dumb://) request policy used by every browser engine.
18// Engines keep only their native request/response translation; routing
19// safety, trust, and asset decoding rules live here once.
20
21const (
22 // SystemviewsAssetDir is the embedded directory holding system-view assets.
23 SystemviewsAssetDir = "systemviews"
24 // MaxSystemviewsWASMBytes bounds the decompressed system-view WASM size.
25 MaxSystemviewsWASMBytes = 64 * 1024 * 1024
26 // SystemviewFaviconSize is the only favicon size served to system views.
27 SystemviewFaviconSize = 32
28)
29
30// SafeSystemviewsAssetPath validates relPath inside assetDir and returns the
31// cleaned full path. It rejects traversal, absolute paths, NUL bytes, and any
32// directory other than SystemviewsAssetDir.
33func SafeSystemviewsAssetPath(assetDir, relPath string) (fullPath, cleanRelPath string, ok bool) {
34 assetDir = strings.Trim(assetDir, "/")
35 if assetDir != SystemviewsAssetDir {
36 return "", "", false
37 }
38
39 relPath = strings.TrimLeft(relPath, "/")
40 if relPath == "" || strings.ContainsRune(relPath, '\x00') {
41 return "", "", false
42 }
43
44 cleanRelPath = path.Clean(relPath)
45 if cleanRelPath == "." || cleanRelPath == ".." || strings.HasPrefix(cleanRelPath, "../") || path.IsAbs(cleanRelPath) {
46 return "", "", false
47 }
48
49 fullPath = path.Join(assetDir, cleanRelPath)
50 if fullPath != assetDir && !strings.HasPrefix(fullPath, assetDir+"/") {
51 return "", "", false
52 }
53 return fullPath, cleanRelPath, true
54}
55
56// ReadSystemviewAsset reads an embedded asset. For .wasm files a sibling .br
57// artifact is authoritative when present: it is decompressed with a
58// MaxSystemviewsWASMBytes bound, and a corrupt or oversized artifact is an
59// error rather than a silent fallback to the raw file.
60func ReadSystemviewAsset(assets fs.FS, fullPath, relPath string) ([]byte, error) {
61 if strings.HasSuffix(relPath, ".wasm") {
62 if compressed, err := fs.ReadFile(assets, fullPath+".br"); err == nil {
63 data, err := io.ReadAll(io.LimitReader(brotli.NewReader(bytes.NewReader(compressed)), MaxSystemviewsWASMBytes+1))
64 if err != nil {
65 return nil, err
66 }
67 if len(data) > MaxSystemviewsWASMBytes {
68 return nil, fmt.Errorf("decompressed asset %s exceeds %d bytes", fullPath, MaxSystemviewsWASMBytes)
69 }
70 return data, nil
71 }
72 }
73 return fs.ReadFile(assets, fullPath)
74}
75
76// SystemviewTrust describes how an engine identifies system-view requesters.
77type SystemviewTrust struct {
78 // IsTrustedURL reports whether an origin or referrer URL is a system view.
79 IsTrustedURL func(string) bool
80 // OpaqueOriginUsesReferrer treats an Origin of "null" like a missing
81 // Origin. WebKit needs this because custom-scheme pages have opaque
82 // origins; engines that serve system views from a real origin must not.
83 OpaqueOriginUsesReferrer bool
84}
85
86// Allows decides whether a request may call private system-view APIs. A
87// present Origin is authoritative; otherwise the referrer is checked.
88func (t SystemviewTrust) Allows(origin, referrer string) bool {
89 if t.IsTrustedURL == nil {
90 return false
91 }
92 origin = strings.TrimSpace(origin)
93 opaque := strings.EqualFold(origin, "null")
94 if origin != "" && (!opaque || !t.OpaqueOriginUsesReferrer) {
95 return t.IsTrustedURL(origin)
96 }
97 return t.IsTrustedURL(strings.TrimSpace(referrer))
98}
99
100// DumbURLHost returns the page host of a dumb:// URL (dumb://history or
101// dumb:history) and whether raw is a dumb:// URL at all.
102func DumbURLHost(raw string) (string, bool) {
103 parsed, err := url.Parse(strings.TrimSpace(raw))
104 if err != nil || !strings.EqualFold(parsed.Scheme, "dumb") {
105 return "", false
106 }
107 host := parsed.Host
108 if host == "" {
109 host = parsed.Opaque
110 }
111 if idx := strings.IndexAny(host, "/?#"); idx >= 0 {
112 host = host[:idx]
113 }
114 return host, true
115}
116
117// Client-facing favicon API request errors.
118var (
119 ErrFaviconMissingDomain = errors.New("missing domain")
120 ErrFaviconUnsupportedSize = errors.New("unsupported favicon size")
121 ErrFaviconInvalidRequestURL = errors.New("invalid request URL")
122)
123
124// ParseSystemviewFaviconRequest extracts the domain and size from a favicon
125// API URL. Only SystemviewFaviconSize is accepted.
126func ParseSystemviewFaviconRequest(rawURL string) (domain string, size int, err error) {
127 parsed, parseErr := url.Parse(rawURL)
128 if parseErr != nil {
129 return "", 0, ErrFaviconInvalidRequestURL
130 }
131 domain = strings.TrimSpace(parsed.Query().Get("domain"))
132 if domain == "" {
133 return "", 0, ErrFaviconMissingDomain
134 }
135 if rawSize := strings.TrimSpace(parsed.Query().Get("size")); rawSize != "" {
136 parsedSize, convErr := strconv.Atoi(rawSize)
137 if convErr != nil || parsedSize != SystemviewFaviconSize {
138 return "", 0, ErrFaviconUnsupportedSize
139 }
140 }
141 return domain, SystemviewFaviconSize, nil
142}