feat: add configurable mirror source generators and version management
This commit is contained in:
@@ -51,12 +51,26 @@ go -C backend build -o ../.local/mirrorouc .
|
|||||||
|
|
||||||
常用镜像的帮助原稿见 [docs/help/](docs/help/README.md),可复制到后台发布;线上编辑的文章保存在数据库中,部署不会自动覆盖。
|
常用镜像的帮助原稿见 [docs/help/](docs/help/README.md),可复制到后台发布;线上编辑的文章保存在数据库中,部署不会自动覆盖。
|
||||||
|
|
||||||
帮助正文可插入交互式 Debian 配置块,`format` 使用 `list`(传统格式)或 `deb822`:
|
帮助正文可插入交互式配置块,例如 Ubuntu:
|
||||||
|
|
||||||
|
```mirror-config
|
||||||
|
{"type":"ubuntu"}
|
||||||
|
```
|
||||||
|
|
||||||
|
后台的“插入配置生成器”可直接选择软件源并插入对应标记。支持 Debian、Ubuntu、Debian Security、Arch 系列、Conda、Kubernetes、Tailscale、Proxmox VE、OpenWrt 和 ELRepo;控件按软件源提供版本、格式、频道等选项。
|
||||||
|
|
||||||
|
可用 `format` 固定配置格式,`options` 设置默认选项。已有 Debian 标记保持兼容:
|
||||||
|
|
||||||
```mirror-config
|
```mirror-config
|
||||||
{"type":"debian","format":"list"}
|
{"type":"debian","format":"list"}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
新增软件源的控件规则在 `src/mirror-config.ts` 中注册,共用界面、复制和 Markdown 解析;APT 格式生成逻辑位于 `src/apt-sources.ts`。
|
||||||
|
|
||||||
|
已有生成器的版本在后台“配置生成器”中维护,支持添加、排序、移除和设置默认版本。Ubuntu 等发行新版本时,填写官方代号与显示名称即可,无需修改代码或重新部署;Debian 的更新组件、Proxmox 的密钥环路径也在此设置。请先确认镜像已同步对应版本,生成器设置不会创建同步任务。
|
||||||
|
|
||||||
|
版本目录保存在数据库中,由 `/api/v1/generators` 提供给帮助页。`backend/generator-defaults.json` 只用于首次初始化,升级不会覆盖后台保存的选项。
|
||||||
|
|
||||||
镜像目录与下载由已有的 Web 服务器提供,路径为 `/mirrors/<源名>/`。自定义目录页的 Fancyindex 模板随前端构建生成在 `dist/fancy-index/` 中。
|
镜像目录与下载由已有的 Web 服务器提供,路径为 `/mirrors/<源名>/`。自定义目录页的 Fancyindex 模板随前端构建生成在 `dist/fancy-index/` 中。
|
||||||
|
|
||||||
构建还会生成 `dist/errors/` 下的独立错误页。后端自动使用这些页面;使用 Nginx 时,可将其错误页指向对应文件,并保留 API 错误的 JSON 响应。
|
构建还会生成 `dist/errors/` 下的独立错误页。后端自动使用这些页面;使用 Nginx 时,可将其错误页指向对应文件,并保留 API 错误的 JSON 响应。
|
||||||
|
|||||||
+9
-2
@@ -77,7 +77,7 @@ func strict(raw []byte, value any) bool {
|
|||||||
}
|
}
|
||||||
func (a *App) listRecords(w http.ResponseWriter, r *http.Request) {
|
func (a *App) listRecords(w http.ResponseWriter, r *http.Request) {
|
||||||
kind := r.PathValue("kind")
|
kind := r.PathValue("kind")
|
||||||
if kind != "announcements" && kind != "mirrors" && kind != "settings" {
|
if kind != "announcements" && kind != "mirrors" && kind != "settings" && kind != "generators" {
|
||||||
fail(w, 404, "NOT_FOUND")
|
fail(w, 404, "NOT_FOUND")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -93,7 +93,7 @@ func (a *App) listRecords(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
func (a *App) putRecord(w http.ResponseWriter, r *http.Request) {
|
func (a *App) putRecord(w http.ResponseWriter, r *http.Request) {
|
||||||
kind, id := r.PathValue("kind"), r.PathValue("id")
|
kind, id := r.PathValue("kind"), r.PathValue("id")
|
||||||
if !validName(id) || (kind != "announcements" && kind != "mirrors" && kind != "settings") {
|
if !validName(id) || (kind != "announcements" && kind != "mirrors" && kind != "settings" && kind != "generators") {
|
||||||
fail(w, 400, "INVALID_INPUT")
|
fail(w, 400, "INVALID_INPUT")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -110,6 +110,13 @@ func (a *App) putRecord(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
var value any
|
var value any
|
||||||
switch kind {
|
switch kind {
|
||||||
|
case "generators":
|
||||||
|
var data GeneratorVersions
|
||||||
|
if !strict(body.Data, &data) || !validGeneratorVersions(id, data) {
|
||||||
|
fail(w, 400, "INVALID_INPUT")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
value = data
|
||||||
case "announcements":
|
case "announcements":
|
||||||
var d Announcement
|
var d Announcement
|
||||||
if !strict(body.Data, &d) || strings.TrimSpace(d.Title) == "" || len(d.Title) > 300 || len(d.Body) > 250000 || (d.Published && strings.TrimSpace(d.Body) == "") {
|
if !strict(body.Data, &d) || strings.TrimSpace(d.Title) == "" || len(d.Title) > 300 || len(d.Body) > 250000 || (d.Published && strings.TrimSpace(d.Body) == "") {
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
{
|
||||||
|
"debian": {
|
||||||
|
"defaultRelease": "trixie",
|
||||||
|
"releases": [
|
||||||
|
{ "id": "trixie", "label": "Debian 13 (trixie)", "stable": true, "firmware": true, "backports": true },
|
||||||
|
{ "id": "bookworm", "label": "Debian 12 (bookworm)", "stable": true, "firmware": true, "backports": false },
|
||||||
|
{ "id": "bullseye", "label": "Debian 11 (bullseye)", "stable": true, "firmware": false, "backports": false },
|
||||||
|
{ "id": "testing", "label": "testing", "stable": false, "firmware": true, "backports": false },
|
||||||
|
{ "id": "sid", "label": "sid", "stable": false, "firmware": true, "backports": false }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"ubuntu": {
|
||||||
|
"defaultRelease": "noble",
|
||||||
|
"releases": [
|
||||||
|
{ "id": "resolute", "label": "Ubuntu 26.04 LTS (resolute)" },
|
||||||
|
{ "id": "noble", "label": "Ubuntu 24.04 LTS (noble)" },
|
||||||
|
{ "id": "jammy", "label": "Ubuntu 22.04 LTS (jammy)" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"kubernetes": {
|
||||||
|
"defaultRelease": "v1.35",
|
||||||
|
"releases": [
|
||||||
|
{ "id": "v1.37", "label": "v1.37" },
|
||||||
|
{ "id": "v1.36", "label": "v1.36" },
|
||||||
|
{ "id": "v1.35", "label": "v1.35" },
|
||||||
|
{ "id": "v1.34", "label": "v1.34" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"tailscale": {
|
||||||
|
"defaultRelease": "debian/bookworm",
|
||||||
|
"releases": [
|
||||||
|
{ "id": "debian/trixie", "label": "Debian 13 (trixie)" },
|
||||||
|
{ "id": "debian/bookworm", "label": "Debian 12 (bookworm)" },
|
||||||
|
{ "id": "ubuntu/resolute", "label": "Ubuntu 26.04 LTS (resolute)" },
|
||||||
|
{ "id": "ubuntu/noble", "label": "Ubuntu 24.04 LTS (noble)" },
|
||||||
|
{ "id": "ubuntu/jammy", "label": "Ubuntu 22.04 LTS (jammy)" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"proxmox": {
|
||||||
|
"defaultRelease": "trixie",
|
||||||
|
"releases": [
|
||||||
|
{ "id": "trixie", "label": "Proxmox VE 9 / Debian 13 (trixie)", "keyring": "/usr/share/keyrings/proxmox-archive-keyring.gpg" },
|
||||||
|
{ "id": "bookworm", "label": "Proxmox VE 8 / Debian 12 (bookworm)", "keyring": "/etc/apt/trusted.gpg.d/proxmox-release-bookworm.gpg" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
_ "embed"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed generator-defaults.json
|
||||||
|
var generatorDefaultsJSON []byte
|
||||||
|
|
||||||
|
type GeneratorRelease struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Label string `json:"label"`
|
||||||
|
Stable *bool `json:"stable,omitempty"`
|
||||||
|
Firmware *bool `json:"firmware,omitempty"`
|
||||||
|
Backports *bool `json:"backports,omitempty"`
|
||||||
|
Keyring string `json:"keyring,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GeneratorVersions struct {
|
||||||
|
DefaultRelease string `json:"defaultRelease"`
|
||||||
|
Releases []GeneratorRelease `json:"releases"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var generatorTypes = []string{"debian", "ubuntu", "kubernetes", "tailscale", "proxmox"}
|
||||||
|
var suiteID = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`)
|
||||||
|
var kubernetesID = regexp.MustCompile(`^v[1-9][0-9]{0,2}\.(0|[1-9][0-9]{0,2})$`)
|
||||||
|
var tailscaleID = regexp.MustCompile(`^(debian|ubuntu)/[a-z][a-z0-9-]{0,31}$`)
|
||||||
|
var keyringPath = regexp.MustCompile(`^/(usr/share/keyrings|etc/apt/trusted\.gpg\.d)/[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}\.gpg$`)
|
||||||
|
|
||||||
|
func generatorType(id string) bool {
|
||||||
|
for _, known := range generatorTypes {
|
||||||
|
if id == known {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Values are inserted into repository files and shell commands. Accept only
|
||||||
|
// version identifiers and keyring paths, never arbitrary templates or scripts.
|
||||||
|
func validGeneratorVersions(id string, data GeneratorVersions) bool {
|
||||||
|
if !generatorType(id) || len(data.Releases) == 0 || len(data.Releases) > 100 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
hasDefault, hasStable := false, false
|
||||||
|
for _, release := range data.Releases {
|
||||||
|
validID := suiteID.MatchString(release.ID)
|
||||||
|
if id == "kubernetes" {
|
||||||
|
validID = kubernetesID.MatchString(release.ID)
|
||||||
|
}
|
||||||
|
if id == "tailscale" {
|
||||||
|
validID = tailscaleID.MatchString(release.ID)
|
||||||
|
}
|
||||||
|
if !validID || seen[release.ID] || strings.TrimSpace(release.Label) == "" || len([]rune(release.Label)) > 160 || strings.IndexFunc(release.Label, unicode.IsControl) >= 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
seen[release.ID] = true
|
||||||
|
hasDefault = hasDefault || release.ID == data.DefaultRelease
|
||||||
|
if id == "debian" {
|
||||||
|
if release.Stable == nil || release.Firmware == nil || release.Backports == nil || (*release.Backports && !*release.Stable) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
hasStable = hasStable || *release.Stable
|
||||||
|
} else if release.Stable != nil || release.Firmware != nil || release.Backports != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if id == "proxmox" {
|
||||||
|
if !keyringPath.MatchString(release.Keyring) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
} else if release.Keyring != "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hasDefault && (id != "debian" || hasStable)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Seed only missing records. Subsequent releases never overwrite admin edits.
|
||||||
|
func (a *App) seedGeneratorVersions() error {
|
||||||
|
var defaults map[string]GeneratorVersions
|
||||||
|
if err := json.Unmarshal(generatorDefaultsJSON, &defaults); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, id := range generatorTypes {
|
||||||
|
data := defaults[id]
|
||||||
|
if !validGeneratorVersions(id, data) {
|
||||||
|
return errors.New("invalid generator defaults: " + id)
|
||||||
|
}
|
||||||
|
if _, err := a.record("generators", id); errors.Is(err, errMissing) {
|
||||||
|
if _, err = a.saveRecord("generators", id, data, 0); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) generatorCatalog(w http.ResponseWriter, r *http.Request) {
|
||||||
|
records, err := a.records("generators")
|
||||||
|
if err != nil {
|
||||||
|
a.internal(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
catalog := map[string]GeneratorVersions{}
|
||||||
|
for _, record := range records {
|
||||||
|
var data GeneratorVersions
|
||||||
|
if decodeData(record.Data, &data) != nil || !validGeneratorVersions(record.ID, data) {
|
||||||
|
a.internal(w, errors.New("invalid generator record: "+record.ID))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
catalog[record.ID] = data
|
||||||
|
}
|
||||||
|
respond(w, 200, catalog)
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGeneratorCatalogPersistenceAndAuthorization(t *testing.T) {
|
||||||
|
c := fixture(t)
|
||||||
|
w := c.call("GET", "/api/v1/generators", nil, false)
|
||||||
|
status(t, w, 200)
|
||||||
|
var catalog map[string]GeneratorVersions
|
||||||
|
json.Unmarshal(w.Body.Bytes(), &catalog)
|
||||||
|
if len(catalog) != 5 {
|
||||||
|
t.Fatal("missing seeded version catalogs")
|
||||||
|
}
|
||||||
|
settingsBefore, _ := c.app.record("settings", "site")
|
||||||
|
before, _ := c.app.record("generators", "ubuntu")
|
||||||
|
versions := catalog["ubuntu"]
|
||||||
|
// Deliberately fictional future data: no official codename is assumed.
|
||||||
|
versions.Releases = append(versions.Releases, GeneratorRelease{ID: "future-test", Label: "Ubuntu future (test fixture)"})
|
||||||
|
versions.DefaultRelease = "future-test"
|
||||||
|
body := map[string]any{"data": versions, "revision": before.Revision}
|
||||||
|
path := "/api/v1/admin/records/generators/ubuntu"
|
||||||
|
status(t, c.call("PUT", path, body, true), 401)
|
||||||
|
c.login("editor")
|
||||||
|
status(t, c.call("GET", "/api/v1/admin/records/generators", nil, false), 403)
|
||||||
|
status(t, c.call("PUT", path, body, true), 403)
|
||||||
|
c.login("admin")
|
||||||
|
status(t, c.call("PUT", path, body, false), 403)
|
||||||
|
status(t, c.call("PUT", path, body, true), 200)
|
||||||
|
status(t, c.call("PUT", path, body, true), 409)
|
||||||
|
status(t, c.call("DELETE", path, map[string]any{"revision": before.Revision + 1}, true), 400)
|
||||||
|
// Starting a new app on the same DB must not overwrite edited defaults.
|
||||||
|
c.app.db.Close()
|
||||||
|
restarted, err := newApp(c.app.cfg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
c.app = restarted
|
||||||
|
t.Cleanup(func() { restarted.db.Close() })
|
||||||
|
w = c.call("GET", "/api/v1/generators", nil, false)
|
||||||
|
status(t, w, 200)
|
||||||
|
json.Unmarshal(w.Body.Bytes(), &catalog)
|
||||||
|
if !reflect.DeepEqual(catalog["ubuntu"], versions) {
|
||||||
|
t.Fatal("saved future release lost after restart")
|
||||||
|
}
|
||||||
|
settingsAfter, _ := c.app.record("settings", "site")
|
||||||
|
if !reflect.DeepEqual(settingsBefore, settingsAfter) {
|
||||||
|
t.Fatal("generator edits changed site settings")
|
||||||
|
}
|
||||||
|
var records []Record
|
||||||
|
w = c.call("GET", "/api/v1/admin/records/generators", nil, false)
|
||||||
|
status(t, w, 200)
|
||||||
|
json.Unmarshal(w.Body.Bytes(), &records)
|
||||||
|
if len(records) != 5 {
|
||||||
|
t.Fatal("admin cannot read saved version catalogs")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGeneratorCatalogRejectsUnsafeAndInconsistentData(t *testing.T) {
|
||||||
|
c := fixture(t)
|
||||||
|
c.login("admin")
|
||||||
|
var defaults map[string]GeneratorVersions
|
||||||
|
json.Unmarshal(generatorDefaultsJSON, &defaults)
|
||||||
|
for _, id := range generatorTypes {
|
||||||
|
if !validGeneratorVersions(id, defaults[id]) {
|
||||||
|
t.Fatal("invalid shared seed", id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, id := range []string{"ubuntu", "kubernetes", "tailscale", "proxmox", "debian"} {
|
||||||
|
for _, bad := range []string{"$(id)", "noble\ntrusted=yes", "../../etc/passwd", "foo;id", "foo bar", "__proto__"} {
|
||||||
|
data := GeneratorVersions{DefaultRelease: bad, Releases: []GeneratorRelease{{ID: bad, Label: "test"}}}
|
||||||
|
if validGeneratorVersions(id, data) {
|
||||||
|
t.Fatal("accepted unsafe ID", id, bad)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
invalid := []any{
|
||||||
|
map[string]any{"defaultRelease": "noble", "releases": []any{}},
|
||||||
|
map[string]any{"defaultRelease": "missing", "releases": []GeneratorRelease{{ID: "noble", Label: "Ubuntu"}}},
|
||||||
|
map[string]any{"defaultRelease": "noble", "releases": []GeneratorRelease{{ID: "noble", Label: "Ubuntu"}, {ID: "noble", Label: "duplicate"}}},
|
||||||
|
map[string]any{"defaultRelease": "noble", "releases": []GeneratorRelease{{ID: "noble", Label: ""}}},
|
||||||
|
map[string]any{"defaultRelease": "noble", "releases": []any{map[string]any{"id": "noble", "label": "Ubuntu", "command": "id"}}},
|
||||||
|
map[string]any{"defaultRelease": "noble", "releases": []GeneratorRelease{{ID: "noble", Label: "Ubuntu", Keyring: "/tmp/other.gpg"}}},
|
||||||
|
}
|
||||||
|
record, _ := c.app.record("generators", "ubuntu")
|
||||||
|
for _, data := range invalid {
|
||||||
|
status(t, c.call("PUT", "/api/v1/admin/records/generators/ubuntu", map[string]any{"data": data, "revision": record.Revision}, true), 400)
|
||||||
|
}
|
||||||
|
status(t, c.call("PUT", "/api/v1/admin/records/generators/unknown", map[string]any{"data": defaults["ubuntu"], "revision": 0}, true), 400)
|
||||||
|
pve := defaults["proxmox"]
|
||||||
|
for _, path := range []string{"/tmp/a.gpg", "/usr/share/keyrings/../../tmp/a.gpg", "/usr/share/keyrings/a.gpg\nmalicious", "/usr/share/keyrings/$(id).gpg"} {
|
||||||
|
pve.Releases[0].Keyring = path
|
||||||
|
if validGeneratorVersions("proxmox", pve) {
|
||||||
|
t.Fatal("accepted unsafe keyring", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
debian := defaults["debian"]
|
||||||
|
for index := range debian.Releases {
|
||||||
|
value := false
|
||||||
|
debian.Releases[index].Stable = &value
|
||||||
|
debian.Releases[index].Backports = &value
|
||||||
|
}
|
||||||
|
if validGeneratorVersions("debian", debian) {
|
||||||
|
t.Fatal("Debian Security lost all stable releases")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -91,6 +91,10 @@ func newApp(cfg Config) (*App, error) {
|
|||||||
db.Close()
|
db.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if err = a.seedGeneratorVersions(); err != nil {
|
||||||
|
db.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
return a, nil
|
return a, nil
|
||||||
}
|
}
|
||||||
func (a *App) handler() http.Handler {
|
func (a *App) handler() http.Handler {
|
||||||
@@ -105,6 +109,7 @@ func (a *App) handler() http.Handler {
|
|||||||
mux.HandleFunc("GET /api/v1/public", a.public)
|
mux.HandleFunc("GET /api/v1/public", a.public)
|
||||||
mux.HandleFunc("GET /api/v1/announcements", a.announcements)
|
mux.HandleFunc("GET /api/v1/announcements", a.announcements)
|
||||||
mux.HandleFunc("GET /api/v1/help", a.helpIndex)
|
mux.HandleFunc("GET /api/v1/help", a.helpIndex)
|
||||||
|
mux.HandleFunc("GET /api/v1/generators", a.generatorCatalog)
|
||||||
mux.HandleFunc("GET /api/v1/help/{name}", a.helpArticle)
|
mux.HandleFunc("GET /api/v1/help/{name}", a.helpArticle)
|
||||||
mux.HandleFunc("GET /api/v1/monitoring", a.monitoring)
|
mux.HandleFunc("GET /api/v1/monitoring", a.monitoring)
|
||||||
mux.HandleFunc("GET /api/v1/job-speeds", a.jobSpeeds)
|
mux.HandleFunc("GET /api/v1/job-speeds", a.jobSpeeds)
|
||||||
|
|||||||
@@ -23,3 +23,19 @@
|
|||||||
| [ubuntu.md](ubuntu.md) | Ubuntu 软件仓库 |
|
| [ubuntu.md](ubuntu.md) | Ubuntu 软件仓库 |
|
||||||
|
|
||||||
文章参考 TUNA 帮助和各项目官方文档编写,原始资料链接见各篇末尾。目录、版本和同步范围以本站实际提供的内容为准。
|
文章参考 TUNA 帮助和各项目官方文档编写,原始资料链接见各篇末尾。目录、版本和同步范围以本站实际提供的内容为准。
|
||||||
|
|
||||||
|
## 交互式配置
|
||||||
|
|
||||||
|
后台可通过“插入配置生成器”添加控件,也可以直接在 Markdown 中插入:
|
||||||
|
|
||||||
|
```mirror-config
|
||||||
|
{"type":"ubuntu"}
|
||||||
|
```
|
||||||
|
|
||||||
|
目前注册的类型为 `debian`、`ubuntu`、`debian-security`、`archlinux`、`archlinuxarm`、`archlinuxcn`、`anaconda`、`kubernetes`、`tailscale`、`proxmox`、`openwrt`、`elrepo`。
|
||||||
|
|
||||||
|
不指定 `format` 时,支持多格式的控件会显示格式选择。指定格式可固定展示,例如 `{"type":"ubuntu","format":"deb822","options":{"release":"noble"}}`。默认选项只接受对应控件已定义的值,不支持脚本或任意模板。
|
||||||
|
|
||||||
|
后台保存文章与控件标记;版本列表和默认版本在“配置生成器”中维护,保存后帮助页会自动读取,无需重新编译。`debian-security` 共用 Debian 中的稳定版选项。移除版本前,需检查文章中是否通过 `options.release` 固定引用了它;失效的配置标记会显示为普通代码供作者修正。
|
||||||
|
|
||||||
|
前端的 `src/mirror-config.ts` 注册生成规则,`MirrorConfig.vue` 和 `ConfigCode.vue` 共用布局和复制逻辑。新增软件源或更改包管理器规则仍需修改代码;`backend/generator-defaults.json` 仅用于首次初始化版本目录。
|
||||||
|
|||||||
+6
-22
@@ -10,21 +10,15 @@ conda config --set show_channel_urls yes
|
|||||||
|
|
||||||
切换前确认所需频道的平台目录已有 `repodata.json`,例如 [conda-forge 的 linux-64 索引](/mirrors/anaconda/cloud/conda-forge/linux-64/)。索引尚未同步完成时,先保留原配置。
|
切换前确认所需频道的平台目录已有 `repodata.json`,例如 [conda-forge 的 linux-64 索引](/mirrors/anaconda/cloud/conda-forge/linux-64/)。索引尚未同步完成时,先保留原配置。
|
||||||
|
|
||||||
## 使用 conda-forge
|
## 生成频道配置
|
||||||
|
|
||||||
将 `.condarc` 中相关配置改为以下内容。已有的 `channels` 应一并检查,避免意外混用不同频道的软件包:
|
在下面选择 conda-forge、Bioconda 或 defaults,将生成的内容合并到 `.condarc`。已有的 `channels` 应一并检查,避免意外混用不同频道的软件包。
|
||||||
|
|
||||||
```yaml
|
```mirror-config
|
||||||
channels:
|
{"type":"anaconda"}
|
||||||
- conda-forge
|
|
||||||
show_channel_urls: true
|
|
||||||
channel_priority: strict
|
|
||||||
custom_channels:
|
|
||||||
conda-forge: https://mirrors.app.itstudio.club/mirrors/anaconda/cloud
|
|
||||||
bioconda: https://mirrors.app.itstudio.club/mirrors/anaconda/cloud
|
|
||||||
```
|
```
|
||||||
|
|
||||||
这里的 `custom_channels` 地址不包含频道名,Conda 会自动补上 `conda-forge` 或 `bioconda`。
|
使用社区频道时,`custom_channels` 地址不包含频道名,Conda 会自动补上相应名称。Bioconda 配置会按 conda-forge、bioconda 的顺序启用频道。
|
||||||
|
|
||||||
刷新索引,并在新环境中验证:
|
刷新索引,并在新环境中验证:
|
||||||
|
|
||||||
@@ -42,17 +36,7 @@ conda create -n bio-test --override-channels -c conda-forge -c bioconda samtools
|
|||||||
|
|
||||||
## 使用 defaults
|
## 使用 defaults
|
||||||
|
|
||||||
如果项目需要 Anaconda 的 `defaults`,可改用下面这套配置。它是上一套配置的替代方案:
|
如果项目需要 Anaconda 的 `defaults`,在上方控件中切换到 defaults,使用生成的 `default_channels` 配置。它是社区频道配置的替代方案,不要将两套配置直接叠加。
|
||||||
|
|
||||||
```yaml
|
|
||||||
channels:
|
|
||||||
- defaults
|
|
||||||
show_channel_urls: true
|
|
||||||
default_channels:
|
|
||||||
- https://mirrors.app.itstudio.club/mirrors/anaconda/pkgs/main
|
|
||||||
- https://mirrors.app.itstudio.club/mirrors/anaconda/pkgs/r
|
|
||||||
- https://mirrors.app.itstudio.club/mirrors/anaconda/pkgs/msys2
|
|
||||||
```
|
|
||||||
|
|
||||||
使用前请查阅 Anaconda 对相应仓库的使用条款。自定义环境文件中的完整 URL、`-c` 参数和其他配置文件可能覆盖 `.condarc`;可通过 `conda config --show-sources` 排查。
|
使用前请查阅 Anaconda 对相应仓库的使用条款。自定义环境文件中的完整 URL、`-c` 参数和其他配置文件可能覆盖 `.condarc`;可通过 `conda config --show-sources` 排查。
|
||||||
|
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ sudo cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak
|
|||||||
|
|
||||||
编辑 `/etc/pacman.d/mirrorlist`,将下面一行放在最前面:
|
编辑 `/etc/pacman.d/mirrorlist`,将下面一行放在最前面:
|
||||||
|
|
||||||
```text
|
```mirror-config
|
||||||
Server = https://mirrors.app.itstudio.club/mirrors/archlinux/$repo/os/$arch
|
{"type":"archlinux"}
|
||||||
```
|
```
|
||||||
|
|
||||||
`$repo` 和 `$arch` 是 pacman 使用的变量,请原样保留。`/etc/pacman.conf` 中相应仓库应继续通过 `Include = /etc/pacman.d/mirrorlist` 引用镜像列表。
|
`$repo` 和 `$arch` 是 pacman 使用的变量,请原样保留。`/etc/pacman.conf` 中相应仓库应继续通过 `Include = /etc/pacman.d/mirrorlist` 引用镜像列表。
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ sudo cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak
|
|||||||
|
|
||||||
将下面一行放到 `/etc/pacman.d/mirrorlist` 的最前面:
|
将下面一行放到 `/etc/pacman.d/mirrorlist` 的最前面:
|
||||||
|
|
||||||
```text
|
```mirror-config
|
||||||
Server = https://mirrors.app.itstudio.club/mirrors/archlinuxarm/$arch/$repo
|
{"type":"archlinuxarm"}
|
||||||
```
|
```
|
||||||
|
|
||||||
保留 `$arch` 和 `$repo` 原样。这里没有 Arch Linux 官方仓库路径中的 `os/`。
|
保留 `$arch` 和 `$repo` 原样。这里没有 Arch Linux 官方仓库路径中的 `os/`。
|
||||||
|
|||||||
@@ -4,9 +4,8 @@ Arch Linux CN 是 Arch Linux 中文社区维护的非官方软件仓库,收录
|
|||||||
|
|
||||||
备份 `/etc/pacman.conf`,在文件末尾添加:
|
备份 `/etc/pacman.conf`,在文件末尾添加:
|
||||||
|
|
||||||
```ini
|
```mirror-config
|
||||||
[archlinuxcn]
|
{"type":"archlinuxcn"}
|
||||||
Server = https://mirrors.app.itstudio.club/mirrors/archlinuxcn/$arch
|
|
||||||
```
|
```
|
||||||
|
|
||||||
`$arch` 保持原样。本站提供的架构可在 [仓库目录](/mirrors/archlinuxcn/)中查看。已有 `[archlinuxcn]` 配置时,修改原来的 `Server`,不要重复添加仓库段。
|
`$arch` 保持原样。本站提供的架构可在 [仓库目录](/mirrors/archlinuxcn/)中查看。已有 `[archlinuxcn]` 配置时,修改原来的 `Server`,不要重复添加仓库段。
|
||||||
|
|||||||
@@ -14,29 +14,15 @@
|
|||||||
|
|
||||||
目录存在不代表该版本仍处于官方安全支持期,请同时查阅 Debian 的安全支持和 LTS 公告。
|
目录存在不代表该版本仍处于官方安全支持期,请同时查阅 Debian 的安全支持和 LTS 公告。
|
||||||
|
|
||||||
## DEB822 格式
|
## 生成安全更新配置
|
||||||
|
|
||||||
以 Debian 13 为例,备份 `/etc/apt/sources.list.d/debian.sources`,将其中安全更新段替换为:
|
备份 `/etc/apt/sources.list` 或 `/etc/apt/sources.list.d/debian.sources`,在下面选择当前系统版本和格式,只替换原有的安全更新段。保留主仓库、updates 等其他配置。
|
||||||
|
|
||||||
```text
|
```mirror-config
|
||||||
Types: deb
|
{"type":"debian-security"}
|
||||||
URIs: https://mirrors.app.itstudio.club/mirrors/debian-security/
|
|
||||||
Suites: trixie-security
|
|
||||||
Components: main contrib non-free non-free-firmware
|
|
||||||
Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg
|
|
||||||
```
|
```
|
||||||
|
|
||||||
保留文件中 Debian 主仓库、updates 等其他段。Debian 12 将 `trixie-security` 改为 `bookworm-security`;Debian 11 使用 `bullseye-security`,并移除 `non-free-firmware` 组件。
|
组件会按发行版调整:Debian 11 不加入 `non-free-firmware`。传统格式和 DEB822 选择一种即可,不要重复添加安全更新源。这里生成的内容会使用本站安全更新镜像;希望保留官方安全更新时,请使用 [Debian 帮助页](/help/debian/)中的完整配置生成器。
|
||||||
|
|
||||||
## 传统 sources.list 格式
|
|
||||||
|
|
||||||
如果系统仍使用传统格式,备份 `/etc/apt/sources.list` 后,将原来的安全更新行改为:
|
|
||||||
|
|
||||||
```text
|
|
||||||
deb https://mirrors.app.itstudio.club/mirrors/debian-security/ trixie-security main contrib non-free non-free-firmware
|
|
||||||
```
|
|
||||||
|
|
||||||
按系统版本调整套件和组件。两种格式选择一种即可,不要重复添加相同的安全更新源。
|
|
||||||
|
|
||||||
## 更新索引
|
## 更新索引
|
||||||
|
|
||||||
|
|||||||
+3
-5
@@ -25,14 +25,12 @@ sudo cp /etc/yum.repos.d/elrepo.repo /etc/yum.repos.d/elrepo.repo.bak
|
|||||||
2. 启用对应的 `baseurl=`,将其中 `http://elrepo.org/linux` 或 `https://elrepo.org/linux` 替换为 `https://mirrors.app.itstudio.club/mirrors/elrepo`。
|
2. 启用对应的 `baseurl=`,将其中 `http://elrepo.org/linux` 或 `https://elrepo.org/linux` 替换为 `https://mirrors.app.itstudio.club/mirrors/elrepo`。
|
||||||
3. 保留路径后面的系统版本、仓库名称及 `$basearch` 变量;保留官方配置中的签名检查和密钥地址。
|
3. 保留路径后面的系统版本、仓库名称及 `$basearch` 变量;保留官方配置中的签名检查和密钥地址。
|
||||||
|
|
||||||
例如 EL9 的基础仓库地址应为:
|
也可以使用下方命令完成备份、启用直接下载地址、替换地址及刷新缓存。命令保留仓库配置中的系统版本、架构和签名校验设置。
|
||||||
|
|
||||||
```ini
|
```mirror-config
|
||||||
baseurl=https://mirrors.app.itstudio.club/mirrors/elrepo/elrepo/el9/$basearch/
|
{"type":"elrepo"}
|
||||||
```
|
```
|
||||||
|
|
||||||
这只是一行地址示例,不是完整的 `.repo` 文件。不要用它覆盖 `enabled`、`gpgcheck`、`gpgkey` 等其他设置。
|
|
||||||
|
|
||||||
## 刷新缓存
|
## 刷新缓存
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
+16
-34
@@ -1,72 +1,54 @@
|
|||||||
本站镜像 Kubernetes 的版本化软件包仓库,可用于安装 `kubelet`、`kubeadm` 和 `kubectl`。容器镜像、容器运行时及集群网络插件需要另行配置。
|
本站镜像 Kubernetes 的版本化软件包仓库,可用于安装 `kubelet`、`kubeadm` 和 `kubectl`。容器镜像、容器运行时及集群网络插件需要另行配置。
|
||||||
|
|
||||||
本文以 `v1.35` 仓库为例。它是示例版本,不代表最新版本;已有集群应根据官方升级流程及版本偏差策略选择次版本,并在所有仓库地址中保持一致。修改软件源不会自动完成集群升级。
|
## 选择版本和软件包格式
|
||||||
|
|
||||||
## Debian / Ubuntu
|
先根据安装或升级计划确定 Kubernetes 次版本。已有集群需要遵守官方版本偏差策略;修改软件源不会自动完成集群升级。控件中的版本是本站已提供的仓库分支,不代表所有版本都仍处于官方支持期。
|
||||||
|
|
||||||
安装所需工具:
|
Debian、Ubuntu 选择 APT,RPM 系统选择 RPM。下面的公钥地址和软件源会一起随版本变化。
|
||||||
|
|
||||||
|
## 准备工具
|
||||||
|
|
||||||
|
APT 系统先安装工具:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo apt update
|
sudo apt update
|
||||||
sudo apt install ca-certificates curl gpg
|
sudo apt install ca-certificates curl gpg
|
||||||
sudo install -d -m 0755 /etc/apt/keyrings
|
|
||||||
```
|
```
|
||||||
|
|
||||||
从 Kubernetes 官方仓库获取该通道的签名公钥。如果同名密钥文件已经存在,先核对、备份,再更新:
|
备份已有 Kubernetes 源文件和同名签名密钥文件,再按控件中的步骤配置。APT 显示的第一段命令导入官方公钥,第二段是需要保存的源文件内容;RPM 配置通过 `gpgkey` 指定对应的官方公钥。
|
||||||
|
|
||||||
```sh
|
```mirror-config
|
||||||
curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.35/deb/Release.key | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg
|
{"type":"kubernetes"}
|
||||||
sudo chmod 0644 /etc/apt/keyrings/kubernetes-apt-keyring.gpg
|
|
||||||
```
|
```
|
||||||
|
|
||||||
备份已有 `/etc/apt/sources.list.d/kubernetes.list`,然后写入:
|
## 刷新索引并安装
|
||||||
|
|
||||||
```text
|
APT 系统查看可安装版本:
|
||||||
deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://mirrors.app.itstudio.club/mirrors/kubernetes/core:/stable:/v1.35/deb/ /
|
|
||||||
```
|
|
||||||
|
|
||||||
更新索引并查看可安装版本:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo apt update
|
sudo apt update
|
||||||
apt-cache madison kubeadm
|
apt-cache madison kubeadm
|
||||||
```
|
```
|
||||||
|
|
||||||
新节点需要安装组件时,可执行:
|
新节点需要安装组件时:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo apt install kubelet kubeadm kubectl
|
sudo apt install kubelet kubeadm kubectl
|
||||||
sudo apt-mark hold kubelet kubeadm kubectl
|
sudo apt-mark hold kubelet kubeadm kubectl
|
||||||
```
|
```
|
||||||
|
|
||||||
已有集群请按升级指南逐个处理节点,不要直接套用新节点安装步骤。
|
RPM 系统查看可安装版本:
|
||||||
|
|
||||||
## RPM 系统
|
|
||||||
|
|
||||||
备份已有 `/etc/yum.repos.d/kubernetes.repo`,配置为:
|
|
||||||
|
|
||||||
```ini
|
|
||||||
[kubernetes]
|
|
||||||
name=Kubernetes
|
|
||||||
baseurl=https://mirrors.app.itstudio.club/mirrors/kubernetes/core:/stable:/v1.35/rpm/
|
|
||||||
enabled=1
|
|
||||||
gpgcheck=1
|
|
||||||
gpgkey=https://pkgs.k8s.io/core:/stable:/v1.35/rpm/repodata/repomd.xml.key
|
|
||||||
exclude=kubelet kubeadm kubectl cri-tools kubernetes-cni
|
|
||||||
```
|
|
||||||
|
|
||||||
刷新缓存并查看版本:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo dnf makecache
|
sudo dnf makecache
|
||||||
dnf --disableexcludes=kubernetes list --showduplicates kubeadm
|
dnf --disableexcludes=kubernetes list --showduplicates kubeadm
|
||||||
```
|
```
|
||||||
|
|
||||||
新节点安装组件时使用 `sudo dnf install kubelet kubeadm kubectl --disableexcludes=kubernetes`。`exclude` 用于避免普通系统更新意外升级集群组件。
|
新节点安装使用 `sudo dnf install kubelet kubeadm kubectl --disableexcludes=kubernetes`。配置中的 `exclude` 避免普通系统更新意外升级集群组件。已有集群应按升级指南逐个处理节点。
|
||||||
|
|
||||||
## 检查地址
|
## 检查地址
|
||||||
|
|
||||||
本站使用 `core:/stable:/v1.xx/` 目录布局,不使用旧的 `apt.kubernetes.io` 地址。其他版本请先查看 [仓库目录](/mirrors/kubernetes/core:/stable:/)是否已同步,并确认该版本仍符合项目的支持策略。
|
本站使用 `core:/stable:/v1.xx/` 目录布局,不使用旧的 `apt.kubernetes.io` 地址。其他版本请查看 [仓库目录](/mirrors/kubernetes/core:/stable:/),并确认对应分支已完成同步。
|
||||||
|
|
||||||
## 参考资料
|
## 参考资料
|
||||||
|
|
||||||
|
|||||||
+4
-14
@@ -6,22 +6,12 @@
|
|||||||
|
|
||||||
OpenWrt 25.12 起使用 APK;24.10 及更早版本使用 OPKG。第三方固件可能更改包管理器或仓库,应以实际系统为准。下面的命令在路由器的 root 会话中执行。
|
OpenWrt 25.12 起使用 APK;24.10 及更早版本使用 OPKG。第三方固件可能更改包管理器或仓库,应以实际系统为准。下面的命令在路由器的 root 会话中执行。
|
||||||
|
|
||||||
## APK:OpenWrt 25.12 及之后
|
## 生成换源命令
|
||||||
|
|
||||||
备份并替换官方仓库域名:
|
根据当前系统选择 APK 或 OPKG。下面的命令先备份配置,再替换仓库地址并刷新索引。
|
||||||
|
|
||||||
```sh
|
```mirror-config
|
||||||
cp /etc/apk/repositories.d/distfeeds.list /etc/apk/repositories.d/distfeeds.list.bak
|
{"type":"openwrt"}
|
||||||
sed -i 's|https\?://downloads.openwrt.org|https://mirrors.app.itstudio.club/mirrors/openwrt|g' /etc/apk/repositories.d/distfeeds.list
|
|
||||||
apk update
|
|
||||||
```
|
|
||||||
|
|
||||||
## OPKG:OpenWrt 24.10 及之前
|
|
||||||
|
|
||||||
```sh
|
|
||||||
cp /etc/opkg/distfeeds.conf /etc/opkg/distfeeds.conf.bak
|
|
||||||
sed -i 's|https\?://downloads.openwrt.org|https://mirrors.app.itstudio.club/mirrors/openwrt|g' /etc/opkg/distfeeds.conf
|
|
||||||
opkg update
|
|
||||||
```
|
```
|
||||||
|
|
||||||
两种方式仅替换官方地址的前缀,保留原来的版本、target、subtarget 和软件包架构路径。自定义仓库保持原样。不要复制其他路由器的整份源配置,否则可能安装不兼容的软件包。
|
两种方式仅替换官方地址的前缀,保留原来的版本、target、subtarget 和软件包架构路径。自定义仓库保持原样。不要复制其他路由器的整份源配置,否则可能安装不兼容的软件包。
|
||||||
|
|||||||
+6
-18
@@ -11,29 +11,17 @@ Proxmox VE 9 基于 Debian 13(`trixie`),Proxmox VE 8 基于 Debian 12(`b
|
|||||||
|
|
||||||
以下操作在节点的 root 终端中执行。操作前备份 `/etc/apt/sources.list` 及 `/etc/apt/sources.list.d/` 中将要修改的文件。
|
以下操作在节点的 root 终端中执行。操作前备份 `/etc/apt/sources.list` 及 `/etc/apt/sources.list.d/` 中将要修改的文件。
|
||||||
|
|
||||||
## Proxmox VE 9:DEB822 格式
|
## 生成仓库配置
|
||||||
|
|
||||||
创建或编辑 `/etc/apt/sources.list.d/proxmox.sources`:
|
选择当前 Proxmox VE 版本和源配置格式,将生成的内容保存到所标注的文件中。PVE 9 通常使用 DEB822,PVE 8 通常使用传统格式。
|
||||||
|
|
||||||
```text
|
```mirror-config
|
||||||
Types: deb
|
{"type":"proxmox"}
|
||||||
URIs: https://mirrors.app.itstudio.club/mirrors/proxmox/debian/pve
|
|
||||||
Suites: trixie
|
|
||||||
Components: pve-no-subscription
|
|
||||||
Signed-By: /usr/share/keyrings/proxmox-archive-keyring.gpg
|
|
||||||
```
|
```
|
||||||
|
|
||||||
密钥环由 Proxmox 官方软件包提供;若文件缺失,请先按官方说明修复密钥环,不要移除 `Signed-By` 或关闭验证。
|
Proxmox 官方安装的软件包负责提供签名密钥;PVE 9 使用 `/usr/share/keyrings/proxmox-archive-keyring.gpg`,PVE 8 的官方密钥文件为 `/etc/apt/trusted.gpg.d/proxmox-release-bookworm.gpg`。文件缺失时先按对应版本的官方说明修复,不要移除签名校验。传统格式继续使用系统已有的官方签名密钥配置。
|
||||||
|
|
||||||
## Proxmox VE 8:传统格式
|
两种格式选择其一,不要重复启用相同仓库。
|
||||||
|
|
||||||
创建或编辑 `/etc/apt/sources.list.d/pve-no-subscription.list`:
|
|
||||||
|
|
||||||
```text
|
|
||||||
deb https://mirrors.app.itstudio.club/mirrors/proxmox/debian/pve bookworm pve-no-subscription
|
|
||||||
```
|
|
||||||
|
|
||||||
继续使用系统已有的官方签名密钥配置。两种格式按当前版本选择其一,不要重复启用相同仓库。
|
|
||||||
|
|
||||||
## 检查仓库并更新
|
## 检查仓库并更新
|
||||||
|
|
||||||
|
|||||||
+10
-33
@@ -1,50 +1,27 @@
|
|||||||
本站提供 Tailscale 稳定通道的 Debian、Ubuntu APT 软件包,分别位于 `tailscale/debian/` 和 `tailscale/ubuntu/`。镜像地址中不含上游的 `stable/` 路径;本站未提供对应的 RPM 仓库。
|
本站提供 Tailscale 稳定通道的 Debian、Ubuntu APT 软件包,分别位于 `tailscale/debian/` 和 `tailscale/ubuntu/`。镜像地址中不含上游的 `stable/` 路径;本站未提供对应的 RPM 仓库。
|
||||||
|
|
||||||
先运行 `cat /etc/os-release` 确认发行版和代号。下面两套配置择一使用,不能在 Ubuntu 上使用 Debian 仓库,反之亦然。
|
## 确认系统
|
||||||
|
|
||||||
## 准备工具
|
运行 `cat /etc/os-release` 确认发行版和代号。不能在 Ubuntu 上选择 Debian 仓库,反之亦然。
|
||||||
|
|
||||||
|
安装工具:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo apt update
|
sudo apt update
|
||||||
sudo apt install ca-certificates curl
|
sudo apt install ca-certificates curl
|
||||||
sudo install -d -m 0755 /usr/share/keyrings
|
|
||||||
```
|
```
|
||||||
|
|
||||||
已有 `/etc/apt/sources.list.d/tailscale.list` 或同名密钥环时,先备份并检查,避免重复配置。密钥从 Tailscale 官方站点获取。
|
已有 `/etc/apt/sources.list.d/tailscale.list`、`tailscale.sources` 或同名密钥环时,先备份并检查,避免重复配置。
|
||||||
|
|
||||||
## Debian 示例
|
## 生成配置
|
||||||
|
|
||||||
以 Debian 12(`bookworm`)为例,下载官方公钥:
|
选择当前系统版本。第一段命令从 Tailscale 官方获取对应公钥,第二段是需要保存的源文件内容,两者会一起随版本变化。传统格式和 DEB822 选择一种即可。
|
||||||
|
|
||||||
```sh
|
```mirror-config
|
||||||
curl -fsSL https://pkgs.tailscale.com/stable/debian/bookworm.noarmor.gpg | sudo tee /usr/share/keyrings/tailscale-archive-keyring.gpg >/dev/null
|
{"type":"tailscale"}
|
||||||
sudo chmod 0644 /usr/share/keyrings/tailscale-archive-keyring.gpg
|
|
||||||
```
|
```
|
||||||
|
|
||||||
将 `/etc/apt/sources.list.d/tailscale.list` 设置为:
|
未列出的版本请先检查 [Debian 目录](/mirrors/tailscale/debian/dists/)或 [Ubuntu 目录](/mirrors/tailscale/ubuntu/dists/)是否有对应套件,并参照官方说明配置。
|
||||||
|
|
||||||
```text
|
|
||||||
deb [signed-by=/usr/share/keyrings/tailscale-archive-keyring.gpg] https://mirrors.app.itstudio.club/mirrors/tailscale/debian bookworm main
|
|
||||||
```
|
|
||||||
|
|
||||||
Debian 13 使用 `trixie`,同时替换官方密钥下载地址和源配置中的代号。其他版本请先确认 [Debian 目录](/mirrors/tailscale/debian/dists/)中存在对应套件。
|
|
||||||
|
|
||||||
## Ubuntu 示例
|
|
||||||
|
|
||||||
以 Ubuntu 24.04 LTS(`noble`)为例:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
curl -fsSL https://pkgs.tailscale.com/stable/ubuntu/noble.noarmor.gpg | sudo tee /usr/share/keyrings/tailscale-archive-keyring.gpg >/dev/null
|
|
||||||
sudo chmod 0644 /usr/share/keyrings/tailscale-archive-keyring.gpg
|
|
||||||
```
|
|
||||||
|
|
||||||
将 `/etc/apt/sources.list.d/tailscale.list` 设置为:
|
|
||||||
|
|
||||||
```text
|
|
||||||
deb [signed-by=/usr/share/keyrings/tailscale-archive-keyring.gpg] https://mirrors.app.itstudio.club/mirrors/tailscale/ubuntu noble main
|
|
||||||
```
|
|
||||||
|
|
||||||
其他 Ubuntu 版本需同时修改密钥地址和套件代号,并确认 [Ubuntu 目录](/mirrors/tailscale/ubuntu/dists/)中已提供该套件。
|
|
||||||
|
|
||||||
## 安装和登录
|
## 安装和登录
|
||||||
|
|
||||||
|
|||||||
+7
-26
@@ -14,38 +14,19 @@ dpkg --print-architecture
|
|||||||
|
|
||||||
切换前检查 [noble 索引目录](/mirrors/ubuntu/dists/noble/)是否有 `InRelease` 或 `Release`。如果索引尚未同步完成,请继续使用官方源,稍后再切换。
|
切换前检查 [noble 索引目录](/mirrors/ubuntu/dists/noble/)是否有 `InRelease` 或 `Release`。如果索引尚未同步完成,请继续使用官方源,稍后再切换。
|
||||||
|
|
||||||
## Ubuntu 24.04 及之后:DEB822 格式
|
## 生成软件源配置
|
||||||
|
|
||||||
先备份 `/etc/apt/sources.list.d/ubuntu.sources`,再将其中的 Ubuntu 仓库配置替换为:
|
先备份系统现有的软件源配置。Ubuntu 24.04 及之后通常使用 `/etc/apt/sources.list.d/ubuntu.sources`,Ubuntu 22.04 通常使用 `/etc/apt/sources.list`。
|
||||||
|
|
||||||
```text
|
在下面选择当前系统的版本和配置格式,将生成的内容替换到对应文件中。配置中的域名随当前访问的镜像站地址变化,右上角按钮可复制完整配置。
|
||||||
Types: deb
|
|
||||||
URIs: https://mirrors.app.itstudio.club/mirrors/ubuntu/
|
|
||||||
Suites: noble noble-updates noble-backports
|
|
||||||
Components: main restricted universe multiverse
|
|
||||||
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
|
|
||||||
|
|
||||||
Types: deb
|
```mirror-config
|
||||||
URIs: http://security.ubuntu.com/ubuntu/
|
{"type":"ubuntu"}
|
||||||
Suites: noble-security
|
|
||||||
Components: main restricted universe multiverse
|
|
||||||
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
|
|
||||||
```
|
```
|
||||||
|
|
||||||
安全更新保留官方源,以减少镜像同步延迟的影响。不要同时保留另一份相同仓库配置。
|
安全更新默认保留官方源,以减少镜像同步延迟的影响。`proposed` 默认关闭,普通使用无需开启。源码开关控制是否获取源码包索引。
|
||||||
|
|
||||||
## Ubuntu 22.04:传统格式
|
保留其他独立软件源的配置。传统格式和 DEB822 格式选择一种即可,不要重复启用相同的 Ubuntu 仓库。选择 HTTP 或 HTTPS 时,请确认当前镜像站入口支持对应协议。
|
||||||
|
|
||||||
备份 `/etc/apt/sources.list` 后,将 Ubuntu 条目替换为:
|
|
||||||
|
|
||||||
```text
|
|
||||||
deb https://mirrors.app.itstudio.club/mirrors/ubuntu/ jammy main restricted universe multiverse
|
|
||||||
deb https://mirrors.app.itstudio.club/mirrors/ubuntu/ jammy-updates main restricted universe multiverse
|
|
||||||
deb https://mirrors.app.itstudio.club/mirrors/ubuntu/ jammy-backports main restricted universe multiverse
|
|
||||||
deb http://security.ubuntu.com/ubuntu/ jammy-security main restricted universe multiverse
|
|
||||||
```
|
|
||||||
|
|
||||||
保留其他独立软件源的配置。需要源码包时,可以在传统格式中增加对应 `deb-src` 行,或将 DEB822 的 `Types` 改为 `deb deb-src`。
|
|
||||||
|
|
||||||
## 更新索引
|
## 更新索引
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
"check:monitoring": "node scripts/check-monitoring.ts",
|
"check:monitoring": "node scripts/check-monitoring.ts",
|
||||||
"check:help": "node scripts/check-help.ts",
|
"check:help": "node scripts/check-help.ts",
|
||||||
"check:debian": "node scripts/check-debian-sources.ts",
|
"check:debian": "node scripts/check-debian-sources.ts",
|
||||||
|
"check:generators": "node scripts/check-mirror-config.ts",
|
||||||
"check:directory": "node scripts/check-directory.ts",
|
"check:directory": "node scripts/check-directory.ts",
|
||||||
"check:errors": "node scripts/check-errors.ts"
|
"check:errors": "node scripts/check-errors.ts"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ assert.throws(() => debianSources({ ...base, release: 'unknown' as DebianSourceO
|
|||||||
const fence = (data: string) => '```mirror-config\n' + data + '\n```\n'
|
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 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)
|
const blocks = helpBlocks(source)
|
||||||
assert.deepEqual(blocks.filter(block => block.kind === 'debian'), [{ kind: 'debian', format: 'list' }, { kind: 'debian', format: 'deb822' }])
|
assert.deepEqual(blocks.filter(block => block.kind === 'config'), [{ kind: 'config', config: { type: 'debian', format: 'list' } }, { kind: 'config', config: { type: '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')
|
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']) {
|
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(fence(data)).every(block => block.kind === 'markdown'), 'Invalid or unsupported blocks must remain ordinary Markdown code')
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { marked } from 'marked'
|
||||||
|
import { mirrorOrigin } from '../src/apt-sources.ts'
|
||||||
|
import { ubuntuReleases, ubuntuSources } from '../src/ubuntu-sources.ts'
|
||||||
|
import { configDefaults, configFields, generateMirrorConfig, mirrorConfigTypes, mirrorGenerators, parseMirrorConfig, type ConfigValues, type MirrorConfig } from '../src/mirror-config.ts'
|
||||||
|
import { helpBlocks } from '../src/help-content.ts'
|
||||||
|
import { defaultGeneratorCatalog, parseGeneratorCatalog, validGeneratorVersions, type GeneratorCatalog } from '../src/generator-catalog.ts'
|
||||||
|
|
||||||
|
const origin = 'https://mirrors.example.edu'
|
||||||
|
let ubuntuCases = 0
|
||||||
|
for (const release of ubuntuReleases) for (const format of ['list', 'deb822'] as const) for (const sources of [true, false]) for (const proposed of [true, false]) for (const securityMirror of [true, false]) {
|
||||||
|
const text = ubuntuSources({ origin, release: release.id, format, sources, proposed, securityMirror })
|
||||||
|
assert.equal(text.includes(`${release.id}-proposed`), proposed)
|
||||||
|
assert.ok(text.includes(`${release.id}-security`))
|
||||||
|
assert.ok(text.includes(`${release.id}-updates`))
|
||||||
|
assert.ok(text.includes(`${release.id}-backports`))
|
||||||
|
assert.equal(text.includes('http://security.ubuntu.com/ubuntu/'), !securityMirror)
|
||||||
|
assert.ok(text.includes('main restricted universe multiverse'))
|
||||||
|
assert.ok(!/trusted=yes|allow-insecure|undefined|NaN|ubuntu-ports/.test(text))
|
||||||
|
if (format === 'deb822') {
|
||||||
|
assert.equal(text.includes('Types: deb deb-src'), sources)
|
||||||
|
assert.ok(text.includes('Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg'))
|
||||||
|
} else assert.equal(text.split('\n').some(line => line.startsWith('deb-src ')), sources)
|
||||||
|
ubuntuCases++
|
||||||
|
}
|
||||||
|
|
||||||
|
const fixtures: { name: string; file: string; format: string; body: string }[] = []
|
||||||
|
let profileCases = 0
|
||||||
|
for (const type of mirrorConfigTypes) {
|
||||||
|
const generator = mirrorGenerators[type]
|
||||||
|
for (const selected of generator.formats) {
|
||||||
|
const config: MirrorConfig = { type, format: selected.value }
|
||||||
|
const initial = configDefaults(config, origin)
|
||||||
|
const states: ConfigValues[] = [initial]
|
||||||
|
for (const field of configFields(type)) {
|
||||||
|
for (const value of field.kind === 'switch' ? [true, false] : field.choices!.map(choice => choice.value)) states.push({ ...initial, [field.key]: value })
|
||||||
|
}
|
||||||
|
for (const values of states) {
|
||||||
|
const files = generateMirrorConfig(config, origin, values)
|
||||||
|
assert.ok(files.length > 0)
|
||||||
|
for (const file of files) {
|
||||||
|
assert.ok(file.path || file.titleKey)
|
||||||
|
assert.ok(file.code.trim())
|
||||||
|
assert.ok(!/undefined|NaN|trusted=yes|SigLevel\s*=\s*Never|gpgcheck=0|curl\s+-k/.test(file.code))
|
||||||
|
assert.ok(file.code.includes('mirrors.example.edu') || file.titleKey === 'mirrors.generator.signingKey')
|
||||||
|
if (file.path?.endsWith('.sources') || file.path?.endsWith('.list') && file.code.startsWith('deb ')) fixtures.push({ name: type, file: file.path, format: file.path.endsWith('.sources') ? 'sources' : 'list', body: file.code })
|
||||||
|
}
|
||||||
|
profileCases++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.ok(generateMirrorConfig({ type: 'ubuntu' }, origin).at(-1)!.code.includes('noble-updates'))
|
||||||
|
assert.ok(!generateMirrorConfig({ type: 'ubuntu' }, origin).at(-1)!.code.includes('noble-proposed'))
|
||||||
|
assert.ok(generateMirrorConfig({ type: 'archlinux' }, origin)[0]!.code.includes('/$repo/os/$arch'))
|
||||||
|
assert.ok(generateMirrorConfig({ type: 'archlinuxarm' }, origin)[0]!.code.includes('/$arch/$repo'))
|
||||||
|
assert.ok(generateMirrorConfig({ type: 'archlinuxcn' }, origin)[0]!.code.includes('[archlinuxcn]'))
|
||||||
|
assert.ok(generateMirrorConfig({ type: 'openwrt' }, origin)[0]!.code.includes('https\\?://downloads.openwrt.org'))
|
||||||
|
assert.ok(generateMirrorConfig({ type: 'kubernetes', options: { release: 'v1.36' } }, origin)[0]!.code.includes('v1.36/deb/Release.key'))
|
||||||
|
const tailscale = generateMirrorConfig({ type: 'tailscale', options: { release: 'ubuntu/noble' } }, origin)
|
||||||
|
assert.ok(tailscale[0]!.code.includes('/stable/ubuntu/noble.noarmor.gpg'))
|
||||||
|
assert.ok(tailscale[1]!.code.includes('/mirrors/tailscale/ubuntu noble main'))
|
||||||
|
assert.ok(!tailscale[1]!.code.includes('/mirrors/tailscale/stable/'))
|
||||||
|
assert.ok(generateMirrorConfig({ type: 'proxmox', format: 'deb822', options: { release: 'bookworm' } }, origin)[0]!.code.includes('Signed-By: /etc/apt/trusted.gpg.d/proxmox-release-bookworm.gpg'))
|
||||||
|
assert.ok(generateMirrorConfig({ type: 'proxmox', format: 'deb822', options: { release: 'trixie' } }, origin)[0]!.code.includes('Signed-By: /usr/share/keyrings/proxmox-archive-keyring.gpg'))
|
||||||
|
assert.throws(() => generateMirrorConfig({ type: 'ubuntu', options: { release: 'sid' } }, origin))
|
||||||
|
assert.throws(() => generateMirrorConfig({ type: 'anaconda' }, "https://bad'host.example"))
|
||||||
|
assert.throws(() => mirrorOrigin('javascript:alert(1)'))
|
||||||
|
assert.throws(() => mirrorOrigin('https://user:password@example.edu'))
|
||||||
|
assert.ok(generateMirrorConfig({ type: 'ubuntu', options: { protocol: 'http' } }, origin)[0]!.code.includes('http://mirrors.example.edu/mirrors/ubuntu/'))
|
||||||
|
|
||||||
|
const fence = (body: string) => '```mirror-config\n' + body + '\n```\n'
|
||||||
|
for (const type of mirrorConfigTypes) {
|
||||||
|
assert.deepEqual(helpBlocks(fence(JSON.stringify({ type }))), [{ kind: 'config', config: { type } }])
|
||||||
|
}
|
||||||
|
for (const value of [null, [], {}, { type: 'constructor' }, { type: '__proto__' }, { type: 'ubuntu', format: 'shell' }, { type: 'ubuntu', options: { release: 'sid' } }, { type: 'ubuntu', options: { sources: 'true' } }, { type: 'ubuntu', options: { __invalid: true } }, { type: 'ubuntu', options: [] }, { type: 'ubuntu', script: 'alert(1)' }, { type: 'ubuntu', options: { protocol: 'javascript' } }]) {
|
||||||
|
assert.equal(parseMirrorConfig(value), null)
|
||||||
|
assert.ok(helpBlocks(fence(JSON.stringify(value))).every(block => block.kind === 'markdown'))
|
||||||
|
}
|
||||||
|
assert.ok(helpBlocks(fence('x'.repeat(2049))).every(block => block.kind === 'markdown'))
|
||||||
|
assert.ok(helpBlocks('````markdown\n' + fence('{"type":"ubuntu"}') + '````').every(block => block.kind === 'markdown'))
|
||||||
|
const blocks = helpBlocks('[Ubuntu][official]\n\n' + fence('{"type":"ubuntu"}') + '\n[official]: https://ubuntu.com/\n')
|
||||||
|
assert.ok(blocks.filter(block => block.kind === 'markdown').map(block => marked.parser(block.tokens)).join('').includes('href="https://ubuntu.com/"'))
|
||||||
|
|
||||||
|
// Use deliberately fictional release names to prove data-only additions work
|
||||||
|
// without asserting the codenames of unreleased distributions.
|
||||||
|
const future: GeneratorCatalog = structuredClone(defaultGeneratorCatalog)
|
||||||
|
future.ubuntu.releases.unshift({ id: 'future-test', label: 'Ubuntu future (test fixture)' })
|
||||||
|
future.ubuntu.defaultRelease = 'future-test'
|
||||||
|
future.debian.releases.unshift({ id: 'future-stable', label: 'Debian future (test fixture)', stable: true, firmware: true, backports: true })
|
||||||
|
future.debian.releases.push({ id: 'future-rolling', label: 'Rolling (test fixture)', stable: false, firmware: true, backports: false })
|
||||||
|
future.debian.defaultRelease = 'future-stable'
|
||||||
|
future.kubernetes.releases.unshift({ id: 'v2.99', label: 'Kubernetes future (test fixture)' })
|
||||||
|
future.kubernetes.defaultRelease = 'v2.99'
|
||||||
|
future.tailscale.releases.unshift({ id: 'ubuntu/future-test', label: 'Ubuntu future (test fixture)' })
|
||||||
|
future.tailscale.defaultRelease = 'ubuntu/future-test'
|
||||||
|
future.proxmox.releases.unshift({ id: 'future-test', label: 'PVE future (test fixture)', keyring: '/usr/share/keyrings/proxmox-future-test.gpg' })
|
||||||
|
future.proxmox.defaultRelease = 'future-test'
|
||||||
|
assert.ok(parseGeneratorCatalog(future))
|
||||||
|
const futureUbuntu = generateMirrorConfig({ type: 'ubuntu' }, origin, {}, future)[0]!.code
|
||||||
|
assert.ok(futureUbuntu.includes('Suites: future-test future-test-updates future-test-backports'))
|
||||||
|
assert.ok(futureUbuntu.includes('Suites: future-test-security'))
|
||||||
|
assert.ok(generateMirrorConfig({ type: 'debian' }, origin, {}, future)[0]!.code.includes('future-stable-backports'))
|
||||||
|
assert.ok(configFields('debian-security', future)[0]!.choices!.some(choice => choice.value === 'future-stable'))
|
||||||
|
assert.ok(!configFields('debian-security', future)[0]!.choices!.some(choice => choice.value === 'future-rolling'))
|
||||||
|
assert.ok(!generateMirrorConfig({ type: 'debian', options: { release: 'future-rolling', securityMirror: true } }, origin, {}, future)[0]!.code.includes('future-rolling-security'))
|
||||||
|
assert.ok(generateMirrorConfig({ type: 'kubernetes' }, origin, {}, future)[0]!.code.includes('/v2.99/deb/Release.key'))
|
||||||
|
assert.ok(generateMirrorConfig({ type: 'tailscale' }, origin, {}, future)[0]!.code.includes('/ubuntu/future-test.noarmor.gpg'))
|
||||||
|
assert.ok(generateMirrorConfig({ type: 'proxmox' }, origin, {}, future)[0]!.code.includes('Signed-By: /usr/share/keyrings/proxmox-future-test.gpg'))
|
||||||
|
assert.equal(helpBlocks(fence('{"type":"ubuntu","options":{"release":"future-test"}}'), future)[0]!.kind, 'config')
|
||||||
|
assert.equal(helpBlocks(fence('{"type":"ubuntu","options":{"release":"future-test"}}'))[0]!.kind, 'markdown')
|
||||||
|
for (const bad of ['foo\ntrusted=yes', 'foo;id', 'foo bar', '$(id)', '../../etc/passwd', '__proto__']) {
|
||||||
|
const invalid = structuredClone(future)
|
||||||
|
invalid.ubuntu.releases[0]!.id = bad
|
||||||
|
invalid.ubuntu.defaultRelease = bad
|
||||||
|
assert.equal(parseGeneratorCatalog(invalid), null)
|
||||||
|
}
|
||||||
|
assert.equal(validGeneratorVersions('proxmox', { defaultRelease: 'foo', releases: [{ id: 'foo', label: 'PVE', keyring: '/tmp/evil.gpg' }] }), false)
|
||||||
|
assert.equal(validGeneratorVersions('ubuntu', { defaultRelease: 'foo', releases: [{ id: 'foo', label: 'A' }, { id: 'foo', label: 'B' }] }), false)
|
||||||
|
assert.equal(validGeneratorVersions('debian', { defaultRelease: 'foo', releases: [{ id: 'foo', label: 'Rolling', stable: false, firmware: true, backports: false }] }), false)
|
||||||
|
assert.equal(parseGeneratorCatalog({ ...future, script: 'id' }), null)
|
||||||
|
|
||||||
|
if (process.argv.includes('--fixtures')) console.log(JSON.stringify(fixtures))
|
||||||
|
else console.log(`Generator checks passed: ${mirrorConfigTypes.length} profiles, ${profileCases} profile states, ${ubuntuCases} Ubuntu combinations, data-only future releases for 5 families, safe Markdown parsing, version-coupled keys and repository paths.`)
|
||||||
@@ -17,12 +17,14 @@ import { content } from './api'
|
|||||||
import { announcementUrl } from './announcements'
|
import { announcementUrl } from './announcements'
|
||||||
import { helpRoute, helpUrl } from './help'
|
import { helpRoute, helpUrl } from './help'
|
||||||
import { usePublicData } from './usePublicData'
|
import { usePublicData } from './usePublicData'
|
||||||
|
import { provideGeneratorCatalog } from './useGeneratorCatalog'
|
||||||
import { useMirrorFormats } from './useMirrorFormats'
|
import { useMirrorFormats } from './useMirrorFormats'
|
||||||
import { type Mirror } from './data'
|
import { type Mirror } from './data'
|
||||||
import { datetimeFormats, readPreference, savePreference, type Locale } from './locales'
|
import { datetimeFormats, readPreference, savePreference, type Locale } from './locales'
|
||||||
|
|
||||||
const { t, locale } = useI18n()
|
const { t, locale } = useI18n()
|
||||||
const isAdminPage = window.location.pathname.startsWith('/admin')
|
const isAdminPage = window.location.pathname.startsWith('/admin')
|
||||||
|
provideGeneratorCatalog(isAdminPage || window.location.pathname.startsWith('/help'))
|
||||||
const { site, mirrors, announcements: articleRecords, source, loading } = usePublicData()
|
const { site, mirrors, announcements: articleRecords, source, loading } = usePublicData()
|
||||||
const announcements = computed(() => articleRecords.value.map(row => ({ id: row.id, ...row.data })))
|
const announcements = computed(() => articleRecords.value.map(row => ({ id: row.id, ...row.data })))
|
||||||
const distributions = computed(() => site.value?.downloads || [])
|
const distributions = computed(() => site.value?.downloads || [])
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
export type AptFormat = 'list' | 'deb822'
|
||||||
|
export interface AptRepository { uri: string; suites: string[]; components: string; keyring: string }
|
||||||
|
|
||||||
|
export function mirrorOrigin(value: string, protocol?: string) {
|
||||||
|
const origin = new URL(value)
|
||||||
|
if (!['http:', 'https:'].includes(origin.protocol) || origin.username || origin.password) throw new Error('Invalid mirror origin')
|
||||||
|
if (!/^[a-z0-9._:\[\]-]+$/i.test(origin.host)) throw new Error('Invalid mirror host')
|
||||||
|
if (protocol !== undefined) {
|
||||||
|
if (protocol !== 'http' && protocol !== 'https') throw new Error('Invalid mirror protocol')
|
||||||
|
origin.protocol = protocol + ':'
|
||||||
|
}
|
||||||
|
return origin.origin
|
||||||
|
}
|
||||||
|
|
||||||
|
export function aptSources(groups: AptRepository[], format: AptFormat, sources: boolean) {
|
||||||
|
if (format !== 'list' && format !== 'deb822') throw new Error('Invalid APT format')
|
||||||
|
if (format === 'deb822') {
|
||||||
|
return groups.map(group => [
|
||||||
|
`Types: ${sources ? 'deb deb-src' : 'deb'}`,
|
||||||
|
`URIs: ${group.uri}`,
|
||||||
|
`Suites: ${group.suites.join(' ')}`,
|
||||||
|
`Components: ${group.components}`,
|
||||||
|
`Signed-By: ${group.keyring}`,
|
||||||
|
].join('\n')).join('\n\n') + '\n'
|
||||||
|
}
|
||||||
|
return groups.flatMap(group => group.suites.map(suite => [
|
||||||
|
`deb ${group.uri} ${suite} ${group.components}`,
|
||||||
|
`${sources ? '' : '# '}deb-src ${group.uri} ${suite} ${group.components}`,
|
||||||
|
].join('\n'))).join('\n\n') + '\n'
|
||||||
|
}
|
||||||
@@ -8,6 +8,10 @@ import { helpUrl } from '../help'
|
|||||||
import MarkdownContent from './MarkdownContent.vue'
|
import MarkdownContent from './MarkdownContent.vue'
|
||||||
import DownloadCatalogEditor from './DownloadCatalogEditor.vue'
|
import DownloadCatalogEditor from './DownloadCatalogEditor.vue'
|
||||||
import MirrorHelpContent from './MirrorHelpContent.vue'
|
import MirrorHelpContent from './MirrorHelpContent.vue'
|
||||||
|
import { mirrorConfigTypes, mirrorGenerators, type MirrorConfigType } from '../mirror-config'
|
||||||
|
import GeneratorCatalogEditor from './GeneratorCatalogEditor.vue'
|
||||||
|
import type { GeneratorVersions } from '../generator-catalog'
|
||||||
|
import { useGeneratorCatalog } from '../useGeneratorCatalog'
|
||||||
|
|
||||||
const { t, te, d, n } = useI18n({ useScope: 'global' })
|
const { t, te, d, n } = useI18n({ useScope: 'global' })
|
||||||
const session = ref<AdminSession | null>(null)
|
const session = ref<AdminSession | null>(null)
|
||||||
@@ -16,13 +20,15 @@ const busy = ref(false)
|
|||||||
const error = ref('')
|
const error = ref('')
|
||||||
const notice = ref('')
|
const notice = ref('')
|
||||||
const tab = ref('overview')
|
const tab = ref('overview')
|
||||||
const tabs = ['overview', 'mirrors', 'announcements', 'downloads', 'config', 'settings', 'users', 'audit']
|
const tabs = ['overview', 'mirrors', 'announcements', 'downloads', 'generators', 'config', 'settings', 'users', 'audit']
|
||||||
const allowedTabs = computed(() => session.value?.role === 'admin' ? tabs : ['announcements', 'users'])
|
const allowedTabs = computed(() => session.value?.role === 'admin' ? tabs : ['announcements', 'users'])
|
||||||
const credentials = reactive({ username: '', password: '' })
|
const credentials = reactive({ username: '', password: '' })
|
||||||
const overview = ref<Overview | null>(null)
|
const overview = ref<Overview | null>(null)
|
||||||
const articles = ref<ContentRecord<AnnouncementContent>[]>([])
|
const articles = ref<ContentRecord<AnnouncementContent>[]>([])
|
||||||
const metadata = ref<ContentRecord<MirrorMetadata>[]>([])
|
const metadata = ref<ContentRecord<MirrorMetadata>[]>([])
|
||||||
const settings = ref<ContentRecord<SiteSettings> | null>(null)
|
const settings = ref<ContentRecord<SiteSettings> | null>(null)
|
||||||
|
const generatorRecords = ref<ContentRecord<GeneratorVersions>[]>([])
|
||||||
|
const { refresh: refreshGenerators } = useGeneratorCatalog()
|
||||||
const downloadEditor = ref<InstanceType<typeof DownloadCatalogEditor>>()
|
const downloadEditor = ref<InstanceType<typeof DownloadCatalogEditor>>()
|
||||||
const users = ref<AdminUser[]>([])
|
const users = ref<AdminUser[]>([])
|
||||||
const audit = ref<AuditPage>({ items: [], page: 1, pageSize: 10, total: 0, totalPages: 1 })
|
const audit = ref<AuditPage>({ items: [], page: 1, pageSize: 10, total: 0, totalPages: 1 })
|
||||||
@@ -35,6 +41,8 @@ const articlePublished = computed(() => articlesEditor.value?.data.published ??
|
|||||||
const sortedArticles = computed(() => [...articles.value].sort((a, b) => Number(b.data.pinned) - Number(a.data.pinned) || Date.parse(b.data.date) - Date.parse(a.data.date)))
|
const sortedArticles = computed(() => [...articles.value].sort((a, b) => Number(b.data.pinned) - Number(a.data.pinned) || Date.parse(b.data.date) - Date.parse(a.data.date)))
|
||||||
const articleDate = computed(() => articlesEditor.value?.data.date ? new Intl.DateTimeFormat('en-CA', { year: 'numeric', month: '2-digit', day: '2-digit', timeZone: 'Asia/Shanghai' }).format(new Date(articlesEditor.value.data.date)) : '')
|
const articleDate = computed(() => articlesEditor.value?.data.date ? new Intl.DateTimeFormat('en-CA', { year: 'numeric', month: '2-digit', day: '2-digit', timeZone: 'Asia/Shanghai' }).format(new Date(articlesEditor.value.data.date)) : '')
|
||||||
const mirrorEditor = ref<ContentRecord<MirrorMetadata> | null>(null)
|
const mirrorEditor = ref<ContentRecord<MirrorMetadata> | null>(null)
|
||||||
|
const mirrorHelpInput = ref<HTMLTextAreaElement>()
|
||||||
|
const helpGenerator = ref<MirrorConfigType>('ubuntu')
|
||||||
const publishedMirrorHelp = computed(() => metadata.value.some(row => row.id === mirrorEditor.value?.id && row.data.visible && row.data.help?.trim()))
|
const publishedMirrorHelp = computed(() => metadata.value.some(row => row.id === mirrorEditor.value?.id && row.data.visible && row.data.help?.trim()))
|
||||||
const editLocale = ref('zh-CN')
|
const editLocale = ref('zh-CN')
|
||||||
const logs = ref<{ name: string; text: string } | null>(null)
|
const logs = ref<{ name: string; text: string } | null>(null)
|
||||||
@@ -85,6 +93,7 @@ async function loadTab(value: string) {
|
|||||||
if (value === 'overview' || value === 'mirrors') await loadOverview()
|
if (value === 'overview' || value === 'mirrors') await loadOverview()
|
||||||
if (value === 'mirrors') metadata.value = await api('/admin/records/mirrors')
|
if (value === 'mirrors') metadata.value = await api('/admin/records/mirrors')
|
||||||
if (value === 'announcements') articles.value = await api('/admin/records/announcements')
|
if (value === 'announcements') articles.value = await api('/admin/records/announcements')
|
||||||
|
if (value === 'generators') generatorRecords.value = await api('/admin/records/generators')
|
||||||
if (value === 'settings' || value === 'downloads') settings.value = (await api<ContentRecord<SiteSettings>[]>('/admin/records/settings'))[0] || null
|
if (value === 'settings' || value === 'downloads') settings.value = (await api<ContentRecord<SiteSettings>[]>('/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 === '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 === 'users' && session.value?.role === 'admin') users.value = await api('/admin/users')
|
||||||
@@ -101,6 +110,11 @@ async function saveRecord<T>(kind: string, value: ContentRecord<T>) {
|
|||||||
const result = await api<ContentRecord<T>>(`/admin/records/${kind}/${encodeURIComponent(value.id)}`, { method: 'PUT', body: jsonBody({ data: value.data, revision: value.revision }) })
|
const result = await api<ContentRecord<T>>(`/admin/records/${kind}/${encodeURIComponent(value.id)}`, { method: 'PUT', body: jsonBody({ data: value.data, revision: value.revision }) })
|
||||||
notice.value = t('admin.saved'); return result
|
notice.value = t('admin.saved'); return result
|
||||||
}
|
}
|
||||||
|
async function saveGenerator(record: ContentRecord<GeneratorVersions>) {
|
||||||
|
const saved = await saveRecord('generators', record)
|
||||||
|
generatorRecords.value = generatorRecords.value.map(row => row.id === saved.id ? saved : row)
|
||||||
|
await refreshGenerators()
|
||||||
|
}
|
||||||
async function ask(message: string, action: () => Promise<void>) {
|
async function ask(message: string, action: () => Promise<void>) {
|
||||||
confirmation.value = { message, action }
|
confirmation.value = { message, action }
|
||||||
await nextTick()
|
await nextTick()
|
||||||
@@ -142,6 +156,19 @@ function deleteArticle(record: ContentRecord<AnnouncementContent>) {
|
|||||||
function editMirror(job: SyncJob) {
|
function editMirror(job: SyncJob) {
|
||||||
mirrorEditor.value = clone(metadata.value.find(row => row.id === job.name) || { id: job.name, revision: 0, updatedAt: 0, data: { name: job.name, description: { 'zh-CN': '', 'en-US': '' }, help: '', category: 'os', visible: true, website: '' } })
|
mirrorEditor.value = clone(metadata.value.find(row => row.id === job.name) || { id: job.name, revision: 0, updatedAt: 0, data: { name: job.name, description: { 'zh-CN': '', 'en-US': '' }, help: '', category: 'os', visible: true, website: '' } })
|
||||||
mirrorEditor.value.data.description ||= {}; mirrorEditor.value.data.help ||= ''
|
mirrorEditor.value.data.description ||= {}; mirrorEditor.value.data.help ||= ''
|
||||||
|
helpGenerator.value = mirrorConfigTypes.includes(job.name as MirrorConfigType) ? job.name as MirrorConfigType : 'ubuntu'
|
||||||
|
}
|
||||||
|
async function insertHelpGenerator() {
|
||||||
|
if (!mirrorEditor.value) return
|
||||||
|
const input = mirrorHelpInput.value
|
||||||
|
const body = mirrorEditor.value.data.help
|
||||||
|
const start = input?.selectionStart ?? body.length
|
||||||
|
const end = input?.selectionEnd ?? start
|
||||||
|
const block = '\n\n```mirror-config\n' + JSON.stringify({ type: helpGenerator.value }) + '\n```\n\n'
|
||||||
|
mirrorEditor.value.data.help = body.slice(0, start) + block + body.slice(end)
|
||||||
|
await nextTick()
|
||||||
|
input?.focus()
|
||||||
|
input?.setSelectionRange(start + block.length, start + block.length)
|
||||||
}
|
}
|
||||||
async function saveMirror() { if (!mirrorEditor.value) return; mirrorEditor.value = await saveRecord('mirrors', mirrorEditor.value); metadata.value = await api('/admin/records/mirrors') }
|
async function saveMirror() { if (!mirrorEditor.value) return; mirrorEditor.value = await saveRecord('mirrors', mirrorEditor.value); metadata.value = await api('/admin/records/mirrors') }
|
||||||
async function saveDownloads() {
|
async function saveDownloads() {
|
||||||
@@ -213,7 +240,8 @@ onBeforeUnmount(() => clearInterval(poll))
|
|||||||
<div class="admin-toolbar"><h3>{{ mirrorEditor.id }} · {{ t('admin.metadata') }}</h3><button type="button" @click="mirrorEditor = null">{{ t('admin.close') }}</button></div>
|
<div class="admin-toolbar"><h3>{{ mirrorEditor.id }} · {{ t('admin.metadata') }}</h3><button type="button" @click="mirrorEditor = null">{{ t('admin.close') }}</button></div>
|
||||||
<label>{{ t('admin.descriptionLanguage') }}<select v-model="editLocale"><option v-for="language in supportedLocales" :key="language" :value="language">{{ t('common.languageName', {}, { locale: language }) }}</option></select></label>
|
<label>{{ t('admin.descriptionLanguage') }}<select v-model="editLocale"><option v-for="language in supportedLocales" :key="language" :value="language">{{ t('common.languageName', {}, { locale: language }) }}</option></select></label>
|
||||||
<label>{{ t('admin.description') }}<textarea v-model="mirrorEditor.data.description[editLocale]" rows="2" /></label>
|
<label>{{ t('admin.description') }}<textarea v-model="mirrorEditor.data.description[editLocale]" rows="2" /></label>
|
||||||
<label>{{ t('admin.helpChinese') }}<textarea v-model="mirrorEditor.data.help" lang="zh-CN" rows="14" /></label>
|
<label>{{ t('admin.helpChinese') }}<textarea ref="mirrorHelpInput" v-model="mirrorEditor.data.help" lang="zh-CN" rows="14" /></label>
|
||||||
|
<div class="help-generator-toolbar"><label>{{ t('admin.configGenerator') }}<select v-model="helpGenerator"><option v-for="type in mirrorConfigTypes" :key="type" :value="type">{{ t(mirrorGenerators[type].nameKey) }}</option></select></label><button type="button" @click="insertHelpGenerator">{{ t('admin.insertGenerator') }}</button></div>
|
||||||
<details v-if="mirrorEditor.data.help.trim()" class="mirror-help-preview"><summary>{{ t('admin.preview') }}</summary><MirrorHelpContent :source="mirrorEditor.data.help" /></details>
|
<details v-if="mirrorEditor.data.help.trim()" class="mirror-help-preview"><summary>{{ t('admin.preview') }}</summary><MirrorHelpContent :source="mirrorEditor.data.help" /></details>
|
||||||
<a v-if="publishedMirrorHelp" class="admin-public-link" :href="helpUrl(mirrorEditor.id)" target="_blank" rel="noopener noreferrer">{{ t('admin.viewHelp') }}</a>
|
<a v-if="publishedMirrorHelp" class="admin-public-link" :href="helpUrl(mirrorEditor.id)" target="_blank" rel="noopener noreferrer">{{ t('admin.viewHelp') }}</a>
|
||||||
<label>{{ t('admin.website') }}<input v-model="mirrorEditor.data.website" type="url" /></label>
|
<label>{{ t('admin.website') }}<input v-model="mirrorEditor.data.website" type="url" /></label>
|
||||||
@@ -240,6 +268,7 @@ onBeforeUnmount(() => clearInterval(poll))
|
|||||||
</form>
|
</form>
|
||||||
<div class="admin-table-wrap articles-table"><table><thead><tr><th>{{ t('admin.articleTitle') }}</th><th>{{ t('admin.status') }}</th><th>{{ t('admin.date') }}</th><th>{{ t('admin.actions') }}</th></tr></thead><tbody><tr v-for="row in sortedArticles" :key="row.id"><td class="article-list-title"><span lang="zh-CN">{{ row.data.title }}</span><span v-if="row.data.pinned" class="article-pin">{{ t('admin.pinned') }}</span></td><td>{{ t(row.data.published ? 'admin.published' : 'admin.draft') }}</td><td><time :datetime="row.data.date">{{ d(new Date(row.data.date), 'article') }}</time></td><td><div class="row-actions"><button :disabled="busy" @click="editArticle(row)">{{ t('admin.edit') }}</button><a v-if="row.data.published" class="admin-public-link" :href="announcementUrl(row.id)" target="_blank" rel="noopener noreferrer">{{ t('admin.viewArticle') }}</a><button :disabled="busy" @click="deleteArticle(row)">{{ t('admin.remove') }}</button></div></td></tr></tbody></table><p v-if="!articles.length">{{ t('admin.empty') }}</p></div>
|
<div class="admin-table-wrap articles-table"><table><thead><tr><th>{{ t('admin.articleTitle') }}</th><th>{{ t('admin.status') }}</th><th>{{ t('admin.date') }}</th><th>{{ t('admin.actions') }}</th></tr></thead><tbody><tr v-for="row in sortedArticles" :key="row.id"><td class="article-list-title"><span lang="zh-CN">{{ row.data.title }}</span><span v-if="row.data.pinned" class="article-pin">{{ t('admin.pinned') }}</span></td><td>{{ t(row.data.published ? 'admin.published' : 'admin.draft') }}</td><td><time :datetime="row.data.date">{{ d(new Date(row.data.date), 'article') }}</time></td><td><div class="row-actions"><button :disabled="busy" @click="editArticle(row)">{{ t('admin.edit') }}</button><a v-if="row.data.published" class="admin-public-link" :href="announcementUrl(row.id)" target="_blank" rel="noopener noreferrer">{{ t('admin.viewArticle') }}</a><button :disabled="busy" @click="deleteArticle(row)">{{ t('admin.remove') }}</button></div></td></tr></tbody></table><p v-if="!articles.length">{{ t('admin.empty') }}</p></div>
|
||||||
</template>
|
</template>
|
||||||
|
<GeneratorCatalogEditor v-if="tab === 'generators'" :records="generatorRecords" :busy="busy" @save="record => run(() => saveGenerator(record))" />
|
||||||
<form v-if="tab === 'downloads' && settings" class="admin-form download-admin-form" @submit.prevent="run(saveDownloads)"><DownloadCatalogEditor ref="downloadEditor" v-model="settings.data.downloads" :busy="busy" /><button type="submit" class="primary" :disabled="busy">{{ t('admin.saveDownloads') }}</button></form>
|
<form v-if="tab === 'downloads' && settings" class="admin-form download-admin-form" @submit.prevent="run(saveDownloads)"><DownloadCatalogEditor ref="downloadEditor" v-model="settings.data.downloads" :busy="busy" /><button type="submit" class="primary" :disabled="busy">{{ t('admin.saveDownloads') }}</button></form>
|
||||||
<form v-if="tab === 'settings' && settings" class="admin-form" @submit.prevent="run(async () => { settings = await saveRecord('settings', settings!) })">
|
<form v-if="tab === 'settings' && settings" class="admin-form" @submit.prevent="run(async () => { settings = await saveRecord('settings', settings!) })">
|
||||||
<label>{{ t('admin.contentLanguage') }}<select v-model="editLocale"><option v-for="language in supportedLocales" :key="language" :value="language">{{ t('common.languageName', {}, { locale: language }) }}</option></select></label>
|
<label>{{ t('admin.contentLanguage') }}<select v-model="editLocale"><option v-for="language in supportedLocales" :key="language" :value="language">{{ t('common.languageName', {}, { locale: language }) }}</option></select></label>
|
||||||
@@ -299,6 +328,9 @@ button:hover { border-color: var(--blue); color: var(--blue); } button:disabled
|
|||||||
.admin-tabs button { flex-shrink: 0; border-color: transparent; background: transparent; } .admin-tabs [aria-current] { border-bottom: 2px solid var(--blue); color: var(--blue); border-radius: 0; font-weight: 700; }
|
.admin-tabs button { flex-shrink: 0; border-color: transparent; background: transparent; } .admin-tabs [aria-current] { border-bottom: 2px solid var(--blue); color: var(--blue); border-radius: 0; font-weight: 700; }
|
||||||
.admin-error, .admin-notice { padding: 12px 16px; border-left: 3px solid var(--blue); background: var(--panel); overflow-wrap: anywhere; } .admin-error { border-color: #d65252; }
|
.admin-error, .admin-notice { padding: 12px 16px; border-left: 3px solid var(--blue); background: var(--panel); overflow-wrap: anywhere; } .admin-error { border-color: #d65252; }
|
||||||
.admin-form { display: grid; gap: 18px; max-width: 1100px; } .admin-login { max-width: 420px; }
|
.admin-form { display: grid; gap: 18px; max-width: 1100px; } .admin-login { max-width: 420px; }
|
||||||
|
.help-generator-toolbar { display: flex; align-items: flex-end; flex-wrap: wrap; gap: 12px; }
|
||||||
|
.help-generator-toolbar label { flex: 1 1 180px; max-width: 320px; }
|
||||||
|
.help-generator-toolbar button { min-height: 44px; }
|
||||||
.download-admin-form { max-width: none; }
|
.download-admin-form { max-width: none; }
|
||||||
label { display: flex; flex-direction: column; gap: 8px; min-width: 0; font-size: 14px; font-weight: 500; }
|
label { display: flex; flex-direction: column; gap: 8px; min-width: 0; font-size: 14px; font-weight: 500; }
|
||||||
input, textarea, select { width: 100%; min-width: 0; min-height: 40px; padding: 9px 11px; border: 1px solid var(--line); border-radius: 4px; background: var(--panel); color: var(--ink); font: inherit; }
|
input, textarea, select { width: 100%; min-width: 0; min-height: 40px; padding: 9px 11px; border: 1px solid var(--line); border-radius: 4px; background: var(--panel); color: var(--ink); font: inherit; }
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onBeforeUnmount, ref, watch } from 'vue'
|
||||||
|
import { useI18n } from 'vue-i18n'
|
||||||
|
import { Check, Copy } from 'lucide-vue-next'
|
||||||
|
import { copyText } from '../copy-text'
|
||||||
|
|
||||||
|
const props = defineProps<{ code: string; caption: string }>()
|
||||||
|
const { t } = useI18n()
|
||||||
|
const copied = ref(false)
|
||||||
|
const failed = ref(false)
|
||||||
|
let revision = 0
|
||||||
|
let disposed = false
|
||||||
|
let reset: ReturnType<typeof setTimeout> | undefined
|
||||||
|
function resetCopy() { revision++; copied.value = false; failed.value = false; clearTimeout(reset) }
|
||||||
|
watch(() => props.code, resetCopy)
|
||||||
|
async function copy() {
|
||||||
|
const current = ++revision
|
||||||
|
clearTimeout(reset)
|
||||||
|
try {
|
||||||
|
await copyText(props.code)
|
||||||
|
if (disposed || current !== revision) return
|
||||||
|
copied.value = true; failed.value = false
|
||||||
|
} catch {
|
||||||
|
if (disposed || current !== revision) return
|
||||||
|
copied.value = false; failed.value = true
|
||||||
|
}
|
||||||
|
reset = setTimeout(resetCopy, 2500)
|
||||||
|
}
|
||||||
|
onBeforeUnmount(() => { disposed = true; clearTimeout(reset) })
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="source-output">
|
||||||
|
<div class="source-code">
|
||||||
|
<div class="source-code-heading"><span>{{ caption }}</span><button type="button" :aria-label="t(copied ? 'common.copied' : 'common.copy')" :title="t(copied ? 'common.copied' : 'common.copy')" @click="copy"><Check v-if="copied" :size="18" aria-hidden="true" /><Copy v-else :size="18" aria-hidden="true" /></button></div>
|
||||||
|
<pre tabindex="0" :aria-label="t('mirrors.generator.generated')"><code>{{ code }}</code></pre>
|
||||||
|
</div>
|
||||||
|
<p class="copy-status" :class="{ 'sr-only': !failed }" role="status">{{ failed ? t('common.copyFailed') : copied ? t('common.copied') : '' }}</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.source-output + .source-output { margin-top: 16px; }
|
||||||
|
.source-code { min-width: 0; overflow: hidden; border: 1px solid var(--line); border-radius: 4px; background: var(--surface); }
|
||||||
|
.source-code-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 7px 10px 0 14px; color: var(--ink-2); font: 12px/1.5 ui-monospace, Consolas, monospace; }
|
||||||
|
.source-code-heading > span { min-width: 0; overflow-wrap: anywhere; }
|
||||||
|
.source-code-heading button { display: inline-flex; flex: 0 0 auto; align-items: center; justify-content: center; width: 36px; height: 36px; border-radius: 3px; color: var(--ink); }
|
||||||
|
.source-code-heading button:hover { color: var(--blue); background: var(--blue-soft); }
|
||||||
|
.source-code pre { max-width: 100%; overflow: auto; margin: 0; padding: 6px 14px 16px; color: var(--ink); font: 13px/1.85 ui-monospace, 'Cascadia Code', Consolas, monospace; white-space: pre; }
|
||||||
|
.copy-status { margin: 10px 0; color: var(--ink); font-size: 14px; line-height: 1.7; }
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.source-code-heading button { width: 44px; height: 44px; }
|
||||||
|
.source-code pre { font-size: 12px; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import { computed, onBeforeUnmount, ref, useId, watch } from 'vue'
|
|
||||||
import { useI18n } from 'vue-i18n'
|
|
||||||
import { Check, Copy } from 'lucide-vue-next'
|
|
||||||
import { debianReleases, debianSources, type DebianFormat, type DebianRelease } from '../debian-sources'
|
|
||||||
import { copyText } from '../copy-text'
|
|
||||||
|
|
||||||
const props = defineProps<{ format: DebianFormat }>()
|
|
||||||
const { t } = useI18n()
|
|
||||||
const id = useId()
|
|
||||||
const release = ref<DebianRelease>('trixie')
|
|
||||||
const sources = ref(false)
|
|
||||||
const nonFree = ref(true)
|
|
||||||
const securityMirror = ref(false)
|
|
||||||
const selection = computed(() => debianReleases.find(entry => entry.id === release.value)!)
|
|
||||||
const code = computed(() => debianSources({ origin: window.location.origin, release: release.value, format: props.format, sources: sources.value, nonFree: nonFree.value, securityMirror: securityMirror.value }))
|
|
||||||
const file = computed(() => props.format === 'list' ? '/etc/apt/sources.list' : '/etc/apt/sources.list.d/debian.sources')
|
|
||||||
const copied = ref(false)
|
|
||||||
const copyFailed = ref(false)
|
|
||||||
let reset: ReturnType<typeof setTimeout> | undefined
|
|
||||||
let revision = 0
|
|
||||||
let disposed = false
|
|
||||||
function resetCopy() { revision++; copied.value = false; copyFailed.value = false; clearTimeout(reset) }
|
|
||||||
watch(code, resetCopy)
|
|
||||||
watch(selection, value => { if (!value.stable) securityMirror.value = false })
|
|
||||||
async function copy() {
|
|
||||||
const current = ++revision
|
|
||||||
clearTimeout(reset)
|
|
||||||
try {
|
|
||||||
await copyText(code.value)
|
|
||||||
if (disposed || current !== revision) return
|
|
||||||
copied.value = true
|
|
||||||
copyFailed.value = false
|
|
||||||
} catch {
|
|
||||||
if (disposed || current !== revision) return
|
|
||||||
copied.value = false
|
|
||||||
copyFailed.value = true
|
|
||||||
}
|
|
||||||
reset = setTimeout(resetCopy, 2500)
|
|
||||||
}
|
|
||||||
onBeforeUnmount(() => { disposed = true; clearTimeout(reset) })
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<section class="debian-sources" :data-format="format" :aria-label="t('mirrors.debian.generator', { format: format === 'list' ? t('mirrors.debian.traditional') : 'DEB822' })">
|
|
||||||
<div class="source-controls">
|
|
||||||
<label class="source-control source-version"><span>{{ t('mirrors.debian.version') }}</span><select v-model="release"><option v-for="entry in debianReleases" :key="entry.id" :value="entry.id">{{ entry.version ? t('mirrors.debian.release', { version: entry.version, codename: entry.id }) : entry.id }}</option></select></label>
|
|
||||||
<label class="source-control"><span>{{ t('mirrors.debian.sources') }}</span><input v-model="sources" type="checkbox" role="switch" /><span class="source-toggle" aria-hidden="true" /></label>
|
|
||||||
<label class="source-control"><span>{{ t('mirrors.debian.nonFree') }}</span><input v-model="nonFree" type="checkbox" role="switch" /><span class="source-toggle" aria-hidden="true" /></label>
|
|
||||||
<label class="source-control" :class="{ 'source-disabled': !selection.stable }"><span>{{ t('mirrors.debian.securityMirror') }}</span><input v-model="securityMirror" type="checkbox" role="switch" :disabled="!selection.stable" :aria-describedby="!selection.stable ? `${id}-branch` : undefined" /><span class="source-toggle" aria-hidden="true" /></label>
|
|
||||||
</div>
|
|
||||||
<p v-if="!selection.stable" :id="`${id}-branch`" class="source-note">{{ t('mirrors.debian.rollingNotice') }}</p>
|
|
||||||
<div class="source-code">
|
|
||||||
<div class="source-code-heading"><span>{{ file }}</span><button type="button" :aria-label="t(copied ? 'common.copied' : 'common.copy')" :title="t(copied ? 'common.copied' : 'common.copy')" @click="copy"><Check v-if="copied" :size="18" aria-hidden="true" /><Copy v-else :size="18" aria-hidden="true" /></button></div>
|
|
||||||
<pre tabindex="0" :aria-label="t('mirrors.debian.generated')"><code>{{ code }}</code></pre>
|
|
||||||
</div>
|
|
||||||
<p class="copy-status" :class="{ 'sr-only': !copyFailed }" role="status">{{ copyFailed ? t('common.copyFailed') : copied ? t('common.copied') : '' }}</p>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.debian-sources { min-width: 0; margin: 20px 0 30px; }
|
|
||||||
.source-controls { display: grid; grid-template-columns: minmax(180px, 1.35fr) repeat(3, minmax(0, 1fr)); gap: 12px; margin-bottom: 16px; }
|
|
||||||
.source-control { position: relative; display: flex; flex-direction: column; justify-content: space-between; align-items: flex-start; gap: 8px; min-width: 0; min-height: 70px; margin: 0; padding: 10px 12px; border: 1px solid var(--line); border-radius: 4px; color: var(--ink); font-size: 13px; line-height: 1.5; cursor: pointer; }
|
|
||||||
.source-control > span:first-child { color: var(--ink-2); }
|
|
||||||
.source-control select { width: 100%; min-width: 0; margin: 0; padding: 0; border: 0; background: var(--paper); color: var(--ink); font: inherit; font-size: 15px; cursor: pointer; }
|
|
||||||
.source-control input { position: absolute; width: 1px; height: 1px; margin: 0; opacity: 0; }
|
|
||||||
.source-toggle { position: relative; width: 32px; height: 18px; border: 1px solid var(--line); border-radius: 999px; background: var(--surface); }
|
|
||||||
.source-toggle::after { position: absolute; top: 3px; left: 3px; width: 10px; height: 10px; border-radius: 50%; background: var(--ink-2); content: ''; transition: transform 120ms; }
|
|
||||||
.source-control input:checked + .source-toggle { border-color: var(--blue); background: var(--blue); }
|
|
||||||
.source-control input:checked + .source-toggle::after { background: var(--on-accent); transform: translateX(14px); }
|
|
||||||
.source-control input:focus-visible + .source-toggle { outline: 2px solid var(--blue); outline-offset: 3px; }
|
|
||||||
.source-disabled { opacity: .55; cursor: default; }
|
|
||||||
.source-note, .copy-status { margin: 10px 0; color: var(--ink); font-size: 14px; line-height: 1.7; }
|
|
||||||
.source-code { min-width: 0; overflow: hidden; border: 1px solid var(--line); border-radius: 4px; background: var(--surface); }
|
|
||||||
.source-code-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 7px 10px 0 14px; color: var(--ink-2); font: 12px/1.5 ui-monospace, Consolas, monospace; }
|
|
||||||
.source-code-heading > span { min-width: 0; overflow-wrap: anywhere; }
|
|
||||||
.source-code-heading button { display: inline-flex; flex: 0 0 auto; align-items: center; justify-content: center; width: 36px; height: 36px; border-radius: 3px; color: var(--ink); }
|
|
||||||
.source-code-heading button:hover { color: var(--blue); background: var(--blue-soft); }
|
|
||||||
.source-code pre { max-width: 100%; overflow: auto; margin: 0; padding: 6px 14px 16px; color: var(--ink); font: 13px/1.85 ui-monospace, 'Cascadia Code', Consolas, monospace; white-space: pre; }
|
|
||||||
@media (max-width: 1100px) { .source-controls { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
|
||||||
@media (max-width: 640px) {
|
|
||||||
.source-controls { gap: 10px; }
|
|
||||||
.source-control { min-height: 80px; padding: 10px; }
|
|
||||||
.source-control select { min-height: 28px; font-size: 14px; }
|
|
||||||
.source-code-heading button { width: 44px; height: 44px; }
|
|
||||||
.source-code pre { font-size: 12px; }
|
|
||||||
}
|
|
||||||
@media (max-width: 360px) { .source-controls { grid-template-columns: minmax(0, 1fr); } }
|
|
||||||
@media (prefers-reduced-motion: reduce) { .source-toggle::after { transition: none; } }
|
|
||||||
</style>
|
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref, watch } from 'vue'
|
||||||
|
import { useI18n } from 'vue-i18n'
|
||||||
|
import type { ContentRecord } from '../api'
|
||||||
|
import { validGeneratorVersions, versionedGenerators, type GeneratorRelease, type GeneratorVersions, type VersionedGenerator } from '../generator-catalog'
|
||||||
|
import { mirrorGenerators } from '../mirror-config'
|
||||||
|
import { useGeneratorCatalog } from '../useGeneratorCatalog'
|
||||||
|
import MirrorConfig from './MirrorConfig.vue'
|
||||||
|
|
||||||
|
const props = defineProps<{ records: ContentRecord<GeneratorVersions>[]; busy: boolean }>()
|
||||||
|
const emit = defineEmits<{ save: [record: ContentRecord<GeneratorVersions>] }>()
|
||||||
|
const { t } = useI18n()
|
||||||
|
const { catalog } = useGeneratorCatalog()
|
||||||
|
const selected = ref<VersionedGenerator>('ubuntu')
|
||||||
|
const draft = ref<ContentRecord<GeneratorVersions> | null>(null)
|
||||||
|
watch([selected, () => props.records], () => {
|
||||||
|
const record = props.records.find(record => record.id === selected.value)
|
||||||
|
draft.value = record ? JSON.parse(JSON.stringify(record)) : null
|
||||||
|
}, { immediate: true })
|
||||||
|
const valid = computed(() => draft.value && validGeneratorVersions(selected.value, draft.value.data))
|
||||||
|
const previewCatalog = computed(() => valid.value && draft.value && catalog.value ? { ...catalog.value, [selected.value]: draft.value.data } : null)
|
||||||
|
function addRelease() {
|
||||||
|
const release: GeneratorRelease = { id: '', label: '' }
|
||||||
|
if (selected.value === 'debian') Object.assign(release, { stable: true, firmware: true, backports: false })
|
||||||
|
if (selected.value === 'proxmox') release.keyring = '/usr/share/keyrings/proxmox-archive-keyring.gpg'
|
||||||
|
draft.value?.data.releases.push(release)
|
||||||
|
}
|
||||||
|
function removeRelease(index: number) {
|
||||||
|
if (!draft.value) return
|
||||||
|
const [removed] = draft.value.data.releases.splice(index, 1)
|
||||||
|
if (removed?.id === draft.value.data.defaultRelease) draft.value.data.defaultRelease = draft.value.data.releases[0]?.id || ''
|
||||||
|
}
|
||||||
|
function moveRelease(index: number, offset: number) {
|
||||||
|
const rows = draft.value?.data.releases
|
||||||
|
if (!rows || index + offset < 0 || index + offset >= rows.length) return
|
||||||
|
const [release] = rows.splice(index, 1)
|
||||||
|
if (release) rows.splice(index + offset, 0, release)
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="generator-editor">
|
||||||
|
<p>{{ t('admin.generatorIntro') }}</p>
|
||||||
|
<label>{{ t('admin.configGenerator') }}<select v-model="selected" :disabled="busy"><option v-for="type in versionedGenerators" :key="type" :value="type">{{ t(mirrorGenerators[type].nameKey) }}</option></select></label>
|
||||||
|
<form v-if="draft" @submit.prevent="valid && emit('save', draft)">
|
||||||
|
<fieldset :disabled="busy">
|
||||||
|
<label>{{ t('admin.defaultRelease') }}<select v-model="draft.data.defaultRelease" required><option v-for="(release, index) in draft.data.releases" :key="index" :value="release.id">{{ release.label || release.id || t('admin.unnamedRelease', { index: index + 1 }) }}</option></select></label>
|
||||||
|
<p class="generator-hint">{{ t(`admin.generatorHint_${selected}`) }}</p>
|
||||||
|
<article v-for="(release, index) in draft.data.releases" :key="index" class="generator-release">
|
||||||
|
<div class="generator-fields">
|
||||||
|
<label>{{ t('admin.releaseLabel') }}<input v-model="release.label" maxlength="160" required /></label>
|
||||||
|
<label>{{ t('admin.releaseId') }}<input v-model="release.id" maxlength="64" required autocapitalize="none" spellcheck="false" /></label>
|
||||||
|
<label v-if="selected === 'proxmox'">{{ t('admin.keyringPath') }}<input v-model="release.keyring" maxlength="150" required spellcheck="false" /></label>
|
||||||
|
</div>
|
||||||
|
<div v-if="selected === 'debian'" class="generator-flags">
|
||||||
|
<label><input v-model="release.stable" type="checkbox" @change="!release.stable && (release.backports = false)" />{{ t('admin.releaseStable') }}</label>
|
||||||
|
<label><input v-model="release.firmware" type="checkbox" />{{ t('admin.releaseFirmware') }}</label>
|
||||||
|
<label><input v-model="release.backports" type="checkbox" :disabled="!release.stable" />{{ t('admin.releaseBackports') }}</label>
|
||||||
|
</div>
|
||||||
|
<div class="generator-actions"><button type="button" :disabled="index === 0" @click="moveRelease(index, -1)">{{ t('admin.moveUp') }}</button><button type="button" :disabled="index === draft.data.releases.length - 1" @click="moveRelease(index, 1)">{{ t('admin.moveDown') }}</button><button type="button" :disabled="draft.data.releases.length === 1" @click="removeRelease(index)">{{ t('admin.remove') }}</button></div>
|
||||||
|
</article>
|
||||||
|
<div class="generator-actions"><button type="button" :disabled="draft.data.releases.length >= 100" @click="addRelease">{{ t('admin.addRelease') }}</button><button type="submit" class="primary" :disabled="!valid">{{ t('admin.save') }}</button></div>
|
||||||
|
</fieldset>
|
||||||
|
<p v-if="!valid" class="generator-invalid" role="status">{{ t('admin.generatorInvalid') }}</p>
|
||||||
|
<p class="generator-hint">{{ t('admin.generatorScope') }}</p>
|
||||||
|
<details v-if="previewCatalog"><summary>{{ t('admin.preview') }}</summary><MirrorConfig :key="`${selected}:${draft.data.defaultRelease}`" :config="{ type: selected }" :catalog="previewCatalog" /></details>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.generator-editor { max-width: 1050px; min-width: 0; }
|
||||||
|
.generator-editor > p { line-height: 1.8; }
|
||||||
|
fieldset { min-width: 0; margin: 20px 0; padding: 0; border: 0; }
|
||||||
|
label { display: grid; gap: 8px; min-width: 0; font-size: 14px; }
|
||||||
|
input:not([type='checkbox']), select { width: 100%; min-width: 0; min-height: 42px; padding: 9px 11px; border: 1px solid var(--line); border-radius: 3px; background: var(--panel); color: var(--ink); font: inherit; }
|
||||||
|
.generator-release { margin: 16px 0; padding: 18px; border: 1px solid var(--line); border-radius: 3px; }
|
||||||
|
.generator-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
|
||||||
|
.generator-fields > label:nth-child(3) { grid-column: 1 / -1; }
|
||||||
|
.generator-flags, .generator-actions { display: flex; flex-wrap: wrap; gap: 12px; margin-top: 16px; }
|
||||||
|
.generator-flags label { display: inline-flex; align-items: center; gap: 8px; }
|
||||||
|
button { min-height: 40px; padding: 8px 14px; border: 1px solid var(--line); border-radius: 3px; background: var(--panel); color: var(--ink); font: inherit; font-size: 14px; cursor: pointer; }
|
||||||
|
button:hover { border-color: var(--blue); color: var(--blue); }
|
||||||
|
button.primary { border-color: var(--blue); background: var(--blue); color: var(--on-accent); }
|
||||||
|
button:disabled { opacity: .5; cursor: default; }
|
||||||
|
.generator-hint { color: var(--ink-2); line-height: 1.8; font-size: 14px; }
|
||||||
|
.generator-invalid { color: var(--red, #c64040); line-height: 1.8; }
|
||||||
|
summary { color: var(--blue); cursor: pointer; }
|
||||||
|
@media (max-width: 640px) { .generator-fields { grid-template-columns: minmax(0, 1fr); } .generator-release { padding: 12px; } button { min-height: 44px; } }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, reactive, ref, useId, watch, watchEffect } from 'vue'
|
||||||
|
import { useI18n } from 'vue-i18n'
|
||||||
|
import { configDefaults, configFields, generateMirrorConfig, getMirrorGenerator, parseMirrorConfig, type ConfigChoice, type ConfigValues, type MirrorConfig } from '../mirror-config'
|
||||||
|
import { defaultGeneratorCatalog, type GeneratorCatalog } from '../generator-catalog'
|
||||||
|
import ConfigCode from './ConfigCode.vue'
|
||||||
|
|
||||||
|
const props = withDefaults(defineProps<{ config: MirrorConfig; catalog?: GeneratorCatalog }>(), { catalog: () => defaultGeneratorCatalog })
|
||||||
|
const { t } = useI18n()
|
||||||
|
const id = useId()
|
||||||
|
const values = reactive<ConfigValues>({})
|
||||||
|
const format = ref('')
|
||||||
|
const generator = computed(() => getMirrorGenerator(props.config.type, props.catalog))
|
||||||
|
const fields = computed(() => configFields(props.config.type, props.catalog))
|
||||||
|
watch(() => JSON.stringify(props.config), () => {
|
||||||
|
for (const key of Object.keys(values)) delete values[key]
|
||||||
|
Object.assign(values, configDefaults(props.config, window.location.origin, props.catalog))
|
||||||
|
format.value = props.config.format || generator.value.defaultFormat
|
||||||
|
}, { immediate: true })
|
||||||
|
watch(() => props.catalog, () => {
|
||||||
|
if (!parseMirrorConfig({ ...props.config, options: { ...props.config.options, ...values } }, props.catalog)) Object.assign(values, configDefaults(props.config, window.location.origin, props.catalog))
|
||||||
|
})
|
||||||
|
watchEffect(() => generator.value.normalize?.(values))
|
||||||
|
const files = computed(() => generateMirrorConfig({ ...props.config, format: format.value }, window.location.origin, values, props.catalog))
|
||||||
|
const notes = computed(() => (generator.value.notes || []).filter(note => !note.when || note.when(values)))
|
||||||
|
const choiceLabel = (choice: ConfigChoice) => choice.labelKey ? t(choice.labelKey) : choice.label
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section class="mirror-config" :data-generator="config.type" :data-format="format" :aria-label="t('mirrors.generator.title', { name: t(generator.nameKey) })">
|
||||||
|
<div class="source-controls">
|
||||||
|
<label v-if="!config.format && generator.formats.length > 1" class="source-control"><span>{{ t('mirrors.generator.format') }}</span><select v-model="format"><option v-for="choice in generator.formats" :key="choice.value" :value="choice.value">{{ choiceLabel(choice) }}</option></select></label>
|
||||||
|
<label v-for="field in fields" :key="field.key" class="source-control" :class="{ 'source-disabled': field.disabled?.(values) }">
|
||||||
|
<span>{{ t(field.labelKey) }}</span>
|
||||||
|
<select v-if="field.kind === 'select'" v-model="values[field.key]"><option v-for="choice in field.choices" :key="choice.value" :value="choice.value">{{ choiceLabel(choice) }}</option></select>
|
||||||
|
<template v-else><input v-model="values[field.key]" type="checkbox" role="switch" :disabled="field.disabled?.(values)" :aria-describedby="field.disabled?.(values) && notes.length ? `${id}-notes` : undefined" /><span class="source-toggle" aria-hidden="true" /></template>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div v-if="notes.length" :id="`${id}-notes`" class="source-notes"><p v-for="note in notes" :key="note.key">{{ t(note.key) }}</p></div>
|
||||||
|
<ConfigCode v-for="(file, index) in files" :key="index" :code="file.code" :caption="file.path || t(file.titleKey!)" />
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.mirror-config { min-width: 0; margin: 20px 0 30px; }
|
||||||
|
.source-controls { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 180px), 1fr)); gap: 12px; margin-bottom: 16px; }
|
||||||
|
.source-control { position: relative; display: flex; flex-direction: column; justify-content: space-between; align-items: flex-start; gap: 8px; min-width: 0; min-height: 70px; margin: 0; padding: 10px 12px; border: 1px solid var(--line); border-radius: 4px; color: var(--ink); font-size: 13px; line-height: 1.5; cursor: pointer; }
|
||||||
|
.source-control > span:first-child { color: var(--ink-2); }
|
||||||
|
.source-control select { width: 100%; min-width: 0; margin: 0; padding: 0; border: 0; background: var(--paper); color: var(--ink); font: inherit; font-size: 15px; cursor: pointer; }
|
||||||
|
.source-control input { position: absolute; width: 1px; height: 1px; margin: 0; opacity: 0; }
|
||||||
|
.source-toggle { position: relative; width: 32px; height: 18px; border: 1px solid var(--line); border-radius: 999px; background: var(--surface); }
|
||||||
|
.source-toggle::after { position: absolute; top: 3px; left: 3px; width: 10px; height: 10px; border-radius: 50%; background: var(--ink-2); content: ''; transition: transform 120ms; }
|
||||||
|
.source-control input:checked + .source-toggle { border-color: var(--blue); background: var(--blue); }
|
||||||
|
.source-control input:checked + .source-toggle::after { background: var(--on-accent); transform: translateX(14px); }
|
||||||
|
.source-control input:focus-visible + .source-toggle { outline: 2px solid var(--blue); outline-offset: 3px; }
|
||||||
|
.source-disabled { opacity: .55; cursor: default; }
|
||||||
|
.source-notes { margin: 10px 0; color: var(--ink); font-size: 14px; line-height: 1.7; }
|
||||||
|
.source-notes p { margin: 6px 0; }
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.source-controls { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
|
||||||
|
.source-control { min-height: 80px; padding: 10px; }
|
||||||
|
.source-control select { min-height: 28px; font-size: 14px; }
|
||||||
|
}
|
||||||
|
@media (max-width: 360px) { .source-controls { grid-template-columns: minmax(0, 1fr); } }
|
||||||
|
@media (prefers-reduced-motion: reduce) { .source-toggle::after { transition: none; } }
|
||||||
|
</style>
|
||||||
@@ -1,18 +1,24 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed } from 'vue'
|
import { computed } from 'vue'
|
||||||
|
import { useI18n } from 'vue-i18n'
|
||||||
|
import { useGeneratorCatalog } from '../useGeneratorCatalog'
|
||||||
import { helpBlocks } from '../help-content'
|
import { helpBlocks } from '../help-content'
|
||||||
import DebianSources from './DebianSources.vue'
|
import MirrorConfig from './MirrorConfig.vue'
|
||||||
import MarkdownContent from './MarkdownContent.vue'
|
import MarkdownContent from './MarkdownContent.vue'
|
||||||
|
|
||||||
const props = defineProps<{ source: string }>()
|
const props = defineProps<{ source: string }>()
|
||||||
const blocks = computed(() => helpBlocks(props.source))
|
const { t } = useI18n()
|
||||||
|
const { catalog, failed, refresh } = useGeneratorCatalog()
|
||||||
|
const blocks = computed(() => catalog.value ? helpBlocks(props.source, catalog.value) : [])
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="mirror-help-content" lang="zh-CN">
|
<div class="mirror-help-content" lang="zh-CN">
|
||||||
|
<p v-if="!catalog" role="status">{{ t(failed ? 'mirrors.generator.catalogFailed' : 'mirrors.guides.loading') }} <button v-if="failed" type="button" @click="refresh">{{ t('mirrors.guides.retry') }}</button></p>
|
||||||
|
<p v-else-if="failed" role="status">{{ t('mirrors.generator.catalogStale') }}</p>
|
||||||
<template v-for="(block, index) in blocks" :key="index">
|
<template v-for="(block, index) in blocks" :key="index">
|
||||||
<DebianSources v-if="block.kind === 'debian'" :format="block.format" />
|
<MirrorConfig v-if="block.kind === 'config' && catalog" :config="block.config" :catalog="catalog" />
|
||||||
<MarkdownContent v-else :tokens="block.tokens" />
|
<MarkdownContent v-else-if="block.kind === 'markdown'" :tokens="block.tokens" />
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
+11
-28
@@ -1,13 +1,9 @@
|
|||||||
export const debianReleases = [
|
import { aptSources, mirrorOrigin, type AptFormat } from './apt-sources.ts'
|
||||||
{ id: 'trixie', version: '13', stable: true, firmware: true, backports: true },
|
import { defaultGeneratorCatalog, type GeneratorRelease } from './generator-catalog.ts'
|
||||||
{ id: 'bookworm', version: '12', stable: true, firmware: true, backports: false },
|
|
||||||
{ id: 'bullseye', version: '11', stable: true, firmware: false, backports: false },
|
|
||||||
{ id: 'testing', version: '', stable: false, firmware: true, backports: false },
|
|
||||||
{ id: 'sid', version: '', stable: false, firmware: true, backports: false },
|
|
||||||
] as const
|
|
||||||
|
|
||||||
export type DebianRelease = typeof debianReleases[number]['id']
|
export const debianReleases = defaultGeneratorCatalog.debian.releases
|
||||||
export type DebianFormat = 'list' | 'deb822'
|
export type DebianRelease = string
|
||||||
|
export type DebianFormat = AptFormat
|
||||||
export interface DebianSourceOptions {
|
export interface DebianSourceOptions {
|
||||||
origin: string
|
origin: string
|
||||||
release: DebianRelease
|
release: DebianRelease
|
||||||
@@ -17,27 +13,14 @@ export interface DebianSourceOptions {
|
|||||||
securityMirror: boolean
|
securityMirror: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export function debianSources(options: DebianSourceOptions) {
|
export function debianSources(options: Omit<DebianSourceOptions, 'release'> & { release: string }, releases: readonly GeneratorRelease[] = defaultGeneratorCatalog.debian.releases) {
|
||||||
const release = debianReleases.find(entry => entry.id === options.release)
|
const release = releases.find(entry => entry.id === options.release)
|
||||||
if (!release || !['list', 'deb822'].includes(options.format)) throw new Error('Invalid Debian configuration')
|
if (!release || !['list', 'deb822'].includes(options.format)) throw new Error('Invalid Debian configuration')
|
||||||
const origin = new URL(options.origin)
|
const origin = mirrorOrigin(options.origin)
|
||||||
if (!['http:', 'https:'].includes(origin.protocol) || origin.username || origin.password) throw new Error('Invalid mirror origin')
|
const mirror = `${origin}/mirrors/debian/`
|
||||||
const mirror = `${origin.origin}/mirrors/debian/`
|
const security = options.securityMirror ? `${origin}/mirrors/debian-security/` : 'https://security.debian.org/debian-security'
|
||||||
const security = options.securityMirror ? `${origin.origin}/mirrors/debian-security/` : 'https://security.debian.org/debian-security'
|
|
||||||
const components = ['main', ...(options.nonFree ? ['contrib', 'non-free', ...(release.firmware ? ['non-free-firmware'] : [])] : [])].join(' ')
|
const components = ['main', ...(options.nonFree ? ['contrib', 'non-free', ...(release.firmware ? ['non-free-firmware'] : [])] : [])].join(' ')
|
||||||
const suites = [release.id, ...(release.stable ? [`${release.id}-updates`] : []), ...(release.backports ? [`${release.id}-backports`] : [])]
|
const suites = [release.id, ...(release.stable ? [`${release.id}-updates`] : []), ...(release.backports ? [`${release.id}-backports`] : [])]
|
||||||
const groups = [{ uri: mirror, suites }, ...(release.stable ? [{ uri: security, suites: [`${release.id}-security`] }] : [])]
|
const groups = [{ uri: mirror, suites }, ...(release.stable ? [{ uri: security, suites: [`${release.id}-security`] }] : [])]
|
||||||
if (options.format === 'deb822') {
|
return aptSources(groups.map(group => ({ ...group, components, keyring: '/usr/share/keyrings/debian-archive-keyring.gpg' })), options.format, options.sources)
|
||||||
return groups.map(group => [
|
|
||||||
`Types: ${options.sources ? 'deb deb-src' : 'deb'}`,
|
|
||||||
`URIs: ${group.uri}`,
|
|
||||||
`Suites: ${group.suites.join(' ')}`,
|
|
||||||
`Components: ${components}`,
|
|
||||||
'Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg',
|
|
||||||
].join('\n')).join('\n\n') + '\n'
|
|
||||||
}
|
|
||||||
return groups.flatMap(group => group.suites.map(suite => [
|
|
||||||
`deb ${group.uri} ${suite} ${components}`,
|
|
||||||
`${options.sources ? '' : '# '}deb-src ${group.uri} ${suite} ${components}`,
|
|
||||||
].join('\n'))).join('\n\n') + '\n'
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import defaults from '../backend/generator-defaults.json' with { type: 'json' }
|
||||||
|
|
||||||
|
export const versionedGenerators = ['debian', 'ubuntu', 'kubernetes', 'tailscale', 'proxmox'] as const
|
||||||
|
export type VersionedGenerator = typeof versionedGenerators[number]
|
||||||
|
export interface GeneratorRelease {
|
||||||
|
id: string
|
||||||
|
label: string
|
||||||
|
stable?: boolean
|
||||||
|
firmware?: boolean
|
||||||
|
backports?: boolean
|
||||||
|
keyring?: string
|
||||||
|
}
|
||||||
|
export interface GeneratorVersions { defaultRelease: string; releases: GeneratorRelease[] }
|
||||||
|
export type GeneratorCatalog = Record<VersionedGenerator, GeneratorVersions>
|
||||||
|
export const defaultGeneratorCatalog: GeneratorCatalog = defaults
|
||||||
|
|
||||||
|
export function validGeneratorVersions(type: VersionedGenerator, value: unknown): value is GeneratorVersions {
|
||||||
|
if (!value || typeof value !== 'object' || Array.isArray(value)) return false
|
||||||
|
const data = value as GeneratorVersions
|
||||||
|
if (Object.keys(data).some(key => !['defaultRelease', 'releases'].includes(key)) || typeof data.defaultRelease !== 'string' || !Array.isArray(data.releases) || !data.releases.length || data.releases.length > 100) return false
|
||||||
|
const seen = new Set<string>()
|
||||||
|
for (const release of data.releases) {
|
||||||
|
if (!release || typeof release !== 'object' || Array.isArray(release) || Object.keys(release).some(key => !['id', 'label', 'stable', 'firmware', 'backports', 'keyring'].includes(key))) return false
|
||||||
|
const idPattern = type === 'kubernetes' ? /^v[1-9][0-9]{0,2}\.(0|[1-9][0-9]{0,2})$/ : type === 'tailscale' ? /^(debian|ubuntu)\/[a-z][a-z0-9-]{0,31}$/ : /^[a-z][a-z0-9-]{0,31}$/
|
||||||
|
if (typeof release.id !== 'string' || !idPattern.test(release.id) || seen.has(release.id) || typeof release.label !== 'string' || !release.label.trim() || [...release.label].length > 160 || /[\p{Cc}]/u.test(release.label)) return false
|
||||||
|
seen.add(release.id)
|
||||||
|
if (type === 'debian') {
|
||||||
|
if (['stable', 'firmware', 'backports'].some(key => typeof release[key as keyof GeneratorRelease] !== 'boolean') || release.backports && !release.stable) return false
|
||||||
|
} else if (['stable', 'firmware', 'backports'].some(key => key in release)) return false
|
||||||
|
if (type === 'proxmox') {
|
||||||
|
if (typeof release.keyring !== 'string' || !/^\/(usr\/share\/keyrings|etc\/apt\/trusted\.gpg\.d)\/[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}\.gpg$/.test(release.keyring)) return false
|
||||||
|
} else if ('keyring' in release) return false
|
||||||
|
}
|
||||||
|
return seen.has(data.defaultRelease) && (type !== 'debian' || data.releases.some(release => release.stable))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseGeneratorCatalog(value: unknown): GeneratorCatalog | null {
|
||||||
|
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
|
||||||
|
const data = value as GeneratorCatalog
|
||||||
|
if (Object.keys(data).length !== versionedGenerators.length || versionedGenerators.some(type => !Object.hasOwn(data, type) || !validGeneratorVersions(type, data[type]))) return null
|
||||||
|
return data
|
||||||
|
}
|
||||||
+7
-7
@@ -1,10 +1,11 @@
|
|||||||
import { marked, type Token, type TokensList } from 'marked'
|
import { marked, type Token, type TokensList } from 'marked'
|
||||||
import type { DebianFormat } from './debian-sources'
|
import { parseMirrorConfig, type MirrorConfig } from './mirror-config.ts'
|
||||||
|
import { defaultGeneratorCatalog, type GeneratorCatalog } from './generator-catalog.ts'
|
||||||
|
|
||||||
export type HelpBlock = { kind: 'markdown'; tokens: TokensList } | { kind: 'debian'; format: DebianFormat }
|
export type HelpBlock = { kind: 'markdown'; tokens: TokensList } | { kind: 'config'; config: MirrorConfig }
|
||||||
|
|
||||||
// Only an allowlisted data block can create a widget; Markdown never executes scripts.
|
// Only an allowlisted data block can create a widget; Markdown never executes scripts.
|
||||||
export function helpBlocks(source: string): HelpBlock[] {
|
export function helpBlocks(source: string, catalog: GeneratorCatalog = defaultGeneratorCatalog): HelpBlock[] {
|
||||||
const document = marked.lexer(source)
|
const document = marked.lexer(source)
|
||||||
const blocks: HelpBlock[] = []
|
const blocks: HelpBlock[] = []
|
||||||
let pending: Token[] = []
|
let pending: Token[] = []
|
||||||
@@ -13,14 +14,13 @@ export function helpBlocks(source: string): HelpBlock[] {
|
|||||||
pending = []
|
pending = []
|
||||||
}
|
}
|
||||||
for (const token of document) {
|
for (const token of document) {
|
||||||
let format: DebianFormat | undefined
|
let config: MirrorConfig | null = null
|
||||||
if (token.type === 'code' && token.lang === 'mirror-config' && token.text.length <= 2048) {
|
if (token.type === 'code' && token.lang === 'mirror-config' && token.text.length <= 2048) {
|
||||||
try {
|
try {
|
||||||
const value: unknown = JSON.parse(token.text)
|
config = parseMirrorConfig(JSON.parse(token.text), catalog)
|
||||||
if (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).every(key => key === 'type' || key === 'format') && 'type' in value && value.type === 'debian' && 'format' in value && (value.format === 'list' || value.format === 'deb822')) format = value.format
|
|
||||||
} catch { /* Invalid blocks remain visible as ordinary code for the author to correct. */ }
|
} catch { /* Invalid blocks remain visible as ordinary code for the author to correct. */ }
|
||||||
}
|
}
|
||||||
if (format) { flush(); blocks.push({ kind: 'debian', format }) }
|
if (config) { flush(); blocks.push({ kind: 'config', config }) }
|
||||||
else pending.push(token)
|
else pending.push(token)
|
||||||
}
|
}
|
||||||
flush()
|
flush()
|
||||||
|
|||||||
@@ -1,4 +1,15 @@
|
|||||||
const pairs = {
|
const pairs = {
|
||||||
|
generators: ['配置生成器', 'Configuration generators'],
|
||||||
|
generatorIntro: ['管理帮助页中的版本选项。保存后即可生效,无需重新编译或部署前端。', 'Manage version choices on help pages. Changes take effect without rebuilding or deploying the frontend.'],
|
||||||
|
defaultRelease: ['默认版本', 'Default version'], releaseLabel: ['显示名称', 'Display name'], releaseId: ['版本代号', 'Release identifier'], keyringPath: ['系统密钥环路径', 'System keyring path'], addRelease: ['添加版本', 'Add release'], unnamedRelease: ['未命名版本 {index}', 'Unnamed release {index}'],
|
||||||
|
releaseStable: ['提供稳定版更新与安全更新', 'Stable updates and security updates'], releaseFirmware: ['提供 non-free-firmware', 'Include non-free-firmware'], releaseBackports: ['提供 backports', 'Include backports'],
|
||||||
|
generatorHint_ubuntu: ['代号填写官方版本代号(如 noble),显示名称填写版本号(如 Ubuntu 24.04 LTS)。', 'Use the official codename (for example noble) as the identifier and the version (for example Ubuntu 24.04 LTS) as its display name.'],
|
||||||
|
generatorHint_debian: ['代号使用官方代号或 testing、sid。稳定版选项决定是否生成 updates 和 security;至少保留一个稳定版供 Debian Security 使用。', 'Use official codenames or testing/sid. Stable releases generate updates and security suites; retain at least one stable release for Debian Security.'],
|
||||||
|
generatorHint_kubernetes: ['版本代号采用 v1.35 形式;仓库地址与官方签名密钥地址会一起更新。', 'Use a minor version such as v1.35. Repository and official signing key URLs change together.'],
|
||||||
|
generatorHint_tailscale: ['代号采用 debian/bookworm 或 ubuntu/noble 形式,匹配上游发行版路径。', 'Use distribution/codename identifiers such as debian/bookworm or ubuntu/noble to match upstream paths.'],
|
||||||
|
generatorHint_proxmox: ['代号填写对应 Debian 代号;密钥环路径须匹配已安装的 Proxmox 版本。', 'Use the matching Debian codename and the keyring path installed by that Proxmox release.'],
|
||||||
|
generatorInvalid: ['请检查代号格式、重复项、默认版本与必填内容;Debian 还需保留稳定版,backports 仅适用于稳定版。', 'Check identifiers, duplicates, the default version and required fields. Debian must retain a stable release; backports requires a stable release.'],
|
||||||
|
generatorScope: ['这里只调整使用帮助,不会新增同步任务。发布新版本前请确认相应仓库已同步;删除版本前请检查文章是否固定引用了该版本。', 'These settings only change usage guides, not sync tasks. Verify repository availability before adding releases, and check articles for fixed references before removing them.'],
|
||||||
viewHelp: ['查看帮助页', 'View usage guide'],
|
viewHelp: ['查看帮助页', 'View usage guide'],
|
||||||
downloadProjects: ['软件项目', 'Software projects'], addDownloadProject: ['添加软件', 'Add software'], removeDownloadProject: ['移除软件', 'Remove software'], softwareName: ['软件名称', 'Software name'],
|
downloadProjects: ['软件项目', 'Software projects'], addDownloadProject: ['添加软件', 'Add software'], removeDownloadProject: ['移除软件', 'Remove software'], softwareName: ['软件名称', 'Software name'],
|
||||||
downloadDescription: ['软件文章(中文,Markdown)', 'Article (Chinese, Markdown)'], saveDownloads: ['保存下载配置', 'Save download catalog'],
|
downloadDescription: ['软件文章(中文,Markdown)', 'Article (Chinese, Markdown)'], saveDownloads: ['保存下载配置', 'Save download catalog'],
|
||||||
@@ -10,6 +21,7 @@ const pairs = {
|
|||||||
auditPagination: ['操作记录分页', 'Audit log pagination'], auditTotal: ['共 {total} 条记录', '{total} entries'], previousPage: ['上一页', 'Previous'], nextPage: ['下一页', 'Next'], pagePosition: ['第 {page} / {pages} 页', 'Page {page} of {pages}'],
|
auditPagination: ['操作记录分页', 'Audit log pagination'], auditTotal: ['共 {total} 条记录', '{total} entries'], previousPage: ['上一页', 'Previous'], nextPage: ['下一页', 'Next'], pagePosition: ['第 {page} / {pages} 页', 'Page {page} of {pages}'],
|
||||||
relatedLinks: ['首页相关链接', 'Home page related links'], linkType: ['链接类型', 'Link type'], urlLink: ['网址', 'URL'], helpLink: ['软件源使用帮助', 'Mirror usage guides'], linkEntry: ['相关链接 {index}', 'Related link {index}'], moveUp: ['上移', 'Move up'], moveDown: ['下移', 'Move down'],
|
relatedLinks: ['首页相关链接', 'Home page related links'], linkType: ['链接类型', 'Link type'], urlLink: ['网址', 'URL'], helpLink: ['软件源使用帮助', 'Mirror usage guides'], linkEntry: ['相关链接 {index}', 'Related link {index}'], moveUp: ['上移', 'Move up'], moveDown: ['下移', 'Move down'],
|
||||||
helpChinese: ['使用说明(中文,Markdown)', 'Usage guide (Chinese, Markdown)'], descriptionLanguage: ['介绍语言', 'Description language'],
|
helpChinese: ['使用说明(中文,Markdown)', 'Usage guide (Chinese, Markdown)'], descriptionLanguage: ['介绍语言', 'Description language'],
|
||||||
|
configGenerator: ['软件源配置生成器', 'Repository configuration generator'], insertGenerator: ['插入配置生成器', 'Insert configuration generator'],
|
||||||
contentLanguage: ['内容语言', 'Content language'],
|
contentLanguage: ['内容语言', 'Content language'],
|
||||||
title: ['站点管理', 'Site administration'], login: ['登录', 'Sign in'], logout: ['退出登录', 'Sign out'], username: ['用户名', 'Username'], password: ['密码', 'Password'], checking: ['正在检查登录状态…', 'Checking session…'],
|
title: ['站点管理', 'Site administration'], login: ['登录', 'Sign in'], logout: ['退出登录', 'Sign out'], username: ['用户名', 'Username'], password: ['密码', 'Password'], checking: ['正在检查登录状态…', 'Checking session…'],
|
||||||
overview: ['运行概况', 'Overview'], mirrors: ['镜像与任务', 'Mirrors & tasks'], announcements: ['公告', 'Announcements'], config: ['同步配置', 'Sync configuration'], settings: ['站点设置', 'Site settings'], users: ['账户', 'Accounts'], audit: ['操作记录', 'Audit log'],
|
overview: ['运行概况', 'Overview'], mirrors: ['镜像与任务', 'Mirrors & tasks'], announcements: ['公告', 'Announcements'], config: ['同步配置', 'Sync configuration'], settings: ['站点设置', 'Site settings'], users: ['账户', 'Accounts'], audit: ['操作记录', 'Audit log'],
|
||||||
|
|||||||
@@ -63,6 +63,29 @@ export default {
|
|||||||
"exampleHint": "This layout example uses the reserved example.invalid domain and cannot be used as a software repository.",
|
"exampleHint": "This layout example uses the reserved example.invalid domain and cannot be used as a software repository.",
|
||||||
"official": "Official project website",
|
"official": "Official project website",
|
||||||
"helpTitle": "Using the mirrors",
|
"helpTitle": "Using the mirrors",
|
||||||
|
"generator": {
|
||||||
|
"catalogFailed": "Could not load configuration generator versions.",
|
||||||
|
"catalogStale": "Version data could not be refreshed. Showing the last loaded choices.",
|
||||||
|
"title": "{name} repository configuration",
|
||||||
|
"format": "Configuration format",
|
||||||
|
"version": "System or repository release",
|
||||||
|
"protocol": "Protocol",
|
||||||
|
"sources": "Enable source packages",
|
||||||
|
"nonFree": "Include non-free packages",
|
||||||
|
"securityMirror": "Use mirror for security updates",
|
||||||
|
"proposed": "Enable proposed",
|
||||||
|
"channel": "Package channel",
|
||||||
|
"generated": "Generated repository configuration",
|
||||||
|
"signingKey": "Fetch the official signing key",
|
||||||
|
"applyCommands": "Replace repository URLs and refresh indexes",
|
||||||
|
"ubuntuScope": "For x86 Ubuntu; ARM and other ports require ubuntu-ports. Check that indexes for the selected release have been synchronized.",
|
||||||
|
"proposedNotice": "proposed contains candidate updates and is disabled by default; ordinary use does not require it.",
|
||||||
|
"kubernetesNotice": "Choose the minor version that matches the cluster installation or upgrade plan. Back up any existing key file before importing a replacement.",
|
||||||
|
"openwrtNotice": "Release builds only. Existing version, target and architecture paths are preserved; keep the original repository for snapshots. Run these commands in the router's root shell.",
|
||||||
|
"elrepoNotice": "Install the matching official ELRepo configuration and keys first. The commands preserve existing signature checks and repository enablement.",
|
||||||
|
"formats": { "list": "Traditional format (.list)" },
|
||||||
|
"names": { "debian": "Debian", "ubuntu": "Ubuntu", "debian-security": "Debian Security", "archlinux": "Arch Linux", "archlinuxarm": "Arch Linux ARM", "archlinuxcn": "Arch Linux CN", "anaconda": "Conda", "kubernetes": "Kubernetes", "tailscale": "Tailscale", "proxmox": "Proxmox VE", "openwrt": "OpenWrt", "elrepo": "ELRepo" }
|
||||||
|
},
|
||||||
"debian": {
|
"debian": {
|
||||||
"generator": "{format} repository configuration",
|
"generator": "{format} repository configuration",
|
||||||
"traditional": "Traditional format",
|
"traditional": "Traditional format",
|
||||||
|
|||||||
@@ -63,6 +63,29 @@ export default {
|
|||||||
"exampleHint": "以下配置仅演示排版,使用 example.invalid 保留域名,不可用于实际软件源配置。",
|
"exampleHint": "以下配置仅演示排版,使用 example.invalid 保留域名,不可用于实际软件源配置。",
|
||||||
"official": "项目官方网站",
|
"official": "项目官方网站",
|
||||||
"helpTitle": "使用帮助",
|
"helpTitle": "使用帮助",
|
||||||
|
"generator": {
|
||||||
|
"catalogFailed": "无法加载配置生成器的版本数据。",
|
||||||
|
"catalogStale": "版本数据暂时无法刷新,正在显示上次加载的选项。",
|
||||||
|
"title": "{name} 软件源配置",
|
||||||
|
"format": "配置格式",
|
||||||
|
"version": "系统或仓库版本",
|
||||||
|
"protocol": "访问协议",
|
||||||
|
"sources": "启用源码源",
|
||||||
|
"nonFree": "使用非自由软件源",
|
||||||
|
"securityMirror": "安全更新使用镜像",
|
||||||
|
"proposed": "启用 proposed",
|
||||||
|
"channel": "软件包频道",
|
||||||
|
"generated": "生成的软件源配置",
|
||||||
|
"signingKey": "获取官方签名公钥",
|
||||||
|
"applyCommands": "替换软件源并刷新索引",
|
||||||
|
"ubuntuScope": "适用于 x86 Ubuntu;ARM 等架构需使用 ubuntu-ports。请先确认所选发行版的索引已同步。",
|
||||||
|
"proposedNotice": "proposed 包含候选更新,默认关闭;普通使用无需启用。",
|
||||||
|
"kubernetesNotice": "选择与集群安装或升级计划一致的次版本。导入公钥前先备份已有同名密钥文件。",
|
||||||
|
"openwrtNotice": "仅适用于正式发行版,保留原配置中的版本、target 和架构路径;snapshots 请继续使用原仓库。命令在路由器 root 终端中执行。",
|
||||||
|
"elrepoNotice": "先按 ELRepo 官方说明安装匹配系统版本的仓库配置与密钥,再执行替换命令;原有签名校验与仓库启用状态保持不变。",
|
||||||
|
"formats": { "list": "传统格式 (.list)" },
|
||||||
|
"names": { "debian": "Debian", "ubuntu": "Ubuntu", "debian-security": "Debian Security", "archlinux": "Arch Linux", "archlinuxarm": "Arch Linux ARM", "archlinuxcn": "Arch Linux CN", "anaconda": "Conda", "kubernetes": "Kubernetes", "tailscale": "Tailscale", "proxmox": "Proxmox VE", "openwrt": "OpenWrt", "elrepo": "ELRepo" }
|
||||||
|
},
|
||||||
"debian": {
|
"debian": {
|
||||||
"generator": "{format} 软件源配置",
|
"generator": "{format} 软件源配置",
|
||||||
"traditional": "传统格式",
|
"traditional": "传统格式",
|
||||||
|
|||||||
@@ -0,0 +1,190 @@
|
|||||||
|
import { aptSources, mirrorOrigin, type AptFormat } from './apt-sources.ts'
|
||||||
|
import { debianSources } from './debian-sources.ts'
|
||||||
|
import { ubuntuSources } from './ubuntu-sources.ts'
|
||||||
|
import { defaultGeneratorCatalog, type GeneratorCatalog, type VersionedGenerator } from './generator-catalog.ts'
|
||||||
|
|
||||||
|
export type MirrorConfigType = 'debian' | 'ubuntu' | 'debian-security' | 'archlinux' | 'archlinuxarm' | 'archlinuxcn' | 'anaconda' | 'kubernetes' | 'tailscale' | 'proxmox' | 'openwrt' | 'elrepo'
|
||||||
|
export type ConfigValues = Record<string, string | boolean>
|
||||||
|
export interface ConfigChoice { value: string; label?: string; labelKey?: string }
|
||||||
|
export interface ConfigField {
|
||||||
|
key: string
|
||||||
|
labelKey: string
|
||||||
|
kind: 'select' | 'switch'
|
||||||
|
choices?: ConfigChoice[]
|
||||||
|
disabled?: (values: ConfigValues) => boolean
|
||||||
|
}
|
||||||
|
export interface ConfigFile { path?: string; titleKey?: string; code: string }
|
||||||
|
interface GeneratorContext { origin: string; format: string; values: ConfigValues; catalog: GeneratorCatalog }
|
||||||
|
export interface MirrorGenerator {
|
||||||
|
nameKey: string
|
||||||
|
formats: ConfigChoice[]
|
||||||
|
defaultFormat: string
|
||||||
|
defaults: ConfigValues
|
||||||
|
fields: ConfigField[]
|
||||||
|
notes?: { key: string; when?: (values: ConfigValues) => boolean }[]
|
||||||
|
normalize?: (values: ConfigValues) => void
|
||||||
|
generate: (context: GeneratorContext) => ConfigFile[]
|
||||||
|
}
|
||||||
|
export interface MirrorConfig { type: MirrorConfigType; format?: string; options?: ConfigValues }
|
||||||
|
|
||||||
|
const aptFormats: ConfigChoice[] = [{ value: 'list', labelKey: 'mirrors.generator.formats.list' }, { value: 'deb822', label: 'DEB822' }]
|
||||||
|
const format = (value: string, label = value): ConfigChoice[] => [{ value, label }]
|
||||||
|
const versionField = (choices: ConfigChoice[]): ConfigField => ({ key: 'release', kind: 'select', labelKey: 'mirrors.generator.version', choices })
|
||||||
|
const sourceField: ConfigField = { key: 'sources', kind: 'switch', labelKey: 'mirrors.generator.sources' }
|
||||||
|
const securityField: ConfigField = { key: 'securityMirror', kind: 'switch', labelKey: 'mirrors.generator.securityMirror' }
|
||||||
|
const nonFreeField: ConfigField = { key: 'nonFree', kind: 'switch', labelKey: 'mirrors.generator.nonFree' }
|
||||||
|
const choices = (type: VersionedGenerator) => defaultGeneratorCatalog[type].releases.map(release => ({ value: release.id, label: release.label }))
|
||||||
|
const aptFile = (name: string, selected: string) => selected === 'list' ? '/etc/apt/sources.list' : `/etc/apt/sources.list.d/${name}.sources`
|
||||||
|
const configText = (path: string, code: string): ConfigFile[] => [{ path, code }]
|
||||||
|
const aptKey = (url: string, path: string): ConfigFile => ({ titleKey: 'mirrors.generator.signingKey', code: `sudo install -d -m 0755 ${path.slice(0, path.lastIndexOf('/'))}\ncurl -fsSL ${url} | sudo gpg --dearmor -o ${path}\nsudo chmod 0644 ${path}\n` })
|
||||||
|
|
||||||
|
// A new generator supplies its fields and configuration rules here; the Markdown
|
||||||
|
// parser, controls, copy behavior and responsive layout are shared by all sources.
|
||||||
|
export const mirrorGenerators: Record<MirrorConfigType, MirrorGenerator> = {
|
||||||
|
debian: {
|
||||||
|
nameKey: 'mirrors.generator.names.debian', formats: aptFormats, defaultFormat: 'list',
|
||||||
|
defaults: { release: defaultGeneratorCatalog.debian.defaultRelease, sources: false, nonFree: true, securityMirror: false },
|
||||||
|
fields: [versionField(choices('debian')), sourceField, nonFreeField, securityField],
|
||||||
|
generate: ({ origin, format, values, catalog }) => configText(aptFile('debian', format), debianSources({ origin, format: format as AptFormat, release: String(values.release), sources: Boolean(values.sources), nonFree: Boolean(values.nonFree), securityMirror: Boolean(values.securityMirror) }, catalog.debian.releases)),
|
||||||
|
},
|
||||||
|
ubuntu: {
|
||||||
|
nameKey: 'mirrors.generator.names.ubuntu', formats: aptFormats, defaultFormat: 'deb822',
|
||||||
|
defaults: { release: defaultGeneratorCatalog.ubuntu.defaultRelease, sources: false, proposed: false, securityMirror: false },
|
||||||
|
fields: [versionField(choices('ubuntu')), sourceField, { key: 'proposed', kind: 'switch', labelKey: 'mirrors.generator.proposed' }, securityField],
|
||||||
|
notes: [{ key: 'mirrors.generator.ubuntuScope' }, { key: 'mirrors.generator.proposedNotice', when: values => Boolean(values.proposed) }],
|
||||||
|
generate: ({ origin, format, values, catalog }) => configText(aptFile('ubuntu', format), ubuntuSources({ origin, format: format as AptFormat, release: String(values.release), sources: Boolean(values.sources), proposed: Boolean(values.proposed), securityMirror: Boolean(values.securityMirror) }, catalog.ubuntu.releases)),
|
||||||
|
},
|
||||||
|
'debian-security': {
|
||||||
|
nameKey: 'mirrors.generator.names.debian-security', formats: aptFormats, defaultFormat: 'deb822',
|
||||||
|
defaults: { release: defaultGeneratorCatalog.debian.defaultRelease, sources: false, nonFree: true }, fields: [versionField(defaultGeneratorCatalog.debian.releases.filter(release => release.stable).map(release => ({ value: release.id, label: release.label }))), sourceField, nonFreeField],
|
||||||
|
generate: ({ origin, format, values, catalog }) => {
|
||||||
|
const release = catalog.debian.releases.find(entry => entry.id === values.release)!
|
||||||
|
const components = ['main', ...(values.nonFree ? ['contrib', 'non-free', ...(release.firmware ? ['non-free-firmware'] : [])] : [])].join(' ')
|
||||||
|
return configText(format === 'list' ? '/etc/apt/sources.list' : '/etc/apt/sources.list.d/debian-security.sources', aptSources([{ uri: `${origin}/mirrors/debian-security/`, suites: [`${release.id}-security`], components, keyring: '/usr/share/keyrings/debian-archive-keyring.gpg' }], format as AptFormat, Boolean(values.sources)))
|
||||||
|
},
|
||||||
|
},
|
||||||
|
archlinux: {
|
||||||
|
nameKey: 'mirrors.generator.names.archlinux', formats: format('pacman', 'pacman'), defaultFormat: 'pacman', defaults: {}, fields: [],
|
||||||
|
generate: ({ origin }) => configText('/etc/pacman.d/mirrorlist', `Server = ${origin}/mirrors/archlinux/$repo/os/$arch\n`),
|
||||||
|
},
|
||||||
|
archlinuxarm: {
|
||||||
|
nameKey: 'mirrors.generator.names.archlinuxarm', formats: format('pacman', 'pacman'), defaultFormat: 'pacman', defaults: {}, fields: [],
|
||||||
|
generate: ({ origin }) => configText('/etc/pacman.d/mirrorlist', `Server = ${origin}/mirrors/archlinuxarm/$arch/$repo\n`),
|
||||||
|
},
|
||||||
|
archlinuxcn: {
|
||||||
|
nameKey: 'mirrors.generator.names.archlinuxcn', formats: format('pacman', 'pacman'), defaultFormat: 'pacman', defaults: {}, fields: [],
|
||||||
|
generate: ({ origin }) => configText('/etc/pacman.conf', `[archlinuxcn]\nServer = ${origin}/mirrors/archlinuxcn/$arch\n`),
|
||||||
|
},
|
||||||
|
anaconda: {
|
||||||
|
nameKey: 'mirrors.generator.names.anaconda', formats: format('condarc', '.condarc'), defaultFormat: 'condarc', defaults: { channel: 'conda-forge' },
|
||||||
|
fields: [{ key: 'channel', kind: 'select', labelKey: 'mirrors.generator.channel', choices: ['conda-forge', 'bioconda', 'defaults'].map(value => ({ value, label: value })) }],
|
||||||
|
generate: ({ origin, values }) => {
|
||||||
|
const prefix = `${origin}/mirrors/anaconda/`
|
||||||
|
if (values.channel === 'defaults') return configText('~/.condarc', `channels:\n - defaults\nshow_channel_urls: true\ndefault_channels:\n - ${prefix}pkgs/main\n - ${prefix}pkgs/r\n - ${prefix}pkgs/msys2\n`)
|
||||||
|
const channels = values.channel === 'bioconda' ? ['conda-forge', 'bioconda'] : ['conda-forge']
|
||||||
|
return configText('~/.condarc', `channels:\n${channels.map(name => ` - ${name}`).join('\n')}\nshow_channel_urls: true\nchannel_priority: strict\ncustom_channels:\n${channels.map(name => ` ${name}: ${prefix}cloud`).join('\n')}\n`)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
kubernetes: {
|
||||||
|
nameKey: 'mirrors.generator.names.kubernetes', formats: [{ value: 'deb', label: 'APT (Debian / Ubuntu)' }, { value: 'rpm', label: 'RPM' }], defaultFormat: 'deb', defaults: { release: defaultGeneratorCatalog.kubernetes.defaultRelease },
|
||||||
|
fields: [versionField(choices('kubernetes'))],
|
||||||
|
notes: [{ key: 'mirrors.generator.kubernetesNotice' }],
|
||||||
|
generate: ({ origin, format, values }) => {
|
||||||
|
const version = String(values.release)
|
||||||
|
const suffix = `core:/stable:/${version}/${format}/`
|
||||||
|
const uri = `${origin}/mirrors/kubernetes/${suffix}`
|
||||||
|
if (format === 'rpm') return configText('/etc/yum.repos.d/kubernetes.repo', `[kubernetes]\nname=Kubernetes\nbaseurl=${uri}\nenabled=1\ngpgcheck=1\ngpgkey=https://pkgs.k8s.io/${suffix}repodata/repomd.xml.key\nexclude=kubelet kubeadm kubectl cri-tools kubernetes-cni\n`)
|
||||||
|
const keyring = '/etc/apt/keyrings/kubernetes-apt-keyring.gpg'
|
||||||
|
return [aptKey(`https://pkgs.k8s.io/${suffix}Release.key`, keyring), { path: '/etc/apt/sources.list.d/kubernetes.list', code: `deb [signed-by=${keyring}] ${uri} /\n` }]
|
||||||
|
},
|
||||||
|
},
|
||||||
|
tailscale: {
|
||||||
|
nameKey: 'mirrors.generator.names.tailscale', formats: aptFormats, defaultFormat: 'list', defaults: { release: defaultGeneratorCatalog.tailscale.defaultRelease },
|
||||||
|
fields: [versionField(choices('tailscale'))],
|
||||||
|
generate: ({ origin, format, values }) => {
|
||||||
|
const [distribution, suite] = String(values.release).split('/')
|
||||||
|
const keyring = '/usr/share/keyrings/tailscale-archive-keyring.gpg'
|
||||||
|
const key: ConfigFile = { titleKey: 'mirrors.generator.signingKey', code: `sudo install -d -m 0755 /usr/share/keyrings\ncurl -fsSL https://pkgs.tailscale.com/stable/${distribution}/${suite}.noarmor.gpg | sudo tee ${keyring} >/dev/null\nsudo chmod 0644 ${keyring}\n` }
|
||||||
|
const uri = `${origin}/mirrors/tailscale/${distribution}`
|
||||||
|
const code = format === 'list' ? `deb [signed-by=${keyring}] ${uri} ${suite} main\n` : aptSources([{ uri, suites: [suite], components: 'main', keyring }], 'deb822', false)
|
||||||
|
return [key, { path: `/etc/apt/sources.list.d/tailscale.${format === 'list' ? 'list' : 'sources'}`, code }]
|
||||||
|
},
|
||||||
|
},
|
||||||
|
proxmox: {
|
||||||
|
nameKey: 'mirrors.generator.names.proxmox', formats: aptFormats, defaultFormat: 'deb822', defaults: { release: defaultGeneratorCatalog.proxmox.defaultRelease },
|
||||||
|
fields: [versionField(choices('proxmox'))],
|
||||||
|
generate: ({ origin, format, values, catalog }) => {
|
||||||
|
const uri = `${origin}/mirrors/proxmox/debian/pve`
|
||||||
|
const keyring = catalog.proxmox.releases.find(release => release.id === values.release)!.keyring!
|
||||||
|
const code = format === 'list' ? `deb ${uri} ${values.release} pve-no-subscription\n` : aptSources([{ uri, suites: [String(values.release)], components: 'pve-no-subscription', keyring }], 'deb822', false)
|
||||||
|
return configText(`/etc/apt/sources.list.d/pve-no-subscription.${format === 'list' ? 'list' : 'sources'}`, code)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
openwrt: {
|
||||||
|
nameKey: 'mirrors.generator.names.openwrt', formats: [{ value: 'apk', label: 'APK (OpenWrt ≥ 25.12)' }, { value: 'opkg', label: 'OPKG (OpenWrt ≤ 24.10)' }], defaultFormat: 'apk', defaults: {}, fields: [],
|
||||||
|
notes: [{ key: 'mirrors.generator.openwrtNotice' }],
|
||||||
|
generate: ({ origin, format }) => {
|
||||||
|
const path = format === 'apk' ? '/etc/apk/repositories.d/distfeeds.list' : '/etc/opkg/distfeeds.conf'
|
||||||
|
return [{ titleKey: 'mirrors.generator.applyCommands', code: `cp ${path} ${path}.bak\nsed -i 's|https\\?://downloads.openwrt.org|${origin}/mirrors/openwrt|g' ${path}\n${format} update\n` }]
|
||||||
|
},
|
||||||
|
},
|
||||||
|
elrepo: {
|
||||||
|
nameKey: 'mirrors.generator.names.elrepo', formats: format('shell', 'Shell'), defaultFormat: 'shell', defaults: {}, fields: [],
|
||||||
|
notes: [{ key: 'mirrors.generator.elrepoNotice' }],
|
||||||
|
generate: ({ origin }) => [{ titleKey: 'mirrors.generator.applyCommands', code: `sudo cp /etc/yum.repos.d/elrepo.repo /etc/yum.repos.d/elrepo.repo.bak\nsudo sed -i -e '/^[[:space:]]*mirrorlist=/s/^/#/' -e 's|^#baseurl=|baseurl=|' -e 's|https\\?://elrepo.org/linux|${origin}/mirrors/elrepo|g' /etc/yum.repos.d/elrepo.repo\nsudo dnf makecache\n` }],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export const mirrorConfigTypes = Object.keys(mirrorGenerators) as MirrorConfigType[]
|
||||||
|
export const protocolField: ConfigField = { key: 'protocol', kind: 'select', labelKey: 'mirrors.generator.protocol', choices: [{ value: 'https', label: 'HTTPS' }, { value: 'http', label: 'HTTP' }] }
|
||||||
|
export function getMirrorGenerator(type: MirrorConfigType, catalog: GeneratorCatalog = defaultGeneratorCatalog): MirrorGenerator {
|
||||||
|
const base = mirrorGenerators[type]
|
||||||
|
const catalogType = type === 'debian-security' ? 'debian' : type
|
||||||
|
if (!Object.hasOwn(catalog, catalogType)) return base
|
||||||
|
const versions = catalog[catalogType as VersionedGenerator]
|
||||||
|
const releases = type === 'debian-security' ? versions.releases.filter(release => release.stable) : versions.releases
|
||||||
|
const defaultRelease = releases.find(release => release.id === versions.defaultRelease)?.id || releases[0]!.id
|
||||||
|
const stable = (values: ConfigValues) => Boolean(versions.releases.find(release => release.id === values.release)?.stable)
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
defaults: { ...base.defaults, release: defaultRelease },
|
||||||
|
fields: base.fields.map(field => field.key === 'release' ? versionField(releases.map(release => ({ value: release.id, label: release.label }))) : type === 'debian' && field.key === 'securityMirror' ? { ...field, disabled: values => !stable(values) } : field),
|
||||||
|
...(type === 'debian' ? { normalize: values => { if (!stable(values)) values.securityMirror = false }, notes: [{ key: 'mirrors.debian.rollingNotice', when: values => !stable(values) }] } : {}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export function configFields(type: MirrorConfigType, catalog: GeneratorCatalog = defaultGeneratorCatalog) { return [...getMirrorGenerator(type, catalog).fields, protocolField] }
|
||||||
|
|
||||||
|
// JSON config selects a registered generator and allowlisted values; it cannot
|
||||||
|
// supply scripts, HTML, functions, arbitrary templates or package-manager flags.
|
||||||
|
export function parseMirrorConfig(value: unknown, catalog: GeneratorCatalog = defaultGeneratorCatalog): MirrorConfig | null {
|
||||||
|
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
|
||||||
|
if (Object.keys(value).some(key => !['type', 'format', 'options'].includes(key)) || !('type' in value) || typeof value.type !== 'string' || !Object.hasOwn(mirrorGenerators, value.type)) return null
|
||||||
|
const type = value.type as MirrorConfigType
|
||||||
|
const generator = getMirrorGenerator(type, catalog)
|
||||||
|
if ('format' in value && (typeof value.format !== 'string' || !generator.formats.some(choice => choice.value === value.format))) return null
|
||||||
|
if ('options' in value) {
|
||||||
|
const options = value.options
|
||||||
|
if (!options || typeof options !== 'object' || Array.isArray(options)) return null
|
||||||
|
const fields = configFields(type, catalog)
|
||||||
|
if (Object.entries(options).some(([key, entry]) => {
|
||||||
|
const field = fields.find(field => field.key === key)
|
||||||
|
return !field || (field.kind === 'switch' ? typeof entry !== 'boolean' : typeof entry !== 'string' || !field.choices!.some(choice => choice.value === entry))
|
||||||
|
})) return null
|
||||||
|
}
|
||||||
|
return { type, ...('format' in value ? { format: value.format as string } : {}), ...('options' in value ? { options: { ...value.options as ConfigValues } } : {}) }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function configDefaults(config: MirrorConfig, origin: string, catalog: GeneratorCatalog = defaultGeneratorCatalog): ConfigValues {
|
||||||
|
const parsed = parseMirrorConfig(config, catalog)
|
||||||
|
if (!parsed) throw new Error('Invalid mirror configuration')
|
||||||
|
return { ...getMirrorGenerator(parsed.type, catalog).defaults, protocol: new URL(mirrorOrigin(origin)).protocol.slice(0, -1), ...parsed.options }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generateMirrorConfig(config: MirrorConfig, origin: string, values: ConfigValues = {}, catalog: GeneratorCatalog = defaultGeneratorCatalog) {
|
||||||
|
const parsed = parseMirrorConfig({ ...config, options: { ...config.options, ...values } }, catalog)
|
||||||
|
if (!parsed) throw new Error('Invalid mirror configuration')
|
||||||
|
const generator = getMirrorGenerator(parsed.type, catalog)
|
||||||
|
const state = configDefaults(parsed, origin, catalog)
|
||||||
|
generator.normalize?.(state)
|
||||||
|
return generator.generate({ origin: mirrorOrigin(origin, String(state.protocol)), format: parsed.format || generator.defaultFormat, values: state, catalog })
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { aptSources, mirrorOrigin, type AptFormat } from './apt-sources.ts'
|
||||||
|
import { defaultGeneratorCatalog, type GeneratorRelease } from './generator-catalog.ts'
|
||||||
|
|
||||||
|
export const ubuntuReleases = defaultGeneratorCatalog.ubuntu.releases
|
||||||
|
|
||||||
|
export interface UbuntuSourceOptions {
|
||||||
|
origin: string
|
||||||
|
release: string
|
||||||
|
format: AptFormat
|
||||||
|
sources: boolean
|
||||||
|
proposed: boolean
|
||||||
|
securityMirror: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ubuntuSources(options: UbuntuSourceOptions, releases: readonly GeneratorRelease[] = defaultGeneratorCatalog.ubuntu.releases) {
|
||||||
|
if (!releases.some(release => release.id === options.release)) throw new Error('Invalid Ubuntu release')
|
||||||
|
const origin = mirrorOrigin(options.origin)
|
||||||
|
const uri = `${origin}/mirrors/ubuntu/`
|
||||||
|
const suites = [options.release, `${options.release}-updates`, `${options.release}-backports`]
|
||||||
|
if (options.proposed) suites.push(`${options.release}-proposed`)
|
||||||
|
return aptSources([
|
||||||
|
{ uri, suites, components: 'main restricted universe multiverse', keyring: '/usr/share/keyrings/ubuntu-archive-keyring.gpg' },
|
||||||
|
{ uri: options.securityMirror ? uri : 'http://security.ubuntu.com/ubuntu/', suites: [`${options.release}-security`], components: 'main restricted universe multiverse', keyring: '/usr/share/keyrings/ubuntu-archive-keyring.gpg' },
|
||||||
|
], options.format, options.sources)
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { inject, onBeforeUnmount, onMounted, provide, ref, shallowRef, type InjectionKey, type Ref, type ShallowRef } from 'vue'
|
||||||
|
import { api } from './api'
|
||||||
|
import { defaultGeneratorCatalog, parseGeneratorCatalog, type GeneratorCatalog } from './generator-catalog'
|
||||||
|
|
||||||
|
interface CatalogContext {
|
||||||
|
catalog: ShallowRef<GeneratorCatalog | null>
|
||||||
|
failed: Ref<boolean>
|
||||||
|
refresh: () => Promise<void>
|
||||||
|
}
|
||||||
|
const catalogKey: InjectionKey<CatalogContext> = Symbol('generator-catalog')
|
||||||
|
|
||||||
|
export function provideGeneratorCatalog(enabled: boolean) {
|
||||||
|
const catalog = shallowRef<GeneratorCatalog | null>(null)
|
||||||
|
const failed = ref(false)
|
||||||
|
let controller: AbortController | undefined
|
||||||
|
let timer: ReturnType<typeof setInterval> | undefined
|
||||||
|
let disposed = false
|
||||||
|
async function refresh() {
|
||||||
|
controller?.abort()
|
||||||
|
const request = new AbortController()
|
||||||
|
controller = request
|
||||||
|
try {
|
||||||
|
const result = parseGeneratorCatalog(await api('/generators', { signal: request.signal }))
|
||||||
|
if (!result) throw new Error('Invalid generator catalog')
|
||||||
|
if (disposed || request.signal.aborted) return
|
||||||
|
if (JSON.stringify(catalog.value) !== JSON.stringify(result)) catalog.value = result
|
||||||
|
failed.value = false
|
||||||
|
} catch {
|
||||||
|
if (!disposed && !request.signal.aborted) failed.value = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
provide(catalogKey, { catalog, failed, refresh })
|
||||||
|
onMounted(() => { if (enabled) { void refresh(); timer = setInterval(() => { if (!document.hidden) void refresh() }, 15000) } })
|
||||||
|
onBeforeUnmount(() => { disposed = true; controller?.abort(); clearInterval(timer) })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useGeneratorCatalog(): CatalogContext {
|
||||||
|
// Isolated previews can use the shared seed; the application always provides
|
||||||
|
// backend data and does not silently substitute defaults after a fetch failure.
|
||||||
|
return inject(catalogKey, { catalog: shallowRef(defaultGeneratorCatalog), failed: ref(false), refresh: async () => {} })
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user