| 1 | package mobilelink |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "crypto/sha256" |
| 7 | "crypto/subtle" |
| 8 | "encoding/base64" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "io/fs" |
| 12 | "net/http" |
| 13 | "net/url" |
| 14 | "os" |
| 15 | "strings" |
| 16 | "sync" |
| 17 | "time" |
| 18 | ) |
| 19 | |
| 20 | const bootstrapJS = `(async()=>{try { |
| 21 | const destination=new URLSearchParams(location.search).get("page")==="archived"?"/?page=archived":"/"; |
| 22 | const token=location.hash.slice(1); history.replaceState(null,"",location.pathname); |
| 23 | const res=await fetch("/link-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token})}); |
| 24 | if (!res.ok) throw Error(); location.replace(destination); |
| 25 | }catch{document.body.textContent="连接入口已失效,请使用本机新生成的入口。";}})();` |
| 26 | |
| 27 | type Browser struct { |
| 28 | mu sync.Mutex |
| 29 | origin *url.URL |
| 30 | launch [32]byte |
| 31 | launchTTL time.Time |
| 32 | cookie string |
| 33 | root *os.Root |
| 34 | api http.Handler |
| 35 | } |
| 36 | |
| 37 | func randomToken() string { |
| 38 | b := make([]byte, 32) |
| 39 | _, _ = rand.Read(b) |
| 40 | return base64.RawURLEncoding.EncodeToString(b) |
| 41 | } |
| 42 | |
| 43 | type OperationClient interface { |
| 44 | Do(context.Context, string, string, []byte) (*Reply, error) |
| 45 | } |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | func NewBrowser(origin, directory string, client OperationClient) (browser *Browser, launchURL string, err error) { |
| 51 | u, err := url.Parse(origin) |
| 52 | if err != nil || u.Scheme != "http" || !loopback(u.Hostname()) || !explicitPort(u) || u.User != nil || |
| 53 | u.Path != "" || u.Fragment != "" || u.RawQuery != "" || u.ForceQuery || client == nil { |
| 54 | return nil, "", errors.New("local UI requires a loopback origin and a connected peer") |
| 55 | } |
| 56 | root, err := os.OpenRoot(directory) |
| 57 | if err != nil { |
| 58 | return nil, "", errors.New("cannot open local mobile build directory") |
| 59 | } |
| 60 | if info, err := root.Stat("mobile.html"); err != nil || !info.Mode().IsRegular() { |
| 61 | root.Close() |
| 62 | return nil, "", errors.New("build directory must contain mobile.html") |
| 63 | } |
| 64 | token := randomToken() |
| 65 | b := &Browser{origin: u, root: root, api: operations(client.Do), launch: sha256.Sum256([]byte(token)), launchTTL: time.Now().Add(2 * time.Minute), cookie: randomToken()} |
| 66 | return b, origin + "/link-bootstrap#" + token, nil |
| 67 | } |
| 68 | |
| 69 | func (b *Browser) Close() error { return b.root.Close() } |
| 70 | |
| 71 | func (b *Browser) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 72 | w.Header().Set("Cache-Control", "no-store") |
| 73 | w.Header().Set("Referrer-Policy", "no-referrer") |
| 74 | w.Header().Set("X-Content-Type-Options", "nosniff") |
| 75 | w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'") |
| 76 | if r.Host != b.origin.Host || (r.Header.Get("Origin") != "" && r.Header.Get("Origin") != b.origin.String()) || |
| 77 | (r.Method != http.MethodGet && r.Header.Get("Origin") != b.origin.String()) || r.URL.RawPath != "" { |
| 78 | http.Error(w, "origin refused", http.StatusForbidden) |
| 79 | return |
| 80 | } |
| 81 | if r.Method == http.MethodGet && (r.URL.RawQuery == "" || (r.URL.Path == "/link-bootstrap" && r.URL.RawQuery == "page=archived")) { |
| 82 | switch r.URL.Path { |
| 83 | case "/link-bootstrap": |
| 84 | w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 85 | _, _ = w.Write([]byte(`<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>Cage</title><body>正在连接 Cage…<script src="/link-bootstrap.js"></script></body></html>`)) |
| 86 | return |
| 87 | case "/link-bootstrap.js": |
| 88 | w.Header().Set("Content-Type", "text/javascript; charset=utf-8") |
| 89 | _, _ = w.Write([]byte(bootstrapJS)) |
| 90 | return |
| 91 | } |
| 92 | } |
| 93 | name := "cage_mobile_link_" + b.origin.Port() |
| 94 | if r.Method == http.MethodPost && r.URL.Path == "/link-session" && r.URL.RawQuery == "" { |
| 95 | var in struct{ Token string } |
| 96 | data, err := limited(r.Body, 512) |
| 97 | if err != nil || json.Unmarshal(data, &in) != nil { |
| 98 | http.Error(w, "invalid entry", http.StatusBadRequest) |
| 99 | return |
| 100 | } |
| 101 | digest := sha256.Sum256([]byte(in.Token)) |
| 102 | b.mu.Lock() |
| 103 | valid := time.Now().Before(b.launchTTL) && subtle.ConstantTimeCompare(digest[:], b.launch[:]) == 1 |
| 104 | if valid { |
| 105 | b.launchTTL = time.Time{} |
| 106 | clear(b.launch[:]) |
| 107 | } |
| 108 | b.mu.Unlock() |
| 109 | if !valid { |
| 110 | http.Error(w, "entry expired", http.StatusUnauthorized) |
| 111 | return |
| 112 | } |
| 113 | http.SetCookie(w, &http.Cookie{Name: name, Value: b.cookie, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode}) |
| 114 | w.WriteHeader(http.StatusNoContent) |
| 115 | return |
| 116 | } |
| 117 | cookie, err := r.Cookie(name) |
| 118 | if err != nil || subtle.ConstantTimeCompare([]byte(cookie.Value), []byte(b.cookie)) != 1 { |
| 119 | http.Error(w, "open the private local launch file", http.StatusUnauthorized) |
| 120 | return |
| 121 | } |
| 122 | if strings.HasPrefix(r.URL.Path, "/api/") { |
| 123 | b.api.ServeHTTP(w, r) |
| 124 | return |
| 125 | } |
| 126 | if r.Method != http.MethodGet { |
| 127 | http.NotFound(w, r) |
| 128 | return |
| 129 | } |
| 130 | file := strings.TrimPrefix(r.URL.Path, "/") |
| 131 | if file == "" { |
| 132 | file = "mobile.html" |
| 133 | } |
| 134 | if (file != "mobile.html" && !strings.HasPrefix(file, "assets/")) || !fs.ValidPath(file) || strings.Contains(file, "\\") { |
| 135 | http.NotFound(w, r) |
| 136 | return |
| 137 | } |
| 138 | f, err := b.root.Open(file) |
| 139 | if err != nil { |
| 140 | http.NotFound(w, r) |
| 141 | return |
| 142 | } |
| 143 | defer f.Close() |
| 144 | info, err := f.Stat() |
| 145 | if err != nil || !info.Mode().IsRegular() { |
| 146 | http.NotFound(w, r) |
| 147 | return |
| 148 | } |
| 149 | http.ServeContent(w, r, info.Name(), info.ModTime(), f) |
| 150 | } |