Compare commits

...

2 Commits

Author SHA1 Message Date
姚章浩 4cb5110845 fix(version-history): 页面链接改走公网 origin(抓取仍走内网)+ tag 补链接
build / build (push) Successful in 1m1s
现象(主人反馈):点「查看提交」打开是空白页。原因:链接用的是**抓取用的内网地址**
(`http://192.168.50.223:3000/...`),内网外的浏览器到不了;而公网地址
`https://gitea.zheromiku.top/...` 实测 200。另外 tag 证据里**根本没有 url**,
页面渲染出空 `href`,点下去像"没反应"。

修复:

- 新增 `VERSION_HISTORY_LINK_ORIGIN`(页面链接 origin,公网;留空 = 与抓取 origin 相同):
  抓取仍匿名走内网白名单地址,**给人点的链接**用公网 origin 拼 —— 两者本就不该共用一个地址;
  校验必须是干净的 http(s) 绝对地址。
- tag 证据补 `url`(`<link origin>/<repo>/src/tag/<name>`),并在前端**没有链接就不渲染**该按钮。
- 测试:客户端(LinkOrigin 生效 / 未配时退回 / 非法拒绝)、规则(tag 链接写入证据 / 无基址不编链接)、
  前端(有链接才渲染「查看 tag」)。

验证:make verify 15/15;真实链路重同步后库里 commit_url = `https://gitea.zheromiku.top/...`(200)、
release_tags 带 url。
2026-10-14 11:06:13 +08:00
姚章浩 90db243a68 fix(web): 旧 index.html 的哈希资源回退到「上一版构建」,页面不再空白/裸奔
build / build (push) Successful in 56s
现象(主人反馈:页面**偶尔**变成"只有文字没样式"):旧入口 index.html 引用的是上一版的
`index-CddbQIqQ.js` / `index-DLg1Y9tN.css`,而新镜像里只剩当次构建的两个文件
⇒ JS 404 白屏、CSS 404 只有文字没样式。触发条件是"短时间内多次重建 web + CDN/浏览器还拿着旧入口"。

修复(三层,各管一段):

1. **入口不缓存**(上一笔已做):`index.html` → `no-cache, must-revalidate`,CDN/浏览器每次回源校验;
2. **旧哈希资源仍可取**(本笔):`/assets/` 未命中时先回退到只读挂载的
   `deploy/legacy-assets/assets`(**上一版构建**的资源),再 404 ⇒ 还持有旧入口的客户端
   不会因为一个文件 404 而白屏/裸奔;该目录由 `scripts/deploy-api-web.sh` 在**每次重建前**
   从"正在运行的那个镜像"里落盘(`LEGACY_ASSETS=` 会打在部署日志里),并加进 .gitignore;
3. **未命中不再回退成 HTML**:避免浏览器把 index.html 当 JS 执行报一堆语法错误。

验证:旧入口的两个引用 `assets/index-CddbQIqQ.js`、`assets/index-DLg1Y9tN.css` 现在都是 200
(旧客户端可用);当前入口的 `assets/index-Dbnd-DW-.js`、`assets/index-Bgkt4A1i.css` 也是 200;
不存在的文件名仍明确 404;`nginx -t` 通过;本机 8088 与公网入口 kg.zheromiku.top 一致;make verify 15/15。
2026-10-14 10:58:01 +08:00
16 changed files with 155 additions and 16 deletions
+3
View File
@@ -35,5 +35,8 @@ TEST_ACCEPTANCE_POLICY_VERSION=structural-v1
VERSION_HISTORY_GITEA_BASE_URL=
VERSION_HISTORY_REPO=Weknora/knowledge-governance
VERSION_HISTORY_ALLOWED_ORIGINS=
# 页面上的「查看提交 / 查看 tag」链接用哪个 origin —— 抓取可以走内网,但链接必须能被
# **点它的人**打开(否则点开是空白)。留空 = 与上面的抓取地址相同。
VERSION_HISTORY_LINK_ORIGIN=https://gitea.zheromiku.top
VERSION_HISTORY_HTTP_TIMEOUT=15s
VERSION_HISTORY_MAX_PAGES=200
+2
View File
@@ -43,3 +43,5 @@ backups/
.ci-remote-tags
.ci-commits-count
.ci-preview-url
# 上一版构建的静态资源(部署脚本落盘、只读挂载的运行时目录,不进 git)
deploy/legacy-assets/
+5 -1
View File
@@ -11,7 +11,11 @@
### Fixed
- 前端入口的缓存策略:`index.html` 此前没有缓存头,CDN/浏览器会启发式缓存它,于是**页面会一直停在旧构建上**(实测被腾讯云 EdgeOne 卡住:源站已是新包,公网入口仍发旧包,看起来像"新菜单/新页面没上线")。现在 `index.html` 每次回源校验(`no-cache, must-revalidate`)、带内容哈希的 `/assets/` 长缓存(`immutable`),旧哈希资源明确 404 而不是回退成 HTML。
- 前端入口与静态资源的缓存语义("新功能看起来没上线"与"页面偶尔裸奔/空白"的根因):
- `index.html` 此前**没有缓存头**,CDN/浏览器按启发式缓存它 ⇒ 页面会一直停在旧构建上(实测被腾讯云 EdgeOne 卡住:源站已是新包,公网入口仍发旧包)。现在 `index.html` 每次回源校验(`no-cache, must-revalidate`);
- 带内容哈希的 `/assets/` 长缓存(`immutable`),但**未命中时先回退到"上一版构建的资源"目录、再 404**(`deploy/legacy-assets` 由部署脚本在每次重建前落盘并只读挂载):CDN/浏览器仍持有旧 `index.html` 时,它引用的旧 JS/CSS 依旧能取到 ⇒ 不会出现"JS 404 白屏"或"CSS 404 只有文字没样式";
- 明确 404 时不再回退成 `index.html`(否则浏览器把 HTML 当 JS 执行,报一堆语法错误)。
- 「版本记录」页的链接改为**抓取与链接分离**:抓取仍走配置的(内网)地址,页面上的「查看提交 / 查看 tag」用 `VERSION_HISTORY_LINK_ORIGIN`(公网 origin)拼 —— 原先两者共用内网地址,内网外的浏览器点开是空白;另外 tag 记录原先不带链接(空 `href` 点下去没反应),现在补上链接、没有链接就不渲染该按钮。
### Security
+1
View File
@@ -118,6 +118,7 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
client, err := versionhistory.NewGiteaClient(versionhistory.GiteaConfig{
BaseURL: config.VersionHistoryGiteaBaseURL,
AllowedBaseURLs: config.VersionHistoryAllowedOrigins,
LinkOrigin: config.VersionHistoryLinkOrigin,
Repo: config.VersionHistoryRepo,
Timeout: config.VersionHistoryHTTPTimeout,
})
+6
View File
@@ -45,6 +45,8 @@ services:
VERSION_HISTORY_GITEA_BASE_URL: "${VERSION_HISTORY_GITEA_BASE_URL:-}"
VERSION_HISTORY_REPO: "${VERSION_HISTORY_REPO:-Weknora/knowledge-governance}"
VERSION_HISTORY_ALLOWED_ORIGINS: "${VERSION_HISTORY_ALLOWED_ORIGINS:-}"
# 页面链接用的 origin(给内网外的浏览器点开);留空 = 与抓取 origin 相同。
VERSION_HISTORY_LINK_ORIGIN: "${VERSION_HISTORY_LINK_ORIGIN:-}"
VERSION_HISTORY_HTTP_TIMEOUT: "${VERSION_HISTORY_HTTP_TIMEOUT:-15s}"
VERSION_HISTORY_MAX_PAGES: "${VERSION_HISTORY_MAX_PAGES:-200}"
# P10 readiness probe reads the routing KB with the same scoped key.
@@ -211,6 +213,10 @@ services:
api:
condition: service_healthy
read_only: true
volumes:
# 上一版构建的静态资源(只读,由部署脚本落盘):CDN/浏览器可能还持有旧 index.html,
# 让它的旧哈希引用不至于 404 —— 否则页面会空白或"只有文字没样式"。
- ./deploy/legacy-assets:/usr/share/nginx/legacy:ro
tmpfs:
- /tmp
- /var/cache/nginx
+8
View File
@@ -30,6 +30,14 @@ server {
location /assets/ {
expires 1y;
add_header Cache-Control "public, max-age=31536000, immutable";
# 当前构建里没有再找**上一版构建**的资源:CDN/浏览器可能还持有旧 index.html,
# 它引用的旧哈希文件若直接 404,页面就会空白或"裸奔"(只有文字没样式)。
# 旧目录由部署脚本在每次重建前落盘(deploy/legacy-assets,只读挂载)。
try_files $uri @legacy;
}
location @legacy {
root /usr/share/nginx/legacy;
try_files $uri =404;
}
+11 -2
View File
@@ -67,8 +67,11 @@ type Config struct {
VersionHistoryGiteaBaseURL string
VersionHistoryRepo string
VersionHistoryAllowedOrigins []string
VersionHistoryHTTPTimeout time.Duration
VersionHistoryMaxPages int
// VersionHistoryLinkOrigin 是**页面链接**用的 origin(给内网外的浏览器点开),
// 留空即与抓取 origin 相同。只用于拼展示链接,不参与任何请求。
VersionHistoryLinkOrigin string
VersionHistoryHTTPTimeout time.Duration
VersionHistoryMaxPages int
}
func Load(getenv func(string) string) (Config, error) {
@@ -113,6 +116,7 @@ func Load(getenv func(string) string) (Config, error) {
VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")),
VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"),
VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")),
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
VersionHistoryHTTPTimeout: 15 * time.Second,
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
}
@@ -215,6 +219,11 @@ func Load(getenv func(string) string) (Config, error) {
if strings.Count(config.VersionHistoryRepo, "/") != 1 {
return Config{}, errors.New("VERSION_HISTORY_REPO 必须是 owner/name 形式")
}
if config.VersionHistoryLinkOrigin != "" {
if err := validateHTTPBaseURL(config.VersionHistoryLinkOrigin); err != nil {
return Config{}, fmt.Errorf("VERSION_HISTORY_LINK_ORIGIN: %w", err)
}
}
}
if config.TestWeKnoraHTTPTimeout, err = durationOrDefault(getenv("TEST_WEKNORA_HTTP_TIMEOUT"), config.TestWeKnoraHTTPTimeout); err != nil {
return Config{}, fmt.Errorf("TEST_WEKNORA_HTTP_TIMEOUT: %w", err)
+24 -6
View File
@@ -15,8 +15,12 @@ import (
// GiteaConfig 是只读客户端的配置。**只用匿名请求**:本客户端不会携带任何凭据,
// 也不接受调用方传入任意 URL —— base 必须在白名单里,仓库只允许配置的那一个。
type GiteaConfig struct {
BaseURL string
AllowedBaseURLs []string
BaseURL string
AllowedBaseURLs []string
// LinkOrigin 是**给人看的链接**用的 origin(例如公网 https://gitea.example)。
// 抓取用内网地址、点链接的人在内网外 —— 两者必须能分开,否则页面上的链接打不开。
// 留空则与 BaseURL 相同。它只用于拼展示链接,不参与任何请求。
LinkOrigin string
Repo string
HTTPClient *http.Client
Timeout time.Duration
@@ -29,6 +33,7 @@ type GiteaConfig struct {
// GiteaClient 只读地访问 Gitea 的提交、tag 与仓库内文件。
type GiteaClient struct {
baseURL *url.URL
linkOrigin string
repo string
client *http.Client
maxBytes int64
@@ -98,16 +103,29 @@ func NewGiteaClient(config GiteaConfig) (*GiteaClient, error) {
if sleep == nil {
sleep = time.Sleep
}
return &GiteaClient{baseURL: base, repo: repo, client: &sameHost, maxBytes: maxBytes,
maxRetries: retries, sleep: sleep, pageSize: pageSize}, nil
linkOrigin := strings.TrimRight(strings.TrimSpace(config.LinkOrigin), "/")
if linkOrigin == "" {
linkOrigin = strings.TrimRight(base.String(), "/")
} else if parsed, perr := url.Parse(linkOrigin); perr != nil || parsed.Host == "" ||
(parsed.Scheme != "http" && parsed.Scheme != "https") {
return nil, fmt.Errorf("版本记录:链接 origin %q 非法(必须是 http(s) 绝对地址)", config.LinkOrigin)
}
return &GiteaClient{baseURL: base, linkOrigin: linkOrigin, repo: repo, client: &sameHost,
maxBytes: maxBytes, maxRetries: retries, sleep: sleep, pageSize: pageSize}, nil
}
// PageSize 是抓取页大小(外层据此做完整性对账)。
func (c *GiteaClient) PageSize() int { return c.pageSize }
// CommitURLBase 给记录页拼提交链接用(白名单 origin + 固定仓库,不接受外部传入)。
// CommitURLBase 给记录页拼提交链接用(**给人看的** origin + 固定仓库,不接受外部传入)。
// 抓取走内网、链接走公网 —— 两者分开,页面上的链接才点得开。
func (c *GiteaClient) CommitURLBase() string {
return strings.TrimRight(c.baseURL.String(), "/") + "/" + c.repo + giteaCommitURLSuffix
return c.linkOrigin + "/" + c.repo + giteaCommitURLSuffix
}
// TagURLBase 给记录页拼 tag 链接用(`<link origin>/<repo>/src/tag/`)。
func (c *GiteaClient) TagURLBase() string {
return c.linkOrigin + "/" + c.repo + "/src/tag/"
}
func (c *GiteaClient) apiURL(path string, query url.Values) string {
+29
View File
@@ -28,6 +28,35 @@ func validConfig(base string) GiteaConfig {
Sleep: func(time.Duration) {}, MaxRetries: 2, PageSize: 50}
}
func TestGiteaClientUsesSeparateLinkOriginForHumanLinks(t *testing.T) {
// 抓取走内网、链接走公网:页面上的链接必须用公网 origin,否则点开是空白。
config := validConfig("http://192.168.50.223:3000")
config.LinkOrigin = "https://gitea.zheromiku.top/"
client, err := NewGiteaClient(config)
if err != nil {
t.Fatalf("构造客户端失败:%v", err)
}
if got := client.CommitURLBase(); got != "https://gitea.zheromiku.top/Weknora/knowledge-governance/commit/" {
t.Fatalf("提交链接基址 = %q(必须用公网 origin)", got)
}
if got := client.TagURLBase(); got != "https://gitea.zheromiku.top/Weknora/knowledge-governance/src/tag/" {
t.Fatalf("tag 链接基址 = %q", got)
}
// 不配 LinkOrigin ⇒ 退回抓取 origin(内网场景仍然一致)
fallback, err := NewGiteaClient(validConfig("http://192.168.50.223:3000"))
if err != nil {
t.Fatalf("构造客户端失败:%v", err)
}
if !strings.HasPrefix(fallback.CommitURLBase(), "http://192.168.50.223:3000/") {
t.Fatalf("未配 LinkOrigin 时应退回抓取 origin:%q", fallback.CommitURLBase())
}
bad := validConfig("http://192.168.50.223:3000")
bad.LinkOrigin = "ftp://nope"
if _, err := NewGiteaClient(bad); err == nil {
t.Fatal("非 http(s) 的链接 origin 必须拒绝")
}
}
func TestGiteaClientRejectsNonWhitelistedOriginAndBadRepo(t *testing.T) {
if _, err := NewGiteaClient(GiteaConfig{BaseURL: "http://evil.example.com",
AllowedBaseURLs: []string{"http://192.168.50.223:3000"}, Repo: "a/b"}); err == nil {
+6 -1
View File
@@ -38,6 +38,7 @@ type ChangelogSource func(sha string) (string, error)
type DeriveInput struct {
RepoKey string
CommitURLBase string // 形如 "<origin>/<owner>/<repo>/commit/",由配置拼好,不接受外部传入
TagURLBase string // 形如 "<origin>/<owner>/<repo>/src/tag/";空则不下发 tag 链接
Commits []RawCommit
Tags []RawTag
Changelog ChangelogSource
@@ -156,8 +157,12 @@ func DeriveVersions(in DeriveInput) DeriveResult {
evidenceTags := make([]governance.VersionTagEvidence, 0, len(tagsByTarget[commit.SHA]))
for _, tag := range tagsByTarget[commit.SHA] {
url := ""
if in.TagURLBase != "" {
url = in.TagURLBase + tag.Name
}
evidenceTags = append(evidenceTags, governance.VersionTagEvidence{
Name: tag.Name, TagSHA: tag.TagSHA, Annotated: tag.Annotated})
Name: tag.Name, TagSHA: tag.TagSHA, Annotated: tag.Annotated, URL: url})
}
sort.Slice(evidenceTags, func(i, j int) bool { return evidenceTags[i].Name < evidenceTags[j].Name })
+19
View File
@@ -177,6 +177,25 @@ func TestDeriveVersionsPicksUpTagAddedAfterwards(t *testing.T) {
}
}
func TestDeriveVersionsFillsTagLinksForHumans(t *testing.T) {
commits := []RawCommit{commit("A", nil, 1)}
tags := []RawTag{{Name: "v0.1.0", TargetSHA: "A", Annotated: true}}
derived := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits, Tags: tags,
CommitURLBase: "https://gitea.example/o/r/commit/",
TagURLBase: "https://gitea.example/o/r/src/tag/",
Changelog: readerFor(map[string]string{"A": "0.1.0"})})
record := find(t, derived.Records, "A")
if len(record.ReleaseTags) != 1 || record.ReleaseTags[0].URL != "https://gitea.example/o/r/src/tag/v0.1.0" {
t.Fatalf("tag 必须带可点的链接:%+v", record.ReleaseTags)
}
// 不给 TagURLBase ⇒ 不下发链接(页面据此不渲染空的 tag 链接)
bare := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits, Tags: tags,
Changelog: readerFor(map[string]string{"A": "0.1.0"})})
if url := find(t, bare.Records, "A").ReleaseTags[0].URL; url != "" {
t.Fatalf("没有基址时不该编链接:%q", url)
}
}
func TestDeriveVersionsSortsDeterministicallyForPaging(t *testing.T) {
sameTime := at(9)
commits := []RawCommit{
+4 -1
View File
@@ -104,6 +104,8 @@ type Source interface {
CommitURLBase() string
ListCommits(ctx context.Context, page, limit int) ([]RawCommit, int, error)
ListTags(ctx context.Context) ([]RawTag, error)
// TagURLBase 是 tag 链接的基址(给人看的 origin,可能与抓取 origin 不同)。
TagURLBase() string
ReadFile(ctx context.Context, sha, path string) (string, error)
// BranchHeadSHA 读分支 HEAD;读不到不算致命(退回"提交列表里最新的那条")。
BranchHeadSHA(ctx context.Context, branch string) (string, error)
@@ -203,7 +205,8 @@ func (s *Syncer) Sync(ctx context.Context, jobID, triggeredBy string) (governanc
}
derived := DeriveVersions(DeriveInput{RepoKey: s.repoKey, CommitURLBase: s.source.CommitURLBase(),
Commits: commits, Tags: tags, SnapshotID: runID,
TagURLBase: s.source.TagURLBase(),
Commits: commits, Tags: tags, SnapshotID: runID,
Changelog: func(sha string) (string, error) {
return s.source.ReadFile(ctx, sha, s.changelog)
}})
+4
View File
@@ -27,6 +27,10 @@ func (f *fakeSource) CommitURLBase() string {
return "http://gitea.test/Weknora/knowledge-governance/commit/"
}
func (f *fakeSource) TagURLBase() string {
return "http://gitea.test/Weknora/knowledge-governance/src/tag/"
}
func (f *fakeSource) ListCommits(_ context.Context, page, limit int) ([]RawCommit, int, error) {
f.listCalls++
if f.commitsErr != nil {
+12
View File
@@ -35,6 +35,18 @@ if [ "${#IDENTITY_ARGS[@]}" -lt 6 ]; then
fi
printf ' %s\n' "${IDENTITY_ARGS[@]}"
echo "=== 1c. 保留上一版构建的静态资源(CDN/浏览器可能还持有旧 index.html)"
# 只保留**当前正在跑的那一版**:旧 index.html 的旧哈希引用仍能取到文件,
# 页面不会因为某个 JS/CSS 404 而空白或"裸奔"。目录只读挂载进 web 容器。
LEGACY_DIR="deploy/legacy-assets"
PREV_WEB_IMAGE=$(docker inspect -f '{{.Image}}' knowledge-governance-p1-web-1 2>/dev/null || true)
mkdir -p "$LEGACY_DIR/assets" && chmod 777 "$LEGACY_DIR" "$LEGACY_DIR/assets"
if [ -n "$PREV_WEB_IMAGE" ]; then
docker run --rm --user 0 --entrypoint sh -v "$PWD/$LEGACY_DIR:/out" "$PREV_WEB_IMAGE" \
-c 'cp -a /usr/share/nginx/html/assets/. /out/assets/ 2>/dev/null || true' >/dev/null 2>&1 || true
echo " LEGACY_ASSETS=$(ls -1 "$LEGACY_DIR/assets" 2>/dev/null | tr '\n' ' ')"
fi
echo "=== 2. 构建 api"
docker build --network host "${PROXY_ARGS[@]}" "${IDENTITY_ARGS[@]}" -f Dockerfile -t knowledge-governance-p1-api:latest . || { echo "API_BUILD_FAILED"; exit 1; }
+13
View File
@@ -186,6 +186,19 @@ describe('VersionHistoryView', () => {
expect(html).not.toContain('同步记录</button>')
})
it('never renders a tag link without a URL (an empty href looks broken)', () => {
const withURL = render()
expect(withURL).toContain('查看 tag v0.1.0')
expect(withURL).toContain('https://gitea.example/Weknora/knowledge-governance/src/tag/v0.1.0')
const withoutURL = render({
page: {
...page,
items: [{ ...releaseItem, release_tags: [{ name: 'v0.1.0', url: '' }] }],
},
})
expect(withoutURL).not.toContain('查看 tag')
})
it('keeps mobile single-column rules so nothing overflows horizontally', () => {
const css = readFileSync(new URL('./versionHistory.css', import.meta.url), 'utf8')
expect(css).toMatch(/@media \(max-width: 760px\)[\s\S]*?\.version-history[\s\S]*?overflow-wrap:\s*anywhere/)
+8 -5
View File
@@ -197,11 +197,14 @@ function TimelineEntry({
查看提交
</a>
) : null}
{item.release_tags.map((tag) => (
<a key={tag.name} href={tag.url} target="_blank" rel="noreferrer noopener">
查看 tag {tag.name}
</a>
))}
{/* 没有链接就不渲染:空 href 点下去像"没反应/空白",比不显示更糟 */}
{item.release_tags
.filter((tag) => tag.url)
.map((tag) => (
<a key={tag.name} href={tag.url} target="_blank" rel="noreferrer noopener">
查看 tag {tag.name}
</a>
))}
</div>
</li>
)