Document engine redistribution requirements; exclude upstream engine assets and keep the viewer disabled by default.
140 lines
5.5 KiB
Go
140 lines
5.5 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httputil"
|
|
"net/url"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"pageswiki/internal/geckorelay"
|
|
)
|
|
|
|
const geckoAPI = feedsAPI + "browser/"
|
|
|
|
type geckoProxy struct {
|
|
origin *url.URL
|
|
key string
|
|
transport *http.Transport
|
|
}
|
|
|
|
func (s *Server) geckoConfig() *geckoProxy {
|
|
s.geckoOnce.Do(func() {
|
|
u, err := url.Parse(os.Getenv("PAGESWIKI_GECKO_RELAY"))
|
|
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
|
|
return
|
|
}
|
|
key, err := os.ReadFile(os.Getenv("PAGESWIKI_GECKO_KEY_FILE"))
|
|
if err != nil || len(strings.TrimSpace(string(key))) < 32 {
|
|
return
|
|
}
|
|
s.gecko = &geckoProxy{origin: u, key: strings.TrimSpace(string(key)), transport: &http.Transport{Proxy: nil, DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext, ResponseHeaderTimeout: 10 * time.Second, TLSHandshakeTimeout: 5 * time.Second, IdleConnTimeout: 30 * time.Second, MaxIdleConnsPerHost: 4}}
|
|
})
|
|
return s.gecko
|
|
}
|
|
|
|
func (s *Server) geckoAvailable(domain string) bool {
|
|
return s.systemExtensionEnabled(domain, "viewer.gecko") && s.geckoConfig() != nil
|
|
}
|
|
|
|
func geckoIsolation(w http.ResponseWriter) {
|
|
w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
|
|
w.Header().Set("Cross-Origin-Embedder-Policy", "require-corp")
|
|
w.Header().Set("Cross-Origin-Resource-Policy", "same-origin")
|
|
}
|
|
|
|
func (s *Server) handleFeedBrowser(w http.ResponseWriter, r *http.Request, domain, actor string, active bool) {
|
|
if !active || !s.geckoAvailable(domain) {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
if r.Method != "GET" || r.URL.RawQuery != "" {
|
|
http.Error(w, "invalid request", 400)
|
|
return
|
|
}
|
|
path := strings.TrimPrefix(r.URL.Path, geckoAPI)
|
|
switch path {
|
|
case "":
|
|
geckoIsolation(w)
|
|
w.Header().Set("Content-Security-Policy", "default-src 'none'; script-src 'self' blob: 'wasm-unsafe-eval'; worker-src 'self' blob:; connect-src 'self' data:; style-src 'self'; img-src 'self' data:; frame-ancestors 'self'; base-uri 'none'; form-action 'none'")
|
|
w.Header().Set("Referrer-Policy", "no-referrer")
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
io.WriteString(w, geckoShell)
|
|
return
|
|
case "assets/v0.0.1/gecko.js", "assets/v0.0.1/gecko.wasm.zst":
|
|
case "wisp/":
|
|
// WebSocket cookies alone are not CSRF protection.
|
|
if r.Header.Get("Origin") != externalURL(r, "") || !strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
|
|
http.Error(w, "forbidden", 403)
|
|
return
|
|
}
|
|
default:
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
cfg := s.geckoConfig()
|
|
ctx, cancel := context.WithCancel(r.Context())
|
|
defer cancel()
|
|
if path == "wisp/" {
|
|
token := s.authTokenFromRequest(r)
|
|
go func() {
|
|
ticker := time.NewTicker(5 * time.Second)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
p, err := s.store.PrincipalForSession(domain, token)
|
|
if err != nil || p.UUID != actor || p.State != "active" || !s.systemExtensionEnabled(domain, "organizer.feeds") || !s.geckoAvailable(domain) {
|
|
cancel()
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
proxy := &httputil.ReverseProxy{Transport: cfg.transport, Rewrite: func(p *httputil.ProxyRequest) {
|
|
p.SetURL(cfg.origin)
|
|
p.Out.URL.Path = "/" + path
|
|
p.Out.URL.RawPath = ""
|
|
// No ambient credentials, forwarding headers, target URL or user-supplied
|
|
// grant crosses this boundary. The relay origin is operator-configured.
|
|
keep := http.Header{}
|
|
for _, h := range []string{"Upgrade", "Connection", "Sec-WebSocket-Key", "Sec-WebSocket-Version", "Origin", "Range", "If-None-Match", "If-Modified-Since"} {
|
|
if value := p.Out.Header.Get(h); value != "" {
|
|
keep.Set(h, value)
|
|
}
|
|
}
|
|
keep.Set(geckorelay.GrantHeader, geckorelay.Sign(cfg.key, geckorelay.Grant{Subject: domain + ":" + actor, Nonce: randomURLToken(24), Expires: time.Now().Add(30 * time.Second).Unix()}))
|
|
p.Out.Header = keep
|
|
}, ModifyResponse: func(resp *http.Response) error {
|
|
resp.Header.Del("Set-Cookie")
|
|
resp.Header.Set("Cross-Origin-Resource-Policy", "same-origin")
|
|
if resp.Header.Get("Cache-Control") == "" {
|
|
resp.Header.Set("Cache-Control", "private, no-store")
|
|
}
|
|
return nil
|
|
}, ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
|
|
w.Header().Set("Cache-Control", "private, no-store")
|
|
http.Error(w, "browser relay unavailable", http.StatusBadGateway)
|
|
}}
|
|
// ReverseProxy adds upstream headers rather than replacing existing values.
|
|
// Do not accidentally append the RSS API's no-store to versioned assets.
|
|
w.Header().Del("Cache-Control")
|
|
proxy.ServeHTTP(w, r.WithContext(ctx))
|
|
}
|
|
|
|
const geckoShell = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="/static/css/feed-gecko.css?v=1"><title>Gecko</title></head><body><p id="status" role="status"></p><canvas id="screen" tabindex="0" aria-label="Original article"></canvas><script type="module" src="/static/js/feed-gecko.js?v=1"></script></body></html>`
|
|
|
|
func init() {
|
|
translations["en"]["feeds.gecko"] = "Gecko RSS browser (experimental)"
|
|
translations["ja"]["feeds.gecko"] = "Gecko RSSブラウザ(実験的)"
|
|
translations["en"]["feeds.gecko_help"] = "Requires a separately deployed authenticated relay. Public HTTP/HTTPS only; browsing uses the relay's IP address."
|
|
translations["ja"]["feeds.gecko_help"] = "認証付き中継サービスの別途配置が必要です。公開HTTP/HTTPSのみ。閲覧先には中継サーバーのIPが使われます。"
|
|
}
|