gui: native WebView host as nested module yetano.dev/yetano/core/gui

Extracted from prototypes/yetano-webview (AP1): packages assets,
document, bridge and window (macOS Cocoa/WKWebView via cgo, Windows
Win32/WebView2 pure Go). No local HTTP listener or port: assets go
through the WebView's resource handler, app routes through the native
message binding. Own go.mod and gui/vX.Y.Z tags keep cgo and the
WebView dependencies out of the main core module. Adds backend-free
tests for the window's dispatch/destroy guards and a yet-gui migration
guide.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
terminarandClaude Opus 5.5 committed 2026-10-23 14:47:26 +02:00
1 parent 90132e2d76
commit 8c63d42a27
27 files changed
+4849 -3

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
package assets
import (
"bytes"
"fmt"
"net/http"
"path"
"strings"
)
// Known types by extension. The extension wins; sniffing only fills gaps.
var mimeByExt = map[string]string{
".html": "text/html; charset=utf-8",
".htm": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".json": "application/json",
".txt": "text/plain; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".webp": "image/webp",
".ico": "image/x-icon",
".ttf": "font/ttf",
".otf": "font/otf",
".woff": "font/woff",
".woff2": "font/woff2",
".wasm": "application/wasm",
}
// strict extensions must never resolve to a generic type, and binary ones are
// checked against their magic bytes.
var wasmMagic = []byte{0x00, 'a', 's', 'm'}
// DetectMIME returns the MIME type for name/data.
func DetectMIME(name string, data []byte) (string, error) {
ext := strings.ToLower(path.Ext(name))
if m, ok := mimeByExt[ext]; ok {
if ext == ".wasm" && !bytes.HasPrefix(data, wasmMagic) {
return "", fmt.Errorf("%s: .wasm without WebAssembly magic bytes", name)
}
return m, nil
}
return http.DetectContentType(data), nil
}
// BaseMIME strips parameters ("text/css; charset=utf-8" -> "text/css").
func BaseMIME(m string) string {
if i := strings.IndexByte(m, ';'); i >= 0 {
m = m[:i]
}
return strings.TrimSpace(m)
}
+103
View File
@@ -0,0 +1,103 @@
package assets
import (
"errors"
"fmt"
"path"
"strings"
)
// ErrInvalidPath marks a virtual asset path that is rejected before any
// source is consulted (traversal, backslash, drive letter, UNC, NUL, ...).
var ErrInvalidPath = errors.New("invalid asset path")
// URL prefixes that address the asset root. "/assets/x" and "assets:x" are
// the same identity "x".
const (
PrefixSlash = "/assets/"
PrefixScheme = "assets:"
)
// IsAssetRef reports whether ref uses one of the two asset reference forms.
func IsAssetRef(ref string) bool {
return strings.HasPrefix(ref, PrefixSlash) || strings.HasPrefix(ref, PrefixScheme)
}
// SplitRef removes query and fragment from a reference. They never take part
// in the lookup.
func SplitRef(ref string) (p, suffix string) {
if i := strings.IndexAny(ref, "?#"); i >= 0 {
return ref[:i], ref[i:]
}
return ref, ""
}
// FromRef turns "/assets/a/b.png?x#y" or "assets:a/b.png" into the canonical
// virtual path "a/b.png". The path is validated with ValidatePath; nothing is
// cleaned silently and nothing is percent-decoded here.
func FromRef(ref string) (string, error) {
p, _ := SplitRef(ref)
switch {
case strings.HasPrefix(p, PrefixSlash):
p = p[len(PrefixSlash):]
case strings.HasPrefix(p, PrefixScheme):
p = p[len(PrefixScheme):]
default:
return "", fmt.Errorf("%w: %q is not an asset reference", ErrInvalidPath, ref)
}
if err := ValidatePath(p); err != nil {
return "", err
}
return p, nil
}
// ValidatePath accepts only canonical, relative, forward-slash paths inside
// the asset root. It rejects instead of cleaning: "a/../b" is an error, not
// "b".
func ValidatePath(p string) error {
bad := func(why string) error { return fmt.Errorf("%w: %q: %s", ErrInvalidPath, p, why) }
switch {
case p == "":
return bad("empty")
case strings.ContainsRune(p, 0):
return bad("NUL byte")
case strings.Contains(p, `\`):
return bad("backslash")
case strings.HasPrefix(p, "/"):
return bad("absolute")
case strings.Contains(p, ":"):
return bad("drive letter or scheme")
case strings.HasSuffix(p, "/"):
return bad("directory")
}
for _, seg := range strings.Split(p, "/") {
switch seg {
case "":
return bad("empty segment")
case ".", "..":
return bad("dot segment")
}
}
if path.Clean(p) != p {
return bad("not canonical")
}
return nil
}
// Join resolves ref relative to the directory of base, both virtual paths.
// Unlike ValidatePath it may use ".." segments, as long as the canonical
// result stays inside the root. This is for references found inside trusted
// asset content (CSS url(), @import), not for paths coming from the browser.
func Join(base, ref string) (string, error) {
if strings.ContainsAny(ref, "\\\x00") {
return "", fmt.Errorf("%w: %q", ErrInvalidPath, ref)
}
joined := path.Join(path.Dir(base), ref)
if joined == "." || joined == ".." || strings.HasPrefix(joined, "../") || strings.HasPrefix(joined, "/") {
return "", fmt.Errorf("%w: %q relative to %q leaves the asset root", ErrInvalidPath, ref, base)
}
if err := ValidatePath(joined); err != nil {
return "", err
}
return joined, nil
}
+272
View File
@@ -0,0 +1,272 @@
// Package assets resolves virtual asset paths against an ordered list of
// sources (embedded folder, ZIP, embedded ZIP, explicit directory root).
package assets
import (
"archive/zip"
"bytes"
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"strings"
)
// DefaultMaxSize bounds a single resolved resource (also the uncompressed
// budget for a ZIP entry).
const DefaultMaxSize = 32 << 20
// Resource is one resolved asset.
type Resource struct {
Name string // canonical virtual path
MIME string
Bytes []byte
Source string // name of the source that served it
}
// Source is one place assets can come from. Open must return an error
// wrapping fs.ErrNotExist for a missing file; any other error is a real
// failure and stops the lookup.
type Source interface {
Name() string
ReadFile(name string, max int64) ([]byte, error)
Close() error
}
// Resolver looks a path up in its sources in order. It falls back to the
// next source only on "not found".
type Resolver struct {
sources []Source
max int64
}
// NewResolver builds a resolver over sources (at least one).
func NewResolver(sources ...Source) (*Resolver, error) {
if len(sources) == 0 {
return nil, errors.New("assets: no sources configured")
}
return &Resolver{sources: sources, max: DefaultMaxSize}, nil
}
// Sources lists the source names in lookup order (for the diagnostic report).
func (r *Resolver) Sources() []string {
out := make([]string, len(r.sources))
for i, s := range r.sources {
out[i] = s.Name()
}
return out
}
// Resolve returns the resource for a canonical virtual path.
func (r *Resolver) Resolve(ctx context.Context, name string) (*Resource, error) {
if err := ValidatePath(name); err != nil {
return nil, err
}
for _, s := range r.sources {
if err := ctx.Err(); err != nil {
return nil, err
}
data, err := s.ReadFile(name, r.max)
if errors.Is(err, fs.ErrNotExist) {
continue
}
if err != nil {
return nil, fmt.Errorf("asset %q from %s: %w", name, s.Name(), err)
}
m, err := DetectMIME(name, data)
if err != nil {
return nil, fmt.Errorf("asset %q from %s: %w", name, s.Name(), err)
}
return &Resource{Name: name, MIME: m, Bytes: data, Source: s.Name()}, nil
}
return nil, fmt.Errorf("asset %q: %w (searched %s)", name, fs.ErrNotExist, strings.Join(r.Sources(), ", "))
}
// ResolveIn returns the resource from one named source only (diagnostics:
// "same bytes from every source").
func (r *Resolver) ResolveIn(name, source string) (*Resource, error) {
if err := ValidatePath(name); err != nil {
return nil, err
}
for _, s := range r.sources {
if s.Name() != source {
continue
}
data, err := s.ReadFile(name, r.max)
if err != nil {
return nil, err
}
m, err := DetectMIME(name, data)
if err != nil {
return nil, err
}
return &Resource{Name: name, MIME: m, Bytes: data, Source: s.Name()}, nil
}
return nil, fmt.Errorf("no source %q", source)
}
// Close closes all sources (ZIP archives, directory roots).
func (r *Resolver) Close() error {
var errs []error
for _, s := range r.sources {
errs = append(errs, s.Close())
}
return errors.Join(errs...)
}
func readLimited(rd io.Reader, max int64, name string) ([]byte, error) {
data, err := io.ReadAll(io.LimitReader(rd, max+1))
if err != nil {
return nil, err
}
if int64(len(data)) > max {
return nil, fmt.Errorf("%s exceeds size limit of %d bytes", name, max)
}
return data, nil
}
// --- fs.FS source (embed.FS, or any fs.FS) -------------------------------
type fsSource struct {
name string
fsys fs.FS
}
// NewFSSource wraps an fs.FS whose root is the asset root (for embed.FS use
// fs.Sub(efs, "assets") first).
func NewFSSource(name string, fsys fs.FS) Source { return &fsSource{name: name, fsys: fsys} }
func (s *fsSource) Name() string { return s.name }
func (s *fsSource) Close() error { return nil }
func (s *fsSource) ReadFile(name string, max int64) ([]byte, error) {
f, err := s.fsys.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return nil, err
}
if st.IsDir() {
return nil, fmt.Errorf("%s: %w (is a directory)", name, fs.ErrNotExist)
}
return readLimited(f, max, name)
}
// --- directory source ----------------------------------------------------
type dirSource struct {
name string
root *os.Root
}
// NewDirSource opens dir as an explicit asset root. os.Root keeps every
// lookup (including symlinks) inside dir.
func NewDirSource(dir string) (Source, error) {
root, err := os.OpenRoot(dir)
if err != nil {
return nil, fmt.Errorf("asset dir %s: %w", dir, err)
}
return &dirSource{name: "dir:" + dir, root: root}, nil
}
func (s *dirSource) Name() string { return s.name }
func (s *dirSource) Close() error { return s.root.Close() }
func (s *dirSource) ReadFile(name string, max int64) ([]byte, error) {
f, err := s.root.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return nil, err
}
if st.IsDir() {
return nil, fmt.Errorf("%s: %w (is a directory)", name, fs.ErrNotExist)
}
return readLimited(f, max, name)
}
// --- ZIP source ----------------------------------------------------------
type zipSource struct {
name string
zr *zip.Reader
prefix string
closer io.Closer
files map[string]*zip.File
}
// NewZipFileSource opens a ZIP file on disk (never extracted). prefix is the
// directory inside the archive that is the asset root ("" = archive root).
func NewZipFileSource(file, prefix string) (Source, error) {
rc, err := zip.OpenReader(file)
if err != nil {
return nil, fmt.Errorf("asset zip %s: %w", file, err)
}
s, err := newZipSource("zip:"+file, &rc.Reader, prefix, rc)
if err != nil {
rc.Close()
return nil, err
}
return s, nil
}
// NewZipBytesSource reads a ZIP held in memory (e.g. an embedded assets.zip).
func NewZipBytesSource(name string, data []byte, prefix string) (Source, error) {
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
return nil, fmt.Errorf("asset zip %s: %w", name, err)
}
return newZipSource(name, zr, prefix, nil)
}
func newZipSource(name string, zr *zip.Reader, prefix string, closer io.Closer) (*zipSource, error) {
if prefix != "" {
if err := ValidatePath(prefix); err != nil {
return nil, fmt.Errorf("zip root: %w", err)
}
prefix += "/"
}
s := &zipSource{name: name, zr: zr, prefix: prefix, closer: closer, files: map[string]*zip.File{}}
for _, f := range zr.File {
if !strings.HasPrefix(f.Name, prefix) || strings.HasSuffix(f.Name, "/") {
continue
}
rel := f.Name[len(prefix):]
// Entries with unsafe names ("../x", "/etc/x", "a\\b") are never
// reachable: they simply do not get an identity.
if ValidatePath(rel) != nil {
continue
}
s.files[rel] = f
}
return s, nil
}
func (s *zipSource) Name() string { return s.name }
func (s *zipSource) Close() error {
if s.closer != nil {
return s.closer.Close()
}
return nil
}
func (s *zipSource) ReadFile(name string, max int64) ([]byte, error) {
f, ok := s.files[name]
if !ok {
return nil, fmt.Errorf("%s: %w", name, fs.ErrNotExist)
}
if f.UncompressedSize64 > uint64(max) {
return nil, fmt.Errorf("%s: uncompressed size %d exceeds budget %d", name, f.UncompressedSize64, max)
}
rc, err := f.Open()
if err != nil {
return nil, err
}
defer rc.Close()
return readLimited(rc, max, name)
}
+219
View File
@@ -0,0 +1,219 @@
package assets
import (
"archive/zip"
"bytes"
"context"
"errors"
"io/fs"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"testing/fstest"
)
func TestValidatePath(t *testing.T) {
ok := []string{"a", "images/logo.png", "a/b/c.wasm", "%2e%2e/x", "dir.with.dots/f"}
bad := []string{"", "/abs", "../x", "a/../b", "./a", "a//b", "a/", `a\b`, "C:/x", "c:x", "a\x00b", "assets:x", ".."}
for _, p := range ok {
if err := ValidatePath(p); err != nil {
t.Errorf("ValidatePath(%q) = %v, want ok", p, err)
}
}
for _, p := range bad {
if err := ValidatePath(p); !errors.Is(err, ErrInvalidPath) {
t.Errorf("ValidatePath(%q) = %v, want ErrInvalidPath", p, err)
}
}
}
func TestFromRefBothForms(t *testing.T) {
for _, ref := range []string{"/assets/images/a.png", "assets:images/a.png", "/assets/images/a.png?v=1#x", "assets:images/a.png#frag"} {
got, err := FromRef(ref)
if err != nil || got != "images/a.png" {
t.Errorf("FromRef(%q) = %q, %v", ref, got, err)
}
}
for _, ref := range []string{"/other/x", "assets:../x", "/assets/", "/assets//etc/passwd"} {
if _, err := FromRef(ref); err == nil {
t.Errorf("FromRef(%q) accepted", ref)
}
}
}
func TestJoinRelativeInsideRoot(t *testing.T) {
cases := map[[2]string]string{
{"css/app.css", "../images/bg.png"}: "images/bg.png",
{"css/app.css", "fonts.css"}: "css/fonts.css",
{"css/a/b.css", "../../x.png"}: "x.png",
}
for in, want := range cases {
if got, err := Join(in[0], in[1]); err != nil || got != want {
t.Errorf("Join(%q,%q) = %q, %v; want %q", in[0], in[1], got, err, want)
}
}
for _, ref := range []string{"../../x.png", "../../../etc/passwd", `..\x`} {
if _, err := Join("css/app.css", ref); err == nil {
t.Errorf("Join escaped root with %q", ref)
}
}
}
func TestMIME(t *testing.T) {
want := map[string]string{
"a.css": "text/css", "a.js": "text/javascript", "a.svg": "image/svg+xml", "a.png": "image/png",
"a.ttf": "font/ttf", "a.woff2": "font/woff2", "a.json": "application/json", "a.ico": "image/x-icon",
}
for name, m := range want {
got, err := DetectMIME(name, []byte("x"))
if err != nil || BaseMIME(got) != m {
t.Errorf("%s: %q %v, want %s", name, got, err, m)
}
}
if m, err := DetectMIME("a.wasm", []byte("\x00asm\x01\x00\x00\x00")); err != nil || m != "application/wasm" {
t.Errorf("wasm: %q %v", m, err)
}
if _, err := DetectMIME("a.wasm", []byte("not wasm")); err == nil {
t.Error("fake .wasm accepted")
}
if m, _ := DetectMIME("noext", []byte("\x89PNG\r\n\x1a\n")); m != "image/png" {
t.Errorf("sniff fallback: %q", m)
}
}
func zipBytes(t *testing.T, files map[string]string) []byte {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for name, data := range files {
w, err := zw.Create(name)
if err != nil {
t.Fatal(err)
}
w.Write([]byte(data))
}
if err := zw.Close(); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
func TestAllSourcesSameIdentity(t *testing.T) {
files := map[string]string{"index.html": "<p>hi</p>", "wasm/a.wasm": "\x00asm\x01\x00\x00\x00", "css/app.css": "body{}"}
mfs := fstest.MapFS{}
dir := t.TempDir()
for name, data := range files {
mfs[name] = &fstest.MapFile{Data: []byte(data)}
os.MkdirAll(filepath.Join(dir, filepath.Dir(name)), 0o755)
os.WriteFile(filepath.Join(dir, name), []byte(data), 0o644)
}
zipPath := filepath.Join(t.TempDir(), "assets.zip")
os.WriteFile(zipPath, zipBytes(t, files), 0o644)
dirSrc, err := NewDirSource(dir)
if err != nil {
t.Fatal(err)
}
zipSrc, err := NewZipFileSource(zipPath, "")
if err != nil {
t.Fatal(err)
}
embZip, err := NewZipBytesSource("embedzip", zipBytes(t, files), "")
if err != nil {
t.Fatal(err)
}
for _, s := range []Source{NewFSSource("embed", mfs), dirSrc, zipSrc, embZip} {
r, _ := NewResolver(s)
for name, data := range files {
res, err := r.Resolve(context.Background(), name)
if err != nil || string(res.Bytes) != data || res.Source != s.Name() {
t.Errorf("%s %s: %v", s.Name(), name, err)
}
}
if err := r.Close(); err != nil {
t.Errorf("close %s: %v", s.Name(), err)
}
}
}
func TestFallbackOnlyOnNotFound(t *testing.T) {
first := fstest.MapFS{"a.txt": {Data: []byte("first")}}
second := fstest.MapFS{"a.txt": {Data: []byte("second")}, "b.txt": {Data: []byte("b")}}
r, _ := NewResolver(NewFSSource("one", first), NewFSSource("two", second))
if res, _ := r.Resolve(context.Background(), "a.txt"); string(res.Bytes) != "first" {
t.Error("override order not respected")
}
if res, _ := r.Resolve(context.Background(), "b.txt"); res.Source != "two" {
t.Error("no fallback on not-found")
}
if _, err := r.Resolve(context.Background(), "c.txt"); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("missing: %v", err)
}
// A real read error in the first source must not fall through.
boom := &errSource{err: errors.New("permission denied")}
r2, _ := NewResolver(boom, NewFSSource("two", second))
if _, err := r2.Resolve(context.Background(), "b.txt"); err == nil || !strings.Contains(err.Error(), "permission denied") {
t.Errorf("read error swallowed: %v", err)
}
}
type errSource struct{ err error }
func (e *errSource) Name() string { return "err" }
func (e *errSource) Close() error { return nil }
func (e *errSource) ReadFile(string, int64) ([]byte, error) { return nil, e.err }
func TestCorruptZipIsError(t *testing.T) {
p := filepath.Join(t.TempDir(), "bad.zip")
os.WriteFile(p, []byte("not a zip"), 0o644)
if _, err := NewZipFileSource(p, ""); err == nil {
t.Error("corrupt zip accepted")
}
}
func TestZipUnsafeNamesAndBudget(t *testing.T) {
data := zipBytes(t, map[string]string{"../evil.txt": "x", "/abs.txt": "x", `a\b.txt`: "x", "assets/ok.txt": "ok", "big.bin": strings.Repeat("x", 2048)})
s, err := NewZipBytesSource("z", data, "")
if err != nil {
t.Fatal(err)
}
for _, name := range []string{"evil.txt", "abs.txt"} {
if _, err := s.ReadFile(name, 1<<20); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("%s reachable: %v", name, err)
}
}
if _, err := s.ReadFile("big.bin", 1024); err == nil || !strings.Contains(err.Error(), "budget") {
t.Errorf("budget not enforced: %v", err)
}
// Explicit zip root for archives that contain an assets/ folder.
s2, _ := NewZipBytesSource("z", data, "assets")
if b, err := s2.ReadFile("ok.txt", 1024); err != nil || string(b) != "ok" {
t.Errorf("zip root: %q %v", b, err)
}
}
func TestDirSymlinkEscape(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("symlink creation needs privileges on Windows")
}
outside := t.TempDir()
os.WriteFile(filepath.Join(outside, "secret.txt"), []byte("secret"), 0o644)
root := t.TempDir()
if err := os.Symlink(filepath.Join(outside, "secret.txt"), filepath.Join(root, "link.txt")); err != nil {
t.Fatal(err)
}
if err := os.Symlink(outside, filepath.Join(root, "linkdir")); err != nil {
t.Fatal(err)
}
s, err := NewDirSource(root)
if err != nil {
t.Fatal(err)
}
defer s.Close()
for _, name := range []string{"link.txt", "linkdir/secret.txt"} {
if b, err := s.ReadFile(name, 1024); err == nil {
t.Errorf("%s escaped root: %q", name, b)
}
}
}