From 70e9f9b884bc0b8f6991e0f2b641a8acc02f0509 Mon Sep 17 00:00:00 2001 From: yaosanqi137 Date: Mon, 2 Nov 2026 00:33:40 +0800 Subject: [PATCH] feat: add mirror help pages and interactive Debian configuration --- README.md | 8 ++ backend/help.go | 108 +++++++++++++++++++++++++ backend/help_test.go | 88 ++++++++++++++++++++ backend/main.go | 6 ++ package.json | 2 + scripts/check-debian-sources.ts | 53 ++++++++++++ scripts/check-help.ts | 13 +++ src/App.vue | 28 ++++--- src/api.ts | 2 + src/components/AdminPage.vue | 16 +++- src/components/DebianSources.vue | 91 +++++++++++++++++++++ src/components/HelpPage.vue | 115 +++++++++++++++++++++++++++ src/components/MarkdownContent.vue | 6 +- src/components/MirrorHelpContent.vue | 18 +++++ src/copy-text.ts | 18 +++++ src/debian-sources.ts | 43 ++++++++++ src/help-content.ts | 28 +++++++ src/help.ts | 13 +++ src/locales/admin-messages.ts | 1 + src/locales/en-US/common.ts | 1 + src/locales/en-US/mirrors.ts | 21 +++++ src/locales/zh-CN/common.ts | 1 + src/locales/zh-CN/mirrors.ts | 21 +++++ src/style.css | 8 +- 24 files changed, 691 insertions(+), 18 deletions(-) create mode 100644 backend/help.go create mode 100644 backend/help_test.go create mode 100644 scripts/check-debian-sources.ts create mode 100644 scripts/check-help.ts create mode 100644 src/components/DebianSources.vue create mode 100644 src/components/HelpPage.vue create mode 100644 src/components/MirrorHelpContent.vue create mode 100644 src/copy-text.ts create mode 100644 src/debian-sources.ts create mode 100644 src/help-content.ts create mode 100644 src/help.ts diff --git a/README.md b/README.md index e9ca3da..94e2734 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,14 @@ go -C backend build -o ../.local/mirrorouc . 默认监听 `127.0.0.1:8081`,可通过 `-listen` 修改。首页为 `/`,公告页为 `/announcements`,管理后台为 `/admin`,同步状态页为 `/status`。数据库与上传文件保存在 `data/`,更新时保留该目录。 +镜像使用帮助位于 `/help/<源名>/`,在后台“镜像与任务”的“展示信息”中使用 Markdown 编辑。所有界面语言使用同一份中文帮助文章;未填写文章的镜像不显示帮助按钮。 + +帮助正文可插入交互式 Debian 配置块,`format` 使用 `list`(传统格式)或 `deb822`: + +```mirror-config +{"type":"debian","format":"list"} +``` + 镜像目录与下载由已有的 Web 服务器提供,路径为 `/mirrors/<源名>/`。自定义目录页的 Fancyindex 模板随前端构建生成在 `dist/fancy-index/` 中。 需要本机监控采集或受限配置写入时,可按需对接 `backend/tools/` 中的工具。更多启动参数可通过 `./mirrorouc -help` 查看。 diff --git a/backend/help.go b/backend/help.go new file mode 100644 index 0000000..d57934a --- /dev/null +++ b/backend/help.go @@ -0,0 +1,108 @@ +package main + +import ( + "errors" + "net/http" + "os" + "path/filepath" + "sort" + "strings" +) + +type helpArticle struct { + Name string `json:"name"` + Description Localized `json:"description"` + Website string `json:"website"` + BrowseURL string `json:"browseUrl"` + Body string `json:"body,omitempty"` +} + +func publishedHelp(meta MirrorMetadata) bool { + return meta.Visible && strings.TrimSpace(meta.Help) != "" +} + +func helpContent(meta MirrorMetadata, body bool) helpArticle { + article := helpArticle{Name: meta.Name, Description: meta.Description, Website: meta.Website, BrowseURL: "/mirrors/" + meta.Name + "/"} + if body { + article.Body = meta.Help + } + return article +} + +func (a *App) findHelp(name string) (MirrorMetadata, error) { + var meta MirrorMetadata + if !validName(name) { + return meta, errMissing + } + record, err := a.record("mirrors", name) + if err != nil { + return meta, err + } + if err := decodeData(record.Data, &meta); err != nil { + return meta, err + } + if meta.Name != name || !publishedHelp(meta) { + return meta, errMissing + } + return meta, nil +} + +func (a *App) helpIndex(w http.ResponseWriter, r *http.Request) { + records, err := a.records("mirrors") + if err != nil { + a.internal(w, err) + return + } + articles := []helpArticle{} + for _, record := range records { + var meta MirrorMetadata + if decodeData(record.Data, &meta) == nil && validName(meta.Name) && meta.Name == record.ID && publishedHelp(meta) { + articles = append(articles, helpContent(meta, false)) + } + } + sort.Slice(articles, func(i, j int) bool { return articles[i].Name < articles[j].Name }) + respond(w, 200, articles) +} + +func (a *App) helpArticle(w http.ResponseWriter, r *http.Request) { + meta, err := a.findHelp(r.PathValue("name")) + if errors.Is(err, errMissing) { + fail(w, 404, "NOT_FOUND") + return + } + if err != nil { + a.internal(w, err) + return + } + respond(w, 200, helpContent(meta, true)) +} + +func (a *App) helpPage(w http.ResponseWriter, r *http.Request) { + path := strings.TrimSuffix(r.URL.Path, "/") + index := filepath.Join(a.cfg.Static, "index.html") + w.Header().Set("Cache-Control", "no-cache") + if path == "/help" { + http.ServeFile(w, r, index) + return + } + _, err := a.findHelp(strings.TrimPrefix(path, "/help/")) + if err == nil { + http.ServeFile(w, r, index) + return + } + if !errors.Is(err, errMissing) { + a.internal(w, err) + return + } + // Return the application for a friendly error page while retaining a real 404. + raw, err := os.ReadFile(index) + if err != nil { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(http.StatusNotFound) + if r.Method != http.MethodHead { + w.Write(raw) + } +} diff --git a/backend/help_test.go b/backend/help_test.go new file mode 100644 index 0000000..74260af --- /dev/null +++ b/backend/help_test.go @@ -0,0 +1,88 @@ +package main + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestPublishedHelpAndDeepLinks(t *testing.T) { + c := fixture(t) + article := MirrorMetadata{Name: "alpine", Description: Localized{"zh-CN": "软件仓库"}, Help: "## 配置软件源\n\n```sh\napk update\n```", Category: "os", Visible: true, Website: "https://alpinelinux.org/"} + for _, meta := range []MirrorMetadata{ + article, + {Name: "hidden", Help: "private draft", Category: "os", Visible: false}, + {Name: "empty", Help: " \n\t", Category: "os", Visible: true}, + } { + if _, err := c.app.saveRecord("mirrors", meta.Name, meta, 0); err != nil { + t.Fatal(err) + } + } + // Reading saved help does not depend on a successful live tunasync poll. + c.app.jobsMu.Lock() + c.app.jobs = nil + c.app.jobsError = "MANAGER_UNAVAILABLE" + c.app.jobsMu.Unlock() + response := c.call("GET", "/api/v1/help", nil, false) + status(t, response, 200) + var index []helpArticle + if err := json.Unmarshal(response.Body.Bytes(), &index); err != nil || len(index) != 1 || index[0].Name != "alpine" || index[0].Body != "" { + t.Fatal("help index leaked hidden content or included unpublished articles") + } + response = c.call("GET", "/api/v1/help/alpine", nil, false) + status(t, response, 200) + var result helpArticle + if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil || result.Body != article.Help || result.BrowseURL != "/mirrors/alpine/" { + t.Fatal("help endpoint did not preserve the shared Chinese Markdown") + } + for _, name := range []string{"hidden", "empty", "missing", "bad%2Fname"} { + status(t, c.call("GET", "/api/v1/help/"+name, nil, false), 404) + } + const html = "MirrorOUC help" + if err := os.WriteFile(filepath.Join(c.app.cfg.Static, "index.html"), []byte(html), 0600); err != nil { + t.Fatal(err) + } + for _, path := range []string{"/help", "/help/", "/help/alpine", "/help/alpine/"} { + response = c.call("GET", path, nil, false) + status(t, response, 200) + if response.Body.String() != html { + t.Fatal("refreshing a help deep link did not serve the application") + } + status(t, c.call("HEAD", path, nil, false), 200) + } + for _, path := range []string{"/help/hidden/", "/help/empty/", "/help/missing/", "/help/alpine/extra"} { + response = c.call("GET", path, nil, false) + status(t, response, 404) + if response.Body.String() != html || !strings.HasPrefix(response.Header().Get("Content-Type"), "text/html") { + t.Fatal("missing help should retain a real 404 and display the application error page") + } + response = c.call("HEAD", path, nil, false) + status(t, response, 404) + if response.Body.Len() != 0 { + t.Fatal("HEAD returned a response body") + } + } + status(t, c.call("POST", "/help/alpine/", nil, false), 405) + status(t, c.call("GET", "/helpful", nil, false), 404) +} + +func TestHelpPublicationUsesMirrorEditorAndPermissions(t *testing.T) { + c := fixture(t) + meta := MirrorMetadata{Name: "alpine", Help: "## 安装\n\n中文说明。", Category: "os", Visible: true} + c.login("admin") + status(t, c.call("PUT", "/api/v1/admin/records/mirrors/alpine", map[string]any{"revision": 0, "data": meta}, true), 200) + status(t, c.call("GET", "/api/v1/help/alpine", nil, false), 200) + c.login("editor") + status(t, c.call("PUT", "/api/v1/admin/records/mirrors/alpine", map[string]any{"revision": 1, "data": meta}, true), 403) + c.login("admin") + meta.Help = "" + status(t, c.call("PUT", "/api/v1/admin/records/mirrors/alpine", map[string]any{"revision": 1, "data": meta}, true), 200) + status(t, c.call("GET", "/api/v1/help/alpine", nil, false), 404) + response := c.call("GET", "/api/v1/help", nil, false) + status(t, response, 200) + if strings.TrimSpace(response.Body.String()) != "[]" { + t.Fatal("clearing help did not remove its public entry") + } +} diff --git a/backend/main.go b/backend/main.go index aad3e71..84abbed 100644 --- a/backend/main.go +++ b/backend/main.go @@ -104,6 +104,8 @@ func (a *App) handler() http.Handler { }) mux.HandleFunc("GET /api/v1/public", a.public) mux.HandleFunc("GET /api/v1/announcements", a.announcements) + mux.HandleFunc("GET /api/v1/help", a.helpIndex) + mux.HandleFunc("GET /api/v1/help/{name}", a.helpArticle) mux.HandleFunc("GET /api/v1/monitoring", a.monitoring) mux.HandleFunc("GET /api/v1/job-speeds", a.jobSpeeds) mux.HandleFunc("POST /api/v1/auth/login", a.login) @@ -141,6 +143,10 @@ func (a *App) handler() http.Handler { return } path := r.URL.Path + if path == "/help" || strings.HasPrefix(path, "/help/") { + a.helpPage(w, r) + return + } if path == "/" || path == "/status" || path == "/status/" || path == "/announcements" || path == "/announcements/" || path == "/admin" || strings.HasPrefix(path, "/admin/") { http.ServeFile(w, r, filepath.Join(a.cfg.Static, "index.html")) return diff --git a/package.json b/package.json index a895cd9..d2e1d6e 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,8 @@ "preview": "vite preview --host 127.0.0.1", "check:i18n": "node scripts/check-locales.ts", "check:monitoring": "node scripts/check-monitoring.ts", + "check:help": "node scripts/check-help.ts", + "check:debian": "node scripts/check-debian-sources.ts", "check:directory": "node scripts/check-directory.ts" }, "dependencies": { diff --git a/scripts/check-debian-sources.ts b/scripts/check-debian-sources.ts new file mode 100644 index 0000000..b142c18 --- /dev/null +++ b/scripts/check-debian-sources.ts @@ -0,0 +1,53 @@ +import assert from 'node:assert/strict' +import { marked } from 'marked' +import { debianReleases, debianSources, type DebianSourceOptions } from '../src/debian-sources.ts' +import { helpBlocks } from '../src/help-content.ts' + +const origin = 'https://mirrors.example.edu' +const base: DebianSourceOptions = { origin, release: 'trixie', format: 'list', sources: false, nonFree: true, securityMirror: false } +const defaultList = debianSources(base) +assert.ok(defaultList.includes('deb https://mirrors.example.edu/mirrors/debian/ trixie main contrib non-free non-free-firmware\n')) +assert.ok(defaultList.includes('deb https://security.debian.org/debian-security trixie-security')) +assert.ok(defaultList.includes('# deb-src https://mirrors.example.edu/mirrors/debian/ trixie ')) + +let cases = 0 +for (const release of debianReleases) for (const format of ['list', 'deb822'] as const) for (const sources of [false, true]) for (const nonFree of [false, true]) for (const securityMirror of [false, true]) { + const value = debianSources({ origin, release: release.id, format, sources, nonFree, securityMirror }) + assert.ok(!/undefined|NaN|trusted=yes|allow-insecure|testing-security|sid-security/.test(value)) + assert.equal(value.includes('non-free-firmware'), nonFree && release.firmware) + assert.equal(value.includes('contrib non-free'), nonFree) + assert.equal(value.includes(`${release.id}-updates`), release.stable) + assert.equal(value.includes(`${release.id}-backports`), release.backports) + assert.equal(value.includes(`${release.id}-security`), release.stable) + if (release.stable) { + assert.equal(value.includes('https://mirrors.example.edu/mirrors/debian-security/'), securityMirror) + assert.equal(value.includes('https://security.debian.org/debian-security'), !securityMirror) + } + if (format === 'list') { + assert.equal(value.split('\n').some(line => line.startsWith('deb-src ')), sources) + assert.ok(value.split('\n').every(line => !line || /^(?:# )?deb(?:-src)? https:\/\/\S+ \S+ main(?: contrib non-free(?: non-free-firmware)?)?$/.test(line))) + } else { + for (const stanza of value.trim().split('\n\n')) { + const fields = Object.fromEntries(stanza.split('\n').map(line => line.split(/: (.*)/s).slice(0, 2))) + assert.equal(fields.Types, sources ? 'deb deb-src' : 'deb') + assert.equal(fields['Signed-By'], '/usr/share/keyrings/debian-archive-keyring.gpg') + assert.ok(fields.URIs && fields.Suites && fields.Components) + } + } + cases++ +} +assert.ok(debianSources({ ...base, origin: 'http://100.69.2.2:8080/path?ignored=true' }).includes('http://100.69.2.2:8080/mirrors/debian/')) +assert.throws(() => debianSources({ ...base, origin: 'javascript:alert(1)' })) +assert.throws(() => debianSources({ ...base, origin: 'https://secret:password@example.edu' })) +assert.throws(() => debianSources({ ...base, release: 'unknown' as DebianSourceOptions['release'] })) + +const fence = (data: string) => '```mirror-config\n' + data + '\n```\n' +const source = '## 配置\n\n[Debian][official]\n\n' + fence('{"type":"debian","format":"list"}') + '\n## 新格式\n\n' + fence('{"type":"debian","format":"deb822"}') + '\n[official]: https://www.debian.org/\n' +const blocks = helpBlocks(source) +assert.deepEqual(blocks.filter(block => block.kind === 'debian'), [{ kind: 'debian', format: 'list' }, { kind: 'debian', format: 'deb822' }]) +assert.ok(blocks.filter(block => block.kind === 'markdown').map(block => marked.parser(block.tokens)).join('').includes('href="https://www.debian.org/"'), 'Reference-style Markdown links must survive widget insertion') +for (const data of ['not JSON', '{"type":"shell","format":"list"}', '{"type":"debian","format":"other"}', '{"type":"debian","format":"list","script":"alert(1)"}', 'null']) { + assert.ok(helpBlocks(fence(data)).every(block => block.kind === 'markdown'), 'Invalid or unsupported blocks must remain ordinary Markdown code') +} +assert.ok(helpBlocks('````markdown\n' + fence('{"type":"debian","format":"list"}') + '````\n').every(block => block.kind === 'markdown'), 'A quoted code example must not instantiate a live widget') +console.log(`Debian help check passed: ${cases} option combinations, release-specific suites, official security defaults, DEB822 fields, widget parsing and Markdown links.`) diff --git a/scripts/check-help.ts b/scripts/check-help.ts new file mode 100644 index 0000000..e32d33a --- /dev/null +++ b/scripts/check-help.ts @@ -0,0 +1,13 @@ +import assert from 'node:assert/strict' +import { helpRoute, helpUrl } from '../src/help.ts' + +for (const name of ['ubuntu', 'debian-cd', 'AOSP', 'gcc.git', 'archlinuxcn', 'test+repo']) { + const url = helpUrl(name) + assert.deepEqual(helpRoute(url), { active: true, name, invalid: false }) + assert.deepEqual(helpRoute(url.slice(0, -1)), { active: true, name, invalid: false }) +} +for (const path of ['/help', '/help/']) assert.deepEqual(helpRoute(path), { active: true, name: null, invalid: false }) +for (const path of ['/', '/helpful', '/announcements']) assert.equal(helpRoute(path).active, false) +for (const path of ['/help/../', '/help/ubuntu/extra', '/help/%2fsecret', '/help/%zz', '/help/%252fsecret']) assert.equal(helpRoute(path).invalid, true) +assert.equal(helpUrl('a/b?c#d'), '/help/a%2Fb%3Fc%23d/') +console.log('Help check passed: index and deep links, case-sensitive names, encoded identifiers and malformed paths.') diff --git a/src/App.vue b/src/App.vue index 2adefb1..6694c6d 100644 --- a/src/App.vue +++ b/src/App.vue @@ -2,7 +2,7 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue' import { useI18n } from 'vue-i18n' import { - ArrowRight, ArrowUpRight, BookOpen, Check, + ArrowRight, ArrowUpRight, CircleHelp, Check, ExternalLink, Menu, Monitor, Moon, Search, Sun, X, } from 'lucide-vue-next' @@ -11,10 +11,11 @@ import LanguagePicker from './components/LanguagePicker.vue' import StatusPage from './components/StatusPage.vue' import AdminPage from './components/AdminPage.vue' import AnnouncementsPage from './components/AnnouncementsPage.vue' -import MarkdownContent from './components/MarkdownContent.vue' +import HelpPage from './components/HelpPage.vue' import DownloadList from './components/DownloadList.vue' import { content } from './api' import { announcementUrl } from './announcements' +import { helpRoute, helpUrl } from './help' import { usePublicData } from './usePublicData' import { useMirrorFormats } from './useMirrorFormats' import { type Mirror } from './data' @@ -42,6 +43,8 @@ const themes: Theme[] = ['light', 'dark', 'system'] const themeIcons = { light: Sun, dark: Moon, system: Monitor } const isStatusPage = window.location.pathname.replace(/\/$/, '') === '/status' const isAnnouncementsPage = window.location.pathname.replace(/\/$/, '') === '/announcements' +const help = helpRoute(window.location.pathname) +const isHelpPage = help.active const navigation = [ { key: 'mirrors', href: '/', active: !isStatusPage && !isAdminPage && !isAnnouncementsPage }, { key: 'news', href: '/announcements', active: isAnnouncementsPage }, @@ -61,7 +64,8 @@ watch(locale, (value) => { }, { immediate: true }) watch([locale, site], () => { const siteTitle = site.value ? `MirrorOUC · ${content(site.value.name, locale.value)}` : t('common.pageTitle') - document.title = isAnnouncementsPage ? `${t('announcements.title')} · ${siteTitle}` : siteTitle + const pageTitle = isHelpPage ? (help.name && !help.invalid ? t('mirrors.helpFor', { name: help.name }) : t('mirrors.helpTitle')) : isAnnouncementsPage ? t('announcements.title') : '' + document.title = pageTitle ? `${pageTitle} · ${siteTitle}` : siteTitle }, { immediate: true }) function selectTheme(value: Theme) { theme.value = value; themeOpen.value = false } @@ -93,13 +97,13 @@ function nextLabel(mirror: Mirror) { } function resetSearch() { search.value = ''; searchInput.value?.focus() } -type Modal = 'help' | 'about' | 'downloads' | 'mirror' +type Modal = 'about' | 'downloads' | 'mirror' const dialog = ref() const modal = ref(null) const selectedMirror = ref(null) const modalTitle = computed(() => { if (modal.value === 'mirror') return selectedMirror.value?.name || '' - const keys = { help: 'mirrors.helpTitle', about: 'common.aboutTitle', downloads: 'announcements.downloadsTitle' } + const keys = { about: 'common.aboutTitle', downloads: 'announcements.downloadsTitle' } return modal.value && modal.value in keys ? t(keys[modal.value as keyof typeof keys]) : '' }) async function openModal(value: Modal, mirror?: Mirror) { @@ -117,7 +121,7 @@ watch(modal, value => { document.body.classList.toggle('dialog-open', value !== function onKeydown(event: KeyboardEvent) { if (event.key === 'Escape') { themeOpen.value = false; mobileOpen.value = false } const target = event.target as HTMLElement - if (!isAdminPage && !isAnnouncementsPage && !dialog.value?.open && ((event.key === 'k' && (event.ctrlKey || event.metaKey)) + if (!isAdminPage && !isAnnouncementsPage && !isHelpPage && !dialog.value?.open && ((event.key === 'k' && (event.ctrlKey || event.metaKey)) || (event.key === '/' && !['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName) && !target.isContentEditable))) { event.preventDefault() if (isStatusPage) statusPage.value?.focusSearch() @@ -155,7 +159,7 @@ onBeforeUnmount(() => {