From 3492ecbe9b3eb9f0ccdd02c42c0bee6ef60a6a75 Mon Sep 17 00:00:00 2001 From: zhaoxing <2558691827@qq.com> Date: Thu, 19 Nov 2026 16:54:50 +0800 Subject: [PATCH] =?UTF-8?q?fix(site):=20=E6=8C=89=20Host=20=E6=B3=A8?= =?UTF-8?q?=E5=85=A5=E7=A7=9F=E6=88=B7=E6=A0=87=E9=A2=98=E4=B8=8E=20SEO=20?= =?UTF-8?q?=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + backend/.env.example | 3 + backend/internal/config/config.go | 19 +- backend/internal/router/router.go | 21 + backend/internal/storefrontshell/handler.go | 148 +++++++ .../internal/storefrontshell/handler_test.go | 321 +++++++++++++++ backend/internal/storefrontshell/shell.go | 382 ++++++++++++++++++ deploy/caddy/Caddyfile | 43 +- deploy/docker-compose.prod.yml | 5 + frontend/index.html | 4 +- frontend/public/site-bootstrap.js | 34 +- frontend/src/stores/distributionSite.ts | 15 +- 12 files changed, 969 insertions(+), 28 deletions(-) create mode 100644 backend/internal/storefrontshell/handler.go create mode 100644 backend/internal/storefrontshell/handler_test.go create mode 100644 backend/internal/storefrontshell/shell.go diff --git a/README.md b/README.md index adc082cd..f71ef91d 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,8 @@ - OCR sidecar:`http://127.0.0.1:18787`(仅本地回环地址,二维码群名识别使用) > 生产环境不使用上述端口:Caddy 按域名分流,主站和解忧商行后台分别通过各自经营域名进入,分销管理后台默认使用 `https://distribution.`,可由 `DISTRIBUTION_ADMIN_DOMAIN` 覆盖;平台运营统计后台使用 `OPS_DOMAIN`,未配置时默认 `https://ops.`(见 `deploy/caddy/Caddyfile`)。主站后台的「打开独立分销后台」与开通凭证通过构建期 `VITE_DISTRIBUTION_ADMIN_URL` 注入该地址;未配置时按 `DISTRIBUTION_ADMIN_DOMAIN` 推导。 +> +> 前台 HTML 的标题、图标和 SEO 信息由后端按 Host 注入:Caddy 只把 HTML 文档请求转发给后端,静态资源仍由 Caddy 托管;构建后的 `index.html` 通过仅容器内网的 `caddy:8081/__internal/storefront-shell.html` 提供给后端。后端对应配置为 `FRONTEND_SHELL_URL`,生产 compose 已默认注入;未配置时回退为静态 HTML。验证方式:`curl -s https://<经营域名>/ | grep ''`。 如需拆分调试,可手动执行: diff --git a/backend/.env.example b/backend/.env.example index 11c68eb2..bf479f8c 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -26,6 +26,9 @@ CADDY_DOMAIN= TENANT_JIEYOU_DOMAIN= OPS_DOMAIN=ops.localhost DISTRIBUTION_ADMIN_DOMAIN=distribution.localhost +# 生产由 compose 注入 Caddy 内网 shell 端点;本地开发留空。 +# 后端用它读取构建后的 index.html,按 Host 注入租户标题、图标和 SEO 信息。 +FRONTEND_SHELL_URL= # 本地 OCR sidecar;留空时回退到后台配置的远程 PaddleOCR API。 OCR_SERVICE_URL=http://127.0.0.1:18787 diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 0ac24ab5..fe108d81 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -29,14 +29,16 @@ type Config struct { TenantJieyouDomain string OpsDomain string DistributionAdminDomain string - Storage StorageConfig - StorageMirror StorageConfig - SMS SMSConfig - Realname RealnameConfig - Log LogConfig - RateLimit RateLimitConfig - Database DatabaseConfig - BackupStatusFile string + // FrontendShellURL 指向 Caddy 内网只读的构建后 index.html;后端据此按 Host 注入租户标题和 SEO 信息。 + FrontendShellURL string + Storage StorageConfig + StorageMirror StorageConfig + SMS SMSConfig + Realname RealnameConfig + Log LogConfig + RateLimit RateLimitConfig + Database DatabaseConfig + BackupStatusFile string } type StorageConfig struct { @@ -118,6 +120,7 @@ func Load() Config { getEnv("DISTRIBUTION_ADMIN_DOMAIN", ""), primaryDomain, ), + FrontendShellURL: strings.TrimSpace(getEnv("FRONTEND_SHELL_URL", "")), Storage: StorageConfig{ Endpoint: getEnv("STORAGE_ENDPOINT", "http://localhost:19090"), Bucket: getEnv("STORAGE_BUCKET", "hfb-sys"), diff --git a/backend/internal/router/router.go b/backend/internal/router/router.go index d92587e9..64dee90e 100644 --- a/backend/internal/router/router.go +++ b/backend/internal/router/router.go @@ -46,6 +46,7 @@ import ( "hfb_sys/backend/internal/modules/user" "hfb_sys/backend/internal/modules/wallet" "hfb_sys/backend/internal/modules/withdrawal" + "hfb_sys/backend/internal/storefrontshell" "hfb_sys/backend/internal/tenancy" _ "hfb_sys/backend/docs" // Swagger 文档 @@ -75,6 +76,16 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine { tenantHandler := tenancy.NewHandler() jwtManager := auth.NewJWTManager(cfg.JWTSecret) + // 前台 HTML 外壳:Caddy 只把 HTML 文档请求转发到这里,由后端按 Host + // 解析出的经营租户注入标题、图标和 SEO 信息。构建产物仍由 Caddy 托管, + // 后端通过内网 shell 端点读取,避免复制 asset hash 不一致的 index.html。 + var storefrontShellHandler *storefrontshell.Handler + if shellURL := strings.TrimSpace(cfg.FrontendShellURL); shellURL != "" { + storefrontShellHandler = storefrontshell.NewHandler(storefrontshell.NewProvider(shellURL, logger), logger) + } else if config.IsProductionEnv(cfg.AppEnv) && logger != nil { + logger.Warn("FRONTEND_SHELL_URL 未配置,前台 HTML 不会按租户注入标题和图标") + } + health := handler.NewHealthHandler(newReadinessChecks(deps)) engine.GET("/health", health.Live) engine.GET("/health/ready", health.Ready) @@ -1060,5 +1071,15 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine { } } + // SPA 兜底:只对 Caddy 转发来的 HTML 文档路径返回租户化外壳, + // 其余未匹配路径保持原有 404 行为。 + engine.NoRoute(func(c *gin.Context) { + if storefrontShellHandler != nil && storefrontshell.IsDocumentPath(c.Request.URL.Path) { + storefrontShellHandler.Serve(c) + return + } + c.String(http.StatusNotFound, "404 page not found") + }) + return engine } diff --git a/backend/internal/storefrontshell/handler.go b/backend/internal/storefrontshell/handler.go new file mode 100644 index 00000000..3674a900 --- /dev/null +++ b/backend/internal/storefrontshell/handler.go @@ -0,0 +1,148 @@ +package storefrontshell + +import ( + "context" + "net/http" + "strconv" + "strings" + + "hfb_sys/backend/internal/sitecode" + "hfb_sys/backend/internal/tenancy" + "hfb_sys/backend/pkg/response" + + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +type shellProvider interface { + Get(ctx context.Context) ([]byte, error) +} + +// Handler serves the SPA shell for extensionless document requests. Caddy +// routes only HTML document paths here; API and static asset paths stay on +// their existing handlers. +type Handler struct { + provider shellProvider + logger *zap.Logger +} + +func NewHandler(provider shellProvider, logger *zap.Logger) *Handler { + return &Handler{provider: provider, logger: logger} +} + +func (h *Handler) Serve(c *gin.Context) { + if h == nil || h.provider == nil || !IsDocumentPath(c.Request.URL.Path) { + response.NotFound(c, "页面不存在") + return + } + if c.Request.Method != http.MethodGet && c.Request.Method != http.MethodHead { + response.NotFound(c, "页面不存在") + return + } + + shell, err := h.provider.Get(c.Request.Context()) + if err != nil { + if h.logger != nil { + h.logger.Error("读取前台 HTML 模板失败", zap.Error(err)) + } + writeUnavailable(c) + return + } + + meta := MetaFromRequest(c) + page := Inject(shell, meta) + etag := ETag(meta, shell) + + c.Header("Cache-Control", "no-cache") + c.Header("Vary", "Host") + c.Header("ETag", etag) + if etagMatches(c.GetHeader("If-None-Match"), etag) { + c.Status(http.StatusNotModified) + c.Writer.WriteHeaderNow() + return + } + if c.Request.Method == http.MethodHead { + c.Header("Content-Type", "text/html; charset=utf-8") + c.Header("Content-Length", strconv.Itoa(len(page))) + c.Status(http.StatusOK) + c.Writer.WriteHeaderNow() + return + } + c.Data(http.StatusOK, "text/html; charset=utf-8", page) +} + +// IsDocumentPath guards the NoRoute handler. Caddy already filters document +// requests, but this keeps direct backend requests from turning API/static +// misses into HTML responses. +func IsDocumentPath(path string) bool { + if path == "" || path == "/" { + return true + } + for _, prefix := range []string{"/api", "/r", "/health", "/assets", "/swagger", "/docs"} { + if path == prefix || strings.HasPrefix(path, prefix+"/") { + return false + } + } + segment := path + if index := strings.LastIndex(path, "/"); index >= 0 { + segment = path[index+1:] + } + return !strings.Contains(segment, ".") +} + +func MetaFromRequest(c *gin.Context) Meta { + profile := map[string]any{} + tenantCode := "" + tenantName := "" + if scope, ok := tenancy.FromContext(c.Request.Context()); ok { + profile = scope.Profile() + tenantCode = scope.TenantCode + tenantName = scope.TenantName + } + + scheme := strings.TrimSpace(c.GetHeader("X-Forwarded-Proto")) + if scheme == "" { + if c.Request.TLS != nil { + scheme = "https" + } else { + scheme = "http" + } + } + host := sitecode.ExtractHost(c.Request.Host) + if host == "" { + host = c.Request.Host + } + path := c.Request.URL.EscapedPath() + if path == "" { + path = "/" + } + return BuildMeta(profile, tenantCode, tenantName, scheme, host, path) +} + +func etagMatches(header, etag string) bool { + for _, part := range strings.Split(header, ",") { + if strings.TrimSpace(part) == etag { + return true + } + } + return false +} + +const unavailablePage = `<!doctype html> +<html lang="zh-CN"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>页面暂时不可用 + + +

页面暂时不可用

+

请稍后刷新重试。

+ +` + +func writeUnavailable(c *gin.Context) { + c.Header("Cache-Control", "no-store") + c.Header("Retry-After", "3") + c.Data(http.StatusServiceUnavailable, "text/html; charset=utf-8", []byte(unavailablePage)) +} diff --git a/backend/internal/storefrontshell/handler_test.go b/backend/internal/storefrontshell/handler_test.go new file mode 100644 index 00000000..4a726ff1 --- /dev/null +++ b/backend/internal/storefrontshell/handler_test.go @@ -0,0 +1,321 @@ +package storefrontshell + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "hfb_sys/backend/internal/middleware" + "hfb_sys/backend/internal/tenancy" + + "github.com/gin-gonic/gin" + "go.uber.org/zap" + "gorm.io/datatypes" +) + +type fakeTenantResolver struct{} + +func (fakeTenantResolver) ResolveHost(_ context.Context, host string) (*tenancy.Scope, error) { + if strings.Contains(host, "zuhaox.com") { + return &tenancy.Scope{ + TenantID: 2, + TenantCode: "jieyou", + TenantName: "解忧商行", + TenantStatus: "active", + Host: host, + }, nil + } + return nil, nil +} + +func (fakeTenantResolver) ResolveCode(context.Context, string) (*tenancy.Scope, error) { + return nil, nil +} + +type staticProvider struct { + body []byte + err error +} + +func (p staticProvider) Get(context.Context) ([]byte, error) { + return p.body, p.err +} + +func TestBuildMetaJieyouFallbacks(t *testing.T) { + meta := BuildMeta(nil, "jieyou", "解忧商行", "https", "zuhaox.com", "/") + + if meta.Title != "解忧商行 - 官方租号平台" { + t.Fatalf("Title = %q", meta.Title) + } + if meta.FaviconURL != "/jieyou-favicon.svg" { + t.Fatalf("FaviconURL = %q", meta.FaviconURL) + } + if meta.AppleIconURL != "/jieyou-apple-touch-icon.png" { + t.Fatalf("AppleIconURL = %q", meta.AppleIconURL) + } + if meta.ThemeColor != "#a64332" { + t.Fatalf("ThemeColor = %q", meta.ThemeColor) + } + if meta.Canonical != "https://zuhaox.com/" { + t.Fatalf("Canonical = %q", meta.Canonical) + } +} + +func TestBuildMetaRejectsUnsafeAssetURL(t *testing.T) { + meta := BuildMeta(map[string]any{ + "site_name": "测试站", + "favicon_url": "javascript:alert(1)", + "logo_url": "data:text/html,", + }, "custom", "", "https", "example.com", "/") + + if meta.FaviconURL != "" { + t.Fatalf("FaviconURL = %q, want empty", meta.FaviconURL) + } + if meta.OGImageURL != "" { + t.Fatalf("OGImageURL = %q, want empty", meta.OGImageURL) + } +} + +func TestBuildMetaEscapesProfileValues(t *testing.T) { + meta := BuildMeta( + map[string]any{"site_name": ``}, + "custom", "", "https", "example.com", "/", + ) + block := meta.HTML(true) + + if strings.Contains(block, "`) + meta := BuildMeta(nil, "jieyou", "解忧商行", "https", "zuhaox.com", "/") + out := string(Inject(shell, meta)) + + if strings.Count(out, "") != 1 { + t.Fatalf("expected exactly one title tag, got: %s", out) + } + if !strings.Contains(out, "<title>解忧商行 - 官方租号平台") { + t.Fatalf("title was not replaced: %s", out) + } + if !strings.Contains(out, `name="description"`) { + t.Fatalf("description was not injected: %s", out) + } + shellMarker := strings.Index(out, `name="site-shell"`) + script := strings.Index(out, "site-bootstrap.js") + if shellMarker < 0 || script < 0 || shellMarker > script { + t.Fatalf("site-shell marker must appear before site-bootstrap.js: %s", out) + } +} + +func TestProviderRevalidatesWithETag(t *testing.T) { + requests := 0 + conditional := "" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + if r.Header.Get("If-None-Match") == `"v1"` { + conditional = r.Header.Get("If-None-Match") + w.WriteHeader(http.StatusNotModified) + return + } + w.Header().Set("ETag", `"v1"`) + _, _ = w.Write([]byte(`shell`)) + })) + defer server.Close() + + provider := NewProvider(server.URL, zap.NewNop()) + provider.ttl = 0 + + first, err := provider.Get(context.Background()) + if err != nil { + t.Fatalf("first Get: %v", err) + } + second, err := provider.Get(context.Background()) + if err != nil { + t.Fatalf("second Get: %v", err) + } + if string(first) != string(second) { + t.Fatalf("cached body changed: %q vs %q", first, second) + } + if requests != 2 { + t.Fatalf("requests = %d, want 2", requests) + } + if conditional != `"v1"` { + t.Fatalf("conditional header = %q", conditional) + } +} + +func TestHandlerServesTenantShell(t *testing.T) { + gin.SetMode(gin.TestMode) + handler := NewHandler(staticProvider{body: []byte( + `官方租号平台
`, + )}, zap.NewNop()) + + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + req := httptest.NewRequest(http.MethodGet, "http://zuhaox.com/listings/1", nil) + req.Header.Set("X-Forwarded-Proto", "https") + req = req.WithContext(tenancy.WithScope(req.Context(), tenancy.Scope{ + TenantID: 2, + TenantCode: "jieyou", + TenantName: "解忧商行", + ProfileJSON: datatypes.JSON([]byte(`{"site_name":"解忧商行"}`)), + })) + c.Request = req + + handler.Serve(c) + + if recorder.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", recorder.Code) + } + body := recorder.Body.String() + if !strings.Contains(body, "解忧商行 - 官方租号平台") { + t.Fatalf("body missing tenant title: %s", body) + } + if !strings.Contains(body, `href="/jieyou-apple-touch-icon.png"`) { + t.Fatalf("body missing tenant apple icon: %s", body) + } + if !strings.Contains(body, `rel="canonical" href="https://zuhaox.com/listings/1"`) { + t.Fatalf("body missing canonical: %s", body) + } + if got := recorder.Header().Get("Vary"); got != "Host" { + t.Fatalf("Vary = %q, want Host", got) + } + if got := recorder.Header().Get("Cache-Control"); got != "no-cache" { + t.Fatalf("Cache-Control = %q, want no-cache", got) + } + if got := recorder.Header().Get("ETag"); got == "" { + t.Fatal("ETag is empty") + } +} + +func TestHandlerSupportsConditionalRequest(t *testing.T) { + gin.SetMode(gin.TestMode) + handler := NewHandler(staticProvider{body: []byte( + `官方租号平台`, + )}, zap.NewNop()) + + first := httptest.NewRecorder() + firstContext, _ := gin.CreateTestContext(first) + firstRequest := httptest.NewRequest(http.MethodGet, "http://zuhaox.com/", nil) + firstRequest = firstRequest.WithContext(tenancy.WithScope(firstRequest.Context(), tenancy.Scope{ + TenantID: 2, + TenantCode: "jieyou", + TenantName: "解忧商行", + })) + firstContext.Request = firstRequest + handler.Serve(firstContext) + + etag := first.Header().Get("ETag") + if etag == "" { + t.Fatal("first response has no ETag") + } + + second := httptest.NewRecorder() + secondContext, _ := gin.CreateTestContext(second) + secondRequest := httptest.NewRequest(http.MethodGet, "http://zuhaox.com/", nil) + secondRequest.Header.Set("If-None-Match", etag) + secondRequest = secondRequest.WithContext(tenancy.WithScope(secondRequest.Context(), tenancy.Scope{ + TenantID: 2, + TenantCode: "jieyou", + TenantName: "解忧商行", + })) + secondContext.Request = secondRequest + handler.Serve(secondContext) + + if second.Code != http.StatusNotModified { + t.Fatalf("status = %d, want 304 (etag=%q responseETag=%q ifNoneMatch=%q)", second.Code, etag, second.Header().Get("ETag"), secondRequest.Header.Get("If-None-Match")) + } + if second.Body.Len() != 0 { + t.Fatalf("304 body = %q, want empty", second.Body.String()) + } +} + +func TestHandlerRejectsAPIPath(t *testing.T) { + gin.SetMode(gin.TestMode) + handler := NewHandler(staticProvider{body: []byte("")}, zap.NewNop()) + + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodGet, "http://zuhaox.com/api/unknown", nil) + + handler.Serve(c) + + if recorder.Code != http.StatusNotFound { + t.Fatalf("status = %d, want 404", recorder.Code) + } + if !strings.Contains(recorder.Header().Get("Content-Type"), "application/json") { + t.Fatalf("content type = %q, want JSON", recorder.Header().Get("Content-Type")) + } +} + +func TestHandlerReturnsUnavailableWhenShellFails(t *testing.T) { + gin.SetMode(gin.TestMode) + handler := NewHandler(staticProvider{err: context.DeadlineExceeded}, zap.NewNop()) + + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodGet, "http://zuhaox.com/", nil) + + handler.Serve(c) + + if recorder.Code != http.StatusServiceUnavailable { + t.Fatalf("status = %d, want 503", recorder.Code) + } + if !strings.Contains(recorder.Body.String(), "页面暂时不可用") { + t.Fatalf("body = %q", recorder.Body.String()) + } +} + +func TestNoRouteUsesTenantContext(t *testing.T) { + gin.SetMode(gin.TestMode) + engine := gin.New() + engine.Use(middleware.TenantContext(fakeTenantResolver{}, "production", zap.NewNop(), "dachui")) + handler := NewHandler(staticProvider{body: []byte( + `官方租号平台`, + )}, zap.NewNop()) + engine.NoRoute(handler.Serve) + + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodGet, "http://zuhaox.com/", nil) + request.Header.Set("X-Forwarded-Proto", "https") + engine.ServeHTTP(recorder, request) + + if recorder.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", recorder.Code) + } + if !strings.Contains(recorder.Body.String(), "解忧商行 - 官方租号平台") { + t.Fatalf("body missing tenant title: %s", recorder.Body.String()) + } +} diff --git a/backend/internal/storefrontshell/shell.go b/backend/internal/storefrontshell/shell.go new file mode 100644 index 00000000..929d247e --- /dev/null +++ b/backend/internal/storefrontshell/shell.go @@ -0,0 +1,382 @@ +// Package storefrontshell turns the built SPA index.html into a per-host HTML +// shell. Tenant names, icons and SEO tags are resolved on the server so that +// crawlers and link previews do not see the main-site brand on tenant domains. +package storefrontshell + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "html" + "io" + "net/http" + "regexp" + "strings" + "sync" + "time" + + "go.uber.org/zap" +) + +const ( + maxShellBytes = 2 << 20 + shellCacheTTL = 3 * time.Second +) + +var ( + shellPlaceholderPattern = regexp.MustCompile(`(?is)]*>`) + fallbackIconLinkPattern = regexp.MustCompile(`(?is)]*id=["']site-(?:apple-touch-)?icon["'][^>]*>\s*`) + titlePattern = regexp.MustCompile(`(?is).*?`) + headPattern = regexp.MustCompile(`(?is)]*>`) +) + +// Provider fetches and caches the built index.html from Caddy's internal +// storefront-shell endpoint. The endpoint serves the exact artifact that Caddy +// is serving, so asset hashes always stay in sync with the frontend build. +type Provider struct { + url string + client *http.Client + logger *zap.Logger + ttl time.Duration + + mu sync.RWMutex + body []byte + etag string + fetchedAt time.Time +} + +func NewProvider(url string, logger *zap.Logger) *Provider { + return &Provider{ + url: strings.TrimSpace(url), + client: &http.Client{Timeout: 3 * time.Second}, + logger: logger, + ttl: shellCacheTTL, + } +} + +func (p *Provider) Get(ctx context.Context) ([]byte, error) { + if p == nil || p.url == "" { + return nil, fmt.Errorf("storefront shell url is empty") + } + + p.mu.RLock() + body := append([]byte(nil), p.body...) + etag := p.etag + fetchedAt := p.fetchedAt + p.mu.RUnlock() + + if len(body) > 0 && time.Since(fetchedAt) < p.ttl { + return body, nil + } + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, p.url, nil) + if err != nil { + return nil, err + } + if etag != "" { + req.Header.Set("If-None-Match", etag) + } + + resp, err := p.client.Do(req) + if err != nil { + if len(body) > 0 { + p.warn("读取前台 HTML 模板失败,使用上次缓存", err) + return body, nil + } + return nil, err + } + defer resp.Body.Close() + + switch resp.StatusCode { + case http.StatusNotModified: + if len(body) == 0 { + return nil, fmt.Errorf("storefront shell returned 304 without cache") + } + p.mu.Lock() + p.fetchedAt = time.Now() + p.mu.Unlock() + return body, nil + case http.StatusOK: + data, readErr := io.ReadAll(io.LimitReader(resp.Body, maxShellBytes)) + if readErr != nil { + if len(body) > 0 { + p.warn("读取前台 HTML 模板失败,使用上次缓存", readErr) + return body, nil + } + return nil, readErr + } + if len(bytes.TrimSpace(data)) == 0 { + return nil, fmt.Errorf("storefront shell is empty") + } + p.mu.Lock() + p.body = data + p.etag = resp.Header.Get("ETag") + p.fetchedAt = time.Now() + p.mu.Unlock() + return data, nil + default: + if len(body) > 0 { + p.warn(fmt.Sprintf("读取前台 HTML 模板返回 %d,使用上次缓存", resp.StatusCode), nil) + return body, nil + } + return nil, fmt.Errorf("storefront shell status %d", resp.StatusCode) + } +} + +func (p *Provider) warn(message string, err error) { + if p.logger == nil { + return + } + if err != nil { + p.logger.Warn(message, zap.Error(err)) + return + } + p.logger.Warn(message) +} + +// Meta holds the tenant-specific values injected into the HTML shell. +type Meta struct { + SiteCode string + SiteName string + Title string + Description string + Canonical string + FaviconURL string + AppleIconURL string + ThemeColor string + OGImageURL string +} + +// BuildMeta derives SEO and brand metadata from the tenant profile. Missing +// profile fields fall back to the same defaults used by the SPA. +func BuildMeta(profile map[string]any, tenantCode, tenantName, scheme, host, path string) Meta { + if profile == nil { + profile = map[string]any{} + } + + siteName := firstNonEmpty(stringValue(profile, "site_name"), tenantName, "官方租号平台") + title := "官方租号平台" + if siteName != "" && !strings.Contains(siteName, "官方租号平台") { + title = siteName + " - 官方租号平台" + } else if siteName != "" { + title = siteName + } + + description := firstNonEmpty(stringValue(profile, "seo_description"), storefrontDescription(profile)) + if description == "" { + if siteName != "" && siteName != "官方租号平台" { + description = siteName + "官方租号平台,精选三角洲行动账号,逐号核验、独立订单与专属售后。" + } else { + description = "精选三角洲行动账号租赁平台,逐号核验、独立订单与专属售后。" + } + } + + favicon, appleIcon, themeColor := fallbackBrand(tenantCode) + favicon = safeAssetURL(firstNonEmpty(stringValue(profile, "favicon_url"), favicon)) + appleIcon = safeAssetURL(firstNonEmpty(stringValue(profile, "apple_touch_icon_url"), appleIcon)) + themeColor = firstNonEmpty(stringValue(profile, "theme_color"), themeColor) + + ogImage := safeAssetURL(firstNonEmpty(stringValue(profile, "og_image_url"), stringValue(profile, "logo_url"))) + ogImage = absoluteURL(scheme, host, ogImage) + + canonicalPath := path + if canonicalPath == "" { + canonicalPath = "/" + } + if !strings.HasPrefix(canonicalPath, "/") { + canonicalPath = "/" + canonicalPath + } + canonical := "" + if scheme != "" && host != "" { + canonical = scheme + "://" + host + canonicalPath + } + + return Meta{ + SiteCode: strings.TrimSpace(tenantCode), + SiteName: siteName, + Title: title, + Description: description, + Canonical: canonical, + FaviconURL: favicon, + AppleIconURL: appleIcon, + ThemeColor: themeColor, + OGImageURL: ogImage, + } +} + +func (m Meta) HTML(includeTitle bool) string { + var b strings.Builder + if includeTitle { + fmt.Fprintf(&b, "%s\n", html.EscapeString(m.Title)) + } + fmt.Fprintf(&b, ``+"\n") + fmt.Fprintf(&b, ``+"\n", html.EscapeString(m.SiteCode)) + fmt.Fprintf(&b, ``+"\n", html.EscapeString(m.SiteName)) + fmt.Fprintf(&b, ``+"\n", html.EscapeString(m.Description)) + fmt.Fprintf(&b, ``+"\n", html.EscapeString(m.ThemeColor)) + fmt.Fprintf(&b, ``+"\n") + fmt.Fprintf(&b, ``+"\n", html.EscapeString(m.SiteName)) + fmt.Fprintf(&b, ``+"\n", html.EscapeString(m.Title)) + fmt.Fprintf(&b, ``+"\n", html.EscapeString(m.Description)) + if m.Canonical != "" { + fmt.Fprintf(&b, ``+"\n", html.EscapeString(m.Canonical)) + fmt.Fprintf(&b, ``+"\n", html.EscapeString(m.Canonical)) + } + if m.OGImageURL != "" { + fmt.Fprintf(&b, ``+"\n", html.EscapeString(m.OGImageURL)) + } + fmt.Fprintf(&b, ``+"\n") + if m.FaviconURL != "" { + fmt.Fprintf(&b, ``+"\n", iconType(m.FaviconURL), html.EscapeString(m.FaviconURL)) + } + if m.AppleIconURL != "" { + fmt.Fprintf(&b, ``+"\n", html.EscapeString(m.AppleIconURL)) + } + return b.String() +} + +// Inject replaces the placeholder block in the built index.html. The title is +// always replaced separately so the fallback title does not become a duplicate +// tag when the server injects description, OG and icon metadata. +func Inject(shell []byte, meta Meta) []byte { + if len(shell) == 0 { + return shell + } + + out := fallbackIconLinkPattern.ReplaceAll(shell, nil) + if titlePattern.Match(out) { + out = titlePattern.ReplaceAll(out, []byte(""+html.EscapeString(meta.Title)+"")) + } + if loc := shellPlaceholderPattern.FindIndex(out); loc != nil { + block := []byte(meta.HTML(false)) + merged := make([]byte, 0, len(out)+len(block)) + merged = append(merged, out[:loc[0]]...) + merged = append(merged, block...) + merged = append(merged, out[loc[1]:]...) + return merged + } + if idx := bytes.Index(out, []byte("")); idx >= 0 { + extra := []byte(meta.HTML(false)) + // 旧版 HTML 没有占位块时,把注入内容放在 开头, + // 确保 site-bootstrap.js 执行前已经能看到 site-shell 标记。 + if head := headPattern.FindIndex(out); head != nil { + merged := make([]byte, 0, len(out)+len(extra)) + merged = append(merged, out[:head[1]]...) + merged = append(merged, extra...) + merged = append(merged, out[head[1]:]...) + return merged + } + merged := make([]byte, 0, len(out)+len(extra)) + merged = append(merged, out[:idx]...) + merged = append(merged, extra...) + merged = append(merged, out[idx:]...) + return merged + } + return out +} + +// ETag returns a stable validator for the rendered shell. It includes both the +// source shell and the tenant metadata so title/profile changes invalidate it. +func ETag(meta Meta, shell []byte) string { + sum := sha256.New() + _, _ = sum.Write(shell) + _, _ = sum.Write([]byte(meta.HTML(true))) + return `"` + hex.EncodeToString(sum.Sum(nil)[:16]) + `"` +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if trimmed := strings.TrimSpace(value); trimmed != "" { + return trimmed + } + } + return "" +} + +func stringValue(values map[string]any, key string) string { + if values == nil { + return "" + } + value, ok := values[key] + if !ok { + return "" + } + text, _ := value.(string) + return strings.TrimSpace(text) +} + +func storefrontDescription(profile map[string]any) string { + if profile == nil { + return "" + } + raw, ok := profile["storefront_text_json"] + if !ok { + return "" + } + switch value := raw.(type) { + case string: + var payload struct { + HeroDesc string `json:"hero_desc"` + } + if json.Unmarshal([]byte(value), &payload) == nil { + return strings.TrimSpace(payload.HeroDesc) + } + case map[string]any: + return stringValue(value, "hero_desc") + } + return "" +} + +func fallbackBrand(tenantCode string) (favicon, appleIcon, themeColor string) { + switch strings.ToLower(strings.TrimSpace(tenantCode)) { + case "jieyou": + return "/jieyou-favicon.svg", "/jieyou-apple-touch-icon.png", "#a64332" + case "dachui": + return "/apple-touch-icon.png", "/apple-touch-icon.png", "#ff6a00" + default: + return "/apple-touch-icon.png", "/apple-touch-icon.png", "#ff6a00" + } +} + +func iconType(url string) string { + path := strings.SplitN(url, "?", 2)[0] + if strings.HasSuffix(strings.ToLower(path), ".svg") { + return "image/svg+xml" + } + return "image/png" +} + +// safeAssetURL 只允许站内相对路径、http(s)、协议相对地址和 data:image。 +// 租户品牌字段来自后台,仍按不可信输入处理,避免 javascript: 等 URL 进入 head。 +func safeAssetURL(value string) string { + value = strings.TrimSpace(value) + if value == "" { + return "" + } + lower := strings.ToLower(value) + if strings.HasPrefix(value, "/") || + strings.HasPrefix(lower, "http://") || + strings.HasPrefix(lower, "https://") || + strings.HasPrefix(value, "//") || + strings.HasPrefix(lower, "data:image/") { + return value + } + return "" +} + +func absoluteURL(scheme, host, value string) string { + value = strings.TrimSpace(value) + if value == "" { + return "" + } + if strings.HasPrefix(value, "http://") || strings.HasPrefix(value, "https://") || strings.HasPrefix(value, "//") { + return value + } + if strings.HasPrefix(value, "/") && scheme != "" && host != "" { + return scheme + "://" + host + value + } + return value +} diff --git a/deploy/caddy/Caddyfile b/deploy/caddy/Caddyfile index 7a7e7cc4..f80811f7 100644 --- a/deploy/caddy/Caddyfile +++ b/deploy/caddy/Caddyfile @@ -86,6 +86,20 @@ respond 404 } + # /index.html 直接访问统一回到 /,避免拿到未注入租户信息的静态 HTML。 + redir /index.html / 308 + + # HTML 文档请求交给后端按 Host 注入租户品牌;静态资源仍由 Caddy 直接返回。 + @storefront_html { + not path /api /api/* /r /r/* /health /health/ready /assets /assets/* /site-bootstrap.js /apple-touch-icon.png /jieyou-favicon.svg /jieyou-apple-touch-icon.png /favicon.ico /robots.txt /sitemap.xml + not path_regexp "\.[A-Za-z0-9]{1,10}$" + } + handle @storefront_html { + reverse_proxy backend:8080 { + import backend_proxy + } + } + # 其余流量返回主站/分销前台前端静态资源。 handle { root * /srv/dist @@ -94,15 +108,32 @@ } } +# 仅容器内网访问:后端通过该端点读取构建后的 index.html, +# 用于按 Host 注入租户标题、图标和 SEO 信息。不要把 8081 映射到宿主机端口。 +:8081 { + handle /__internal/storefront-shell.html { + root * /srv/dist + rewrite * /index.html + header Cache-Control "no-store" + file_server + } + respond 404 +} + +# 后台 HTML 也由后端按 Host 注入品牌;/assets 等静态资源由 storefront 的最终 handle 返回。 +(admin_html) { + reverse_proxy backend:8080 { + import backend_proxy + } +} + # 主站与过渡子域名共享同一套配置:域名迁移期间新旧域名同时可访问, # 避免 DNS 缓存未生效导致部分用户打不开。迁移完成后可移除 h5.{$CADDY_DOMAIN}。 {$CADDY_DOMAIN}, h5.{$CADDY_DOMAIN} { - # 主站后台隐藏入口只在本域名提供静态资源;分销站点域名由 storefront 片段统一 404。 + # 主站后台隐藏入口只在本域名提供;HTML 由后端注入,静态资源仍由 storefront 返回。 @main_admin path {$ADMIN_BASE_PATH:/manage-7x9k2p} {$ADMIN_BASE_PATH:/manage-7x9k2p}/* handle @main_admin { - root * /srv/dist - try_files {path} /index.html - file_server + import admin_html } import storefront @@ -113,9 +144,7 @@ {$TENANT_JIEYOU_DOMAIN:tenant-jieyou.invalid} { @tenant_admin path {$ADMIN_BASE_PATH:/manage-7x9k2p} {$ADMIN_BASE_PATH:/manage-7x9k2p}/* handle @tenant_admin { - root * /srv/dist - try_files {path} /index.html - file_server + import admin_html } import storefront diff --git a/deploy/docker-compose.prod.yml b/deploy/docker-compose.prod.yml index 37d67337..54b88f8d 100644 --- a/deploy/docker-compose.prod.yml +++ b/deploy/docker-compose.prod.yml @@ -23,6 +23,9 @@ services: ports: - "80:80" - "443:443" + # 仅容器内网使用:后端通过该端口读取构建后的 index.html,不映射到宿主机。 + expose: + - "8081" volumes: - ./caddy/Caddyfile:/etc/caddy/Caddyfile:ro - ./caddy/conf.d:/etc/caddy/conf.d:ro @@ -113,6 +116,8 @@ services: TZ: Asia/Shanghai DISTRIBUTION_ADMIN_DOMAIN: ${DISTRIBUTION_ADMIN_DOMAIN:-distribution.${CADDY_DOMAIN}} OCR_SERVICE_URL: ${OCR_SERVICE_URL:-http://ocr:8787} + # 后端按 Host 注入前台 HTML 的租户品牌;该端点只在容器内网监听。 + FRONTEND_SHELL_URL: ${FRONTEND_SHELL_URL:-http://caddy:8081/__internal/storefront-shell.html} volumes: - ../backend/logs:/app/logs # 仅挂载备份状态摘要,后端无法读取备份文件、Docker socket 或 OSS 凭证文件。 diff --git a/frontend/index.html b/frontend/index.html index a74ea65a..89e38b8e 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -3,7 +3,9 @@ - 大锤商行 + 官方租号平台 + + diff --git a/frontend/public/site-bootstrap.js b/frontend/public/site-bootstrap.js index 1ef6d290..02f7b9b1 100644 --- a/frontend/public/site-bootstrap.js +++ b/frontend/public/site-bootstrap.js @@ -1,6 +1,10 @@ /* global document, URLSearchParams, window */ -(() => { +;(() => { + // 生产 HTML 已由后端按 Host 注入 title/meta/icon;已注入时不要重复覆盖。 + // 这里仅作为静态兜底,兼容缓存中的旧 HTML 和尚未接入后端注入的域名。 + if (document.querySelector('meta[name="site-shell"]')) return + const host = window.location.hostname.toLowerCase() const params = new URLSearchParams(window.location.search) const tenantHint = (params.get('tenant_code') || params.get('tenant') || '').toLowerCase() @@ -12,13 +16,25 @@ if (!isJieyou) return document.title = '解忧商行 - 官方租号平台' - const icon = document.getElementById('site-icon') - if (icon) { - icon.href = '/jieyou-favicon.svg' - icon.type = 'image/svg+xml' - } - const appleIcon = document.getElementById('site-apple-touch-icon') - if (appleIcon) { - appleIcon.href = '/jieyou-apple-touch-icon.png' + document.documentElement.dataset.siteBootstrap = 'jieyou' + + function applyIcon(id, rel, href, type) { + let link = document.getElementById(id) + if (!link) { + link = document.createElement('link') + link.id = id + link.rel = rel + document.head.appendChild(link) + } + link.href = href + if (type) link.type = type } + + applyIcon('site-icon', 'icon', '/jieyou-favicon.svg', 'image/svg+xml') + applyIcon( + 'site-apple-touch-icon', + 'apple-touch-icon', + '/jieyou-apple-touch-icon.png', + 'image/png' + ) })() diff --git a/frontend/src/stores/distributionSite.ts b/frontend/src/stores/distributionSite.ts index 9df5674f..f985b6e5 100644 --- a/frontend/src/stores/distributionSite.ts +++ b/frontend/src/stores/distributionSite.ts @@ -473,9 +473,18 @@ export const useDistributionSiteStore = defineStore('distributionSite', { sessionStorage.removeItem('hfb_site_name') localStorage.removeItem('hfb_site_code') localStorage.removeItem('hfb_site_name') - document.title = '大锤商行 - 官方租号平台' - this.faviconUrl = siteBrandFor('dachui').favicon - this.applyFavicon() + // 服务端注入或静态 bootstrap 已经给出正确品牌时,不要因为接口失败 + // 把经营租户域名回退成主站标题和图标。 + const serverInjected = + typeof document !== 'undefined' && + document.querySelector('meta[name="site-shell"]') !== null + const bootstrapped = + typeof document !== 'undefined' && Boolean(document.documentElement.dataset.siteBootstrap) + if (!serverInjected && !bootstrapped) { + document.title = '大锤商行 - 官方租号平台' + this.faviconUrl = siteBrandFor('dachui').favicon + this.applyFavicon() + } }, applyTenantContext(info: TenantSiteContext) {