From 4cb51108454c3559e8a6305ad3316f74ed4e2daf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Wed, 14 Oct 2026 11:06:13 +0800 Subject: [PATCH] =?UTF-8?q?fix(version-history):=20=E9=A1=B5=E9=9D=A2?= =?UTF-8?q?=E9=93=BE=E6=8E=A5=E6=94=B9=E8=B5=B0=E5=85=AC=E7=BD=91=20origin?= =?UTF-8?q?=EF=BC=88=E6=8A=93=E5=8F=96=E4=BB=8D=E8=B5=B0=E5=86=85=E7=BD=91?= =?UTF-8?q?=EF=BC=89+=20tag=20=E8=A1=A5=E9=93=BE=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 现象(主人反馈):点「查看提交」打开是空白页。原因:链接用的是**抓取用的内网地址** (`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`(`//src/tag/`),并在前端**没有链接就不渲染**该按钮。 - 测试:客户端(LinkOrigin 生效 / 未配时退回 / 非法拒绝)、规则(tag 链接写入证据 / 无基址不编链接)、 前端(有链接才渲染「查看 tag」)。 验证:make verify 15/15;真实链路重同步后库里 commit_url = `https://gitea.zheromiku.top/...`(200)、 release_tags 带 url。 --- .env.example | 3 +++ CHANGELOG.md | 1 + cmd/worker/main.go | 1 + compose.yaml | 2 ++ internal/appconfig/config.go | 13 ++++++++++-- internal/versionhistory/gitea.go | 30 +++++++++++++++++++++------ internal/versionhistory/gitea_test.go | 29 ++++++++++++++++++++++++++ internal/versionhistory/rules.go | 7 ++++++- internal/versionhistory/rules_test.go | 19 +++++++++++++++++ internal/versionhistory/sync.go | 5 ++++- internal/versionhistory/sync_test.go | 4 ++++ web/src/VersionHistory.test.tsx | 13 ++++++++++++ web/src/VersionHistory.tsx | 13 +++++++----- 13 files changed, 125 insertions(+), 15 deletions(-) diff --git a/.env.example b/.env.example index 7a01b8a..7ff1da6 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d3ef5d..260cb0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/cmd/worker/main.go b/cmd/worker/main.go index ab27e35..055bfa4 100644 --- a/cmd/worker/main.go +++ b/cmd/worker/main.go @@ -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, }) diff --git a/compose.yaml b/compose.yaml index ab7693b..8eccca4 100644 --- a/compose.yaml +++ b/compose.yaml @@ -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. diff --git a/internal/appconfig/config.go b/internal/appconfig/config.go index 3b9b4f7..14aa71b 100644 --- a/internal/appconfig/config.go +++ b/internal/appconfig/config.go @@ -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) diff --git a/internal/versionhistory/gitea.go b/internal/versionhistory/gitea.go index fa50ef3..7d04160 100644 --- a/internal/versionhistory/gitea.go +++ b/internal/versionhistory/gitea.go @@ -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 链接用(`//src/tag/`)。 +func (c *GiteaClient) TagURLBase() string { + return c.linkOrigin + "/" + c.repo + "/src/tag/" } func (c *GiteaClient) apiURL(path string, query url.Values) string { diff --git a/internal/versionhistory/gitea_test.go b/internal/versionhistory/gitea_test.go index 896905b..b02c3ce 100644 --- a/internal/versionhistory/gitea_test.go +++ b/internal/versionhistory/gitea_test.go @@ -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 { diff --git a/internal/versionhistory/rules.go b/internal/versionhistory/rules.go index 9a3368a..e4a826d 100644 --- a/internal/versionhistory/rules.go +++ b/internal/versionhistory/rules.go @@ -38,6 +38,7 @@ type ChangelogSource func(sha string) (string, error) type DeriveInput struct { RepoKey string CommitURLBase string // 形如 "///commit/",由配置拼好,不接受外部传入 + TagURLBase string // 形如 "///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 }) diff --git a/internal/versionhistory/rules_test.go b/internal/versionhistory/rules_test.go index 2bef35c..0adcd4f 100644 --- a/internal/versionhistory/rules_test.go +++ b/internal/versionhistory/rules_test.go @@ -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{ diff --git a/internal/versionhistory/sync.go b/internal/versionhistory/sync.go index 9433a4c..b2cf0ff 100644 --- a/internal/versionhistory/sync.go +++ b/internal/versionhistory/sync.go @@ -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) }}) diff --git a/internal/versionhistory/sync_test.go b/internal/versionhistory/sync_test.go index 4e2ca4e..59f981a 100644 --- a/internal/versionhistory/sync_test.go +++ b/internal/versionhistory/sync_test.go @@ -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 { diff --git a/web/src/VersionHistory.test.tsx b/web/src/VersionHistory.test.tsx index 09d717d..9e139ef 100644 --- a/web/src/VersionHistory.test.tsx +++ b/web/src/VersionHistory.test.tsx @@ -186,6 +186,19 @@ describe('VersionHistoryView', () => { expect(html).not.toContain('同步记录') }) + 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/) diff --git a/web/src/VersionHistory.tsx b/web/src/VersionHistory.tsx index 36a8a60..dd09dd8 100644 --- a/web/src/VersionHistory.tsx +++ b/web/src/VersionHistory.tsx @@ -197,11 +197,14 @@ function TimelineEntry({ 查看提交 ) : null} - {item.release_tags.map((tag) => ( - - 查看 tag {tag.name} - - ))} + {/* 没有链接就不渲染:空 href 点下去像"没反应/空白",比不显示更糟 */} + {item.release_tags + .filter((tag) => tag.url) + .map((tag) => ( + + 查看 tag {tag.name} + + ))} )