41 Commits

Author SHA1 Message Date
starry
6ff610f5af Update docker-ghcr.yml 2026-01-11 00:09:48 +08:00
user123
7534c64197 https 2026-01-10 23:54:04 +08:00
user123
5928a0a9e4 Default Registry 2026-01-10 23:46:26 +08:00
user123
685388fff9 shell OOM 2026-01-10 23:04:16 +08:00
user123
c6d95e683f update 2026-01-10 21:23:38 +08:00
user123
f8828ccb74 v1.2.1 2026-01-10 21:06:02 +08:00
user123
fdc156adad 修复GitHub用户名通配符 2026-01-10 20:54:45 +08:00
user123
80b0173d7c 兼容Containerd的ns参数 2026-01-10 20:29:42 +08:00
starry
31f62fde35 v1.2.0 2025-11-28 22:16:57 +08:00
starry
8d7619c7e4 判断是否已经添加加速域名,避免重复添加。 2025-11-28 13:37:23 +00:00
starry
a09db34787 Update README with documentation links
Added links to Chinese and English documentation in README.
2025-11-16 08:58:51 +08:00
starry
31a3b67ab0 更新文档 2025-11-16 08:49:12 +08:00
starry
3590c7c073 Update README.md 2025-11-16 08:46:24 +08:00
starry
3f614e8011 Merge pull request #74 from eryajf/main
feat: 针对action流水线做了一些优化
2025-09-29 14:20:49 +08:00
eryajf
198a18508b refactor: 重构 Docker 构建流程,使用多阶段构建 2025-09-29 14:18:40 +08:00
eryajf
780ac14a8f feat: 优化构建流程,使用预编译二进制文件 2025-09-29 10:11:02 +08:00
eryajf
62b3cb6b70 feat: 添加 UPX 压缩二进制文件 2025-09-29 09:51:23 +08:00
starry
714224bd29 Update README.md 2025-09-17 02:05:46 +08:00
starry
7f6c46f0c8 add截图 2025-09-17 01:58:46 +08:00
starry
fd9b0cf829 add截图 2025-09-17 01:51:41 +08:00
starry
42ddfaab9d Update docker-compose.yml 2025-09-13 03:45:28 +08:00
starry
6144883a6e Update docker-compose.yml 2025-09-13 03:44:25 +08:00
starry
c704923b64 禁用CGO 2025-09-09 12:25:21 +08:00
starry
dcb502d3c8 v1.1.9 2025-09-08 00:02:51 +08:00
starry
a011d560c6 shell转换中确保host有协议头 2025-09-04 04:13:21 +08:00
starry
53060d50db update 2025-09-02 12:34:42 +08:00
starry
68868388d3 更新为v1.1.8 2025-09-02 10:33:41 +08:00
starry
75833b937b 放宽gist匹配限制 2025-09-02 10:06:32 +08:00
starry
45b4acc31f 调整一些默认配置 2025-09-02 01:03:50 +08:00
starry
0cd5a7334d 增加.ps1脚本的处理 2025-09-01 12:16:42 +08:00
starry
40f5b597ab 增加检查是否为网页类型 2025-09-01 12:05:16 +08:00
starry
30bc88ed93 去掉greenteagc 2025-09-01 02:22:07 +08:00
starry
737a522afc Update README.md 2025-09-01 01:50:10 +08:00
starry
eee0a3220c Update README.md 2025-08-29 22:27:50 +08:00
user123456
9d5d3012a5 更新依赖,开启Green Tea GC新特性 2025-08-29 22:12:00 +08:00
starry
e2413fc30d 写响应的最大允许时间改为30分钟
h2写响应的最大允许时间从5分钟增加至30分钟,兼容大文件下载
2025-08-15 21:52:00 +08:00
starry
6193a07837 Update .gitattributes 2025-08-01 14:43:04 +08:00
starry
bb2f7bcda6 启动显示版本号 2025-08-01 13:23:52 +08:00
starry
4ec36da9b5 优化github上游链接404的处理 2025-08-01 13:19:47 +08:00
starry
83a1211067 Merge pull request #51 from RedwindA/fix/ratelimit-when-0
fix: 仅白名单
2025-08-01 10:47:49 +08:00
RedwindA
367038a4b5 移除InitGlobalLimiter中burstSize的最小值设置以正确实现仅白名单功能 2025-08-01 04:58:15 +08:00
21 changed files with 250 additions and 178 deletions

3
.gitattributes vendored
View File

@@ -1 +1,2 @@
* text=auto eol=lf
* text=auto eol=lf
*.html linguist-vendored

BIN
.github/demo/demo1.jpg vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

View File

@@ -3,9 +3,9 @@ on:
workflow_dispatch:
inputs:
version:
description: 'Version number'
description: '版本号 (例如: v1.0.0)'
required: true
default: 'latest'
default: 'v1.0.0'
jobs:
build:
@@ -15,13 +15,13 @@ jobs:
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v2
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
uses: docker/setup-buildx-action@v3
- name: Cache Docker layers
uses: actions/cache@v3
uses: actions/cache@v4
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-${{ github.sha }}
@@ -29,14 +29,19 @@ jobs:
${{ runner.os }}-buildx-
- name: Log in to GitHub Docker Registry
uses: docker/login-action@v2
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set version from input
run: echo "VERSION=${{ github.event.inputs.version }}" >> $GITHUB_ENV
run: |
VERSION=${{ github.event.inputs.version }}
if [[ $VERSION == v* ]]; then
VERSION=${VERSION:1}
fi
echo "VERSION=$VERSION" >> $GITHUB_ENV
- name: Convert repository name to lowercase
run: |
@@ -47,10 +52,9 @@ jobs:
- name: Build and push Docker image
run: |
docker buildx build --push \
--platform linux/amd64,linux/arm64/v8 \
--platform linux/amd64 \
--tag ghcr.io/${{ env.REPO_LOWER }}:${{ env.VERSION }} \
--tag ghcr.io/${{ env.REPO_LOWER }}:latest \
--build-arg VERSION=${{ env.VERSION }} \
-f Dockerfile .
env:
GHCR_PUBLIC: true # 将镜像设置为公开
GHCR_PUBLIC: true

View File

@@ -1,7 +1,7 @@
name: 发布二进制文件
on:
workflow_dispatch: # 手动触发
workflow_dispatch:
inputs:
version:
description: '版本号 (例如: v1.0.0)'
@@ -18,12 +18,13 @@ jobs:
- name: 检出代码
uses: actions/checkout@v4
with:
fetch-depth: 0 # 获取完整历史,用于生成变更日志
fetch-depth: 0
- name: 设置Go环境
uses: actions/setup-go@v4
uses: actions/setup-go@v5
with:
go-version: '1.24'
go-version-file: "src/go.mod"
cache-dependency-path: "src/go.sum"
- name: 获取版本号
id: version
@@ -53,15 +54,24 @@ jobs:
run: |
mkdir -p build/hubproxy
- name: 安装 UPX
uses: crazy-max/ghaction-upx@v3
with:
install-only: true
- name: 编译二进制文件
run: |
cd src
# Linux AMD64
GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o ../build/hubproxy/hubproxy-linux-amd64 .
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o ../build/hubproxy/hubproxy-linux-amd64 .
# Linux ARM64
GOOS=linux GOARCH=arm64 go build -ldflags="-s -w" -o ../build/hubproxy/hubproxy-linux-arm64 .
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="-s -w" -o ../build/hubproxy/hubproxy-linux-arm64 .
# 压缩二进制文件
upx -9 ../build/hubproxy/hubproxy-linux-amd64
upx -9 ../build/hubproxy/hubproxy-linux-arm64
- name: 复制配置文件
run: |
@@ -107,7 +117,7 @@ jobs:
cat checksums.txt
- name: 创建或更新Release
uses: softprops/action-gh-release@v1
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.version.outputs.version }}
name: "HubProxy ${{ steps.version.outputs.version }}"
@@ -125,4 +135,4 @@ jobs:
build/checksums.txt
draft: false
prerelease: false
token: ${{ secrets.GITHUB_TOKEN }}
token: ${{ secrets.GITHUB_TOKEN }}

3
.gitignore vendored
View File

@@ -1,4 +1,5 @@
.idea
.vscode
.DS_Store
hubproxy*
hubproxy*
!hubproxy.service

View File

@@ -1,11 +1,14 @@
FROM golang:1.24-alpine AS builder
FROM golang:1.25-alpine AS builder
ARG TARGETARCH
WORKDIR /app
COPY src/go.mod src/go.sum ./
RUN go mod download
RUN go mod download && apk add upx
COPY src/ .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -trimpath -o hubproxy .
RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build -ldflags="-s -w" -trimpath -o hubproxy . && upx -9 hubproxy
FROM alpine
@@ -14,4 +17,4 @@ WORKDIR /root/
COPY --from=builder /app/hubproxy .
COPY --from=builder /app/config.toml .
CMD ["./hubproxy"]
CMD ["./hubproxy"]

View File

@@ -1,27 +1,35 @@
# HubProxy
🚀 **Docker 和 GitHub 加速代理服务器**
**Docker 和 GitHub 加速代理服务器**
一个轻量级、高性能的多功能代理服务,提供 Docker 镜像加速、GitHub 文件加速、下载离线镜像、在线搜索 Docker 镜像等功能。
<p align="center">
<img src="https://count.getloli.com/get/@sky22333.hubproxy?theme=rule34" alt="Visitors">
</p>
## 特性
## 特性
- 🐳 **Docker 镜像加速** - 单域名实现 Docker Hub、GHCR、Quay 等多个镜像仓库加速,流式传输优化拉取速度。
- 🐳 **Docker 镜像加速** - 支持 Docker Hub、GHCR、Quay 等多个镜像仓库加速,流式传输优化拉取速度。
- 🐳 **离线镜像包** - 支持下载离线镜像包,流式传输加防抖设计。
- 📁 **GitHub 文件加速** - 加速 GitHub Release、Raw 文件下载,支持`api.github.com`,脚本嵌套加速等等
- 🤖 **AI 模型库支持** - 支持 Hugging Face 模型下载加速
- 🛡️ **智能限流** - IP 限流保护,防止滥用
- 🚫 **仓库审计** - 强大的自定义黑名单白名单同时审计镜像仓库和GitHub仓库
- 🔍 **镜像搜索** - 在线搜索 Docker 镜像
-**轻量高效** - 基于 Go 语言,单二进制文件运行,资源占用低,优雅的内存清理机制
- 🔧 **统一配置** - 统一配置管理
-**轻量高效** - 基于 Go 语言,单二进制文件运行,资源占用低。
- 🔧 **统一配置** - 统一配置管理,便于维护。
- 🛡️ **完全自托管** - 避免依赖免费第三方服务的不稳定性,例如`cloudflare`等等。
- 🚀 **多服务统一加速** - 单个程序即可统一加速 Docker、GitHub、Hugging Face 等多种服务,简化部署与管理。
## 详细文档
## 🚀 快速开始
[中文文档](https://zread.ai/sky22333/hubproxy)
[English](https://deepwiki.com/sky22333/hubproxy)
## 快速开始
### Docker部署推荐
```
@@ -32,25 +40,21 @@ docker run -d \
ghcr.io/sky22333/hubproxy
```
### 一键脚本安装
```bash
curl -fsSL https://raw.githubusercontent.com/sky22333/hubproxy/main/install.sh | sudo bash
```
也可以直接下载二进制文件执行`./hubproxy`使用无需配置文件即可启动内置默认配置支持所有功能。初始内存占用约18M二进制文件大小约12M
支持单个二进制文件直接启动,无需其他配置,内置默认配置,支持所有功能。
这个命令会:
- 🔍 自动检测系统架构AMD64/ARM64
- 📥 从 GitHub Releases 下载最新版本
- ⚙️ 自动配置系统服务
- 🔄 保留现有配置(升级时)
这个脚本会:
- 自动检测系统架构AMD64/ARM64
- 从 GitHub Releases 下载最新版本
- 自动配置系统服务
- 保留现有配置(升级时)
## 📖 使用方法
## 使用方法
### Docker 镜像加速
@@ -79,8 +83,7 @@ docker pull yourdomain.com/ghcr.io/sky22333/hubproxy
}
```
若已设置其他加速地址,直接并列添加后保存,
再执行 `sudo systemctl restart docker` 重启docker服务让配置生效。
若已设置其他加速地址,直接并列添加后保存,再执行 `sudo systemctl restart docker` 重启docker服务让配置生效。
### GitHub 文件加速
@@ -95,12 +98,12 @@ https://yourdomain.com/https://github.com/user/repo/releases/download/v1.0.0/fil
git clone https://yourdomain.com/https://github.com/sky22333/hubproxy.git
```
## ⚙️ 配置
## 配置
<details>
<summary>config.toml 配置说明</summary>
*此配置是默认配置,已经内置在程序中了,可以不用添加。*
*此配置是默认配置,已经内置在程序中了*
```
[server]
@@ -224,6 +227,7 @@ example.com {
}
```
> 对于使用nginx反代的用户Github加速提示`无效输入`的问题可以参见[issues/62](https://github.com/sky22333/hubproxy/issues/62#issuecomment-3219572440)
## ⚠️ 免责声明
@@ -240,7 +244,9 @@ example.com {
</div>
## 界面预览
![1](./.github/demo/demo1.jpg)
## Star 趋势
[![Star 趋势](https://starchart.cc/sky22333/hubproxy.svg?variant=adaptive)](https://starchart.cc/sky22333/hubproxy)

View File

@@ -1,8 +1,14 @@
services:
hubproxy:
build: .
image: ghcr.io/sky22333/hubproxy
container_name: hubproxy
restart: always
ports:
- '5000:5000'
- "5000:5000"
volumes:
- ./src/config.toml:/root/config.toml
- ./src/config.toml:/root/config.toml
logging:
driver: json-file
options:
max-size: "1g"
max-file: "2"

View File

@@ -83,6 +83,12 @@ authHost = "registry.k8s.io"
authType = "anonymous"
enabled = true
# Default Registry
[defaultRegistry]
upstream = "registry-1.docker.io"
authHost = "auth.docker.io"
enabled = true
[tokenCache]
# 是否启用缓存(同时控制Token和Manifest缓存)显著提升性能
enabled = true

View File

@@ -49,6 +49,8 @@ type AppConfig struct {
} `toml:"download"`
Registries map[string]RegistryMapping `toml:"registries"`
DefaultRegistry RegistryMapping `toml:"defaultRegistry"`
TokenCache struct {
Enabled bool `toml:"enabled"`
@@ -84,8 +86,8 @@ func DefaultConfig() *AppConfig {
RequestLimit int `toml:"requestLimit"`
PeriodHours float64 `toml:"periodHours"`
}{
RequestLimit: 200,
PeriodHours: 1.0,
RequestLimit: 500,
PeriodHours: 3.0,
},
Security: struct {
WhiteList []string `toml:"whiteList"`

View File

@@ -1,13 +1,13 @@
module hubproxy
go 1.24.0
go 1.25
require (
github.com/gin-gonic/gin v1.10.0
github.com/google/go-containerregistry v0.20.5
github.com/pelletier/go-toml/v2 v2.2.3
golang.org/x/net v0.33.0
golang.org/x/time v0.11.0
github.com/gin-gonic/gin v1.10.1
github.com/google/go-containerregistry v0.20.6
github.com/pelletier/go-toml/v2 v2.2.4
golang.org/x/net v0.43.0
golang.org/x/time v0.12.0
)
require (
@@ -16,7 +16,7 @@ require (
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/containerd/stargz-snapshotter/estargz v0.16.3 // indirect
github.com/docker/cli v28.1.1+incompatible // indirect
github.com/docker/cli v28.2.2+incompatible // indirect
github.com/docker/distribution v2.8.3+incompatible // indirect
github.com/docker/docker-credential-helpers v0.9.3 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
@@ -28,7 +28,6 @@ require (
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.18.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/kr/pretty v0.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
@@ -37,17 +36,15 @@ require (
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rogpeppe/go-internal v1.9.0 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
github.com/vbatts/tar-split v0.12.1 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.32.0 // indirect
golang.org/x/sync v0.14.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/text v0.21.0 // indirect
golang.org/x/crypto v0.41.0 // indirect
golang.org/x/sync v0.16.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/text v0.28.0 // indirect
google.golang.org/protobuf v1.36.3 // indirect
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

View File

@@ -8,12 +8,11 @@ github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/containerd/stargz-snapshotter/estargz v0.16.3 h1:7evrXtoh1mSbGj/pfRccTampEyKpjpOnS3CyiV1Ebr8=
github.com/containerd/stargz-snapshotter/estargz v0.16.3/go.mod h1:uyr4BfYfOj3G9WBVE8cOlQmXAbPN9VEQpBBeJIuOipU=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/docker/cli v28.1.1+incompatible h1:eyUemzeI45DY7eDPuwUcmDyDj1pM98oD5MdSpiItp8k=
github.com/docker/cli v28.1.1+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
github.com/docker/cli v28.2.2+incompatible h1:qzx5BNUDFqlvyq4AHzdNB7gSyVTmU4cgsyN9SdInc1A=
github.com/docker/cli v28.2.2+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk=
github.com/docker/distribution v2.8.3+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
github.com/docker/docker-credential-helpers v0.9.3 h1:gAm/VtF9wgqJMoxzT3Gj5p4AqIjCBS4wrsOh9yRqcz8=
@@ -22,8 +21,8 @@ github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uq
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
github.com/gin-gonic/gin v1.10.1 h1:T0ujvqyCSqRopADpgPgiTT63DUQVSfojyME59Ei63pQ=
github.com/gin-gonic/gin v1.10.1/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
@@ -36,8 +35,8 @@ github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/go-containerregistry v0.20.5 h1:4RnlYcDs5hoA++CeFjlbZ/U9Yp1EuWr+UhhTyYQjOP0=
github.com/google/go-containerregistry v0.20.5/go.mod h1:Q14vdOOzug02bwnhMkZKD4e30pDaD9W65qzXpyzF49E=
github.com/google/go-containerregistry v0.20.6 h1:cvWX87UxxLgaH76b4hIvya6Dzz9qHB31qAwjAohdSTU=
github.com/google/go-containerregistry v0.20.6/go.mod h1:T0x8MuoAoKX/873bkeSfLD2FAkwCDf9/HZgsFJ02E2Y=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
@@ -47,13 +46,6 @@ github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa02
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
@@ -69,15 +61,12 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@@ -99,28 +88,25 @@ github.com/vbatts/tar-split v0.12.1/go.mod h1:eF6B6i6ftWQcDqEn3/iGFRFRo8cBIMSJVO
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ=
golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
google.golang.org/protobuf v1.36.3 h1:82DV7MYdb8anAVi3qge1wSnMDrnKK7ebr+I0hHRN1BU=
google.golang.org/protobuf v1.36.3/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -5,6 +5,7 @@ import (
"fmt"
"io"
"net/http"
"regexp"
"strings"
"time"
@@ -16,6 +17,8 @@ import (
"hubproxy/utils"
)
var realmRegex = regexp.MustCompile(`realm="(https?://)([^/"]+)(/?[^"]*)"`)
// DockerProxy Docker代理配置
type DockerProxy struct {
registry name.Registry
@@ -28,9 +31,16 @@ var dockerProxy *DockerProxy
type RegistryDetector struct{}
// detectRegistryDomain 检测Registry域名并返回域名和剩余路径
func (rd *RegistryDetector) detectRegistryDomain(path string) (string, string) {
func (rd *RegistryDetector) detectRegistryDomain(c *gin.Context, path string) (string, string) {
cfg := config.GetConfig()
// 兼容Containerd的ns参数
if ns := c.Query("ns"); ns != "" {
if mapping, exists := cfg.Registries[ns]; exists && mapping.Enabled {
return ns, path
}
}
for domain := range cfg.Registries {
if strings.HasPrefix(path, domain+"/") {
remainingPath := strings.TrimPrefix(path, domain+"/")
@@ -61,7 +71,13 @@ var registryDetector = &RegistryDetector{}
// InitDockerProxy 初始化Docker代理
func InitDockerProxy() {
registry, err := name.NewRegistry("registry-1.docker.io")
cfg := config.GetConfig()
upstream := "registry-1.docker.io"
if cfg.DefaultRegistry.Upstream != "" {
upstream = cfg.DefaultRegistry.Upstream
}
registry, err := name.NewRegistry(upstream)
if err != nil {
fmt.Printf("创建Docker registry失败: %v\n", err)
return
@@ -99,7 +115,7 @@ func ProxyDockerRegistryGin(c *gin.Context) {
func handleRegistryRequest(c *gin.Context, path string) {
pathWithoutV2 := strings.TrimPrefix(path, "/v2/")
if registryDomain, remainingPath := registryDetector.detectRegistryDomain(pathWithoutV2); registryDomain != "" {
if registryDomain, remainingPath := registryDetector.detectRegistryDomain(c, pathWithoutV2); registryDomain != "" {
if registryDetector.isRegistryEnabled(registryDomain) {
c.Set("target_registry_domain", registryDomain)
c.Set("target_path", remainingPath)
@@ -346,17 +362,21 @@ func (r *ResponseRecorder) Write(data []byte) (int, error) {
}
func proxyDockerAuthOriginal(c *gin.Context) {
var authURL string
cfg := config.GetConfig()
authHost := "auth.docker.io"
if cfg.DefaultRegistry.AuthHost != "" {
authHost = cfg.DefaultRegistry.AuthHost
}
if targetDomain, exists := c.Get("target_registry_domain"); exists {
if mapping, found := registryDetector.getRegistryMapping(targetDomain.(string)); found {
authURL = "https://" + mapping.AuthHost + c.Request.URL.Path
} else {
authURL = "https://auth.docker.io" + c.Request.URL.Path
authHost = mapping.AuthHost
}
} else {
authURL = "https://auth.docker.io" + c.Request.URL.Path
}
authURL := "https://" + authHost + c.Request.URL.Path
if c.Request.URL.RawQuery != "" {
authURL += "?" + c.Request.URL.RawQuery
}
@@ -399,10 +419,15 @@ func proxyDockerAuthOriginal(c *gin.Context) {
}
}
scheme := "http"
if c.Request.TLS != nil || c.GetHeader("X-Forwarded-Proto") == "https" {
scheme = "https"
}
for key, values := range resp.Header {
for _, value := range values {
if key == "Www-Authenticate" {
value = rewriteAuthHeader(value, proxyHost)
value = rewriteAuthHeader(value, scheme, proxyHost)
}
c.Header(key, value)
}
@@ -413,13 +438,8 @@ func proxyDockerAuthOriginal(c *gin.Context) {
}
// rewriteAuthHeader 重写认证头
func rewriteAuthHeader(authHeader, proxyHost string) string {
authHeader = strings.ReplaceAll(authHeader, "https://auth.docker.io", "http://"+proxyHost)
authHeader = strings.ReplaceAll(authHeader, "https://ghcr.io", "http://"+proxyHost)
authHeader = strings.ReplaceAll(authHeader, "https://gcr.io", "http://"+proxyHost)
authHeader = strings.ReplaceAll(authHeader, "https://quay.io", "http://"+proxyHost)
return authHeader
func rewriteAuthHeader(authHeader, scheme, proxyHost string) string {
return realmRegex.ReplaceAllString(authHeader, fmt.Sprintf(`realm="%s://%s$3"`, scheme, proxyHost))
}
// handleMultiRegistryRequest 处理多Registry请求
@@ -598,11 +618,5 @@ func createUpstreamOptions(mapping config.RegistryMapping) []remote.Option {
remote.WithTransport(utils.GetGlobalHTTPClient().Transport),
}
switch mapping.AuthType {
case "github":
case "google":
case "quay":
}
return options
}

View File

@@ -20,7 +20,7 @@ var (
regexp.MustCompile(`^(?:https?://)?github\.com/([^/]+)/([^/]+)/(?:blob|raw)/.*`),
regexp.MustCompile(`^(?:https?://)?github\.com/([^/]+)/([^/]+)/(?:info|git-).*`),
regexp.MustCompile(`^(?:https?://)?raw\.github(?:usercontent|)\.com/([^/]+)/([^/]+)/.+?/.+`),
regexp.MustCompile(`^(?:https?://)?gist\.(?:githubusercontent|github)\.com/(.+?)/(.+?)/.+\.[a-zA-Z0-9]+$`),
regexp.MustCompile(`^(?:https?://)?gist\.(?:githubusercontent|github)\.com/([^/]+)/([^/]+).*`),
regexp.MustCompile(`^(?:https?://)?api\.github\.com/repos/([^/]+)/([^/]+)/.*`),
regexp.MustCompile(`^(?:https?://)?huggingface\.co(?:/spaces)?/([^/]+)/(.+)`),
regexp.MustCompile(`^(?:https?://)?cdn-lfs\.hf\.co(?:/spaces)?/([^/]+)/([^/]+)(?:/(.*))?`),
@@ -29,6 +29,14 @@ var (
}
)
// 全局变量:被阻止的内容类型
var blockedContentTypes = map[string]bool{
"text/html": true,
"application/xhtml+xml": true,
"text/xml": true,
"application/xml": true,
}
// GitHubProxyHandler GitHub代理处理器
func GitHubProxyHandler(c *gin.Context) {
rawPath := strings.TrimPrefix(c.Request.URL.RequestURI(), "/")
@@ -121,6 +129,17 @@ func proxyGitHubWithRedirect(c *gin.Context, u string, redirectCount int) {
fmt.Printf("关闭响应体失败: %v\n", err)
}
}()
// 检查并处理被阻止的内容类型
if c.Request.Method == "GET" {
if contentType := resp.Header.Get("Content-Type"); blockedContentTypes[strings.ToLower(strings.Split(contentType, ";")[0])] {
c.JSON(http.StatusForbidden, map[string]string{
"error": "Content type not allowed",
"message": "检测到网页类型,本服务不支持加速网页,请检查您的链接是否正确。",
})
return
}
}
// 检查文件大小限制
cfg := config.GetConfig()
@@ -146,15 +165,15 @@ func proxyGitHubWithRedirect(c *gin.Context, u string, redirectCount int) {
realHost = "https://" + realHost
}
// 处理.sh文件的智能处理
if strings.HasSuffix(strings.ToLower(u), ".sh") {
// 处理.sh和.ps1文件的智能处理
if strings.HasSuffix(strings.ToLower(u), ".sh") || strings.HasSuffix(strings.ToLower(u), ".ps1") {
isGzipCompressed := resp.Header.Get("Content-Encoding") == "gzip"
processedBody, processedSize, err := utils.ProcessSmart(resp.Body, isGzipCompressed, realHost)
if err != nil {
fmt.Printf("智能处理失败,回退到直接代理: %v\n", err)
processedBody = resp.Body
processedSize = 0
fmt.Printf("脚本处理失败: %v\n", err)
c.String(http.StatusBadGateway, "Script processing failed: %v", err)
return
}
// 智能设置响应头

View File

@@ -116,22 +116,23 @@ func main() {
router.NoRoute(handlers.GitHubProxyHandler)
cfg := config.GetConfig()
fmt.Printf("🚀 HubProxy 启动成功\n")
fmt.Printf("📡 监听地址: %s:%d\n", cfg.Server.Host, cfg.Server.Port)
fmt.Printf("限流配置: %d请求/%g小时\n", cfg.RateLimit.RequestLimit, cfg.RateLimit.PeriodHours)
fmt.Printf("HubProxy 启动成功\n")
fmt.Printf("监听地址: %s:%d\n", cfg.Server.Host, cfg.Server.Port)
fmt.Printf("限流配置: %d请求/%g小时\n", cfg.RateLimit.RequestLimit, cfg.RateLimit.PeriodHours)
// 显示HTTP/2支持状态
if cfg.Server.EnableH2C {
fmt.Printf("H2c: 已启用\n")
}
fmt.Printf("🔗 项目地址: https://github.com/sky22333/hubproxy\n")
fmt.Printf("版本号: v1.2.1\n")
fmt.Printf("项目地址: https://github.com/sky22333/hubproxy\n")
// 创建HTTP2服务器
server := &http.Server{
Addr: fmt.Sprintf("%s:%d", cfg.Server.Host, cfg.Server.Port),
ReadTimeout: 60 * time.Second,
WriteTimeout: 300 * time.Second,
WriteTimeout: 30 * time.Minute,
IdleTimeout: 120 * time.Second,
}

View File

@@ -1,13 +1,13 @@
<!DOCTYPE html>
<html lang="zh">
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Docker镜像流式下载工具,即点即下,无需等待">
<meta name="keywords" content="Docker,镜像下载,流式下载,即时下载">
<meta name="description" content="Docker镜像流式下载工具即点即下无需等待">
<meta name="keywords" content="Docker镜像下载流式下载即时下载">
<meta name="color-scheme" content="dark light">
<title>Docker离线镜像下载</title>
<link rel="icon" href="./favicon.ico">
<link rel="icon" href="/favicon.ico">
<style>
:root {
--background: #ffffff;

15
src/public/index.html vendored
View File

@@ -1,14 +1,13 @@
<!DOCTYPE html>
<html lang="zh">
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Github文件加速,docker镜像加速">
<meta name="keywords" content="Github,文件加速,ghproxy,docker镜像加速">
<meta name="description" content="Github文件加速docker镜像加速">
<meta name="keywords" content="Github文件加速ghproxydocker镜像加速">
<meta name="color-scheme" content="dark light">
<title>Github文件加速</title>
<link rel="icon" href="./favicon.ico">
<title>Github、Docker加速</title>
<link rel="icon" href="/favicon.ico">
<style>
:root {
--background: #ffffff;
@@ -602,7 +601,7 @@
<div class="hero">
<h1 class="hero-title">GitHub 文件加速</h1>
<p class="hero-subtitle">
快速下载GitHub上的文件和仓库解决国内访问GitHub速度慢的问题支持AI模型库Hugging Face
快速下载GitHub上的文件和仓库解决国内访问GitHub速度慢的问题支持Docker镜像加速和Hugging Face仓库。
</p>
</div>
@@ -685,7 +684,7 @@
<strong>Quay.io 镜像:</strong>
docker pull <span class="domain-base"></span>/quay.io/org/image
<strong>K8s 镜像:</strong>
<strong>Kubernetes 镜像:</strong>
docker pull <span class="domain-base"></span>/registry.k8s.io/pause:3.8
</div>
</div>

View File

@@ -1,13 +1,13 @@
<!DOCTYPE html>
<html lang="zh">
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Docker镜像搜索">
<meta name="keywords" content="Docker,镜像搜索,docker search">
<meta name="keywords" content="Docker镜像搜索docker search">
<meta name="color-scheme" content="dark light">
<title>Docker镜像搜索</title>
<link rel="icon" href="./favicon.ico">
<link rel="icon" href="/favicon.ico">
<style>
:root {
--background: #ffffff;

View File

@@ -200,6 +200,13 @@ func (ac *AccessController) checkList(matches, list []string) bool {
if strings.HasPrefix(fullRepo, item+"/") {
return true
}
if strings.HasPrefix(item, "*/") {
p := item[2:]
if p == repoName || (strings.HasSuffix(p, "*") && strings.HasPrefix(repoName, p[:len(p)-1])) {
return true
}
}
}
return false
}

View File

@@ -10,49 +10,46 @@ import (
)
// GitHub URL正则表达式
var githubRegex = regexp.MustCompile(`https?://(?:github\.com|raw\.githubusercontent\.com|raw\.github\.com|gist\.githubusercontent\.com|gist\.github\.com|api\.github\.com)[^\s'"]+`)
var githubRegex = regexp.MustCompile(`(?:^|[\s'"(=,\[{;|&<>])https?://(?:github\.com|raw\.githubusercontent\.com|raw\.github\.com|gist\.githubusercontent\.com|gist\.github\.com|api\.github\.com)[^\s'")]*`)
// MaxShellSize 限制最大处理大小为 10MB
const MaxShellSize = 10 * 1024 * 1024
// ProcessSmart Shell脚本智能处理函数
func ProcessSmart(input io.ReadCloser, isCompressed bool, host string) (io.Reader, int64, error) {
defer input.Close()
func ProcessSmart(input io.Reader, isCompressed bool, host string) (io.Reader, int64, error) {
content, err := readShellContent(input, isCompressed)
if err != nil {
return nil, 0, fmt.Errorf("内容读取失败: %v", err)
return nil, 0, err
}
if len(content) == 0 {
return strings.NewReader(""), 0, nil
}
if len(content) > 10*1024*1024 {
return strings.NewReader(content), int64(len(content)), nil
if !bytes.Contains(content, []byte("github.com")) && !bytes.Contains(content, []byte("githubusercontent.com")) {
return bytes.NewReader(content), int64(len(content)), nil
}
if !strings.Contains(content, "github.com") && !strings.Contains(content, "githubusercontent.com") {
return strings.NewReader(content), int64(len(content)), nil
}
processed := processGitHubURLs(content, host)
processed := processGitHubURLs(string(content), host)
return strings.NewReader(processed), int64(len(processed)), nil
}
func readShellContent(input io.ReadCloser, isCompressed bool) (string, error) {
func readShellContent(input io.Reader, isCompressed bool) ([]byte, error) {
var reader io.Reader = input
if isCompressed {
peek := make([]byte, 2)
n, err := input.Read(peek)
if err != nil && err != io.EOF {
return "", fmt.Errorf("读取数据失败: %v", err)
return nil, fmt.Errorf("读取数据失败: %v", err)
}
if n >= 2 && peek[0] == 0x1f && peek[1] == 0x8b {
combinedReader := io.MultiReader(bytes.NewReader(peek[:n]), input)
gzReader, err := gzip.NewReader(combinedReader)
if err != nil {
return "", fmt.Errorf("gzip解压失败: %v", err)
return nil, fmt.Errorf("gzip解压失败: %v", err)
}
defer gzReader.Close()
reader = gzReader
@@ -61,17 +58,30 @@ func readShellContent(input io.ReadCloser, isCompressed bool) (string, error) {
}
}
data, err := io.ReadAll(reader)
limit := int64(MaxShellSize + 1)
limitedReader := io.LimitReader(reader, limit)
data, err := io.ReadAll(limitedReader)
if err != nil {
return "", fmt.Errorf("读取内容失败: %v", err)
return nil, fmt.Errorf("读取内容失败: %v", err)
}
return string(data), nil
if int64(len(data)) > MaxShellSize {
return nil, fmt.Errorf("脚本文件过大,超过 %d MB 限制", MaxShellSize/1024/1024)
}
return data, nil
}
func processGitHubURLs(content, host string) string {
return githubRegex.ReplaceAllStringFunc(content, func(url string) string {
return transformURL(url, host)
return githubRegex.ReplaceAllStringFunc(content, func(match string) string {
// 如果匹配包含前缀分隔符,保留它,防止出现重复转换
if len(match) > 0 && match[0] != 'h' {
prefix := match[0:1]
url := match[1:]
return prefix + transformURL(url, host)
}
return transformURL(match, host)
})
}
@@ -86,9 +96,12 @@ func transformURL(url, host string) string {
} else if !strings.HasPrefix(url, "https://") && !strings.HasPrefix(url, "//") {
url = "https://" + url
}
cleanHost := strings.TrimPrefix(host, "https://")
cleanHost = strings.TrimPrefix(cleanHost, "http://")
cleanHost = strings.TrimSuffix(cleanHost, "/")
return cleanHost + "/" + url
}
// 确保 host 有协议头
if !strings.HasPrefix(host, "http://") && !strings.HasPrefix(host, "https://") {
host = "https://" + host
}
host = strings.TrimSuffix(host, "/")
return host + "/" + url
}

View File

@@ -13,7 +13,7 @@ import (
)
const (
CleanupInterval = 10 * time.Minute
CleanupInterval = 20 * time.Minute
MaxIPCacheSize = 10000
)
@@ -71,9 +71,6 @@ func InitGlobalLimiter() *IPRateLimiter {
ratePerSecond := rate.Limit(float64(cfg.RateLimit.RequestLimit) / (cfg.RateLimit.PeriodHours * 3600))
burstSize := cfg.RateLimit.RequestLimit
if burstSize < 1 {
burstSize = 1
}
limiter := &IPRateLimiter{
ips: make(map[string]*rateLimiterEntry),
@@ -101,7 +98,7 @@ func (i *IPRateLimiter) cleanupRoutine() {
i.mu.RLock()
for ip, entry := range i.ips {
if now.Sub(entry.lastAccess) > 1*time.Hour {
if now.Sub(entry.lastAccess) > 2*time.Hour {
expired = append(expired, ip)
}
}