mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-09-29 05:56:38 +08:00
feat(pages): import deployment packages from URL
Add upload-from-url so admins can paste an HTTP(S) link and let the control plane download the archive with browser-like headers. Private/LAN hosts and insecure TLS certificates are allowed for internal artifact stores; package size and format checks reuse the existing local-upload pipeline.
This commit is contained in:
@@ -34,6 +34,7 @@ sidebar: false
|
||||
- 明确 Pages 历史部署保留语义为每个项目最多 N 条(激活必留、其余按从新到旧填充),裁剪失败会记录日志且不回滚已成功上传。
|
||||
- 主配置版本与 Pages 部署双轨管理:Agent 以 Pages 项目 ID 为锚点请求最新激活部署包,项目内切换激活版本无需重新发布主配置即可在边缘自动更新。
|
||||
- Agent 边缘仅保留每个 Pages 项目的最新部署包,新包就绪并切换成功后清理旧 release;拉取 latest 时增加 hash 二次校验与重试以降低激活竞态失败;单个项目同步失败不再阻塞同批其它项目。
|
||||
- Pages 支持从 URL 导入部署包:填写下载链接后由控制面代为拉取并创建部署。
|
||||
|
||||
## [v3.3.0] - 2026-07-14
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
## 核心功能
|
||||
|
||||
Pages 静态托管子系统包含以下核心能力:
|
||||
* **Direct Upload 部署模式**:支持直接上传预构建的静态资源压缩包(`zip`、`tar.gz`、`tar.xz`、`tar.bz2`、`tar`、`7z`),省去复杂的 Git 集成和构建环境依赖。
|
||||
* **Direct Upload 部署模式**:支持直接上传预构建的静态资源压缩包(`zip`、`tar.gz`、`tar.xz`、`tar.bz2`、`tar`、`7z`),或填写 URL 由控制面代为下载导入(允许内网地址与自签证书),省去复杂的 Git 集成和构建环境依赖。
|
||||
* **不可变部署快照**:每次上传产生一个带唯一 ID 和 SHA-256 Checksum 的不可变部署记录。支持按系统配置保留最近 N 个历史部署,并可随时激活和回滚。
|
||||
* **SPA Fallback 支持**:支持对单页应用(SPA)进行 Fallback 路由配置,请求找不到静态文件时自动重定向到入口文件。
|
||||
* **内置 API 反代服务**:支持在 Pages 规则内一键启用 API 代理,消除跨域问题,将请求转发给指定的后端服务。
|
||||
|
||||
+212
-4
@@ -4475,7 +4475,7 @@ const docTemplate = `{
|
||||
"AgentTokenAuth": []
|
||||
}
|
||||
],
|
||||
"description": "返回 upload 框架记录的 SHA-256 哈希,供 Agent 对比本地缓存并按需拉取部署包",
|
||||
"description": "返回 upload 框架记录的 SHA-256 哈希,供 Agent 对比本地缓存并按需拉取部署包(兼容旧路径)",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -4533,7 +4533,7 @@ const docTemplate = `{
|
||||
"AgentTokenAuth": []
|
||||
}
|
||||
],
|
||||
"description": "流式下载指定部署的静态资源压缩包,供 Agent 边缘分发",
|
||||
"description": "流式下载指定部署的静态资源压缩包,供 Agent 边缘分发(兼容旧路径)",
|
||||
"produces": [
|
||||
"application/octet-stream"
|
||||
],
|
||||
@@ -4572,6 +4572,110 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/agent/pages/projects/{project_id}/latest/hash": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"AgentTokenAuth": []
|
||||
}
|
||||
],
|
||||
"description": "按项目 ID 返回当前激活部署的包哈希(类似 latest 指针),Agent 无需关心具体部署 ID",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"openflare-agent"
|
||||
],
|
||||
"summary": "查询 Pages 项目最新激活部署哈希",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Pages 项目 ID",
|
||||
"name": "project_id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/response.Any"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/definitions/github_com_Rain-kl_Wavelet_pkg_protocol.PagesProjectLatestHashResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "参数错误",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Token 无效",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/agent/pages/projects/{project_id}/latest/package": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"AgentTokenAuth": []
|
||||
}
|
||||
],
|
||||
"description": "按项目 ID 下载当前激活部署的压缩包,供 Agent 边缘分发",
|
||||
"produces": [
|
||||
"application/octet-stream"
|
||||
],
|
||||
"tags": [
|
||||
"openflare-agent"
|
||||
],
|
||||
"summary": "下载 Pages 项目最新激活部署包",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Pages 项目 ID",
|
||||
"name": "project_id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "部署包文件",
|
||||
"schema": {
|
||||
"type": "file"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "参数错误",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Token 无效",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/agent/waf/ip-groups/sync": {
|
||||
"post": {
|
||||
"security": [
|
||||
@@ -8198,7 +8302,7 @@ const docTemplate = `{
|
||||
"SessionCookie": []
|
||||
}
|
||||
],
|
||||
"description": "为指定项目上传 ZIP 部署包,需要管理员权限",
|
||||
"description": "为指定项目上传静态资源压缩包(zip/tar.gz/tar.xz/tar.bz2/tar/7z),需要管理员权限",
|
||||
"consumes": [
|
||||
"multipart/form-data"
|
||||
],
|
||||
@@ -8219,7 +8323,7 @@ const docTemplate = `{
|
||||
},
|
||||
{
|
||||
"type": "file",
|
||||
"description": "部署包 ZIP 文件",
|
||||
"description": "部署包文件",
|
||||
"name": "package",
|
||||
"in": "formData",
|
||||
"required": true
|
||||
@@ -8271,6 +8375,88 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/d/pages/{id}/deployments/upload-from-url": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"SessionCookie": []
|
||||
}
|
||||
],
|
||||
"description": "从用户提供的 HTTP(S) 链接下载部署包并创建部署记录;服务端使用浏览器伪装请求头拉取,需要管理员权限",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"openflare-pages"
|
||||
],
|
||||
"summary": "从 URL 导入 Pages 部署包",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "项目 ID",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "下载链接",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/pages.UploadFromURLInput"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "部署记录",
|
||||
"schema": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/response.Any"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/definitions/pages.DeploymentView"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "参数错误",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "未登录",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "项目不存在",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "内部错误",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/d/pages/{id}/deployments/{deployment_id}/activate": {
|
||||
"post": {
|
||||
"security": [
|
||||
@@ -14220,6 +14406,20 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"github_com_Rain-kl_Wavelet_pkg_protocol.PagesProjectLatestHashResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"deployment_id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"hash": {
|
||||
"type": "string"
|
||||
},
|
||||
"project_id": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"github_com_Rain-kl_Wavelet_pkg_protocol.WAFIPGroup": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -16821,6 +17021,14 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"pages.UploadFromURLInput": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"url": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"pages.View": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
+212
-4
@@ -4468,7 +4468,7 @@
|
||||
"AgentTokenAuth": []
|
||||
}
|
||||
],
|
||||
"description": "返回 upload 框架记录的 SHA-256 哈希,供 Agent 对比本地缓存并按需拉取部署包",
|
||||
"description": "返回 upload 框架记录的 SHA-256 哈希,供 Agent 对比本地缓存并按需拉取部署包(兼容旧路径)",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -4526,7 +4526,7 @@
|
||||
"AgentTokenAuth": []
|
||||
}
|
||||
],
|
||||
"description": "流式下载指定部署的静态资源压缩包,供 Agent 边缘分发",
|
||||
"description": "流式下载指定部署的静态资源压缩包,供 Agent 边缘分发(兼容旧路径)",
|
||||
"produces": [
|
||||
"application/octet-stream"
|
||||
],
|
||||
@@ -4565,6 +4565,110 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/agent/pages/projects/{project_id}/latest/hash": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"AgentTokenAuth": []
|
||||
}
|
||||
],
|
||||
"description": "按项目 ID 返回当前激活部署的包哈希(类似 latest 指针),Agent 无需关心具体部署 ID",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"openflare-agent"
|
||||
],
|
||||
"summary": "查询 Pages 项目最新激活部署哈希",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Pages 项目 ID",
|
||||
"name": "project_id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/response.Any"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/definitions/github_com_Rain-kl_Wavelet_pkg_protocol.PagesProjectLatestHashResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "参数错误",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Token 无效",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/agent/pages/projects/{project_id}/latest/package": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"AgentTokenAuth": []
|
||||
}
|
||||
],
|
||||
"description": "按项目 ID 下载当前激活部署的压缩包,供 Agent 边缘分发",
|
||||
"produces": [
|
||||
"application/octet-stream"
|
||||
],
|
||||
"tags": [
|
||||
"openflare-agent"
|
||||
],
|
||||
"summary": "下载 Pages 项目最新激活部署包",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Pages 项目 ID",
|
||||
"name": "project_id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "部署包文件",
|
||||
"schema": {
|
||||
"type": "file"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "参数错误",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Token 无效",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/agent/waf/ip-groups/sync": {
|
||||
"post": {
|
||||
"security": [
|
||||
@@ -8191,7 +8295,7 @@
|
||||
"SessionCookie": []
|
||||
}
|
||||
],
|
||||
"description": "为指定项目上传 ZIP 部署包,需要管理员权限",
|
||||
"description": "为指定项目上传静态资源压缩包(zip/tar.gz/tar.xz/tar.bz2/tar/7z),需要管理员权限",
|
||||
"consumes": [
|
||||
"multipart/form-data"
|
||||
],
|
||||
@@ -8212,7 +8316,7 @@
|
||||
},
|
||||
{
|
||||
"type": "file",
|
||||
"description": "部署包 ZIP 文件",
|
||||
"description": "部署包文件",
|
||||
"name": "package",
|
||||
"in": "formData",
|
||||
"required": true
|
||||
@@ -8264,6 +8368,88 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/d/pages/{id}/deployments/upload-from-url": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"SessionCookie": []
|
||||
}
|
||||
],
|
||||
"description": "从用户提供的 HTTP(S) 链接下载部署包并创建部署记录;服务端使用浏览器伪装请求头拉取,需要管理员权限",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"openflare-pages"
|
||||
],
|
||||
"summary": "从 URL 导入 Pages 部署包",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "项目 ID",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "下载链接",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/pages.UploadFromURLInput"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "部署记录",
|
||||
"schema": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/response.Any"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/definitions/pages.DeploymentView"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "参数错误",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "未登录",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "项目不存在",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "内部错误",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/response.Any"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/d/pages/{id}/deployments/{deployment_id}/activate": {
|
||||
"post": {
|
||||
"security": [
|
||||
@@ -14213,6 +14399,20 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"github_com_Rain-kl_Wavelet_pkg_protocol.PagesProjectLatestHashResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"deployment_id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"hash": {
|
||||
"type": "string"
|
||||
},
|
||||
"project_id": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"github_com_Rain-kl_Wavelet_pkg_protocol.WAFIPGroup": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -16814,6 +17014,14 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"pages.UploadFromURLInput": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"url": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"pages.View": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
+131
-4
@@ -778,6 +778,15 @@ definitions:
|
||||
hash:
|
||||
type: string
|
||||
type: object
|
||||
github_com_Rain-kl_Wavelet_pkg_protocol.PagesProjectLatestHashResponse:
|
||||
properties:
|
||||
deployment_id:
|
||||
type: integer
|
||||
hash:
|
||||
type: string
|
||||
project_id:
|
||||
type: integer
|
||||
type: object
|
||||
github_com_Rain-kl_Wavelet_pkg_protocol.WAFIPGroup:
|
||||
properties:
|
||||
checksum:
|
||||
@@ -2499,6 +2508,11 @@ definitions:
|
||||
spa_fallback_path:
|
||||
type: string
|
||||
type: object
|
||||
pages.UploadFromURLInput:
|
||||
properties:
|
||||
url:
|
||||
type: string
|
||||
type: object
|
||||
pages.View:
|
||||
properties:
|
||||
active_deployment:
|
||||
@@ -6641,7 +6655,7 @@ paths:
|
||||
- openflare-agent
|
||||
/api/v1/agent/pages/deployments/{deployment_id}/hash:
|
||||
get:
|
||||
description: 返回 upload 框架记录的 SHA-256 哈希,供 Agent 对比本地缓存并按需拉取部署包
|
||||
description: 返回 upload 框架记录的 SHA-256 哈希,供 Agent 对比本地缓存并按需拉取部署包(兼容旧路径)
|
||||
parameters:
|
||||
- description: 部署 ID
|
||||
in: path
|
||||
@@ -6675,7 +6689,7 @@ paths:
|
||||
- openflare-agent
|
||||
/api/v1/agent/pages/deployments/{deployment_id}/package:
|
||||
get:
|
||||
description: 流式下载指定部署的静态资源压缩包,供 Agent 边缘分发
|
||||
description: 流式下载指定部署的静态资源压缩包,供 Agent 边缘分发(兼容旧路径)
|
||||
parameters:
|
||||
- description: 部署 ID
|
||||
in: path
|
||||
@@ -6702,6 +6716,69 @@ paths:
|
||||
summary: 下载 Pages 部署包
|
||||
tags:
|
||||
- openflare-agent
|
||||
/api/v1/agent/pages/projects/{project_id}/latest/hash:
|
||||
get:
|
||||
description: 按项目 ID 返回当前激活部署的包哈希(类似 latest 指针),Agent 无需关心具体部署 ID
|
||||
parameters:
|
||||
- description: Pages 项目 ID
|
||||
in: path
|
||||
name: project_id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: '#/definitions/response.Any'
|
||||
- properties:
|
||||
data:
|
||||
$ref: '#/definitions/github_com_Rain-kl_Wavelet_pkg_protocol.PagesProjectLatestHashResponse'
|
||||
type: object
|
||||
"400":
|
||||
description: 参数错误
|
||||
schema:
|
||||
$ref: '#/definitions/response.Any'
|
||||
"401":
|
||||
description: Token 无效
|
||||
schema:
|
||||
$ref: '#/definitions/response.Any'
|
||||
security:
|
||||
- AgentTokenAuth: []
|
||||
summary: 查询 Pages 项目最新激活部署哈希
|
||||
tags:
|
||||
- openflare-agent
|
||||
/api/v1/agent/pages/projects/{project_id}/latest/package:
|
||||
get:
|
||||
description: 按项目 ID 下载当前激活部署的压缩包,供 Agent 边缘分发
|
||||
parameters:
|
||||
- description: Pages 项目 ID
|
||||
in: path
|
||||
name: project_id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/octet-stream
|
||||
responses:
|
||||
"200":
|
||||
description: 部署包文件
|
||||
schema:
|
||||
type: file
|
||||
"400":
|
||||
description: 参数错误
|
||||
schema:
|
||||
$ref: '#/definitions/response.Any'
|
||||
"401":
|
||||
description: Token 无效
|
||||
schema:
|
||||
$ref: '#/definitions/response.Any'
|
||||
security:
|
||||
- AgentTokenAuth: []
|
||||
summary: 下载 Pages 项目最新激活部署包
|
||||
tags:
|
||||
- openflare-agent
|
||||
/api/v1/agent/waf/ip-groups/sync:
|
||||
post:
|
||||
consumes:
|
||||
@@ -8930,14 +9007,14 @@ paths:
|
||||
post:
|
||||
consumes:
|
||||
- multipart/form-data
|
||||
description: 为指定项目上传 ZIP 部署包,需要管理员权限
|
||||
description: 为指定项目上传静态资源压缩包(zip/tar.gz/tar.xz/tar.bz2/tar/7z),需要管理员权限
|
||||
parameters:
|
||||
- description: 项目 ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
- description: 部署包 ZIP 文件
|
||||
- description: 部署包文件
|
||||
in: formData
|
||||
name: package
|
||||
required: true
|
||||
@@ -8975,6 +9052,56 @@ paths:
|
||||
summary: 上传 Pages 部署包
|
||||
tags:
|
||||
- openflare-pages
|
||||
/api/v1/d/pages/{id}/deployments/upload-from-url:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: 从用户提供的 HTTP(S) 链接下载部署包并创建部署记录;服务端使用浏览器伪装请求头拉取,需要管理员权限
|
||||
parameters:
|
||||
- description: 项目 ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
- description: 下载链接
|
||||
in: body
|
||||
name: request
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/pages.UploadFromURLInput'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: 部署记录
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: '#/definitions/response.Any'
|
||||
- properties:
|
||||
data:
|
||||
$ref: '#/definitions/pages.DeploymentView'
|
||||
type: object
|
||||
"400":
|
||||
description: 参数错误
|
||||
schema:
|
||||
$ref: '#/definitions/response.Any'
|
||||
"401":
|
||||
description: 未登录
|
||||
schema:
|
||||
$ref: '#/definitions/response.Any'
|
||||
"404":
|
||||
description: 项目不存在
|
||||
schema:
|
||||
$ref: '#/definitions/response.Any'
|
||||
"500":
|
||||
description: 内部错误
|
||||
schema:
|
||||
$ref: '#/definitions/response.Any'
|
||||
security:
|
||||
- SessionCookie: []
|
||||
summary: 从 URL 导入 Pages 部署包
|
||||
tags:
|
||||
- openflare-pages
|
||||
/api/v1/d/pages/{id}/update:
|
||||
post:
|
||||
consumes:
|
||||
|
||||
@@ -468,7 +468,8 @@ export function OpenFlareOpsSettings() {
|
||||
/>
|
||||
</div>
|
||||
<p className='text-xs text-muted-foreground'>
|
||||
每个项目最多保留 N 条部署:激活部署始终保留,其余按从新到旧填充;超出的非激活部署会在上传成功后自动清理。支持
|
||||
每个项目最多保留 N
|
||||
条部署:激活部署始终保留,其余按从新到旧填充;超出的非激活部署会在上传成功后自动清理。支持
|
||||
zip、tar.gz、tar.xz、tar.bz2、tar、7z 格式。
|
||||
</p>
|
||||
</CardContent>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useRef, useState } from 'react';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Loader2, UploadCloud } from 'lucide-react';
|
||||
import { Link2, Loader2, UploadCloud } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { PagesService } from '@/lib/services/openflare';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
@@ -61,12 +62,15 @@ export function DeploymentUploadDialog({
|
||||
}: DeploymentUploadDialogProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [mode, setMode] = useState<'file' | 'url'>('file');
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [packageURL, setPackageURL] = useState('');
|
||||
const [isDragActive, setIsDragActive] = useState(false);
|
||||
const [uploadProgress, setUploadProgress] = useState<number | null>(null);
|
||||
|
||||
const resetForm = () => {
|
||||
setFile(null);
|
||||
setPackageURL('');
|
||||
setIsDragActive(false);
|
||||
setUploadProgress(null);
|
||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
||||
@@ -77,7 +81,17 @@ export function DeploymentUploadDialog({
|
||||
onOpenChange(nextOpen);
|
||||
};
|
||||
|
||||
const uploadMutation = useMutation({
|
||||
const invalidate = async () => {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: deploymentsQueryKey(projectId),
|
||||
}),
|
||||
queryClient.invalidateQueries({ queryKey: projectQueryKey(projectId) }),
|
||||
queryClient.invalidateQueries({ queryKey: projectsQueryKey }),
|
||||
]);
|
||||
};
|
||||
|
||||
const uploadFileMutation = useMutation({
|
||||
mutationFn: () => {
|
||||
if (!file) throw new Error('请选择部署包');
|
||||
return PagesService.uploadDeployment(projectId, {
|
||||
@@ -87,13 +101,7 @@ export function DeploymentUploadDialog({
|
||||
},
|
||||
onSuccess: async () => {
|
||||
toast.success('部署包上传成功');
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: deploymentsQueryKey(projectId),
|
||||
}),
|
||||
queryClient.invalidateQueries({ queryKey: projectQueryKey(projectId) }),
|
||||
queryClient.invalidateQueries({ queryKey: projectsQueryKey }),
|
||||
]);
|
||||
await invalidate();
|
||||
handleClose(false);
|
||||
},
|
||||
onError: (error) => {
|
||||
@@ -102,6 +110,27 @@ export function DeploymentUploadDialog({
|
||||
},
|
||||
});
|
||||
|
||||
const uploadURLMutation = useMutation({
|
||||
mutationFn: () => {
|
||||
const url = packageURL.trim();
|
||||
if (!url) throw new Error('请填写部署包下载链接');
|
||||
if (!/^https?:\/\//i.test(url)) {
|
||||
throw new Error('链接必须以 http:// 或 https:// 开头');
|
||||
}
|
||||
return PagesService.uploadDeploymentFromURL(projectId, { url });
|
||||
},
|
||||
onSuccess: async () => {
|
||||
toast.success('已从链接下载并创建部署');
|
||||
await invalidate();
|
||||
handleClose(false);
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error instanceof Error ? error.message : '从链接导入失败');
|
||||
},
|
||||
});
|
||||
|
||||
const isPending = uploadFileMutation.isPending || uploadURLMutation.isPending;
|
||||
|
||||
const handleFileSelect = (selected: File | null) => {
|
||||
if (!selected) return;
|
||||
if (!isSupportedPagesPackage(selected.name)) {
|
||||
@@ -111,80 +140,129 @@ export function DeploymentUploadDialog({
|
||||
setFile(selected);
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (mode === 'file') {
|
||||
uploadFileMutation.mutate();
|
||||
return;
|
||||
}
|
||||
uploadURLMutation.mutate();
|
||||
};
|
||||
|
||||
const canSubmit =
|
||||
mode === 'file' ? Boolean(file) : packageURL.trim().length > 0;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent>
|
||||
<DialogContent className='sm:max-w-lg'>
|
||||
<DialogHeader>
|
||||
<DialogTitle>上传部署包</DialogTitle>
|
||||
<DialogDescription>
|
||||
上传已构建的静态资源压缩包(zip / tar.gz / tar.xz / tar.bz2 / tar /
|
||||
7z),部署后可在列表中激活。
|
||||
支持本地上传或从 URL 下载静态资源压缩包(zip / tar.gz / tar.xz /
|
||||
tar.bz2 / tar / 7z),创建部署后可在列表中激活。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-lg border border-dashed p-8 text-center transition',
|
||||
isDragActive ? 'border-primary bg-primary/5' : 'bg-muted/20',
|
||||
)}
|
||||
onDragEnter={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragActive(true);
|
||||
}}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDragLeave={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragActive(false);
|
||||
}}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragActive(false);
|
||||
handleFileSelect(e.dataTransfer.files[0] ?? null);
|
||||
}}
|
||||
<Tabs
|
||||
value={mode}
|
||||
onValueChange={(value) => setMode(value as 'file' | 'url')}
|
||||
className='w-full'
|
||||
>
|
||||
<UploadCloud className='size-8 mx-auto text-muted-foreground' />
|
||||
<p className='mt-3 text-sm'>拖拽部署包到此处,或点击选择文件</p>
|
||||
<p className='mt-1 text-xs text-muted-foreground'>
|
||||
支持 zip、tar.gz、tar.xz、tar.bz2、tar、7z
|
||||
</p>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='mt-3'
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
选择文件
|
||||
</Button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type='file'
|
||||
accept={PAGES_PACKAGE_ACCEPT}
|
||||
className='hidden'
|
||||
onChange={(e) => handleFileSelect(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
</div>
|
||||
<TabsList className='grid w-full grid-cols-2'>
|
||||
<TabsTrigger value='file'>本地上传</TabsTrigger>
|
||||
<TabsTrigger value='url'>从 URL 下载</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{file ? (
|
||||
<div className='rounded-lg border border-dashed px-4 py-3 text-sm'>
|
||||
<p className='font-medium'>{file.name}</p>
|
||||
<p className='text-xs text-muted-foreground mt-1'>
|
||||
{formatBytes(file.size)}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{uploadProgress !== null ? (
|
||||
<div className='space-y-1.5'>
|
||||
<div className='flex justify-between text-xs text-muted-foreground'>
|
||||
<span>{uploadProgress >= 100 ? '服务端处理中' : '上传进度'}</span>
|
||||
<span>
|
||||
{uploadProgress >= 100 ? '请稍候' : `${uploadProgress}%`}
|
||||
</span>
|
||||
<TabsContent value='file' className='space-y-4 mt-4'>
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-lg border border-dashed p-8 text-center transition',
|
||||
isDragActive ? 'border-primary bg-primary/5' : 'bg-muted/20',
|
||||
)}
|
||||
onDragEnter={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragActive(true);
|
||||
}}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDragLeave={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragActive(false);
|
||||
}}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragActive(false);
|
||||
handleFileSelect(e.dataTransfer.files[0] ?? null);
|
||||
}}
|
||||
>
|
||||
<UploadCloud className='size-8 mx-auto text-muted-foreground' />
|
||||
<p className='mt-3 text-sm'>拖拽部署包到此处,或点击选择文件</p>
|
||||
<p className='mt-1 text-xs text-muted-foreground'>
|
||||
支持 zip、tar.gz、tar.xz、tar.bz2、tar、7z
|
||||
</p>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='mt-3'
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
选择文件
|
||||
</Button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type='file'
|
||||
accept={PAGES_PACKAGE_ACCEPT}
|
||||
className='hidden'
|
||||
onChange={(e) => handleFileSelect(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
</div>
|
||||
<Progress value={uploadProgress >= 100 ? 100 : uploadProgress} />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{file ? (
|
||||
<div className='rounded-lg border border-dashed px-4 py-3 text-sm'>
|
||||
<p className='font-medium'>{file.name}</p>
|
||||
<p className='text-xs text-muted-foreground mt-1'>
|
||||
{formatBytes(file.size)}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{uploadProgress !== null ? (
|
||||
<div className='space-y-1.5'>
|
||||
<div className='flex justify-between text-xs text-muted-foreground'>
|
||||
<span>
|
||||
{uploadProgress >= 100 ? '服务端处理中' : '上传进度'}
|
||||
</span>
|
||||
<span>
|
||||
{uploadProgress >= 100 ? '请稍候' : `${uploadProgress}%`}
|
||||
</span>
|
||||
</div>
|
||||
<Progress
|
||||
value={uploadProgress >= 100 ? 100 : uploadProgress}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='url' className='space-y-4 mt-4'>
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='package-url'>部署包下载链接</Label>
|
||||
<div className='relative'>
|
||||
<Link2 className='absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground' />
|
||||
<Input
|
||||
id='package-url'
|
||||
className='pl-9'
|
||||
placeholder='https://example.com/dist/site.zip'
|
||||
value={packageURL}
|
||||
onChange={(e) => setPackageURL(e.target.value)}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
<p className='text-xs text-muted-foreground'>
|
||||
服务端将使用浏览器环境请求头从该链接下载压缩包,支持内网地址与自签证书
|
||||
HTTPS。
|
||||
</p>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<div className='space-y-1.5'>
|
||||
<Label htmlFor='entryFile'>入口文件</Label>
|
||||
@@ -195,15 +273,14 @@ export function DeploymentUploadDialog({
|
||||
<Button variant='outline' onClick={() => handleClose(false)}>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => uploadMutation.mutate()}
|
||||
disabled={!file || uploadMutation.isPending}
|
||||
>
|
||||
{uploadMutation.isPending ? (
|
||||
<Button onClick={handleSubmit} disabled={!canSubmit || isPending}>
|
||||
{isPending ? (
|
||||
<>
|
||||
<Loader2 className='size-4 animate-spin mr-1' />
|
||||
上传中...
|
||||
{mode === 'url' ? '下载中...' : '上传中...'}
|
||||
</>
|
||||
) : mode === 'url' ? (
|
||||
'下载并创建部署'
|
||||
) : (
|
||||
'上传并创建部署'
|
||||
)}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { OpenFlareBaseService } from './base.service';
|
||||
import type {
|
||||
PagesDeployment,
|
||||
PagesDeploymentFile,
|
||||
PagesDeploymentUploadFromURLPayload,
|
||||
PagesDeploymentUploadPayload,
|
||||
PagesProject,
|
||||
PagesProjectPayload,
|
||||
@@ -67,6 +68,16 @@ export class PagesService extends OpenFlareBaseService {
|
||||
);
|
||||
}
|
||||
|
||||
static uploadDeploymentFromURL(
|
||||
projectId: number,
|
||||
payload: PagesDeploymentUploadFromURLPayload,
|
||||
): Promise<PagesDeployment> {
|
||||
return this.post<PagesDeployment>(
|
||||
`/${projectId}/deployments/upload-from-url`,
|
||||
payload,
|
||||
);
|
||||
}
|
||||
|
||||
static activateDeployment(
|
||||
projectId: number,
|
||||
deploymentId: number,
|
||||
|
||||
@@ -469,6 +469,10 @@ export interface PagesDeploymentUploadPayload {
|
||||
onProgress?: (percent: number) => void;
|
||||
}
|
||||
|
||||
export interface PagesDeploymentUploadFromURLPayload {
|
||||
url: string;
|
||||
}
|
||||
|
||||
// ==================== Origins ====================
|
||||
|
||||
export interface OriginItem {
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package pages
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/pkg/pagesarchive"
|
||||
)
|
||||
|
||||
const (
|
||||
pagesURLDownloadTimeout = 10 * time.Minute
|
||||
pagesURLMaxRedirects = 5
|
||||
pagesMagicSniffBytes = 16
|
||||
pagesURLDialTimeout = 30 * time.Second
|
||||
pagesURLTLSHandshake = 15 * time.Second
|
||||
pagesBrowserUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
||||
pagesBrowserAccept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"
|
||||
pagesBrowserAcceptLang = "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
|
||||
pagesBrowserSecCHUA = `"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"`
|
||||
pagesBrowserSecCHUAMobile = "?0"
|
||||
pagesBrowserSecCHUAPlat = `"Windows"`
|
||||
)
|
||||
|
||||
// downloadPagesPackageFromURL fetches a remote archive with browser-like headers
|
||||
// and writes it to a temp file. Allows private/LAN hosts and insecure TLS certs
|
||||
// (self-signed / internal CA) so operators can pull from internal artifact stores.
|
||||
func downloadPagesPackageFromURL(ctx context.Context, rawURL string, maxPackageBytes int64) (tempPath string, checksum string, size int64, format pagesarchive.Format, fileName string, err error) {
|
||||
parsed, err := parseAndValidatePagesDownloadURL(rawURL)
|
||||
if err != nil {
|
||||
return "", "", 0, "", "", err
|
||||
}
|
||||
|
||||
resp, err := doBrowserDownload(ctx, parsed)
|
||||
if err != nil {
|
||||
return "", "", 0, "", "", err
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", "", 0, "", "", fmt.Errorf("%s: HTTP %d", errPagesPackageURLDownloadFailed, resp.StatusCode)
|
||||
}
|
||||
if resp.ContentLength > 0 && resp.ContentLength > maxPackageBytes {
|
||||
return "", "", 0, "", "", errors.New(errPagesPackageURLTooLarge)
|
||||
}
|
||||
|
||||
fileName = fileNameFromDownload(resp, parsed)
|
||||
format, _ = pagesarchive.DetectFormatFromName(fileName)
|
||||
|
||||
tempPath, checksum, size, err = writeLimitedPackageTemp(resp.Body, format, maxPackageBytes)
|
||||
if err != nil {
|
||||
return "", "", 0, "", "", err
|
||||
}
|
||||
format, fileName, err = ensurePackageFormat(tempPath, format, fileName)
|
||||
if err != nil {
|
||||
_ = os.Remove(tempPath)
|
||||
return "", "", 0, "", "", err
|
||||
}
|
||||
return tempPath, checksum, size, format, fileName, nil
|
||||
}
|
||||
|
||||
func newPagesURLDownloadClient() *http.Client {
|
||||
transport := &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: pagesURLDialTimeout,
|
||||
KeepAlive: pagesURLDialTimeout,
|
||||
}).DialContext,
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxIdleConns: 32,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: pagesURLTLSHandshake,
|
||||
ExpectContinueTimeout: time.Second,
|
||||
// Allow self-signed / internal certificates for artifact hosts.
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec // intentional for internal/dev artifact URLs
|
||||
}
|
||||
client := &http.Client{
|
||||
Timeout: pagesURLDownloadTimeout,
|
||||
Transport: transport,
|
||||
}
|
||||
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= pagesURLMaxRedirects {
|
||||
return errors.New(errPagesPackageURLDownloadFailed)
|
||||
}
|
||||
if err := validatePagesDownloadURLValue(req.URL); err != nil {
|
||||
return err
|
||||
}
|
||||
applyBrowserDownloadHeaders(req, via[0].URL.String())
|
||||
return nil
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
func doBrowserDownload(ctx context.Context, parsed *url.URL) (*http.Response, error) {
|
||||
client := newPagesURLDownloadClient()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
|
||||
if err != nil {
|
||||
return nil, errors.New(errPagesPackageURLInvalid)
|
||||
}
|
||||
applyBrowserDownloadHeaders(req, "")
|
||||
resp, err := client.Do(req) //nolint:gosec // scheme validated; private hosts and insecure TLS intentionally allowed
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", errPagesPackageURLDownloadFailed, err)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func writeLimitedPackageTemp(body io.Reader, format pagesarchive.Format, maxPackageBytes int64) (tempPath, checksum string, size int64, err error) {
|
||||
temp, err := os.CreateTemp("", "openflare-pages-url-*."+safeTempSuffixOrBin(format))
|
||||
if err != nil {
|
||||
return "", "", 0, err
|
||||
}
|
||||
tempPath = temp.Name()
|
||||
defer func() {
|
||||
_ = temp.Close()
|
||||
if err != nil {
|
||||
_ = os.Remove(tempPath)
|
||||
}
|
||||
}()
|
||||
|
||||
hash := sha256.New()
|
||||
written, copyErr := io.Copy(io.MultiWriter(temp, hash), io.LimitReader(body, maxPackageBytes+1))
|
||||
if copyErr != nil {
|
||||
err = fmt.Errorf("%s: %w", errPagesPackageURLDownloadFailed, copyErr)
|
||||
return "", "", 0, err
|
||||
}
|
||||
if written > maxPackageBytes {
|
||||
err = errors.New(errPagesPackageURLTooLarge)
|
||||
return "", "", 0, err
|
||||
}
|
||||
if written == 0 {
|
||||
err = errors.New(errPagesPackageEmpty)
|
||||
return "", "", 0, err
|
||||
}
|
||||
return tempPath, hex.EncodeToString(hash.Sum(nil)), written, nil
|
||||
}
|
||||
|
||||
func ensurePackageFormat(tempPath string, format pagesarchive.Format, fileName string) (pagesarchive.Format, string, error) {
|
||||
if format != "" {
|
||||
return format, fileName, nil
|
||||
}
|
||||
detected, ok := sniffPackageFormat(tempPath)
|
||||
if !ok {
|
||||
return "", fileName, errors.New(errPagesPackageUnsupported)
|
||||
}
|
||||
if !strings.Contains(strings.ToLower(fileName), ".") {
|
||||
fileName = fileName + "." + pagesarchive.Extension(detected)
|
||||
}
|
||||
return detected, fileName, nil
|
||||
}
|
||||
|
||||
func sniffPackageFormat(tempPath string) (pagesarchive.Format, bool) {
|
||||
file, err := os.Open(tempPath) //nolint:gosec // temp path created by us
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
defer func() { _ = file.Close() }()
|
||||
head := make([]byte, pagesMagicSniffBytes)
|
||||
n, _ := io.ReadFull(file, head)
|
||||
if n <= 0 {
|
||||
return "", false
|
||||
}
|
||||
return pagesarchive.DetectFormatFromBytes(head[:n])
|
||||
}
|
||||
|
||||
func safeTempSuffixOrBin(format pagesarchive.Format) string {
|
||||
if format == "" {
|
||||
return "bin"
|
||||
}
|
||||
return safeTempSuffix(format)
|
||||
}
|
||||
|
||||
func applyBrowserDownloadHeaders(req *http.Request, referer string) {
|
||||
if req == nil {
|
||||
return
|
||||
}
|
||||
req.Header.Set("User-Agent", pagesBrowserUserAgent)
|
||||
req.Header.Set("Accept", pagesBrowserAccept)
|
||||
req.Header.Set("Accept-Language", pagesBrowserAcceptLang)
|
||||
req.Header.Set("Cache-Control", "no-cache")
|
||||
req.Header.Set("Pragma", "no-cache")
|
||||
req.Header.Set("Upgrade-Insecure-Requests", "1")
|
||||
req.Header.Set("Sec-Fetch-Dest", "document")
|
||||
req.Header.Set("Sec-Fetch-Mode", "navigate")
|
||||
req.Header.Set("Sec-Fetch-Site", "none")
|
||||
req.Header.Set("Sec-Fetch-User", "?1")
|
||||
req.Header.Set("Sec-Ch-Ua", pagesBrowserSecCHUA)
|
||||
req.Header.Set("Sec-Ch-Ua-Mobile", pagesBrowserSecCHUAMobile)
|
||||
req.Header.Set("Sec-Ch-Ua-Platform", pagesBrowserSecCHUAPlat)
|
||||
if referer != "" {
|
||||
req.Header.Set("Referer", referer)
|
||||
req.Header.Set("Sec-Fetch-Site", "cross-site")
|
||||
return
|
||||
}
|
||||
if req.URL != nil {
|
||||
req.Header.Set("Referer", req.URL.Scheme+"://"+req.URL.Host+"/")
|
||||
}
|
||||
}
|
||||
|
||||
func parseAndValidatePagesDownloadURL(raw string) (*url.URL, error) {
|
||||
value := strings.TrimSpace(raw)
|
||||
if value == "" {
|
||||
return nil, errors.New(errPagesPackageURLRequired)
|
||||
}
|
||||
parsed, err := url.Parse(value)
|
||||
if err != nil {
|
||||
return nil, errors.New(errPagesPackageURLInvalid)
|
||||
}
|
||||
if err := validatePagesDownloadURLValue(parsed); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func validatePagesDownloadURLValue(parsed *url.URL) error {
|
||||
if parsed == nil {
|
||||
return errors.New(errPagesPackageURLInvalid)
|
||||
}
|
||||
scheme := strings.ToLower(strings.TrimSpace(parsed.Scheme))
|
||||
if scheme != "http" && scheme != "https" {
|
||||
return errors.New(errPagesPackageURLInvalid)
|
||||
}
|
||||
if strings.TrimSpace(parsed.Hostname()) == "" {
|
||||
return errors.New(errPagesPackageURLInvalid)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func fileNameFromDownload(resp *http.Response, parsed *url.URL) string {
|
||||
if name := fileNameFromContentDisposition(resp); name != "" {
|
||||
return name
|
||||
}
|
||||
if parsed != nil {
|
||||
base := path.Base(parsed.Path)
|
||||
if base != "" && base != "." && base != "/" {
|
||||
return base
|
||||
}
|
||||
}
|
||||
return "package.bin"
|
||||
}
|
||||
|
||||
func fileNameFromContentDisposition(resp *http.Response) string {
|
||||
if resp == nil {
|
||||
return ""
|
||||
}
|
||||
cd := resp.Header.Get("Content-Disposition")
|
||||
if cd == "" {
|
||||
return ""
|
||||
}
|
||||
_, params, err := mime.ParseMediaType(cd)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
name := strings.TrimSpace(params["filename"])
|
||||
if name == "" {
|
||||
return ""
|
||||
}
|
||||
return path.Base(filepath.ToSlash(name))
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package pages
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParseAndValidatePagesDownloadURL(t *testing.T) {
|
||||
_, err := parseAndValidatePagesDownloadURL("")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "填写")
|
||||
|
||||
_, err = parseAndValidatePagesDownloadURL("ftp://example.com/a.zip")
|
||||
require.Error(t, err)
|
||||
|
||||
// Private / local hosts are allowed (operator-controlled artifact hosts).
|
||||
for _, raw := range []string{
|
||||
"http://127.0.0.1/a.zip",
|
||||
"https://localhost/a.zip",
|
||||
"http://192.168.1.10:8080/site.tar.gz",
|
||||
"https://example.com/dist/site.tar.gz?x=1",
|
||||
} {
|
||||
parsed, parseErr := parseAndValidatePagesDownloadURL(raw)
|
||||
require.NoError(t, parseErr, raw)
|
||||
assert.NotEmpty(t, parsed.Hostname(), raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadPagesPackageFromURLAllowsPrivateHost(t *testing.T) {
|
||||
var body bytes.Buffer
|
||||
zw := zip.NewWriter(&body)
|
||||
w, err := zw.Create("index.html")
|
||||
require.NoError(t, err)
|
||||
_, err = w.Write([]byte("ok"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, zw.Close())
|
||||
zipBytes := body.Bytes()
|
||||
|
||||
var sawBrowserUA bool
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.Contains(r.Header.Get("User-Agent"), "Mozilla") {
|
||||
sawBrowserUA = true
|
||||
}
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="remote-site.zip"`)
|
||||
w.Header().Set("Content-Type", "application/zip")
|
||||
_, _ = w.Write(zipBytes)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, server.URL+"/pkg.zip", nil)
|
||||
require.NoError(t, err)
|
||||
applyBrowserDownloadHeaders(req, "")
|
||||
assert.Contains(t, req.Header.Get("User-Agent"), "Mozilla")
|
||||
assert.Contains(t, req.Header.Get("Sec-Fetch-Mode"), "navigate")
|
||||
|
||||
tempPath, checksum, size, format, fileName, err := downloadPagesPackageFromURL(
|
||||
context.Background(),
|
||||
server.URL+"/pkg.zip",
|
||||
10*1024*1024,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = os.Remove(tempPath) })
|
||||
assert.True(t, sawBrowserUA)
|
||||
assert.NotEmpty(t, checksum)
|
||||
assert.Positive(t, size)
|
||||
assert.Equal(t, "zip", string(format))
|
||||
assert.Equal(t, "remote-site.zip", fileName)
|
||||
}
|
||||
|
||||
func TestUploadDeploymentFromURLPrivateHost(t *testing.T) {
|
||||
cleanup := setupPagesTestDB(t)
|
||||
defer cleanup()
|
||||
_, disableStorage := setupPagesStorageMock(t)
|
||||
defer disableStorage()
|
||||
ctx := context.Background()
|
||||
|
||||
var body bytes.Buffer
|
||||
zw := zip.NewWriter(&body)
|
||||
w, err := zw.Create("index.html")
|
||||
require.NoError(t, err)
|
||||
_, err = w.Write([]byte("from-url"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, zw.Close())
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="from-url.zip"`)
|
||||
_, _ = w.Write(body.Bytes())
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
project, err := CreateProject(ctx, Input{Name: "URL Site", Slug: "url-site", Enabled: true})
|
||||
require.NoError(t, err)
|
||||
|
||||
deployment, err := UploadDeploymentFromURL(ctx, project.ID, server.URL+"/from-url.zip", "root")
|
||||
require.NoError(t, err)
|
||||
assert.NotZero(t, deployment.ID)
|
||||
assert.Equal(t, 1, deployment.FileCount)
|
||||
}
|
||||
@@ -14,6 +14,10 @@ const (
|
||||
errPagesDeploymentMismatch = "pages 部署不属于该项目"
|
||||
errPagesDeleteActiveDeploy = "不能删除当前激活的 Pages 部署"
|
||||
errPagesPackageMissing = "缺少 Pages 部署包"
|
||||
errPagesPackageURLRequired = "请填写部署包下载链接"
|
||||
errPagesPackageURLInvalid = "部署包下载链接无效,仅支持 http/https"
|
||||
errPagesPackageURLDownloadFailed = "从链接下载部署包失败"
|
||||
errPagesPackageURLTooLarge = "链接指向的部署包超过大小限制"
|
||||
errPagesPackageNotZip = "pages 部署包必须是 .zip 文件" // legacy alias kept for tests
|
||||
errPagesPackageUnsupported = "pages 部署包仅支持 zip、tar.gz、tar.xz、tar.bz2、tar、7z 格式"
|
||||
errPagesPackageInvalidZip = "pages 部署包不是有效 zip 文件" // legacy alias
|
||||
|
||||
@@ -243,7 +243,7 @@ func ListDeploymentFiles(ctx context.Context, deploymentID uint) ([]DeploymentFi
|
||||
return views, nil
|
||||
}
|
||||
|
||||
// UploadDeployment 上传 Pages 部署包。
|
||||
// UploadDeployment 上传 Pages 部署包(本地 multipart 文件)。
|
||||
func UploadDeployment(ctx context.Context, projectID uint, fileHeader *multipart.FileHeader, createdBy string) (*DeploymentView, error) {
|
||||
project, err := model.GetPagesProjectByID(ctx, projectID)
|
||||
if err != nil {
|
||||
@@ -253,16 +253,52 @@ func UploadDeployment(ctx context.Context, projectID uint, fileHeader *multipart
|
||||
return nil, errors.New(errPagesPackageMissing)
|
||||
}
|
||||
limits := resolvePagesLimits(ctx)
|
||||
rootDir, err := validateAndNormalizePagesRootDir(project.RootDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entryFile := normalizePagesEntryFile(project.EntryFile)
|
||||
tempPath, checksum, _, format, err := persistPagesUploadTemp(fileHeader, limits.PackageBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = os.Remove(tempPath) }()
|
||||
return createDeploymentFromTempPackage(ctx, project, tempPath, checksum, format, fileHeader.Filename, createdBy, limits)
|
||||
}
|
||||
|
||||
// UploadFromURLInput is the request body for downloading a deployment package from a remote URL.
|
||||
type UploadFromURLInput struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// UploadDeploymentFromURL downloads a package from url and creates a deployment.
|
||||
func UploadDeploymentFromURL(ctx context.Context, projectID uint, rawURL string, createdBy string) (*DeploymentView, error) {
|
||||
project, err := model.GetPagesProjectByID(ctx, projectID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
limits := resolvePagesLimits(ctx)
|
||||
tempPath, checksum, _, format, fileName, err := downloadPagesPackageFromURL(ctx, rawURL, limits.PackageBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = os.Remove(tempPath) }()
|
||||
return createDeploymentFromTempPackage(ctx, project, tempPath, checksum, format, fileName, createdBy, limits)
|
||||
}
|
||||
|
||||
func createDeploymentFromTempPackage(
|
||||
ctx context.Context,
|
||||
project *model.PagesProject,
|
||||
tempPath string,
|
||||
checksum string,
|
||||
format pagesarchive.Format,
|
||||
fileName string,
|
||||
createdBy string,
|
||||
limits pagesLimits,
|
||||
) (*DeploymentView, error) {
|
||||
if project == nil {
|
||||
return nil, errors.New(errPagesProjectNotFound)
|
||||
}
|
||||
rootDir, err := validateAndNormalizePagesRootDir(project.RootDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entryFile := normalizePagesEntryFile(project.EntryFile)
|
||||
manifest, err := inspectPagesPackage(tempPath, format, rootDir, entryFile, limits)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -272,7 +308,7 @@ func UploadDeployment(ctx context.Context, projectID uint, fileHeader *multipart
|
||||
tempPath,
|
||||
checksum,
|
||||
project.Slug,
|
||||
fileHeader.Filename,
|
||||
fileName,
|
||||
format,
|
||||
)
|
||||
if err != nil {
|
||||
@@ -321,8 +357,6 @@ func UploadDeployment(ctx context.Context, projectID uint, fileHeader *multipart
|
||||
}
|
||||
ingestCommitted = true
|
||||
|
||||
// History prune must not fail the already-committed upload. Log and continue;
|
||||
// a later upload (or a retry pass inside prune) will re-attempt cleanup.
|
||||
if pruneErr := pruneProjectDeploymentHistory(ctx, project.ID, limits.HistoryCount); pruneErr != nil {
|
||||
logger.ErrorF(ctx,
|
||||
"[Pages] prune deployment history failed: project_id=%d keep=%d error=%v",
|
||||
|
||||
@@ -190,13 +190,13 @@ func ListDeploymentsHandler(c *gin.Context) {
|
||||
|
||||
// UploadDeploymentHandler 上传 Pages 部署包。
|
||||
// @Summary 上传 Pages 部署包
|
||||
// @Description 为指定项目上传 ZIP 部署包,需要管理员权限
|
||||
// @Description 为指定项目上传静态资源压缩包(zip/tar.gz/tar.xz/tar.bz2/tar/7z),需要管理员权限
|
||||
// @Tags openflare-pages
|
||||
// @Accept multipart/form-data
|
||||
// @Produce json
|
||||
// @Security SessionCookie
|
||||
// @Param id path int true "项目 ID"
|
||||
// @Param package formData file true "部署包 ZIP 文件"
|
||||
// @Param package formData file true "部署包文件"
|
||||
// @Success 200 {object} response.Any{data=pages.DeploymentView} "部署记录"
|
||||
// @Failure 400 {object} response.Any "参数错误"
|
||||
// @Failure 401 {object} response.Any "未登录"
|
||||
@@ -221,6 +221,39 @@ func UploadDeploymentHandler(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, response.OK(deployment))
|
||||
}
|
||||
|
||||
// UploadDeploymentFromURLHandler 从 URL 下载并创建 Pages 部署。
|
||||
// @Summary 从 URL 导入 Pages 部署包
|
||||
// @Description 从用户提供的 HTTP(S) 链接下载部署包并创建部署记录;服务端使用浏览器伪装请求头拉取,允许内网地址与不安全 TLS 证书,需要管理员权限
|
||||
// @Tags openflare-pages
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security SessionCookie
|
||||
// @Param id path int true "项目 ID"
|
||||
// @Param request body pages.UploadFromURLInput true "下载链接"
|
||||
// @Success 200 {object} response.Any{data=pages.DeploymentView} "部署记录"
|
||||
// @Failure 400 {object} response.Any "参数错误"
|
||||
// @Failure 401 {object} response.Any "未登录"
|
||||
// @Failure 404 {object} response.Any "无权限或不存在"
|
||||
// @Failure 404 {object} response.Any "项目不存在"
|
||||
// @Failure 500 {object} response.Any "内部错误"
|
||||
// @Router /api/v1/d/pages/{id}/deployments/upload-from-url [post]
|
||||
func UploadDeploymentFromURLHandler(c *gin.Context) {
|
||||
id, ok := apiutil.IDParam(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req UploadFromURLInput
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.AbortBadRequest(c, errPagesPackageURLRequired)
|
||||
return
|
||||
}
|
||||
deployment, err := UploadDeploymentFromURL(c.Request.Context(), id, req.URL, "")
|
||||
if handleLogicError(c, err) {
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, response.OK(deployment))
|
||||
}
|
||||
|
||||
// ActivateDeploymentHandler 激活 Pages 部署。
|
||||
// @Summary 激活 Pages 部署
|
||||
// @Description 将指定部署设为项目当前生效版本,需要管理员权限
|
||||
|
||||
@@ -20,6 +20,7 @@ func registerPagesRoutes(apiGroup *gin.RouterGroup) {
|
||||
pagesRoute.POST("/:id/delete", pages.DeleteProjectHandler)
|
||||
pagesRoute.GET("/:id/deployments", pages.ListDeploymentsHandler)
|
||||
pagesRoute.POST("/:id/deployments/upload", pages.UploadDeploymentHandler)
|
||||
pagesRoute.POST("/:id/deployments/upload-from-url", pages.UploadDeploymentFromURLHandler)
|
||||
pagesRoute.POST("/:id/deployments/:deployment_id/activate", pages.ActivateDeploymentHandler)
|
||||
pagesRoute.POST("/:id/deployments/:deployment_id/delete", pages.DeleteDeploymentHandler)
|
||||
pagesRoute.GET("/deployments/:deployment_id/files", pages.ListDeploymentFilesHandler)
|
||||
|
||||
Reference in New Issue
Block a user