package handler import ( "embed" "errors" "fmt" "html/template" "io/fs" "net/http" "path" "strconv" ) //go:embed chatpage/* var chatPageAssets embed.FS // ChatPageOptions configures the optional browser-based compatibility client. // AppID is a public route identifier; callers must never pass an auth token here. type ChatPageOptions struct { AppID string } // ChatPageHandler serves the self-contained browser client under /chat/. type ChatPageHandler struct { appID string page *template.Template assets fs.FS } // NewChatPageHandler constructs the optional chat page. Whether it is mounted // is intentionally left to application configuration. func NewChatPageHandler(options ChatPageOptions) (*ChatPageHandler, error) { if !validDashScopeAppID(options.AppID) { return nil, errors.New("chat page app ID is invalid") } pageTemplate, err := template.ParseFS(chatPageAssets, "chatpage/index.html") if err != nil { return nil, fmt.Errorf("parse embedded chat page: %w", err) } assets, err := fs.Sub(chatPageAssets, "chatpage") if err != nil { return nil, fmt.Errorf("open embedded chat page assets: %w", err) } return &ChatPageHandler{appID: options.AppID, page: pageTemplate, assets: assets}, nil } func (h *ChatPageHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.setSecurityHeaders(w) if r.Method != http.MethodGet && r.Method != http.MethodHead { w.Header().Set("Allow", http.MethodGet+", "+http.MethodHead) http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } switch r.URL.Path { case "/chat/": w.Header().Set("Content-Type", "text/html; charset=utf-8") if r.Method == http.MethodHead { w.WriteHeader(http.StatusOK) return } if err := h.page.ExecuteTemplate(w, "index.html", struct{ AppID string }{AppID: h.appID}); err != nil { http.Error(w, "chat page unavailable", http.StatusInternalServerError) } case "/chat/app.css", "/chat/app.js": name := path.Base(r.URL.Path) if name == "app.css" { w.Header().Set("Content-Type", "text/css; charset=utf-8") } else { w.Header().Set("Content-Type", "text/javascript; charset=utf-8") } content, err := fs.ReadFile(h.assets, name) if err != nil { http.NotFound(w, r) return } w.Header().Set("Content-Length", strconv.Itoa(len(content))) if r.Method == http.MethodGet { _, _ = w.Write(content) } default: http.NotFound(w, r) } } func (h *ChatPageHandler) setSecurityHeaders(w http.ResponseWriter) { w.Header().Set("Cache-Control", "no-store") w.Header().Set("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'") w.Header().Set("Cross-Origin-Opener-Policy", "same-origin") w.Header().Set("Cross-Origin-Resource-Policy", "same-origin") w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()") w.Header().Set("Referrer-Policy", "no-referrer") w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("X-Frame-Options", "DENY") }