383 lines
11 KiB
Go
383 lines
11 KiB
Go
// 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)<meta\s+name=["']site-shell-placeholder["'][^>]*>`)
|
|
fallbackIconLinkPattern = regexp.MustCompile(`(?is)<link\s+[^>]*id=["']site-(?:apple-touch-)?icon["'][^>]*>\s*`)
|
|
titlePattern = regexp.MustCompile(`(?is)<title>.*?</title>`)
|
|
headPattern = regexp.MustCompile(`(?is)<head[^>]*>`)
|
|
)
|
|
|
|
// 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, "<title>%s</title>\n", html.EscapeString(m.Title))
|
|
}
|
|
fmt.Fprintf(&b, `<meta name="site-shell" content="server" />`+"\n")
|
|
fmt.Fprintf(&b, `<meta name="site-code" content="%s" />`+"\n", html.EscapeString(m.SiteCode))
|
|
fmt.Fprintf(&b, `<meta name="site-name" content="%s" />`+"\n", html.EscapeString(m.SiteName))
|
|
fmt.Fprintf(&b, `<meta name="description" content="%s" />`+"\n", html.EscapeString(m.Description))
|
|
fmt.Fprintf(&b, `<meta name="theme-color" content="%s" />`+"\n", html.EscapeString(m.ThemeColor))
|
|
fmt.Fprintf(&b, `<meta property="og:type" content="website" />`+"\n")
|
|
fmt.Fprintf(&b, `<meta property="og:site_name" content="%s" />`+"\n", html.EscapeString(m.SiteName))
|
|
fmt.Fprintf(&b, `<meta property="og:title" content="%s" />`+"\n", html.EscapeString(m.Title))
|
|
fmt.Fprintf(&b, `<meta property="og:description" content="%s" />`+"\n", html.EscapeString(m.Description))
|
|
if m.Canonical != "" {
|
|
fmt.Fprintf(&b, `<meta property="og:url" content="%s" />`+"\n", html.EscapeString(m.Canonical))
|
|
fmt.Fprintf(&b, `<link rel="canonical" href="%s" />`+"\n", html.EscapeString(m.Canonical))
|
|
}
|
|
if m.OGImageURL != "" {
|
|
fmt.Fprintf(&b, `<meta property="og:image" content="%s" />`+"\n", html.EscapeString(m.OGImageURL))
|
|
}
|
|
fmt.Fprintf(&b, `<meta name="twitter:card" content="summary" />`+"\n")
|
|
if m.FaviconURL != "" {
|
|
fmt.Fprintf(&b, `<link id="site-icon" rel="icon" type="%s" href="%s" />`+"\n", iconType(m.FaviconURL), html.EscapeString(m.FaviconURL))
|
|
}
|
|
if m.AppleIconURL != "" {
|
|
fmt.Fprintf(&b, `<link id="site-apple-touch-icon" rel="apple-touch-icon" href="%s" />`+"\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("<title>"+html.EscapeString(meta.Title)+"</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("</head>")); idx >= 0 {
|
|
extra := []byte(meta.HTML(false))
|
|
// 旧版 HTML 没有占位块时,把注入内容放在 <head> 开头,
|
|
// 确保 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
|
|
}
|