curseforge-mcp 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ recursive-include tests *.py
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.4
2
+ Name: curseforge-mcp
3
+ Version: 1.0.0
4
+ Summary: Unofficial local stdio MCP server for the CurseForge Core API
5
+ Requires-Python: >=3.11
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: mcp<2,>=1.30
8
+ Requires-Dist: httpx<1,>=0.27
9
+ Requires-Dist: pydantic<3,>=2.7
10
+ Provides-Extra: test
11
+ Requires-Dist: pytest<10,>=8; extra == "test"
12
+
13
+ # CurseForge MCP
14
+
15
+ <div align="center">
16
+
17
+ [![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-blue.svg)](https://www.python.org/) [![MCP 1.x](https://img.shields.io/badge/MCP-1.x-green.svg)](https://modelcontextprotocol.io/)
18
+
19
+ **按游戏版本和加载器查找 Mod,查看每个文件的前置并下载。**
20
+
21
+ </div>
22
+
23
+ ---
24
+
25
+ ## ✨ 项目简介
26
+
27
+ 这个非官方本地 stdio 服务把 CurseForge 的游戏目录、项目资料和版本文件接入 MCP 客户端。一个 Mod 的不同文件可以有不同的前置,因此选定游戏版本和加载器后,再按 `file_id` 查询依赖。
28
+
29
+ ## ⚡ 快速开始
30
+
31
+ ### 前置条件
32
+
33
+ - Python 3.11 或更高版本,以及 [uv](https://docs.astral.sh/uv/)。
34
+ - 一个获批的 CurseForge Core API Key,可从 [CurseForge for Studios](https://console.curseforge.com/) 申请。
35
+
36
+ ### 安装与更新
37
+
38
+ 在 `curseforge-mcp` 仓库根目录执行:
39
+
40
+ ```sh
41
+ uv sync --python 3.11
42
+ ```
43
+
44
+ 更新仓库源码后,重新执行上面的命令并重启客户端中的服务。若使用已有的 Python 虚拟环境,也可以用 `python -m pip install --upgrade .` 安装或更新,启动命令为 `curseforge-mcp`。
45
+
46
+ ### 配置客户端
47
+
48
+ 在仓库根目录创建 `.env`。已有配置可直接复用。将密钥放在单引号内,以保留可能出现的 `$` 等字符。
49
+
50
+ ```dotenv
51
+ CURSEFORGE_API_KEY='替换为你的 Core API Key'
52
+ # 可选;默认目录为 ~/Downloads/CurseForge
53
+ # CURSEFORGE_DOWNLOAD_DIR=E:/Downloads/CurseForge
54
+ ```
55
+
56
+ 客户端可以在没有 Key 时列出工具;读取站点数据需要 Key。
57
+
58
+ 将以下条目加入使用 `mcpServers` 格式的客户端,把 `--directory` 后的示例路径替换为本仓库的绝对路径。使用 VS Code 的 `.vscode/mcp.json` 时,顶层键使用 `servers`。
59
+
60
+ ```json
61
+ {
62
+ "mcpServers": {
63
+ "curseforge-mcp": {
64
+ "type": "stdio",
65
+ "command": "uv",
66
+ "args": ["--directory", "E:/GitHub/mcp/curseforge-mcp", "run", "--no-sync", "--env-file", ".env", "curseforge-mcp"]
67
+ }
68
+ }
69
+ }
70
+ ```
71
+
72
+ ### 第一次调用
73
+
74
+ 让客户端执行 `search_mods(game_id=432, slug="sodium")` 查找 Minecraft 的 Sodium。将结果中的 `id` 传给 `list_mod_files`,选择合适的文件,再用 `get_file_dependencies(file_id=…, required_only=true)` 查看必需前置。
75
+
76
+ ## 🧰 工具列表
77
+
78
+ | 工具 | 主要参数 | 用途 |
79
+ | ----------------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- |
80
+ | `list_games` | `name`、`slug`、`index`、`page_size` 可选 | 分页列游戏。名称匹配子串,slug 精确匹配,两者都忽略大小写。 |
81
+ | `get_game` | `game_id` | 取得游戏详情及图片。 |
82
+ | `list_categories` | `game_id`;可选 `class_id`、`classes_only` | 取得指定游戏的分类或大类 ID。 |
83
+ | `get_game_versions` | `game_id` | 取得站点公布的游戏版本。 |
84
+ | `search_mods` | `game_id`;可选 `keyword`、`slug`、`category_id`、`class_id` 等 | 按关键词、分类、版本、加载器筛选。使用 `mod_loader_type` 时同时指定 `game_version`;支持排序与分页。 |
85
+ | `get_mod` | `mod_id` | 返回完整项目资料,包括作者、主页、封面和截图,并补充 `descriptionHtml`;正文请求失败时返回 `descriptionError`。 |
86
+ | `get_mod_description` | `mod_id` | 单独读取项目的 HTML 介绍。 |
87
+ | `list_mod_files` | `mod_id`;可选 `game_version`、`mod_loader_type`、`game_version_type_id` | 按兼容条件分页列出文件及已有的哈希、大小和下载地址。 |
88
+ | `get_mod_file` | `file_id`;可选 `mod_id` | 获取指定文件的原始元数据。 |
89
+ | `get_file_dependencies` | `file_id`;可选 `mod_id`、`required_only` | 保留原始依赖关系。`required_only=true` 只返回必需依赖(`relationType=3`)。 |
90
+ | `get_file_changelog` | `file_id`、`mod_id` | 取得所选文件的 HTML 更新日志。 |
91
+ | `get_file_download_url` | `file_id`、`mod_id` | 查询官方为此文件签发的下载地址。 |
92
+ | `download_file` | `file_id`;可选 `mod_id` | 下载选定文件到本地,返回绝对路径、字节数及已验证的哈希。 |
93
+
94
+ **分页。** `index` 是从 0 开始的上游偏移量,`page_size` 最大为 50,两者之和最多为 10,000。`list_games` 在每个上游页面内筛选,即使本页没有匹配项,也应按返回的 `nextIndex`、`nextPageSize` 继续。
95
+
96
+ **依赖关系。** `relationType` 的 1–6 依次表示内嵌库、可选依赖、必需依赖、工具、不兼容和包含内容。关系指向目标 Mod,具体兼容文件须从该项目的文件列表中选择。
97
+
98
+ **下载权限与校验。** 工具使用官方 `/download-url`。若站点拒绝第三方下载,可从 `get_mod` 返回的 `data.links.websiteUrl` 打开项目文件页。仅向官方 API 和 `edge.forgecdn.net` 发送密钥;其他允许的 CDN 跳转不携带密钥。下载器核对可用的大小、SHA-1 和 MD5,成功后保存文件,遇到同名文件时保留原件。
99
+
100
+ ## 测试
101
+
102
+ ```sh
103
+ uv run --extra test pytest -q
104
+ uv run --env-file .env python tests/live_smoke.py
105
+ ```
106
+
107
+ 第一条使用模拟 API 和 CDN。第二条使用当前 Key 读取实站资料;如需验证真实下载,追加 `--download --download-dir ./live-downloads`。
108
+
109
+ ## 构建与发布到 PyPI
110
+
111
+ 本地可运行 `uv build`,在 `dist/` 检查 wheel 和源码包。
112
+
113
+ 在 PyPI 为 `curseforge-mcp` 配置 GitHub Actions Trusted Publisher:仓库为 `GlossMod/curseforge-mcp`(Owner:`GlossMod`,Repository:`curseforge-mcp`),Workflow:`publish.yml`,Environment:`pypi`。
114
+
115
+ 在 GitHub 发布带版本标签的 Release(例如 `v0.1.1`)后,`.github/workflows/publish.yml` 会使用标签版本构建并检查 wheel 和源码包,通过后自动发布到 PyPI。版本只在 CI 中替换,不会回写仓库。
116
+
117
+ 参考:[CurseForge REST API](https://docs.curseforge.com/rest-api/) · [CDN 下载鉴权](https://blog.curseforge.com/introducing-api-key-authentication-for-curseforge-file-downloads/)
@@ -0,0 +1,105 @@
1
+ # CurseForge MCP
2
+
3
+ <div align="center">
4
+
5
+ [![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-blue.svg)](https://www.python.org/) [![MCP 1.x](https://img.shields.io/badge/MCP-1.x-green.svg)](https://modelcontextprotocol.io/)
6
+
7
+ **按游戏版本和加载器查找 Mod,查看每个文件的前置并下载。**
8
+
9
+ </div>
10
+
11
+ ---
12
+
13
+ ## ✨ 项目简介
14
+
15
+ 这个非官方本地 stdio 服务把 CurseForge 的游戏目录、项目资料和版本文件接入 MCP 客户端。一个 Mod 的不同文件可以有不同的前置,因此选定游戏版本和加载器后,再按 `file_id` 查询依赖。
16
+
17
+ ## ⚡ 快速开始
18
+
19
+ ### 前置条件
20
+
21
+ - Python 3.11 或更高版本,以及 [uv](https://docs.astral.sh/uv/)。
22
+ - 一个获批的 CurseForge Core API Key,可从 [CurseForge for Studios](https://console.curseforge.com/) 申请。
23
+
24
+ ### 安装与更新
25
+
26
+ 在 `curseforge-mcp` 仓库根目录执行:
27
+
28
+ ```sh
29
+ uv sync --python 3.11
30
+ ```
31
+
32
+ 更新仓库源码后,重新执行上面的命令并重启客户端中的服务。若使用已有的 Python 虚拟环境,也可以用 `python -m pip install --upgrade .` 安装或更新,启动命令为 `curseforge-mcp`。
33
+
34
+ ### 配置客户端
35
+
36
+ 在仓库根目录创建 `.env`。已有配置可直接复用。将密钥放在单引号内,以保留可能出现的 `$` 等字符。
37
+
38
+ ```dotenv
39
+ CURSEFORGE_API_KEY='替换为你的 Core API Key'
40
+ # 可选;默认目录为 ~/Downloads/CurseForge
41
+ # CURSEFORGE_DOWNLOAD_DIR=E:/Downloads/CurseForge
42
+ ```
43
+
44
+ 客户端可以在没有 Key 时列出工具;读取站点数据需要 Key。
45
+
46
+ 将以下条目加入使用 `mcpServers` 格式的客户端,把 `--directory` 后的示例路径替换为本仓库的绝对路径。使用 VS Code 的 `.vscode/mcp.json` 时,顶层键使用 `servers`。
47
+
48
+ ```json
49
+ {
50
+ "mcpServers": {
51
+ "curseforge-mcp": {
52
+ "type": "stdio",
53
+ "command": "uv",
54
+ "args": ["--directory", "E:/GitHub/mcp/curseforge-mcp", "run", "--no-sync", "--env-file", ".env", "curseforge-mcp"]
55
+ }
56
+ }
57
+ }
58
+ ```
59
+
60
+ ### 第一次调用
61
+
62
+ 让客户端执行 `search_mods(game_id=432, slug="sodium")` 查找 Minecraft 的 Sodium。将结果中的 `id` 传给 `list_mod_files`,选择合适的文件,再用 `get_file_dependencies(file_id=…, required_only=true)` 查看必需前置。
63
+
64
+ ## 🧰 工具列表
65
+
66
+ | 工具 | 主要参数 | 用途 |
67
+ | ----------------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- |
68
+ | `list_games` | `name`、`slug`、`index`、`page_size` 可选 | 分页列游戏。名称匹配子串,slug 精确匹配,两者都忽略大小写。 |
69
+ | `get_game` | `game_id` | 取得游戏详情及图片。 |
70
+ | `list_categories` | `game_id`;可选 `class_id`、`classes_only` | 取得指定游戏的分类或大类 ID。 |
71
+ | `get_game_versions` | `game_id` | 取得站点公布的游戏版本。 |
72
+ | `search_mods` | `game_id`;可选 `keyword`、`slug`、`category_id`、`class_id` 等 | 按关键词、分类、版本、加载器筛选。使用 `mod_loader_type` 时同时指定 `game_version`;支持排序与分页。 |
73
+ | `get_mod` | `mod_id` | 返回完整项目资料,包括作者、主页、封面和截图,并补充 `descriptionHtml`;正文请求失败时返回 `descriptionError`。 |
74
+ | `get_mod_description` | `mod_id` | 单独读取项目的 HTML 介绍。 |
75
+ | `list_mod_files` | `mod_id`;可选 `game_version`、`mod_loader_type`、`game_version_type_id` | 按兼容条件分页列出文件及已有的哈希、大小和下载地址。 |
76
+ | `get_mod_file` | `file_id`;可选 `mod_id` | 获取指定文件的原始元数据。 |
77
+ | `get_file_dependencies` | `file_id`;可选 `mod_id`、`required_only` | 保留原始依赖关系。`required_only=true` 只返回必需依赖(`relationType=3`)。 |
78
+ | `get_file_changelog` | `file_id`、`mod_id` | 取得所选文件的 HTML 更新日志。 |
79
+ | `get_file_download_url` | `file_id`、`mod_id` | 查询官方为此文件签发的下载地址。 |
80
+ | `download_file` | `file_id`;可选 `mod_id` | 下载选定文件到本地,返回绝对路径、字节数及已验证的哈希。 |
81
+
82
+ **分页。** `index` 是从 0 开始的上游偏移量,`page_size` 最大为 50,两者之和最多为 10,000。`list_games` 在每个上游页面内筛选,即使本页没有匹配项,也应按返回的 `nextIndex`、`nextPageSize` 继续。
83
+
84
+ **依赖关系。** `relationType` 的 1–6 依次表示内嵌库、可选依赖、必需依赖、工具、不兼容和包含内容。关系指向目标 Mod,具体兼容文件须从该项目的文件列表中选择。
85
+
86
+ **下载权限与校验。** 工具使用官方 `/download-url`。若站点拒绝第三方下载,可从 `get_mod` 返回的 `data.links.websiteUrl` 打开项目文件页。仅向官方 API 和 `edge.forgecdn.net` 发送密钥;其他允许的 CDN 跳转不携带密钥。下载器核对可用的大小、SHA-1 和 MD5,成功后保存文件,遇到同名文件时保留原件。
87
+
88
+ ## 测试
89
+
90
+ ```sh
91
+ uv run --extra test pytest -q
92
+ uv run --env-file .env python tests/live_smoke.py
93
+ ```
94
+
95
+ 第一条使用模拟 API 和 CDN。第二条使用当前 Key 读取实站资料;如需验证真实下载,追加 `--download --download-dir ./live-downloads`。
96
+
97
+ ## 构建与发布到 PyPI
98
+
99
+ 本地可运行 `uv build`,在 `dist/` 检查 wheel 和源码包。
100
+
101
+ 在 PyPI 为 `curseforge-mcp` 配置 GitHub Actions Trusted Publisher:仓库为 `GlossMod/curseforge-mcp`(Owner:`GlossMod`,Repository:`curseforge-mcp`),Workflow:`publish.yml`,Environment:`pypi`。
102
+
103
+ 在 GitHub 发布带版本标签的 Release(例如 `v0.1.1`)后,`.github/workflows/publish.yml` 会使用标签版本构建并检查 wheel 和源码包,通过后自动发布到 PyPI。版本只在 CI 中替换,不会回写仓库。
104
+
105
+ 参考:[CurseForge REST API](https://docs.curseforge.com/rest-api/) · [CDN 下载鉴权](https://blog.curseforge.com/introducing-api-key-authentication-for-curseforge-file-downloads/)
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "curseforge-mcp"
7
+ version = "1.0.0"
8
+ description = "Unofficial local stdio MCP server for the CurseForge Core API"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ dependencies = ["mcp>=1.30,<2", "httpx>=0.27,<1", "pydantic>=2.7,<3"]
12
+
13
+ [project.optional-dependencies]
14
+ test = ["pytest>=8,<10"]
15
+
16
+ [project.scripts]
17
+ curseforge-mcp = "curseforge_mcp.server:main"
18
+
19
+ [tool.setuptools.packages.find]
20
+ where = ["src"]
21
+
22
+ [tool.pytest.ini_options]
23
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ """Unofficial CurseForge MCP server."""
@@ -0,0 +1,4 @@
1
+ from .server import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,153 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import httpx
6
+
7
+ API_ORIGIN = "https://api.curseforge.com"
8
+ PAGE_LIMIT = 10_000
9
+ MAX_PAGE_SIZE = 50
10
+ JsonObject = dict[str, Any]
11
+
12
+
13
+ class CurseForgeError(Exception):
14
+ """A user-facing error that must not contain credentials or signed CDN URLs."""
15
+
16
+ def __init__(self, message: str, status: int | None = None) -> None:
17
+ super().__init__(message)
18
+ self.status = status
19
+
20
+
21
+ def page_params(index: int, page_size: int) -> dict[str, int]:
22
+ if not 1 <= page_size <= MAX_PAGE_SIZE or index < 0 or index + page_size > PAGE_LIMIT:
23
+ raise CurseForgeError("分页要求 1 <= page_size <= 50、index >= 0、index + page_size <= 10000。")
24
+ return {"index": index, "pageSize": page_size}
25
+
26
+
27
+ def paginated(payload: JsonObject, index: int, page_size: int) -> JsonObject:
28
+ data = payload["data"]
29
+ if not isinstance(data, list):
30
+ raise CurseForgeError("CurseForge 分页响应的 data 不是列表。")
31
+ pagination = payload.get("pagination")
32
+ total = pagination.get("totalCount") if isinstance(pagination, dict) else None
33
+ next_index = index + len(data)
34
+ more = next_index < total if type(total) is int else len(data) == page_size
35
+ continuation = {
36
+ "nextIndex": next_index,
37
+ "nextPageSize": min(page_size, PAGE_LIMIT - next_index),
38
+ } if data and more and next_index < PAGE_LIMIT else {}
39
+ return {**payload, **continuation}
40
+
41
+
42
+ class CurseForgeClient:
43
+ def __init__(self, http: httpx.AsyncClient, api_key: str | None) -> None:
44
+ self.http = http
45
+ self._api_key = (api_key or "").strip()
46
+
47
+ def auth_headers(self) -> dict[str, str]:
48
+ if not self._api_key:
49
+ raise CurseForgeError("未设置 CURSEFORGE_API_KEY;请在 MCP 服务进程环境中配置获批的 Core API Key。")
50
+ if not self._api_key.isascii() or not all(33 <= ord(ch) <= 126 for ch in self._api_key):
51
+ raise CurseForgeError("CURSEFORGE_API_KEY 包含无效的字符。")
52
+ return {"x-api-key": self._api_key}
53
+
54
+ async def request(
55
+ self, path: str, *, params: dict[str, Any] | None = None, body: JsonObject | None = None
56
+ ) -> JsonObject:
57
+ try:
58
+ response = await self.http.request(
59
+ "GET" if body is None else "POST",
60
+ API_ORIGIN + path,
61
+ params={key: value for key, value in (params or {}).items() if value is not None},
62
+ json=body,
63
+ headers={"Accept": "application/json", **self.auth_headers()},
64
+ follow_redirects=False,
65
+ )
66
+ except httpx.RequestError:
67
+ raise CurseForgeError(f"请求 CurseForge API {path} 超时或连接失败。") from None
68
+ status = response.status_code
69
+ if status != 200:
70
+ hint = {
71
+ 401: "请检查 CURSEFORGE_API_KEY 是否有效。",
72
+ 403: "API Key 无权访问,请核对项目、文件或游戏的访问权限。",
73
+ 404: "资源不存在或当前凭据不可见。",
74
+ 429: "达到请求限额,请稍后重试。",
75
+ }.get(status, "请核对请求参数或稍后重试。")
76
+ raise CurseForgeError(f"CurseForge API {path} 返回 HTTP {status}。{hint}", status)
77
+ try:
78
+ payload = response.json()
79
+ except ValueError:
80
+ raise CurseForgeError(f"CurseForge API {path} 没有返回有效 JSON。") from None
81
+ if not isinstance(payload, dict) or "data" not in payload:
82
+ raise CurseForgeError(f"CurseForge API {path} 响应缺少 data 字段。")
83
+ return payload
84
+
85
+ async def page(
86
+ self, path: str, index: int, page_size: int, **params: Any
87
+ ) -> JsonObject:
88
+ payload = await self.request(path, params={**page_params(index, page_size), **params})
89
+ return paginated(payload, index, page_size)
90
+
91
+ async def list_games(
92
+ self, index: int, page_size: int, name: str | None, slug: str | None
93
+ ) -> JsonObject:
94
+ page = await self.page("/v1/games", index, page_size)
95
+ if name is None and slug is None:
96
+ return page
97
+ name_needle = name.strip().casefold() if name is not None else None
98
+ slug_needle = slug.strip().casefold() if slug is not None else None
99
+
100
+ def matches(game: JsonObject, field: str, needle: str | None, *, exact: bool) -> bool:
101
+ if needle is None:
102
+ return True
103
+ value = game.get(field)
104
+ if not isinstance(value, str):
105
+ return False
106
+ return value.casefold() == needle if exact else needle in value.casefold()
107
+
108
+ return {
109
+ **page,
110
+ "data": [
111
+ game for game in page["data"] if isinstance(game, dict)
112
+ and matches(game, "name", name_needle, exact=False)
113
+ and matches(game, "slug", slug_needle, exact=True)
114
+ ],
115
+ }
116
+
117
+ async def get_mod_file(self, file_id: int, mod_id: int | None) -> JsonObject:
118
+ if mod_id is not None:
119
+ payload = await self.request(f"/v1/mods/{mod_id}/files/{file_id}")
120
+ else:
121
+ batch = await self.request("/v1/mods/files", body={"fileIds": [file_id]})
122
+ if not isinstance(batch["data"], list):
123
+ raise CurseForgeError("CurseForge 批量文件响应的 data 不是列表。")
124
+ selected = [
125
+ item for item in batch["data"]
126
+ if isinstance(item, dict) and type(item.get("id")) is int and item["id"] == file_id
127
+ ]
128
+ if not selected:
129
+ raise CurseForgeError(f"未找到 file_id={file_id},或当前凭据不可见。", 404)
130
+ if len(selected) != 1:
131
+ raise CurseForgeError(f"CurseForge 返回了重复的 file_id={file_id}。")
132
+ payload = {**batch, "data": selected[0]}
133
+ file = payload["data"]
134
+ if not isinstance(file, dict) or type(file.get("id")) is not int or file["id"] != file_id:
135
+ raise CurseForgeError("CurseForge 返回的文件与请求的 file_id 不匹配。")
136
+ if mod_id is not None and "modId" in file and file["modId"] != mod_id:
137
+ raise CurseForgeError("CurseForge 返回的文件不属于请求的 mod_id。")
138
+ return payload
139
+
140
+ async def get_download_url(self, mod_id: int, file_id: int) -> JsonObject:
141
+ path = f"/v1/mods/{mod_id}/files/{file_id}/download-url"
142
+ try:
143
+ payload = await self.request(path)
144
+ except CurseForgeError as exc:
145
+ if exc.status in (403, 404):
146
+ raise CurseForgeError(
147
+ f"{exc} 官方 API 未提供第三方下载地址;如可用,请前往 CurseForge 项目文件页。",
148
+ exc.status,
149
+ ) from None
150
+ raise
151
+ if not isinstance(payload["data"], str) or not payload["data"].strip():
152
+ raise CurseForgeError("官方 API 未提供第三方下载地址;如可用,请前往 CurseForge 项目文件页。")
153
+ return payload
@@ -0,0 +1,185 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import os
5
+ import re
6
+ import tempfile
7
+ from pathlib import Path, PureWindowsPath
8
+ from typing import BinaryIO
9
+
10
+ import httpx
11
+
12
+ from .client import CurseForgeClient, CurseForgeError, JsonObject
13
+
14
+ EDGE_HOST = "edge.forgecdn.net"
15
+ REDIRECT_CODES = (301, 302, 303, 307, 308)
16
+ REFRESH_CODES = (403, 404, 410)
17
+ HASH_NAMES = {1: "sha1", 2: "md5"}
18
+
19
+
20
+ def file_name(file: JsonObject) -> str:
21
+ value = file.get("fileName")
22
+ if (
23
+ not isinstance(value, str) or not value or value in (".", "..")
24
+ or value.endswith((" ", ".")) or re.search(r'[<>:"/\\|?*\x00-\x1f\x7f]', value)
25
+ or PureWindowsPath(value).is_reserved()
26
+ ):
27
+ raise CurseForgeError("文件元数据没有安全的 fileName,未保存文件。")
28
+ return value
29
+
30
+
31
+ def cdn_url(value: str) -> httpx.URL:
32
+ try:
33
+ url = httpx.URL(value)
34
+ allowed = (
35
+ url.scheme == "https" and url.port in (None, 443) and not url.userinfo
36
+ and (url.host == "forgecdn.net" or url.host.endswith(".forgecdn.net"))
37
+ and not any(key.casefold() in ("api-key", "x-api-key") for key in url.params)
38
+ )
39
+ except (httpx.InvalidURL, ValueError):
40
+ allowed = False
41
+ if not allowed:
42
+ raise CurseForgeError("下载 URL 或重定向不符合 CurseForge CDN 安全规则(HTTPS、官方 forgecdn.net、无内嵌凭据)。")
43
+ return url
44
+
45
+
46
+ def hash_expectations(file: JsonObject) -> tuple[dict[str, str], list[int]]:
47
+ hashes = file.get("hashes")
48
+ if hashes is None:
49
+ return {}, []
50
+ if not isinstance(hashes, list):
51
+ raise CurseForgeError("CurseForge 文件哈希列表格式无效。")
52
+ expected: dict[str, str] = {}
53
+ unsupported: list[int] = []
54
+ for entry in hashes:
55
+ if not isinstance(entry, dict) or type(entry.get("algo")) is not int:
56
+ raise CurseForgeError("CurseForge 文件哈希条目格式无效。")
57
+ name = HASH_NAMES.get(entry["algo"])
58
+ if name is None:
59
+ if entry["algo"] not in unsupported:
60
+ unsupported.append(entry["algo"])
61
+ continue
62
+ value = entry.get("value")
63
+ length = 40 if name == "sha1" else 32
64
+ if not isinstance(value, str) or not re.fullmatch(rf"[a-fA-F0-9]{{{length}}}", value):
65
+ raise CurseForgeError(f"CurseForge 文件的 {name.upper()} 校验值格式无效。")
66
+ value = value.lower()
67
+ if name in expected and expected[name] != value:
68
+ raise CurseForgeError(f"CurseForge 文件的 {name.upper()} 校验值相互冲突。")
69
+ expected[name] = value
70
+ return expected, unsupported
71
+
72
+
73
+ class Downloader:
74
+ def __init__(self, client: CurseForgeClient, directory: Path) -> None:
75
+ self.client = client
76
+ self.directory = directory
77
+
78
+ async def _transfer(
79
+ self, url: httpx.URL, output: BinaryIO, hashers: dict, expected_size: int | None
80
+ ) -> int:
81
+ try:
82
+ for hop in range(6): # one initial request and at most five redirects
83
+ headers = {"Accept-Encoding": "identity"}
84
+ if url.host == EDGE_HOST:
85
+ # httpx can forward custom headers during redirects. Build each hop ourselves.
86
+ headers.update(self.client.auth_headers())
87
+ async with self.client.http.stream(
88
+ "GET", url, headers=headers, follow_redirects=False
89
+ ) as response:
90
+ status = response.status_code
91
+ if status in REDIRECT_CODES:
92
+ location = response.headers.get("Location")
93
+ if not location or hop == 5:
94
+ raise CurseForgeError("CDN 重定向缺少目标或超过五次。")
95
+ try:
96
+ url = cdn_url(str(url.join(location)))
97
+ except (httpx.InvalidURL, ValueError):
98
+ raise CurseForgeError("CDN 重定向 URL 格式无效。") from None
99
+ continue
100
+ if status != 200:
101
+ hint = {
102
+ 401: "请核对 CURSEFORGE_API_KEY 是否有效且有下载权限。",
103
+ 403: "无下载权限或链接已过期。",
104
+ 404: "文件不可用或链接已过期。",
105
+ 410: "该链接已过期或文件已移除。",
106
+ 429: "下载达到请求限额,请稍后重试。",
107
+ }.get(status, "未保存该文件。")
108
+ raise CurseForgeError(f"CurseForge CDN 返回 HTTP {status}。{hint}", status)
109
+ encoding = response.headers.get("Content-Encoding", "identity").lower()
110
+ if encoding != "identity":
111
+ raise CurseForgeError("CDN 返回了非 identity 编码,不能安全校验原始文件。")
112
+ size = 0
113
+ async for chunk in response.aiter_raw():
114
+ size += len(chunk)
115
+ if expected_size is not None and size > expected_size:
116
+ raise CurseForgeError("下载内容字节数超过上游 fileLength。")
117
+ output.write(chunk)
118
+ for hasher in hashers.values():
119
+ hasher.update(chunk)
120
+ return size
121
+ except httpx.RequestError:
122
+ raise CurseForgeError("CDN 下载超时、连接失败或传输中断;未保留未完成文件。") from None
123
+ raise AssertionError("unreachable redirect state")
124
+
125
+ async def download(self, file_id: int, mod_id: int | None) -> JsonObject:
126
+ file = (await self.client.get_mod_file(file_id, mod_id))["data"]
127
+ if file.get("isAvailable") is False:
128
+ raise CurseForgeError("CurseForge 标记此文件不可用,未尝试下载。")
129
+ if mod_id is None:
130
+ mod_id = file.get("modId")
131
+ if type(mod_id) is not int or mod_id <= 0:
132
+ raise CurseForgeError("文件元数据缺少有效的 modId;请显式提供 mod_id。")
133
+ name = file_name(file)
134
+ expected, unsupported = hash_expectations(file)
135
+ hashers = {algo: hashlib.new(algo, usedforsecurity=False) for algo in expected}
136
+ expected_size = file.get("fileLength")
137
+ if expected_size is not None and (type(expected_size) is not int or expected_size < 0):
138
+ raise CurseForgeError("CurseForge 文件的 fileLength 格式无效。")
139
+
140
+ tmp: Path | None = None
141
+ try:
142
+ directory = self.directory.resolve()
143
+ directory.mkdir(parents=True, exist_ok=True)
144
+ destination = directory / name
145
+ if os.path.lexists(destination):
146
+ raise CurseForgeError("下载目录下已存在同名文件,未覆盖。")
147
+ url = cdn_url((await self.client.get_download_url(mod_id, file_id))["data"])
148
+ with tempfile.NamedTemporaryFile(
149
+ mode="wb", dir=directory, prefix=".curseforge-", suffix=".part", delete=False
150
+ ) as output:
151
+ tmp = Path(output.name)
152
+ try:
153
+ size = await self._transfer(url, output, hashers, expected_size)
154
+ except CurseForgeError as exc:
155
+ if exc.status not in REFRESH_CODES:
156
+ raise
157
+ fresh = cdn_url((await self.client.get_download_url(mod_id, file_id))["data"])
158
+ size = await self._transfer(fresh, output, hashers, expected_size)
159
+
160
+ if expected_size is not None and size != expected_size:
161
+ raise CurseForgeError(f"下载大小不匹配:上游 fileLength 为 {expected_size},实际为 {size} 字节。")
162
+ for algo, digest in expected.items():
163
+ if hashers[algo].hexdigest() != digest:
164
+ raise CurseForgeError(f"下载文件的 {algo.upper()} 与上游校验值不一致。")
165
+
166
+ # No overwrite even when another download finishes after our initial existence check.
167
+ if os.name == "nt":
168
+ tmp.rename(destination)
169
+ else:
170
+ os.link(tmp, destination)
171
+ except FileExistsError:
172
+ raise CurseForgeError("目标路径已存在,未覆盖任何文件。") from None
173
+ except OSError as exc:
174
+ raise CurseForgeError(f"无法保存本地下载文件({exc.strerror or type(exc).__name__})。") from None
175
+ finally:
176
+ if tmp is not None:
177
+ tmp.unlink(missing_ok=True)
178
+
179
+ result = {
180
+ "path": str(destination), "bytes": size, "fileId": file_id, "modId": mod_id,
181
+ "sizeVerified": expected_size is not None, "verifiedHashes": expected,
182
+ }
183
+ if unsupported:
184
+ result["unverifiedHashAlgorithms"] = unsupported
185
+ return result