fix(version-history): 页面链接改走公网 origin(抓取仍走内网)+ tag 补链接

现象(主人反馈):点「查看提交」打开是空白页。原因:链接用的是**抓取用的内网地址**
(`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。
This commit is contained in:
姚章浩
2026-10-14 11:06:13 +08:00
parent 90db243a68
commit b9f0f06e96
13 changed files with 125 additions and 15 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
+1
View File
@@ -15,6 +15,7 @@
- `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,
})
+2
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.
+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 {
+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>
)