仰望星辰工作室

feat: 仓库开源协议选择与源码压缩包下载

F fqh 提交于 2026-11-11 23:12 · 765763d ·父提交 c06085a
feat: 仓库开源协议选择与源码压缩包下载

开源协议:repos 增加 license 字段(schema v6),项目设置/后台可选择常见 SPDX 协议,项目主页展示徽章并提供协议说明页;新增 /licenses 目录与 /licenses/view/{id} 详情。源码压缩包:git archive 流式输出,/ {repo}/archive 支持按 ref 下载 zip。
19 个文件变更 +1043 -11 fqh@example.com
•README.md +2 -1
•internal/gitx/gitx.go +32 -0
•internal/license/license.go +249 -0
•internal/server/admin.go +10 -0
•internal/server/archive_test.go +75 -0
•internal/server/home.go +3 -0
•internal/server/license_test.go +181 -0
•internal/server/licenses.go +88 -0
•internal/server/repo.go +56 -0
•internal/server/server.go +10 -1
•internal/store/repos.go +31 -7
•internal/store/store.go +20 -1
•internal/store/store_test.go +101 -0
•webroot/static/style.css +45 -1
•webroot/templates/admin_repo.html +13 -0
•webroot/templates/license.html +54 -0
•webroot/templates/licenses.html +30 -0
•webroot/templates/repo_home.html +30 -0
•webroot/templates/repo_settings.html +13 -0
变更内容
diff --git a/README.md b/README.md
index c7536c9..5eb318b 100644
--- a/README.md
+++ b/README.md
@@ -41,6 +41,7 @@ gitcat -addr :12747 -data ./data
 | 🌐 **Git Smart HTTP** | 完整支持 clone / fetch / push,任何标准 git 客户端即插即用 |
 | 🖥️ **Web 界面** | 仓库浏览(目录树 / 代码高亮预览 / 提交详情 / 分支标签 / 贡献者与语言统计)、全站动态、用户与仓库后台 |
 | 🚀 **发行版 Releases** | 为每个项目发布带附件的发行版,最大单附件 4 GiB,分片上传断点续传,公开下载 |
+| 🏷️ **开源协议** | 为项目选择 MIT / Apache-2.0 / GPL 等常见协议,项目主页展示徽章并链接协议说明;协议正文仍以仓库内 LICENSE 文件为准 |
 | ↩️ **推送回滚** | 每次推送留存完整引用快照,创建者/管理员可在动态页一键回滚;回滚本身也可撤销,配合默认开启的强推/删分支保护 |
 | 🤖 **AI 更新说明** | 每次推送自动调用大模型阅读 diff,生成面向访客的「What's New」 |
 | 💬 **AI 项目助手** | 项目主页右下角的对话助手,能实际查阅仓库代码后回答访客问题 |
@@ -221,7 +222,7 @@ data/
 
 ### 数据库
 
-SQLite 单文件(`gitcat.db`),共 9 张表:`settings`(KV 配置)、`users`、`sessions`、`repos`、`pushes`(推送留痕,含 `ref_changes` 引用快照)、`releases`、`release_assets`、`issues`(议题)、`schema_meta`(结构版本)。当前结构版本为 v5。
+SQLite 单文件(`gitcat.db`),共 9 张表:`settings`(KV 配置)、`users`、`sessions`、`repos`(含私有、归档与开源协议标记)、`pushes`(推送留痕,含 `ref_changes` 引用快照)、`releases`、`release_assets`、`issues`(议题)、`schema_meta`(结构版本)。当前结构版本为 v6。
 
 - 结构版本化迁移:新版本首次启动自动执行增量迁移,迁移前用 `VACUUM INTO` 快照备份到 `data/backups/`
 - 降级保护:用旧二进制打开被新版本迁移过的库会直接拒绝启动,避免写坏数据
diff --git a/internal/gitx/gitx.go b/internal/gitx/gitx.go
index 380e6dd..f5ff66a 100644
--- a/internal/gitx/gitx.go
+++ b/internal/gitx/gitx.go
@@ -538,6 +538,38 @@ func blobSpec(ref, path string) string {
 	return ref + ":" + strings.Trim(path, "/")
 }
 
+// ArchiveZip 把 ref 指向的代码树打包成 zip,边打包边写入 w。
+//
+// 走 git archive 子命令而不是在 Go 里遍历对象:服务端不需要把仓库内容
+// 整体读进内存,大仓库也能边压缩边下载;.gitattributes 里的
+// export-ignore 等规则也与 git 原生命令保持一致。
+func ArchiveZip(ctx context.Context, repo, ref, prefix string, w io.Writer) error {
+	if !ValidRef(ref) {
+		return ErrInvalidRefOrObject
+	}
+	if ctx == nil {
+		ctx = context.Background()
+	}
+	if _, ok := ctx.Deadline(); !ok {
+		var cancel context.CancelFunc
+		ctx, cancel = context.WithTimeout(ctx, 30*time.Minute)
+		defer cancel()
+	}
+	cmd := exec.CommandContext(ctx, "git", "archive", "--format=zip", "--prefix="+prefix, ref)
+	cmd.Dir = repo
+	cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0", "LC_ALL=C")
+	cmd.Stdout = w
+	var stderr bytes.Buffer
+	cmd.Stderr = &stderr
+	if err := cmd.Run(); err != nil {
+		if msg := strings.TrimSpace(stderr.String()); msg != "" {
+			return fmt.Errorf("git archive: %s", msg)
+		}
+		return err
+	}
+	return nil
+}
+
 // BlobSize 返回文件字节数。
 func BlobSize(repo, ref, path string) int64 {
 	out, err := run(repo, "cat-file", "-s", blobSpec(ref, path))
diff --git a/internal/license/license.go b/internal/license/license.go
new file mode 100644
index 0000000..21c86b3
--- /dev/null
+++ b/internal/license/license.go
@@ -0,0 +1,249 @@
+// Package license 是仓库可选择的常见开源协议目录。
+//
+// 这里只保存"元数据"(SPDX 标识、名称、要点与官方链接),不保存协议全文:
+// 协议全文属于仓库内容,应当由维护者作为 LICENSE 文件提交到仓库根目录。
+// gitcat 在项目设置里记录选择,仅用于展示项目信息,不会改写仓库。
+package license
+
+import "strings"
+
+// License 描述一种可选的开源协议。
+type License struct {
+	// ID 是 SPDX 标识(也是数据库中保存的值),例如 MIT、Apache-2.0。
+	ID string
+	// Name 是协议的官方英文名称。
+	Name string
+	// SPDX 与 ID 相同,单独保留字段便于模板语义化展示。
+	SPDX string
+	// Category 是中文分类:宽松 / 弱著佐权 / 强著佐权 / 公共领域。
+	Category string
+	// Summary 是一句话说明,面向不熟悉许可证的成员。
+	Summary string
+	// Points 是权利人需要知道的关键权利与义务摘要(不是法律意见)。
+	Points []string
+	// URL 是 SPDX 官方条目页;TextURL 是协议正文的纯文本来源。
+	URL     string
+	TextURL string
+	// Popular 表示是否进入设置页的"常用协议"分组。
+	Popular bool
+}
+
+// Group 是设置页下拉框里的一组协议。
+type Group struct {
+	Title    string
+	Licenses []License
+}
+
+// catalog 的顺序即展示顺序:先常用,后其他;同类内按使用广度排列。
+var catalog = []License{
+	{
+		ID: "MIT", Name: "MIT License", SPDX: "MIT", Category: "宽松", Popular: true,
+		Summary: "最短、最常见的宽松协议:保留版权与许可声明,就能自由使用、修改和再分发,允许闭源商用。",
+		Points: []string{
+			"允许商用、修改、再许可与闭源分发",
+			"分发时保留原始版权声明与本许可声明",
+			"软件按“现状”提供,作者不承担担保责任",
+		},
+		URL:     "https://spdx.org/licenses/MIT.html",
+		TextURL: "https://raw.githubusercontent.com/spdx/license-list-data/main/text/MIT.txt",
+	},
+	{
+		ID: "Apache-2.0", Name: "Apache License 2.0", SPDX: "Apache-2.0", Category: "宽松", Popular: true,
+		Summary: "宽松协议,并额外提供明确的专利授权;修改过的文件需要保留变更说明。",
+		Points: []string{
+			"允许商用、修改与闭源再分发",
+			"保留版权、许可声明,并保留仓库中的 NOTICE 文件",
+			"修改过的文件需标注“已被修改”",
+			"贡献者授予专利许可,并对发起专利诉讼者收回授权",
+		},
+		URL:     "https://spdx.org/licenses/Apache-2.0.html",
+		TextURL: "https://raw.githubusercontent.com/spdx/license-list-data/main/text/Apache-2.0.txt",
+	},
+	{
+		ID: "GPL-3.0-only", Name: "GNU General Public License v3.0", SPDX: "GPL-3.0-only", Category: "强著佐权", Popular: true,
+		Summary: "最强常见的著佐权协议:分发衍生作品时,整体都必须以 GPL-3.0 开源,并附带安装信息。",
+		Points: []string{
+			"分发二进制或源码时,必须提供完整对应源码",
+			"衍生作品整体继续使用 GPL-3.0(不能闭源分发)",
+			"为用户提供安装修改版本所需的信息(反 Tivo 化条款)",
+			"包含专利授权与终止条款",
+		},
+		URL:     "https://spdx.org/licenses/GPL-3.0-only.html",
+		TextURL: "https://raw.githubusercontent.com/spdx/license-list-data/main/text/GPL-3.0-only.txt",
+	},
+	{
+		ID: "AGPL-3.0-only", Name: "GNU Affero General Public License v3.0", SPDX: "AGPL-3.0-only", Category: "强著佐权", Popular: true,
+		Summary: "在 GPL-3.0 基础上增加网络条款:通过网络提供服务也视为分发,必须向用户提供源码。",
+		Points: []string{
+			"包含 GPL-3.0 的全部义务",
+			"用户通过网络与软件交互时,必须提供获取源码的方式",
+			"适合服务端 / SaaS 项目,防止“只开服务不开源”",
+		},
+		URL:     "https://spdx.org/licenses/AGPL-3.0-only.html",
+		TextURL: "https://raw.githubusercontent.com/spdx/license-list-data/main/text/AGPL-3.0-only.txt",
+	},
+	{
+		ID: "BSD-3-Clause", Name: "BSD 3-Clause \"New\" or \"Revised\" License", SPDX: "BSD-3-Clause", Category: "宽松", Popular: true,
+		Summary: "宽松协议,要求保留版权声明,并禁止用作者或组织名义为衍生产品背书。",
+		Points: []string{
+			"允许商用、修改与闭源再分发",
+			"保留版权声明、条件列表与免责声明",
+			"未经书面许可,不得用作者或组织名称为衍生产品背书",
+		},
+		URL:     "https://spdx.org/licenses/BSD-3-Clause.html",
+		TextURL: "https://raw.githubusercontent.com/spdx/license-list-data/main/text/BSD-3-Clause.txt",
+	},
+	{
+		ID: "MPL-2.0", Name: "Mozilla Public License 2.0", SPDX: "MPL-2.0", Category: "弱著佐权", Popular: true,
+		Summary: "文件级弱著佐权:修改过的 MPL 文件需要公开源码,但可以与闭源代码组合成更大的作品。",
+		Points: []string{
+			"修改过的 MPL 文件须继续以 MPL 公开源码",
+			"未修改的 MPL 文件与自有代码可以一起闭源分发",
+			"保留版权与许可声明,并说明源码获取方式",
+			"包含专利授权条款",
+		},
+		URL:     "https://spdx.org/licenses/MPL-2.0.html",
+		TextURL: "https://raw.githubusercontent.com/spdx/license-list-data/main/text/MPL-2.0.txt",
+	},
+	{
+		ID: "LGPL-3.0-only", Name: "GNU Lesser General Public License v3.0", SPDX: "LGPL-3.0-only", Category: "弱著佐权", Popular: true,
+		Summary: "面向库的弱著佐权:动态链接使用可以闭源,但修改库本身时需要公开库的源码。",
+		Points: []string{
+			"修改库本体后须以 LGPL 公开对应源码",
+			"通过动态链接使用库时,自有代码可以不公开",
+			"必须允许用户替换库版本(提供链接方式或目标文件)",
+			"包含 GPL-3.0 的专利与终止条款",
+		},
+		URL:     "https://spdx.org/licenses/LGPL-3.0-only.html",
+		TextURL: "https://raw.githubusercontent.com/spdx/license-list-data/main/text/LGPL-3.0-only.txt",
+	},
+	{
+		ID: "Unlicense", Name: "The Unlicense", SPDX: "Unlicense", Category: "公共领域", Popular: true,
+		Summary: "把作品贡献到公共领域,任何人可以做任何事,不要求署名。",
+		Points: []string{
+			"放弃著作权与相关权利,允许任何用途",
+			"不要求保留版权声明或署名",
+			"在著作权不可放弃的法域,视为无条件、不可撤销的许可",
+		},
+		URL:     "https://spdx.org/licenses/Unlicense.html",
+		TextURL: "https://raw.githubusercontent.com/spdx/license-list-data/main/text/Unlicense.txt",
+	},
+	{
+		ID: "GPL-2.0-only", Name: "GNU General Public License v2.0", SPDX: "GPL-2.0-only", Category: "强著佐权",
+		Summary: "经典强著佐权协议,仅适用于 2.0 版本本身;分发衍生作品须整体开源。",
+		Points: []string{
+			"分发时提供完整对应源码",
+			"衍生作品整体继续使用 GPL-2.0",
+			"与 GPL-3.0 不完全兼容,混用前需确认",
+		},
+		URL:     "https://spdx.org/licenses/GPL-2.0-only.html",
+		TextURL: "https://raw.githubusercontent.com/spdx/license-list-data/main/text/GPL-2.0-only.txt",
+	},
+	{
+		ID: "BSD-2-Clause", Name: "BSD 2-Clause \"Simplified\" License", SPDX: "BSD-2-Clause", Category: "宽松",
+		Summary: "比 BSD-3-Clause 更简单的宽松协议,只要求保留版权声明与免责声明。",
+		Points: []string{
+			"允许商用、修改与闭源再分发",
+			"保留版权声明、条件列表与免责声明",
+			"没有禁止背书条款",
+		},
+		URL:     "https://spdx.org/licenses/BSD-2-Clause.html",
+		TextURL: "https://raw.githubusercontent.com/spdx/license-list-data/main/text/BSD-2-Clause.txt",
+	},
+	{
+		ID: "ISC", Name: "ISC License", SPDX: "ISC", Category: "宽松",
+		Summary: "与 MIT / BSD-2-Clause 等效的宽松协议,措辞更简短。",
+		Points: []string{
+			"允许商用、修改与闭源再分发",
+			"保留版权声明与本许可声明",
+			"软件按“现状”提供,不承担担保责任",
+		},
+		URL:     "https://spdx.org/licenses/ISC.html",
+		TextURL: "https://raw.githubusercontent.com/spdx/license-list-data/main/text/ISC.txt",
+	},
+	{
+		ID: "EPL-2.0", Name: "Eclipse Public License 2.0", SPDX: "EPL-2.0", Category: "弱著佐权",
+		Summary: "模块级弱著佐权,常用于 Eclipse 生态;修改过的贡献代码需要继续以 EPL 开源。",
+		Points: []string{
+			"修改过的 EPL 代码须继续以 EPL 公开",
+			"可以与其它许可的代码组合分发",
+			"包含专利授权与商业分发允许条款",
+		},
+		URL:     "https://spdx.org/licenses/EPL-2.0.html",
+		TextURL: "https://raw.githubusercontent.com/spdx/license-list-data/main/text/EPL-2.0.txt",
+	},
+	{
+		ID: "BSL-1.0", Name: "Boost Software License 1.0", SPDX: "BSL-1.0", Category: "宽松",
+		Summary: "非常宽松的协议,只要求在分发时保留许可文本;适合头文件库。",
+		Points: []string{
+			"允许商用、修改与闭源再分发",
+			"源码分发保留许可文本;二进制分发在文档中附上许可声明",
+			"不要求署名,也不提供担保",
+		},
+		URL:     "https://spdx.org/licenses/BSL-1.0.html",
+		TextURL: "https://raw.githubusercontent.com/spdx/license-list-data/main/text/BSL-1.0.txt",
+	},
+	{
+		ID: "CC0-1.0", Name: "Creative Commons Zero v1.0 Universal", SPDX: "CC0-1.0", Category: "公共领域",
+		Summary: "放弃著作权的公共领域奉献。OSI 未将其认定为开源许可,但可用于代码与文档。",
+		Points: []string{
+			"尽可能放弃著作权,允许任何用途",
+			"不要求署名",
+			"不包含专利与商标授权,用于软件前需自行评估",
+		},
+		URL:     "https://spdx.org/licenses/CC0-1.0.html",
+		TextURL: "https://raw.githubusercontent.com/spdx/license-list-data/main/text/CC0-1.0.txt",
+	},
+}
+
+// All 返回完整目录(常用在前)。
+func All() []License {
+	out := make([]License, len(catalog))
+	copy(out, catalog)
+	return out
+}
+
+// Groups 把目录拆成设置页用的分组:常用协议 / 其他协议。
+func Groups() []Group {
+	var popular, other []License
+	for _, l := range catalog {
+		if l.Popular {
+			popular = append(popular, l)
+		} else {
+			other = append(other, l)
+		}
+	}
+	return []Group{
+		{Title: "常用协议", Licenses: popular},
+		{Title: "其他协议", Licenses: other},
+	}
+}
+
+// Lookup 按 SPDX 标识查找协议,大小写不敏感(mit → MIT)。
+// 空字符串不算合法协议,调用方应单独处理"未选择"。
+func Lookup(id string) (License, bool) {
+	id = strings.TrimSpace(id)
+	if id == "" {
+		return License{}, false
+	}
+	for _, l := range catalog {
+		if strings.EqualFold(l.ID, id) {
+			return l, true
+		}
+	}
+	return License{}, false
+}
+
+// Normalize 把用户输入归一化为目录里的标准 SPDX 标识。
+// 空输入返回空串(表示未选择);未收录的取值返回 ok=false。
+func Normalize(raw string) (id string, ok bool) {
+	raw = strings.TrimSpace(raw)
+	if raw == "" {
+		return "", true
+	}
+	l, found := Lookup(raw)
+	if !found {
+		return "", false
+	}
+	return l.ID, true
+}
diff --git a/internal/server/admin.go b/internal/server/admin.go
index 73e7d31..b7d75ba 100644
--- a/internal/server/admin.go
+++ b/internal/server/admin.go
@@ -10,6 +10,7 @@ import (
 
 	"gitcat/internal/ai"
 	"gitcat/internal/gitx"
+	"gitcat/internal/license"
 	"gitcat/internal/store"
 )
 
@@ -303,6 +304,8 @@ func (s *Server) handleAdminRepoDetail(w http.ResponseWriter, r *http.Request) {
 	p.Data["Users"] = users
 	p.Data["Pushes"] = pushes
 	p.Data["Branches"] = branches
+	p.Data["LicenseGroups"] = license.Groups()
+	applyLicenseData(p.Data, repo)
 	p.Data["SizeText"] = humanSize(gitx.RepoSize(dir))
 	p.Data["CommitCount"] = gitx.CountCommits(dir, repo.DefaultBranch)
 	p.Data["CloneURL"] = cloneURL(r, repo.Name)
@@ -330,7 +333,14 @@ func (s *Server) handleAdminRepoSave(w http.ResponseWriter, r *http.Request) {
 		http.Redirect(w, r, redirect, http.StatusFound)
 		return
 	}
+	repoLicense, ok := normalizeRepoLicense(r.FormValue("license"))
+	if !ok {
+		setFlash(w, "未知的开源协议,请从列表中选择")
+		http.Redirect(w, r, redirect, http.StatusFound)
+		return
+	}
 	repo.Description = desc
+	repo.License = repoLicense
 	repo.AIEnabled = r.FormValue("ai_enabled") == "on"
 	repo.IsArchived = r.FormValue("is_archived") == "on"
 
diff --git a/internal/server/archive_test.go b/internal/server/archive_test.go
new file mode 100644
index 0000000..e3f1da8
--- /dev/null
+++ b/internal/server/archive_test.go
@@ -0,0 +1,75 @@
+package server
+
+import (
+	"archive/zip"
+	"bytes"
+	"io"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+)
+
+// TestArchiveDownload 确认源码包端点按 ref 输出可解压的 zip,且默认使用
+// 仓库默认分支;非法 ref 不得进入 git 命令行。
+func TestArchiveDownload(t *testing.T) {
+	srv, st, _, _ := newTestServer(t)
+	dir := makeRepo(t, srv, st, "proj", nil)
+	commitFiles(t, dir, "init", map[string]string{"a.txt": "hello", "b.txt": "world"})
+
+	check := func(path string) {
+		t.Helper()
+		r := httptest.NewRequest(http.MethodGet, path, nil)
+		w := httptest.NewRecorder()
+		srv.Handler().ServeHTTP(w, r)
+		if w.Code != http.StatusOK {
+			t.Fatalf("%s 状态码 = %d,期望 200", path, w.Code)
+		}
+		if ct := w.Header().Get("Content-Type"); ct != "application/zip" {
+			t.Errorf("Content-Type = %q,期望 application/zip", ct)
+		}
+		if disp := w.Header().Get("Content-Disposition"); !strings.Contains(disp, "proj-main.zip") {
+			t.Errorf("Content-Disposition = %q,期望包含 proj-main.zip", disp)
+		}
+		zr, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len()))
+		if err != nil {
+			t.Fatalf("响应不是合法 zip: %v", err)
+		}
+		files := map[string]string{}
+		for _, f := range zr.File {
+			rc, err := f.Open()
+			if err != nil {
+				t.Fatalf("打开 %s 失败: %v", f.Name, err)
+			}
+			b, _ := io.ReadAll(rc)
+			_ = rc.Close()
+			files[f.Name] = string(b)
+		}
+		for name, want := range map[string]string{"proj-main/a.txt": "hello", "proj-main/b.txt": "world"} {
+			if files[name] != want {
+				t.Errorf("zip 内 %s = %q,期望 %q", name, files[name], want)
+			}
+		}
+	}
+
+	check("/proj/archive?ref=main")
+	check("/proj/archive") // 缺省 ref 使用默认分支
+
+	// 仓库主页应出现下载入口,并指向当前 ref。
+	r := httptest.NewRequest(http.MethodGet, "/proj", nil)
+	w := httptest.NewRecorder()
+	srv.Handler().ServeHTTP(w, r)
+	if !strings.Contains(w.Body.String(), "Download ZIP") ||
+		!strings.Contains(w.Body.String(), `/proj/archive?ref=main`) {
+		t.Error("项目主页缺少 Download ZIP 入口")
+	}
+
+	for _, ref := range []string{"--upload-pack=evil", "-x", "a..b"} {
+		r := httptest.NewRequest(http.MethodGet, "/proj/archive?ref="+ref, nil)
+		w := httptest.NewRecorder()
+		srv.Handler().ServeHTTP(w, r)
+		if w.Code == http.StatusOK {
+			t.Errorf("非法 ref %q 被放行", ref)
+		}
+	}
+}
diff --git a/internal/server/home.go b/internal/server/home.go
index ac55de5..ca74886 100644
--- a/internal/server/home.go
+++ b/internal/server/home.go
@@ -13,6 +13,9 @@ var reservedRepoNames = map[string]bool{
 	"admin": true, "login": true, "logout": true, "install": true, "new": true,
 	"settings": true, "static": true, "media": true, "favicon.ico": true, "api": true,
 	"avatars": true, "assets": true, "help": true, "about": true, "issues": true,
+	// licenses 是全局协议目录页的路径;若允许项目占用,该项目的所有页面
+	// 都会被字面量路由遮蔽。
+	"licenses": true,
 }
 
 func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/server/license_test.go b/internal/server/license_test.go
new file mode 100644
index 0000000..352d5db
--- /dev/null
+++ b/internal/server/license_test.go
@@ -0,0 +1,181 @@
+package server
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"net/url"
+	"strconv"
+	"strings"
+	"testing"
+)
+
+// getAs 以指定会话(可为空)请求页面。
+func getAs(srv *Server, path, session string) *httptest.ResponseRecorder {
+	r := httptest.NewRequest(http.MethodGet, path, nil)
+	if session != "" {
+		r.AddCookie(&http.Cookie{Name: SessionCookieName, Value: session})
+	}
+	w := httptest.NewRecorder()
+	srv.Handler().ServeHTTP(w, r)
+	return w
+}
+
+// postFormAs 以指定会话提交表单。
+func postFormAs(srv *Server, path, session string, form url.Values) *httptest.ResponseRecorder {
+	r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode()))
+	r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+	r.AddCookie(&http.Cookie{Name: SessionCookieName, Value: session})
+	w := httptest.NewRecorder()
+	srv.Handler().ServeHTTP(w, r)
+	return w
+}
+
+// TestRepoSettingsSavesLicense 覆盖协议设置的完整链路:大小写归一化、
+// 非法值拒绝、以及清空选择。
+func TestRepoSettingsSavesLicense(t *testing.T) {
+	srv, st, _, _ := newTestServer(t)
+	makeRepo(t, srv, st, "licproj", nil)
+
+	sess := sessionCookie(t, login(t, srv, "alice", testPass))
+	csrf := csrfOf(t, srv, "/licproj/settings", sess)
+	save := func(lic string) *httptest.ResponseRecorder {
+		return postFormAs(srv, "/licproj/settings", sess, url.Values{
+			"csrf":        {csrf},
+			"description": {"带协议的项目"},
+			"license":     {lic},
+		})
+	}
+
+	// 大小写不敏感,落库的是标准 SPDX 标识。
+	if w := save("mit"); w.Code != http.StatusFound {
+		t.Fatalf("保存协议返回 %d,应为 302:%s", w.Code, w.Body.String())
+	}
+	repo, err := st.RepoByName("licproj")
+	if err != nil {
+		t.Fatalf("读取仓库失败: %v", err)
+	}
+	if repo.License != "MIT" {
+		t.Fatalf("协议未按 SPDX 标识保存: %q", repo.License)
+	}
+
+	// 未收录的协议必须被拒绝,且不能破坏已有值。
+	if w := save("Totally-Not-A-License"); w.Code != http.StatusBadRequest {
+		t.Errorf("非法协议返回 %d,应为 400", w.Code)
+	}
+	if repo, _ = st.RepoByName("licproj"); repo.License != "MIT" {
+		t.Errorf("非法协议覆盖了原有选择: %q", repo.License)
+	}
+
+	// 空值表示"未选择"。
+	if w := save(""); w.Code != http.StatusFound {
+		t.Fatalf("清空协议返回 %d,应为 302", w.Code)
+	}
+	if repo, _ = st.RepoByName("licproj"); repo.License != "" {
+		t.Errorf("协议未被清空: %q", repo.License)
+	}
+}
+
+// TestRepoLicenseRequiresManage 普通成员不能通过设置页改协议。
+func TestRepoLicenseRequiresManage(t *testing.T) {
+	srv, st, _, _ := newTestServer(t)
+	makeRepo(t, srv, st, "strict", nil)
+
+	bobSess := sessionCookie(t, login(t, srv, "bob", testPass))
+	csrf := csrfOf(t, srv, "/settings", bobSess)
+	w := postFormAs(srv, "/strict/settings", bobSess, url.Values{
+		"csrf":    {csrf},
+		"license": {"MIT"},
+	})
+	if w.Code != http.StatusForbidden {
+		t.Fatalf("非创建者修改设置返回 %d,应为 403", w.Code)
+	}
+	if repo, _ := st.RepoByName("strict"); repo.License != "" {
+		t.Errorf("越权请求竟然修改了协议: %q", repo.License)
+	}
+}
+
+// TestRepoHomeShowsLicense 验证项目主页的协议徽章与仓库内 LICENSE 文件入口。
+func TestRepoHomeShowsLicense(t *testing.T) {
+	srv, st, _, _ := newTestServer(t)
+	dir := makeRepo(t, srv, st, "licensed", nil)
+	commitFiles(t, dir, "init", map[string]string{
+		"LICENSE":   "MIT License\n",
+		"README.md": "# licensed\n",
+	})
+
+	repo, err := st.RepoByName("licensed")
+	if err != nil {
+		t.Fatalf("读取仓库失败: %v", err)
+	}
+	repo.License = "MIT"
+	if err := st.UpdateRepo(repo); err != nil {
+		t.Fatalf("写入协议失败: %v", err)
+	}
+
+	body := getAs(srv, "/licensed", "").Body.String()
+	for _, want := range []string{"/licenses/view/MIT", "MIT License", "/blob/main/LICENSE"} {
+		if !strings.Contains(body, want) {
+			t.Errorf("项目主页缺少 %q", want)
+		}
+	}
+}
+
+// TestLicensePages 覆盖协议目录与详情页,以及未收录 ID 的 404。
+func TestLicensePages(t *testing.T) {
+	srv, _, _, _ := newTestServer(t)
+
+	if w := getAs(srv, "/licenses", ""); w.Code != http.StatusOK ||
+		!strings.Contains(w.Body.String(), "MIT License") {
+		t.Fatalf("协议目录页异常: code=%d", w.Code)
+	}
+	// URL 里的大小写不影响查找,页面展示标准名称。
+	if w := getAs(srv, "/licenses/view/apache-2.0", ""); w.Code != http.StatusOK ||
+		!strings.Contains(w.Body.String(), "Apache License 2.0") {
+		t.Fatalf("协议详情页异常: code=%d", w.Code)
+	}
+	if w := getAs(srv, "/licenses/view/no-such-license", ""); w.Code != http.StatusNotFound {
+		t.Fatalf("未知协议返回 %d,应为 404", w.Code)
+	}
+}
+
+// TestAdminRepoSaveLicense 后台修改协议与项目设置共用同一个字段。
+func TestAdminRepoSaveLicense(t *testing.T) {
+	srv, st, _, _ := newTestServer(t)
+	makeRepo(t, srv, st, "adm", nil)
+	repo, err := st.RepoByName("adm")
+	if err != nil {
+		t.Fatalf("读取仓库失败: %v", err)
+	}
+
+	sess := sessionCookie(t, login(t, srv, "alice", testPass))
+	path := "/admin/repos/" + strconv.FormatInt(repo.ID, 10)
+	csrf := csrfOf(t, srv, path, sess)
+
+	w := postFormAs(srv, path, sess, url.Values{
+		"csrf":        {csrf},
+		"description": {"后台改的"},
+		"license":     {"apache-2.0"},
+	})
+	if w.Code != http.StatusFound {
+		t.Fatalf("后台保存返回 %d:%s", w.Code, w.Body.String())
+	}
+	got, _ := st.RepoByID(repo.ID)
+	if got.License != "Apache-2.0" {
+		t.Errorf("后台保存的协议不正确: %q", got.License)
+	}
+	if got.Description != "后台改的" {
+		t.Errorf("同一次保存里的描述丢了: %q", got.Description)
+	}
+
+	// 非法值:不写库,保留原值。
+	bad := postFormAs(srv, path, sess, url.Values{
+		"csrf":    {csrf},
+		"license": {"nope"},
+	})
+	if bad.Code != http.StatusFound {
+		t.Fatalf("非法协议应回跳并提示,返回 %d", bad.Code)
+	}
+	if got, _ := st.RepoByID(repo.ID); got.License != "Apache-2.0" {
+		t.Errorf("非法协议覆盖了后台的选择: %q", got.License)
+	}
+}
diff --git a/internal/server/licenses.go b/internal/server/licenses.go
new file mode 100644
index 0000000..5c3d025
--- /dev/null
+++ b/internal/server/licenses.go
@@ -0,0 +1,88 @@
+// 开源协议页面:协议目录、协议详情,以及仓库设置里的协议选择。
+//
+// 这里刻意不提供"一键写入 LICENSE 文件"的功能:仓库内容属于维护者,服务端
+// 不应代替用户提交文件。gitcat 只记录选择并在页面上展示,同时提示用户把
+// 官方协议正文放到仓库根目录。
+package server
+
+import (
+	"net/http"
+	"strings"
+
+	"gitcat/internal/gitx"
+	"gitcat/internal/license"
+	"gitcat/internal/store"
+)
+
+// normalizeRepoLicense 校验并归一化表单里的协议值。
+// 空串表示"未选择";未收录的协议会被拒绝,避免数据库里出现无法展示的脏值。
+func normalizeRepoLicense(raw string) (string, bool) {
+	return license.Normalize(raw)
+}
+
+// applyLicenseData 把仓库当前协议放进模板数据:
+// 已收录的协议给出完整元数据,未收录的旧值原样保留以便展示。
+func applyLicenseData(data map[string]any, repo *store.Repo) {
+	if repo == nil || repo.License == "" {
+		return
+	}
+	if lic, ok := license.Lookup(repo.License); ok {
+		data["License"] = lic
+		return
+	}
+	data["LicenseRaw"] = repo.License
+}
+
+// licenseFileNames 是仓库根目录里被视为"协议文件"的文件名(大写比较)。
+// 只做展示提示,不参与任何写入操作。
+var licenseFileNames = []string{
+	"LICENSE", "LICENCE", "COPYING", "COPYRIGHT", "UNLICENSE",
+	"LICENSE.MD", "LICENCE.MD", "COPYING.MD", "LICENSE.TXT", "LICENCE.TXT", "COPYING.TXT",
+}
+
+// licenseFileFromEntries 在仓库根目录条目里找协议文件,优先精确命中的常用
+// 文件名。复用调用方已经读取的 Tree,避免为了提示再跑一次 git。
+func licenseFileFromEntries(entries []gitx.TreeEntry) string {
+	best := ""
+	bestScore := len(licenseFileNames) + 1
+	for _, e := range entries {
+		if e.IsDir() {
+			continue
+		}
+		upper := strings.ToUpper(e.Name)
+		for i, want := range licenseFileNames {
+			if upper != want {
+				continue
+			}
+			// 列表越靠前优先级越高;相同优先级保留 git tree 里的先后顺序。
+			if i < bestScore {
+				best, bestScore = e.Name, i
+			}
+			break
+		}
+	}
+	return best
+}
+
+// handleLicensesList 展示全部可选的协议,附使用项目数。
+func (s *Server) handleLicensesList(w http.ResponseWriter, r *http.Request) {
+	p := s.page(r, "开源协议")
+	p.Active = "licenses"
+	p.Data["Groups"] = license.Groups()
+	p.Data["Usage"] = s.st.LicenseUsage()
+	s.render(w, r, "licenses", p)
+}
+
+// handleLicenseDetail 展示单个协议的说明与使用指引。
+func (s *Server) handleLicenseDetail(w http.ResponseWriter, r *http.Request) {
+	lic, ok := license.Lookup(r.PathValue("id"))
+	if !ok {
+		s.renderError(w, r, http.StatusNotFound, "没有收录这个开源协议")
+		return
+	}
+	p := s.page(r, lic.Name)
+	p.Active = "licenses"
+	p.Data["License"] = lic
+	p.Data["Usage"] = s.st.LicenseUsage()[lic.ID]
+	s.render(w, r, "license", p)
+}
diff --git a/internal/server/repo.go b/internal/server/repo.go
index 2a8f7c1..26603e6 100644
--- a/internal/server/repo.go
+++ b/internal/server/repo.go
@@ -14,6 +14,7 @@ import (
 	"strings"
 
 	"gitcat/internal/gitx"
+	"gitcat/internal/license"
 	"gitcat/internal/store"
 )
 
@@ -142,6 +143,8 @@ func (s *Server) repoCommon(r *http.Request, repo *store.Repo, dir string, ref s
 	data["CanWrite"] = s.canWriteRepo(u, repo)
 	data["CloneURL"] = cloneURL(r, repo.Name)
 	data["CloneHTTP"] = cloneURL(r, repo.Name)
+	// 协议元数据:仓库所有页面都可用(首页"关于"卡片、设置页回显)。
+	applyLicenseData(data, repo)
 
 	branches, _ := gitx.Branches(dir)
 	tags, _ := gitx.Tags(dir)
@@ -230,6 +233,9 @@ func (s *Server) handleRepoHome(w http.ResponseWriter, r *http.Request) {
 	p.Data["Entries"] = list
 	p.Data["Path"] = ""
 	p.Data["Breadcrumbs"] = nil
+	// 仓库根目录若已有 LICENSE / COPYING 文件,首页给出直接入口;
+	// 与设置里选择的协议互相独立,避免"选了协议但仓库其实没有正文"的误解。
+	p.Data["LicenseFile"] = licenseFileFromEntries(entries)
 
 	if readmeName, content, found := gitx.Readme(dir, ref); found {
 		isMarkdown := strings.HasSuffix(strings.ToLower(readmeName), ".md") || strings.HasSuffix(strings.ToLower(readmeName), ".markdown")
@@ -509,6 +515,47 @@ func (s *Server) handleRepoRaw(w http.ResponseWriter, r *http.Request) {
 	}
 }
 
+// handleRepoArchive 把指定 ref 的代码打包成 zip 下载。
+//
+// 与 raw 一样,响应是用户内容:强制 attachment,避免浏览器把 zip 当页面
+// 渲染。打包走 git archive 流式输出,不占内存;私有仓库沿用 loadRepo 的
+// 登录拦截,游客拿不到源码包。
+func (s *Server) handleRepoArchive(w http.ResponseWriter, r *http.Request) {
+	repo, dir, ok := s.loadRepo(w, r)
+	if !ok {
+		return
+	}
+	if !gitx.HasCommits(dir) {
+		s.renderError(w, r, http.StatusNotFound, "仓库还没有任何提交,暂时无法下载")
+		return
+	}
+	ref := strings.TrimSpace(r.URL.Query().Get("ref"))
+	if ref == "" {
+		ref = s.pickRef(dir, repo, "")
+	}
+	if !gitx.ValidRef(ref) {
+		s.renderError(w, r, http.StatusBadRequest, "非法的引用名")
+		return
+	}
+	if _, err := gitx.Resolve(dir, ref); err != nil {
+		s.renderError(w, r, http.StatusNotFound, "找不到引用 "+ref)
+		return
+	}
+
+	// 分支名可能带 "/",放进文件名或 zip 内层目录都会变成额外层级,
+	// 统一替换成 "-"。
+	label := strings.ReplaceAll(ref, "/", "-")
+	filename := repo.Name + "-" + label + ".zip"
+	w.Header().Set("Content-Type", "application/zip")
+	w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+url.PathEscape(filename))
+	w.Header().Set("Cache-Control", "no-store")
+	w.Header().Set("X-Content-Type-Options", "nosniff")
+	if err := gitx.ArchiveZip(r.Context(), dir, ref, repo.Name+"-"+label+"/", w); err != nil {
+		// 响应头已发出,无法再改状态码;只记录并中断传输。
+		fmt.Fprintf(os.Stderr, "打包下载 %s@%s 失败: %v\n", repo.Name, ref, err)
+	}
+}
+
 // looksBinaryName 按扩展名粗判二进制,用于在流式响应里决定内联还是下载。
 func looksBinaryName(ext string) bool {
 	switch ext {
@@ -642,6 +689,8 @@ func (s *Server) handleRepoSettingsPage(w http.ResponseWriter, r *http.Request)
 	p := s.page(r, repo.Name+" · 设置")
 	p.Active = "repo"
 	p.Data = s.repoCommon(r, repo, dir, s.pickRef(dir, repo, ""))
+	// 设置页的协议下拉框:常用协议与其他协议各一组。
+	p.Data["LicenseGroups"] = license.Groups()
 	s.render(w, r, "repo_settings", p)
 }
 
@@ -664,6 +713,12 @@ func (s *Server) handleRepoSettingsSave(w http.ResponseWriter, r *http.Request)
 		s.renderError(w, r, http.StatusBadRequest, "项目描述不能超过 300 个字符")
 		return
 	}
+	// 协议校验放在改名/写库之前:非法值不能留下"名字已改、设置没存"的中间状态。
+	repoLicense, ok := normalizeRepoLicense(r.FormValue("license"))
+	if !ok {
+		s.renderError(w, r, http.StatusBadRequest, "未知的开源协议,请从列表中选择")
+		return
+	}
 	if raw := strings.TrimSpace(r.FormValue("new_name")); raw != "" {
 		newName, err := validateNewRepoName(raw)
 		if err != nil {
@@ -695,6 +750,7 @@ func (s *Server) handleRepoSettingsSave(w http.ResponseWriter, r *http.Request)
 		_ = gitx.SetDefaultBranch(dir, defaultBranch)
 	}
 	repo.Description = desc
+	repo.License = repoLicense
 	repo.AIEnabled = r.FormValue("ai_enabled") == "on"
 	repo.IsArchived = r.FormValue("is_archived") == "on"
 	repo.IsPrivate = r.FormValue("is_private") == "on"
diff --git a/internal/server/server.go b/internal/server/server.go
index 71bc549..c3733e1 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -86,7 +86,7 @@ func New(cfg Config, st *store.Store) (*Server, error) {
 			goldmark.WithExtensions(extension.GFM, extension.Table, extension.Strikethrough, extension.TaskList),
 			goldmark.WithRendererOptions(html.WithHardWraps()),
 		),
-		guests: newGuestLimiter(),
+		guests:   newGuestLimiter(),
 		captchas: captcha.NewStore(captchaTTL),
 	}
 	if err := s.buildTemplates(); err != nil {
@@ -191,6 +191,7 @@ func (s *Server) buildTemplates() error {
 		"repo_home", "repo_commits", "repo_commit", "repo_blob", "repo_branches", "repo_activity", "repo_settings",
 		"repo_releases", "repo_release", "repo_release_new",
 		"issues", "issue_new", "issue",
+		"licenses", "license",
 		"profile",
 		"admin_dashboard", "admin_users", "admin_user", "admin_repos", "admin_repo", "admin_ai", "admin_settings", "admin_activity", "admin_upgrade",
 	}
@@ -285,11 +286,19 @@ func (s *Server) routes() {
 	m.HandleFunc("POST /settings/avatar", s.handleAvatarUpload)
 	m.HandleFunc("POST /settings/password", s.handlePasswordChange)
 
+	// 开源协议目录。详情必须带一级固定前缀:`/licenses/{id}` 会与
+	// `/{repo}/archive` 之类的两段路由互相冲突(两者都能匹配
+	// /licenses/archive,且谁都不更具体),ServeMux 会直接 panic。
+	m.HandleFunc("GET /licenses", s.handleLicensesList)
+	m.HandleFunc("GET /licenses/view/{id}", s.handleLicenseDetail)
+
 	// 项目页面
 	m.HandleFunc("GET /{repo}", s.handleRepoHome)
 	m.HandleFunc("GET /{repo}/tree/{ref}/{path...}", s.handleRepoTree)
 	m.HandleFunc("GET /{repo}/blob/{ref}/{path...}", s.handleRepoBlob)
 	m.HandleFunc("GET /{repo}/raw/{ref}/{path...}", s.handleRepoRaw)
+	// 源码压缩包下载:?ref= 指定分支/标签,缺省用当前默认分支。
+	m.HandleFunc("GET /{repo}/archive", s.handleRepoArchive)
 	m.HandleFunc("GET /{repo}/commits/{ref}", s.handleRepoCommits)
 	m.HandleFunc("GET /{repo}/commit/{sha}", s.handleRepoCommit)
 	m.HandleFunc("GET /{repo}/branches", s.handleRepoBranches)
diff --git a/internal/store/repos.go b/internal/store/repos.go
index 6c27bee..646cbf1 100644
--- a/internal/store/repos.go
+++ b/internal/store/repos.go
@@ -19,8 +19,11 @@ type Repo struct {
 	IsArchived    bool
 	IsPrivate     bool // 私有仓库:仅登录的工作室成员可访问,游客不可见
 	AIEnabled     bool
-	CreatedAt     time.Time
-	UpdatedAt     time.Time
+	// License 是 SPDX 协议标识(如 MIT、Apache-2.0),空串表示未选择。
+	// 这里只存标识,协议正文以仓库根目录的 LICENSE 文件为准。
+	License   string
+	CreatedAt time.Time
+	UpdatedAt time.Time
 }
 
 // RepoCard 是首页 / 后台列表用的仓库条目(附带展示统计)。
@@ -48,7 +51,7 @@ func (s *Store) CreateRepo(name, description string, ownerID int64) (*Repo, erro
 	return s.RepoByID(id)
 }
 
-const repoCols = `id, name, description, owner_id, default_branch, is_archived, is_private, ai_enabled, created_at, updated_at`
+const repoCols = `id, name, description, owner_id, default_branch, is_archived, is_private, ai_enabled, created_at, updated_at, license`
 
 func scanRepo(row interface {
 	Scan(dest ...any) error
@@ -57,7 +60,7 @@ func scanRepo(row interface {
 	var owner sql.NullInt64
 	var archived, private, ai int
 	var created, updated string
-	if err := row.Scan(&r.ID, &r.Name, &r.Description, &owner, &r.DefaultBranch, &archived, &private, &ai, &created, &updated); err != nil {
+	if err := row.Scan(&r.ID, &r.Name, &r.Description, &owner, &r.DefaultBranch, &archived, &private, &ai, &created, &updated, &r.License); err != nil {
 		if errors.Is(err, sql.ErrNoRows) {
 			return nil, ErrNotFound
 		}
@@ -113,7 +116,7 @@ func (s *Store) ListRepos(q string) ([]*RepoCard, error) {
 		var archived, private, ai int
 		var created, updated, lastPush string
 		if err := rows.Scan(&c.ID, &c.Name, &c.Description, &owner, &c.DefaultBranch, &archived, &private, &ai,
-			&created, &updated, &c.OwnerName, &c.PushCount, &lastPush, &c.LastWhatsNew, &c.LastPusher); err != nil {
+			&created, &updated, &c.License, &c.OwnerName, &c.PushCount, &lastPush, &c.LastWhatsNew, &c.LastPusher); err != nil {
 			return nil, err
 		}
 		if owner.Valid {
@@ -144,11 +147,32 @@ func (s *Store) UpdateRepo(r *Repo) error {
 		}
 		return 0
 	}
-	_, err := s.db.Exec(`UPDATE repos SET description = ?, default_branch = ?, is_archived = ?, is_private = ?, ai_enabled = ?, updated_at = ? WHERE id = ?`,
-		r.Description, r.DefaultBranch, b2i(r.IsArchived), b2i(r.IsPrivate), b2i(r.AIEnabled), nowString(), r.ID)
+	_, err := s.db.Exec(`UPDATE repos SET description = ?, default_branch = ?, is_archived = ?, is_private = ?, ai_enabled = ?, license = ?, updated_at = ? WHERE id = ?`,
+		r.Description, r.DefaultBranch, b2i(r.IsArchived), b2i(r.IsPrivate), b2i(r.AIEnabled), r.License, nowString(), r.ID)
 	return err
 }
 
+// LicenseUsage 统计各协议被多少个项目使用(空选择不计入)。
+// 协议详情/目录页据此展示热度,数据量很小,一次 GROUP BY 足够。
+func (s *Store) LicenseUsage() map[string]int {
+	out := map[string]int{}
+	rows, err := s.db.Query(`SELECT license, COUNT(*) FROM repos WHERE license <> '' GROUP BY license`)
+	if err != nil {
+		return out
+	}
+	defer rows.Close()
+	for rows.Next() {
+		var id string
+		var n int
+		if rows.Scan(&id, &n) == nil {
+			out[id] = n
+		}
+	}
+	// 统计只用于展示,读取失败时返回已取到的部分即可。
+	_ = rows.Err()
+	return out
+}
+
 // SetRepoPrivate 单独更新仓库的私有状态。
 func (s *Store) SetRepoPrivate(id int64, private bool) error {
 	v := 0
diff --git a/internal/store/store.go b/internal/store/store.go
index 4b74950..42b2c92 100644
--- a/internal/store/store.go
+++ b/internal/store/store.go
@@ -131,7 +131,7 @@ var schema = []string{
 // 版本 1 = 最原始的 5 张表(无 schema_meta),用于识别旧版数据库。
 
 // SchemaVersion 是当前二进制支持的最新数据库版本。
-const SchemaVersion = 5
+const SchemaVersion = 6
 
 // execer 让迁移既能跑在事务里(*sql.Tx)也能直接跑在连接上(*sql.DB)。
 type execer interface {
@@ -212,6 +212,25 @@ var migrations = []migration{
 			return err
 		},
 	},
+	{
+		version: 6,
+		name:    "仓库开源协议",
+		run: func(e execer) error {
+			// license 只存 SPDX 标识(如 MIT、Apache-2.0),空串表示未选择。
+			// 协议正文不落库:它属于仓库内容,应由维护者以 LICENSE 文件提交。
+			rows, err := e.Query(`SELECT 1 FROM pragma_table_info('repos') WHERE name = 'license'`)
+			if err != nil {
+				return err
+			}
+			exists := rows.Next()
+			_ = rows.Close()
+			if exists {
+				return nil
+			}
+			_, err = e.Exec(`ALTER TABLE repos ADD COLUMN license TEXT NOT NULL DEFAULT ''`)
+			return err
+		},
+	},
 }
 
 const schemaMetaTable = `CREATE TABLE IF NOT EXISTS schema_meta (
diff --git a/internal/store/store_test.go b/internal/store/store_test.go
index 55f521f..dd0fd78 100644
--- a/internal/store/store_test.go
+++ b/internal/store/store_test.go
@@ -219,4 +219,105 @@ func TestMigrationAddsPushRefChanges(t *testing.T) {
 	}
 }
 
+// TestMigrationAddsRepoLicense 模拟 v5 库升级:repos 表缺少 license 列时,
+// v6 迁移必须补上,且新列能正常读写。
+func TestMigrationAddsRepoLicense(t *testing.T) {
+	path := filepath.Join(t.TempDir(), "gitcat.db")
+	st, err := Open(path)
+	if err != nil {
+		t.Fatalf("打开新库失败: %v", err)
+	}
+	u, err := st.CreateUser("alice", "Alice", "", "hash", true)
+	if err != nil {
+		t.Fatalf("建用户失败: %v", err)
+	}
+	repo, err := st.CreateRepo("demo", "", u.ID)
+	if err != nil {
+		t.Fatalf("建仓库失败: %v", err)
+	}
+	// 新库的 license 列可写可读。
+	repo.License = "Apache-2.0"
+	if err := st.UpdateRepo(repo); err != nil {
+		t.Fatalf("写入协议失败: %v", err)
+	}
+	if got, _ := st.RepoByID(repo.ID); got.License != "Apache-2.0" {
+		t.Fatalf("协议未持久化: %q", got.License)
+	}
+	// 列表查询也要带上该列(scan 顺序错位会让整页报错)。
+	cards, err := st.ListRepos("")
+	if err != nil {
+		t.Fatalf("列表查询失败: %v", err)
+	}
+	if len(cards) != 1 || cards[0].License != "Apache-2.0" {
+		t.Fatalf("列表里的协议不正确: %+v", cards)
+	}
+
+	// 退回 v5:删列 + 版本号回退。
+	if _, err := st.db.Exec(`ALTER TABLE repos DROP COLUMN license`); err != nil {
+		_ = st.Close()
+		t.Skipf("当前 SQLite 不支持 DROP COLUMN,跳过此用例: %v", err)
+	}
+	if _, err := st.db.Exec(`UPDATE schema_meta SET value='5' WHERE key='schema_version'`); err != nil {
+		t.Fatalf("回退版本号失败: %v", err)
+	}
+	_ = st.Close()
+
+	st2, err := Open(path)
+	if err != nil {
+		t.Fatalf("升级 v5 库失败: %v", err)
+	}
+	defer st2.Close()
+	if got := st2.SchemaVersion(); got != SchemaVersion {
+		t.Fatalf("升级后版本 = %d, 期望 %d", got, SchemaVersion)
+	}
+	upgraded, err := st2.RepoByName("demo")
+	if err != nil {
+		t.Fatalf("升级后读取仓库失败: %v", err)
+	}
+	if upgraded.License != "" {
+		t.Errorf("旧仓库的协议应为空,得到 %q", upgraded.License)
+	}
+	upgraded.License = "MIT"
+	if err := st2.UpdateRepo(upgraded); err != nil {
+		t.Fatalf("升级后写入协议失败: %v", err)
+	}
+	if got, _ := st2.RepoByID(repo.ID); got.License != "MIT" {
+		t.Errorf("升级后协议未生效: %q", got.License)
+	}
+}
+
+// TestLicenseUsage 验证按协议统计项目数,空选择不计入。
+func TestLicenseUsage(t *testing.T) {
+	st, err := Open(filepath.Join(t.TempDir(), "gitcat.db"))
+	if err != nil {
+		t.Fatalf("打开库失败: %v", err)
+	}
+	defer st.Close()
+	u, err := st.CreateUser("owner", "Owner", "", "x", false)
+	if err != nil {
+		t.Fatalf("建用户失败: %v", err)
+	}
+	for _, item := range []struct{ name, lic string }{
+		{"a", "MIT"}, {"b", "MIT"}, {"c", "Apache-2.0"}, {"d", ""},
+	} {
+		r, err := st.CreateRepo(item.name, "", u.ID)
+		if err != nil {
+			t.Fatalf("建仓库 %s 失败: %v", item.name, err)
+		}
+		if item.lic != "" {
+			r.License = item.lic
+			if err := st.UpdateRepo(r); err != nil {
+				t.Fatalf("写入协议失败: %v", err)
+			}
+		}
+	}
+	usage := st.LicenseUsage()
+	if usage["MIT"] != 2 || usage["Apache-2.0"] != 1 {
+		t.Fatalf("协议统计不正确: %+v", usage)
+	}
+	if _, ok := usage[""]; ok {
+		t.Error("未选择协议的仓库不应出现在统计里")
+	}
+}
+
 var _ = os.Stat // 保持 os 导入(Windows 下 TempDir 清理相关)
diff --git a/webroot/static/style.css b/webroot/static/style.css
index 2dc617b..41dc35e 100644
--- a/webroot/static/style.css
+++ b/webroot/static/style.css
@@ -455,7 +455,9 @@ a.btn.disabled { pointer-events: none; opacity: .45; cursor: not-allowed; }
 .repo-title { display: flex; gap: 14px; align-items: center; min-width: 0; }
 .repo-title h1 { margin: 0; font-size: clamp(1.3rem, 1.1rem + 1vw, 1.7rem); display: flex; align-items: center; gap: 10px; flex-wrap: wrap; word-break: break-all; }
 .repo-sub { margin: 6px 0 0; color: var(--ink-2); font-size: .94rem; max-width: 70ch; }
-.repo-actions { display: flex; gap: 10px; align-items: center; min-width: 0; }
+.repo-actions { display: flex; gap: 10px; align-items: center; justify-content: flex-end; flex-wrap: wrap; min-width: 0; }
+/* 下载源码包:与 clone 框同一行,窄屏时自动换到下一行 */
+.dl-zip { flex: none; }
 
 .clonebox {
   display: flex; align-items: center; gap: 8px; padding: 5px 6px 5px 12px; background: #fff;
@@ -1096,7 +1098,49 @@ a.release-name:hover { color: var(--green-700); }
 .ai-send:hover:not(:disabled) { transform: translateY(-1px); }
 .ai-send:disabled { opacity: .45; cursor: not-allowed; }
 
+/* ---------------------------------------------------------- 开源协议 */
+
+.license-line {
+  display: flex; align-items: center; gap: 10px;
+  margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--line-2);
+}
+.license-line > div { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
+.license-line a { font-weight: 650; }
+.license-badge {
+  flex: none; display: inline-block; padding: 3px 10px; border-radius: 8px;
+  background: #eef3f6; color: var(--ink-2); font-size: .78rem; font-weight: 700;
+  border: 1px solid var(--line); letter-spacing: .01em;
+}
+a.license-badge:hover { border-color: var(--mint-300); color: var(--green-700); }
+.license-file { margin: 8px 0 0; word-break: break-all; }
+
+.license-section { margin: 0 0 26px; }
+.license-section h2 { font-size: 1rem; color: var(--ink-2); margin-bottom: 12px; }
+.license-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 14px; }
+.license-card { padding: 16px; display: flex; flex-direction: column; gap: 8px; }
+.license-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; }
+.license-name { font-weight: 700; line-height: 1.35; }
+.license-sum { font-size: .86rem; color: var(--ink-2); line-height: 1.6; margin: 0; }
+.license-foot {
+  margin-top: auto; padding-top: 4px; display: flex; align-items: center;
+  gap: 10px; flex-wrap: wrap; font-size: .8rem; color: var(--ink-3);
+}
+.license-foot .quiet { margin-left: auto; }
+.license-spdx {
+  display: inline-block; padding: 1px 7px; border-radius: 6px;
+  background: #eef3f6; color: var(--ink-2); font-size: .76rem;
+}
+.license-note { margin-top: 6px; line-height: 1.7; }
+.license-crumb { margin: 0 0 6px; font-size: .82rem; color: var(--ink-3); }
+.license-crumb .sep { margin: 0 6px; }
+.license-meta { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
+.license-points { margin: 0; padding-left: 1.2em; display: flex; flex-direction: column; gap: 9px; font-size: .92rem; color: var(--ink-2); }
+.license-points li::marker { color: var(--green); }
+.license-steps { margin: 0; padding-left: 1.3em; display: flex; flex-direction: column; gap: 9px; font-size: .92rem; color: var(--ink-2); }
+.license-steps code { font-size: .84rem; }
+
 @media (max-width: 640px) {
+  .license-cards { grid-template-columns: 1fr; }
   .ai-assist { right: 14px; bottom: 14px; }
   .ai-fab { width: 54px; height: 54px; }
   .ai-panel { right: 10px; left: 10px; bottom: 10px; width: auto; height: min(78vh, 560px); }
diff --git a/webroot/templates/admin_repo.html b/webroot/templates/admin_repo.html
index 9a54575..c9e5b35 100644
--- a/webroot/templates/admin_repo.html
+++ b/webroot/templates/admin_repo.html
@@ -28,6 +28,19 @@
             </select>
           </label>
         </div>
+        <label class="field">
+          <span>开源协议</span>
+          <select name="license">
+            <option value="">未选择 / 不声明</option>
+            {{range .Data.LicenseGroups}}
+            <optgroup label="{{.Title}}">
+              {{range .Licenses}}<option value="{{.ID}}" {{if eq .ID $r.License}}selected{{end}}>{{.Name}}({{.SPDX}})</option>{{end}}
+            </optgroup>
+            {{end}}
+            {{if .Data.LicenseRaw}}<option value="{{$r.License}}" selected>{{$r.License}}(未收录,需重新选择)</option>{{end}}
+          </select>
+          <em class="field-hint">与项目设置里的选择是同一个字段,保存后项目主页会展示协议徽章。</em>
+        </label>
         <label class="check"><input type="checkbox" name="ai_enabled" {{if $r.AIEnabled}}checked{{end}}><span>推送后自动生成「What's New」</span></label>
         <label class="check"><input type="checkbox" name="is_archived" {{if $r.IsArchived}}checked{{end}}><span>归档项目(拒绝推送,访客可浏览)</span></label>
         <label class="check"><input type="checkbox" name="owner_none"><span>清除归属(变为工作室公共项目)</span></label>
diff --git a/webroot/templates/license.html b/webroot/templates/license.html
new file mode 100644
index 0000000..b85d20d
--- /dev/null
+++ b/webroot/templates/license.html
@@ -0,0 +1,54 @@
+{{define "content"}}
+{{$lic := .Data.License}}
+<div class="pagehead license-pagehead">
+  <p class="license-crumb"><a class="quiet" href="/licenses">开源协议</a><span class="sep">/</span><span>{{$lic.SPDX}}</span></p>
+  <h1>{{$lic.Name}}</h1>
+  <p class="muted">{{$lic.Summary}}</p>
+  <div class="license-meta">
+    <span class="tag tag-plain">{{$lic.Category}}</span>
+    <code class="license-spdx">{{$lic.SPDX}}</code>
+    {{with .Data.Usage}}<span class="muted small">{{.}} 个项目使用</span>{{end}}
+    <a class="quiet" href="{{$lic.URL}}" target="_blank" rel="noopener noreferrer">SPDX 官方条目 ↗</a>
+  </div>
+</div>
+
+<div class="split">
+  <div class="col-main">
+    <div class="card">
+      <h3>权利与义务</h3>
+      <ul class="license-points">
+        {{range $lic.Points}}<li>{{.}}</li>{{end}}
+      </ul>
+      <p class="field-hint">要点摘要仅帮助选型,不构成法律意见;实际约束以协议正文为准。</p>
+    </div>
+
+    <div class="card">
+      <h3>在项目中使用</h3>
+      <ol class="license-steps">
+        <li>进入项目的 <strong>设置 → 开源协议</strong>,选择「{{$lic.Name}}」并保存。</li>
+        <li>把协议正文保存为仓库根目录的 <code>LICENSE</code>(或 <code>LICENSE.md</code>)并提交。gitcat 不会代替你写入仓库。</li>
+        <li>项目主页的「关于」卡片会显示协议徽章,并链接到仓库里的协议文件。</li>
+      </ol>
+      <p class="field-hint">可以从 SPDX 获取正文:</p>
+      <pre class="code">curl -o LICENSE {{$lic.TextURL}}</pre>
+      <p class="field-hint">若项目需要署名,记得在协议正文中补上版权年份与著作权人。</p>
+    </div>
+  </div>
+
+  <aside class="col-side">
+    <div class="card about">
+      <h3>协议信息</h3>
+      <ul class="kv">
+        <li><span>SPDX</span><code class="csha">{{$lic.SPDX}}</code></li>
+        <li><span>分类</span><strong>{{$lic.Category}}</strong></li>
+        <li><span>官方说明</span><a class="quiet" href="{{$lic.URL}}" target="_blank" rel="noopener noreferrer">spdx.org ↗</a></li>
+      </ul>
+    </div>
+    <div class="card">
+      <h3>拿不准选哪个?</h3>
+      <p class="muted small">希望别人能自由使用(包括闭源商用),优先考虑 MIT 或 Apache-2.0;希望衍生作品保持开源,选 GPL-3.0;库项目可考虑 LGPL-3.0 或 MPL-2.0。</p>
+      <a class="quiet" href="/licenses">查看全部协议 →</a>
+    </div>
+  </aside>
+</div>
+{{end}}
diff --git a/webroot/templates/licenses.html b/webroot/templates/licenses.html
new file mode 100644
index 0000000..47d93fc
--- /dev/null
+++ b/webroot/templates/licenses.html
@@ -0,0 +1,30 @@
+{{define "content"}}
+<div class="pagehead">
+  <h1>开源协议</h1>
+  <p class="muted">为项目选择协议后,徽章会展示在项目主页。这里只做记录与说明,不会自动改写仓库内容——真正生效的是仓库根目录的 <code>LICENSE</code> 文件。</p>
+</div>
+
+{{range .Data.Groups}}
+<section class="license-section">
+  <h2>{{.Title}}</h2>
+  <div class="license-cards">
+    {{range .Licenses}}
+    <article class="card license-card">
+      <div class="license-head">
+        <a class="license-name" href="/licenses/view/{{.ID}}">{{.Name}}</a>
+        <span class="tag tag-plain">{{.Category}}</span>
+      </div>
+      <p class="license-sum">{{.Summary}}</p>
+      <div class="license-foot">
+        <code class="license-spdx">{{.SPDX}}</code>
+        {{with index $.Data.Usage .ID}}<span class="muted small">{{.}} 个项目使用</span>{{end}}
+        <a class="quiet" href="/licenses/view/{{.ID}}">详情 →</a>
+      </div>
+    </article>
+    {{end}}
+  </div>
+</section>
+{{end}}
+
+<p class="license-note muted small">以上为常见协议的要点摘要,不构成法律意见。完整条款以协议正文为准,混合使用多种协议前建议咨询专业人士。</p>
+{{end}}
diff --git a/webroot/templates/repo_home.html b/webroot/templates/repo_home.html
index 6a213fe..d5ea338 100644
--- a/webroot/templates/repo_home.html
+++ b/webroot/templates/repo_home.html
@@ -16,6 +16,15 @@
       <input type="text" readonly size="{{len .Data.CloneURL}}" value="{{.Data.CloneURL}}" aria-label="仓库地址">
       <button class="btn btn-mini" type="button" data-copy="{{.Data.CloneURL}}">复制</button>
     </div>
+    {{if not .Data.IsEmpty}}
+    <a class="btn btn-mini dl-zip" href="/{{$repo.Name}}/archive?ref={{.Data.Ref}}" title="下载 {{.Data.Ref}} 的完整代码压缩包">
+      <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+        <path d="M6 3.5h8l4 4v13H6z"/><path d="M14 3.5v4h4"/>
+        <path d="M12 11.5v4.5"/><path d="m9.8 14 2.2 2.2 2.2-2.2"/>
+      </svg>
+      Download ZIP
+    </a>
+    {{end}}
   </div>
 </header>
 
@@ -97,6 +106,27 @@ git push -u origin main</pre>
     <div class="card about">
       <h3>关于</h3>
       <p>{{if $repo.Description}}{{$repo.Description}}{{else}}<span class="muted">暂无描述</span>{{end}}</p>
+      {{with .Data.License}}
+      <div class="license-line">
+        <a class="license-badge" href="/licenses/view/{{.ID}}" title="{{.Summary}}">{{.SPDX}}</a>
+        <div>
+          <a href="/licenses/view/{{.ID}}">{{.Name}}</a>
+          <span class="muted small">{{.Category}}</span>
+        </div>
+      </div>
+      {{else}}
+      {{with .Data.LicenseRaw}}
+      <div class="license-line">
+        <span class="license-badge">{{.}}</span>
+        <div><span>{{.}}</span><span class="muted small">未收录的协议</span></div>
+      </div>
+      {{end}}
+      {{end}}
+      {{if .Data.LicenseFile}}
+      <p class="license-file muted small">协议文件:<a href="/{{$repo.Name}}/blob/{{.Data.Ref}}/{{.Data.LicenseFile}}">{{.Data.LicenseFile}}</a></p>
+      {{else if not .Data.IsEmpty}}
+      <p class="license-file muted small">仓库根目录还没有 LICENSE 文件{{if .Data.CanManage}} · <a class="quiet" href="/{{$repo.Name}}/settings">去选择协议</a>{{end}}</p>
+      {{end}}
       <div class="stat-grid">
         <div><strong>{{num .Data.CommitCount}}</strong><span>提交</span></div>
         <div><strong>{{num .Data.BranchCount}}</strong><span>分支</span></div>
diff --git a/webroot/templates/repo_settings.html b/webroot/templates/repo_settings.html
index 8075e7f..3edaf9f 100644
--- a/webroot/templates/repo_settings.html
+++ b/webroot/templates/repo_settings.html
@@ -32,6 +32,19 @@
           </select>
           <em class="field-hint">克隆与项目主页默认展示这个分支。</em>
         </label>
+        <label class="field">
+          <span>开源协议</span>
+          <select name="license">
+            <option value="">未选择 / 不声明</option>
+            {{range .Data.LicenseGroups}}
+            <optgroup label="{{.Title}}">
+              {{range .Licenses}}<option value="{{.ID}}" {{if eq .ID $repo.License}}selected{{end}}>{{.Name}}({{.SPDX}})</option>{{end}}
+            </optgroup>
+            {{end}}
+            {{if .Data.LicenseRaw}}<option value="{{$repo.License}}" selected>{{$repo.License}}(未收录,需重新选择)</option>{{end}}
+          </select>
+          <em class="field-hint">只记录在项目页展示,不会改写仓库内容。协议全文需自行以 <code>LICENSE</code> 文件提交到仓库根目录。{{if .Data.LicenseRaw}}当前值不在收录列表中,保存前请重新选择。{{end}}<a href="/licenses">了解常见协议 →</a></em>
+        </label>
         <label class="check">
           <input type="checkbox" name="is_private" {{if $repo.IsPrivate}}checked{{end}}>
           <span>私有仓库<em>仅工作室成员(登录用户)可以浏览和克隆,游客无法访问项目页面、代码与发行版</em></span>