diff --git a/backend/content.go b/backend/content.go index d919eaf..79075f6 100644 --- a/backend/content.go +++ b/backend/content.go @@ -170,11 +170,19 @@ func (a *App) putRecord(w http.ResponseWriter, r *http.Request) { return } } - for _, download := range d.Downloads { - if strings.TrimSpace(download.Name) == "" || len(download.Name) > 100 || len(download.Version) > 100 || !webURL(download.URL, false) { - fail(w, 400, "INVALID_INPUT") + if _, provided := fields["downloads"]; !provided { + current, err := a.record("settings", "site") + var existing Settings + if err != nil || decodeData(current.Data, &existing) != nil { + fail(w, 409, "CONFLICT") return } + d.Downloads = existing.Downloads + } + d.Downloads = normalizeDownloads(d.Downloads) + if !validDownloads(d.Downloads) { + fail(w, 400, "INVALID_INPUT") + return } value = d } diff --git a/backend/downloads.go b/backend/downloads.go new file mode 100644 index 0000000..1c9eb0c --- /dev/null +++ b/backend/downloads.go @@ -0,0 +1,55 @@ +package main + +import ( + "crypto/sha256" + "fmt" + "strings" +) + +// Normalize on read, leaving original database rows intact until an administrator saves. +func normalizeDownloads(input []Download) []Download { + output := []Download{} + legacy := map[string]int{} + for _, item := range input { + if item.ID == "" && item.Category == "" && item.Description == "" && item.Files == nil && (item.URL != "" || item.Version != "") { + name := strings.TrimSpace(item.Name) + index, exists := legacy[name] + if !exists { + hash := sha256.Sum256([]byte(name)) + index = len(output) + legacy[name] = index + output = append(output, Download{ID: fmt.Sprintf("legacy-%x", hash[:12]), Name: name, Category: "software", Files: []DownloadFile{}}) + } + label := strings.TrimSpace(item.Version) + if label == "" { + label = name + } + output[index].Files = append(output[index].Files, DownloadFile{Label: label, URL: item.URL}) + } else { + output = append(output, item) + } + } + return output +} + +func validDownloads(items []Download) bool { + if len(items) > 100 { + return false + } + ids := map[string]bool{} + for _, item := range items { + if !validName(item.ID) || ids[item.ID] || strings.TrimSpace(item.Name) == "" || len(item.Name) > 300 || len(item.Description) > 100000 || len(item.Files) < 1 || len(item.Files) > 100 || item.Version != "" || item.URL != "" { + return false + } + if item.Category != "os" && item.Category != "software" && item.Category != "fonts" { + return false + } + ids[item.ID] = true + for _, file := range item.Files { + if strings.TrimSpace(file.Label) == "" || len(file.Label) > 500 || !navigationURL(file.URL) { + return false + } + } + } + return true +} diff --git a/backend/downloads_test.go b/backend/downloads_test.go new file mode 100644 index 0000000..61948c8 --- /dev/null +++ b/backend/downloads_test.go @@ -0,0 +1,120 @@ +package main + +import ( + "encoding/json" + "path/filepath" + "reflect" + "testing" +) + +func TestDownloadCatalogLegacyCompatibilityAndPersistence(t *testing.T) { + c := fixture(t) + c.login("admin") + initial, _ := c.app.record("settings", "site") + var old map[string]any + decodeData(initial.Data, &old) + old["downloads"] = []map[string]string{ + {"name": "Ubuntu", "version": "24.04 (amd64)", "url": "https://example.invalid/ubuntu.iso"}, + {"name": "Ubuntu", "version": "24.04 (arm64)", "url": "https://example.invalid/ubuntu-arm.iso"}, + {"name": "Tool", "version": "", "url": "https://example.invalid/tool.zip"}, + } + legacy, err := c.app.saveRecord("settings", "site", old, initial.Revision) + if err != nil { + t.Fatal(err) + } + var rawBefore, rawAfter string + c.app.db.QueryRow("SELECT data FROM records WHERE kind='settings' AND id='site'").Scan(&rawBefore) + read := c.call("GET", "/api/v1/public", nil, false) + status(t, read, 200) + var public struct{ Site Settings } + if err := json.Unmarshal(read.Body.Bytes(), &public); err != nil { + t.Fatal(err) + } + items := public.Site.Downloads + if len(items) != 2 || items[0].Name != "Ubuntu" || len(items[0].Files) != 2 || items[0].Files[1].Label != "24.04 (arm64)" || items[1].Files[0].Label != "Tool" || items[0].Category != "software" || !validName(items[0].ID) || items[0].URL != "" { + t.Fatalf("legacy projects or version links lost: %+v", items) + } + c.app.db.QueryRow("SELECT data FROM records WHERE kind='settings' AND id='site'").Scan(&rawAfter) + if rawBefore != rawAfter { + t.Fatal("reading public data changed stored settings") + } + // Old open forms may still submit the former flat download structure. + w := c.call("PUT", "/api/v1/admin/records/settings/site", map[string]any{"data": old, "revision": legacy.Revision}, true) + status(t, w, 200) + var saved Record + json.Unmarshal(w.Body.Bytes(), &saved) + var settings Settings + decodeData(saved.Data, &settings) + if !reflect.DeepEqual(settings.Downloads, items) { + t.Fatal("older form lost downloads or changed stable project IDs") + } + settings.Downloads[0].Category = "os" + settings.Downloads[0].Description = "## Ubuntu\n\n选择适合设备架构的版本。" + settings.Downloads[0].Files[0].URL = "/mirrors/ubuntu-releases/24.04/ubuntu.iso" + settings.Downloads = append(settings.Downloads, Download{ID: "fonts", Name: "字体", Category: "fonts", Files: []DownloadFile{{Label: "字体压缩包", URL: "https://example.invalid/font.zip"}}}) + w = c.call("PUT", "/api/v1/admin/records/settings/site", map[string]any{"data": settings, "revision": saved.Revision}, true) + status(t, w, 200) + status(t, c.call("PUT", "/api/v1/admin/records/settings/site", map[string]any{"data": settings, "revision": saved.Revision}, true), 409) + json.Unmarshal(w.Body.Bytes(), &saved) + var omitted map[string]any + decodeData(settings, &omitted) + delete(omitted, "downloads") + w = c.call("PUT", "/api/v1/admin/records/settings/site", map[string]any{"data": omitted, "revision": saved.Revision}, true) + status(t, w, 200) + json.Unmarshal(w.Body.Bytes(), &saved) + c.app.db.Close() + c.app.db, err = openDatabase(filepath.Join(c.app.cfg.Data, "mirrorouc.db")) + if err != nil { + t.Fatal(err) + } + record, _ := c.app.record("settings", "site") + var restored Settings + decodeData(record.Data, &restored) + if !reflect.DeepEqual(restored.Downloads, settings.Downloads) { + t.Fatal("catalog changed after an older form save or process restart") + } + settings.Downloads = []Download{} + w = c.call("PUT", "/api/v1/admin/records/settings/site", map[string]any{"data": settings, "revision": saved.Revision}, true) + status(t, w, 200) + json.Unmarshal(w.Body.Bytes(), &saved) + decodeData(saved.Data, &restored) + if restored.Downloads == nil || len(restored.Downloads) != 0 { + t.Fatal("explicitly clearing the catalog was not preserved") + } +} + +func TestDownloadCatalogValidationAndPermissions(t *testing.T) { + c := fixture(t) + c.login("admin") + record, _ := c.app.record("settings", "site") + base := Download{ID: "ubuntu", Name: "Ubuntu", Category: "os", Files: []DownloadFile{{Label: "24.04 LTS (amd64)", URL: "/mirrors/ubuntu-releases/24.04/ubuntu.iso"}}} + mutations := []func(*Download){ + func(d *Download) { d.ID = "" }, + func(d *Download) { d.Category = "unknown" }, + func(d *Download) { d.Name = " " }, + func(d *Download) { d.Files = nil }, + func(d *Download) { d.Files[0].Label = " " }, + func(d *Download) { d.Files[0].URL = "javascript:alert(1)" }, + func(d *Download) { d.Files[0].URL = "//example.invalid/a.iso" }, + func(d *Download) { d.Files[0].URL = "/\\example.invalid/a.iso" }, + func(d *Download) { d.Files[0].URL = "https://user:password@example.invalid/a.iso" }, + func(d *Download) { d.URL = "https://example.invalid/ambiguous-old-field" }, + } + for index, mutate := range mutations { + var item Download + decodeData(base, &item) + mutate(&item) + settings := initialSettings() + settings.Downloads = []Download{item} + w := c.call("PUT", "/api/v1/admin/records/settings/site", map[string]any{"data": settings, "revision": record.Revision}, true) + if w.Code != 400 { + t.Fatalf("invalid download case %d: status %d", index, w.Code) + } + } + settings := initialSettings() + settings.Downloads = []Download{base, base} + status(t, c.call("PUT", "/api/v1/admin/records/settings/site", map[string]any{"data": settings, "revision": record.Revision}, true), 400) + settings.Downloads = []Download{base} + c.login("editor") + status(t, c.call("PUT", "/api/v1/admin/records/settings/site", map[string]any{"data": settings, "revision": record.Revision}, true), 403) +} diff --git a/backend/models.go b/backend/models.go index 70705b6..1c839c5 100644 --- a/backend/models.go +++ b/backend/models.go @@ -13,9 +13,18 @@ type RelatedLink struct { URL string `json:"url"` } type Download struct { - Name string `json:"name"` - Version string `json:"version"` - URL string `json:"url"` + ID string `json:"id"` + Name string `json:"name"` + Category string `json:"category"` + Description string `json:"description"` + Files []DownloadFile `json:"files"` + // Read old settings and submissions without losing existing download links. + Version string `json:"version,omitempty"` + URL string `json:"url,omitempty"` +} +type DownloadFile struct { + Label string `json:"label"` + URL string `json:"url"` } type Settings struct { Name Localized `json:"name"` @@ -122,6 +131,10 @@ func settingsDefaults(data any) any { if value, exists := object["relatedLinks"]; !exists || value == nil { object["relatedLinks"] = initialRelatedLinks() } + var downloads []Download + if decodeData(object["downloads"], &downloads) == nil { + object["downloads"] = normalizeDownloads(downloads) + } } return data } diff --git a/src/App.vue b/src/App.vue index ce5918e..2adefb1 100644 --- a/src/App.vue +++ b/src/App.vue @@ -12,6 +12,7 @@ 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 DownloadList from './components/DownloadList.vue' import { content } from './api' import { announcementUrl } from './announcements' import { usePublicData } from './usePublicData' @@ -277,12 +278,12 @@ onBeforeUnmount(() => { - +

{{ modalTitle }}

- +
diff --git a/src/api.ts b/src/api.ts index 3c9a46e..c3ca2f0 100644 --- a/src/api.ts +++ b/src/api.ts @@ -1,7 +1,9 @@ export type Localized = Record export interface SiteLink { title: Localized; url: string } export interface RelatedLink extends SiteLink { kind: 'url' | 'help' } -export interface SiteDownload { name: string; version: string; url: string } +export type DownloadCategory = 'os' | 'software' | 'fonts' +export interface DownloadFile { label: string; url: string } +export interface SiteDownload { id: string; name: string; category: DownloadCategory; description: string; files: DownloadFile[] } export interface SiteSettings { name: Localized; description: Localized; logoLight: string; logoDark: string; favicon: string; avatar: string email: string; address: Localized; links: SiteLink[]; relatedLinks: RelatedLink[]; downloads: SiteDownload[] diff --git a/src/components/AdminPage.vue b/src/components/AdminPage.vue index ff05e88..1a73ff0 100644 --- a/src/components/AdminPage.vue +++ b/src/components/AdminPage.vue @@ -5,6 +5,7 @@ import { api, ApiError, jsonBody, setSession, type AdminSession, type AdminUser, import { supportedLocales } from '../locales' import { announcementUrl } from '../announcements' import MarkdownContent from './MarkdownContent.vue' +import DownloadCatalogEditor from './DownloadCatalogEditor.vue' const { t, te, d, n } = useI18n({ useScope: 'global' }) const session = ref(null) @@ -13,13 +14,14 @@ const busy = ref(false) const error = ref('') const notice = ref('') const tab = ref('overview') -const tabs = ['overview', 'mirrors', 'announcements', 'config', 'settings', 'users', 'audit'] +const tabs = ['overview', 'mirrors', 'announcements', 'downloads', 'config', 'settings', 'users', 'audit'] const allowedTabs = computed(() => session.value?.role === 'admin' ? tabs : ['announcements', 'users']) const credentials = reactive({ username: '', password: '' }) const overview = ref(null) const articles = ref[]>([]) const metadata = ref[]>([]) const settings = ref | null>(null) +const downloadEditor = ref>() const users = ref([]) const audit = ref({ items: [], page: 1, pageSize: 10, total: 0, totalPages: 1 }) const search = ref('') @@ -80,7 +82,7 @@ async function loadTab(value: string) { if (value === 'overview' || value === 'mirrors') await loadOverview() if (value === 'mirrors') metadata.value = await api('/admin/records/mirrors') if (value === 'announcements') articles.value = await api('/admin/records/announcements') - if (value === 'settings') settings.value = (await api[]>('/admin/records/settings'))[0] || null + if (value === 'settings' || value === 'downloads') settings.value = (await api[]>('/admin/records/settings'))[0] || null if (value === 'config') { config.value = await api('/admin/config'); versions.value = await api('/admin/config/versions'); draft.value = null; selectedConfig.value = ''; mirrorConfig.value = null } if (value === 'users' && session.value?.role === 'admin') users.value = await api('/admin/users') if (value === 'audit') await loadAudit() @@ -139,6 +141,11 @@ function editMirror(job: SyncJob) { mirrorEditor.value.data.description ||= {}; mirrorEditor.value.data.help ||= '' } async function saveMirror() { if (!mirrorEditor.value) return; mirrorEditor.value = await saveRecord('mirrors', mirrorEditor.value); metadata.value = await api('/admin/records/mirrors') } +async function saveDownloads() { + if (!settings.value) return + if (!downloadEditor.value?.validate()) { error.value = t('admin.incompleteDownload'); return } + settings.value = await saveRecord('settings', settings.value) +} function command(job: SyncJob, action: string) { void ask(t('admin.commandConfirm', { name: job.name, action: t(`admin.${action}`) }), async () => { await api(`/admin/jobs/${encodeURIComponent(job.name)}/${action}`, { method: 'POST' }); notice.value = t('admin.submitted'); await loadOverview() @@ -219,6 +226,7 @@ onBeforeUnmount(() => clearInterval(poll))
{{ t('admin.articleTitle') }}{{ t('admin.status') }}{{ t('admin.date') }}{{ t('admin.actions') }}
{{ row.data.title }}{{ t('admin.pinned') }}{{ t(row.data.published ? 'admin.published' : 'admin.draft') }}
{{ t('admin.viewArticle') }}

{{ t('admin.empty') }}

+