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:
ryan
2026-07-17 17:55:12 +08:00
parent ce736e2de4
commit 79820b33eb
15 changed files with 1196 additions and 103 deletions
+1
View File
@@ -34,6 +34,7 @@ sidebar: false
- 明确 Pages 历史部署保留语义为每个项目最多 N 条(激活必留、其余按从新到旧填充),裁剪失败会记录日志且不回滚已成功上传。 - 明确 Pages 历史部署保留语义为每个项目最多 N 条(激活必留、其余按从新到旧填充),裁剪失败会记录日志且不回滚已成功上传。
- 主配置版本与 Pages 部署双轨管理:Agent 以 Pages 项目 ID 为锚点请求最新激活部署包,项目内切换激活版本无需重新发布主配置即可在边缘自动更新。 - 主配置版本与 Pages 部署双轨管理:Agent 以 Pages 项目 ID 为锚点请求最新激活部署包,项目内切换激活版本无需重新发布主配置即可在边缘自动更新。
- Agent 边缘仅保留每个 Pages 项目的最新部署包,新包就绪并切换成功后清理旧 release;拉取 latest 时增加 hash 二次校验与重试以降低激活竞态失败;单个项目同步失败不再阻塞同批其它项目。 - Agent 边缘仅保留每个 Pages 项目的最新部署包,新包就绪并切换成功后清理旧 release;拉取 latest 时增加 hash 二次校验与重试以降低激活竞态失败;单个项目同步失败不再阻塞同批其它项目。
- Pages 支持从 URL 导入部署包:填写下载链接后由控制面代为拉取并创建部署。
## [v3.3.0] - 2026-07-14 ## [v3.3.0] - 2026-07-14
+1 -1
View File
@@ -19,7 +19,7 @@
## 核心功能 ## 核心功能
Pages 静态托管子系统包含以下核心能力: 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 个历史部署,并可随时激活和回滚。 * **不可变部署快照**:每次上传产生一个带唯一 ID 和 SHA-256 Checksum 的不可变部署记录。支持按系统配置保留最近 N 个历史部署,并可随时激活和回滚。
* **SPA Fallback 支持**:支持对单页应用(SPA)进行 Fallback 路由配置,请求找不到静态文件时自动重定向到入口文件。 * **SPA Fallback 支持**:支持对单页应用(SPA)进行 Fallback 路由配置,请求找不到静态文件时自动重定向到入口文件。
* **内置 API 反代服务**:支持在 Pages 规则内一键启用 API 代理,消除跨域问题,将请求转发给指定的后端服务。 * **内置 API 反代服务**:支持在 Pages 规则内一键启用 API 代理,消除跨域问题,将请求转发给指定的后端服务。
+212 -4
View File
@@ -4475,7 +4475,7 @@ const docTemplate = `{
"AgentTokenAuth": [] "AgentTokenAuth": []
} }
], ],
"description": "返回 upload 框架记录的 SHA-256 哈希,供 Agent 对比本地缓存并按需拉取部署包", "description": "返回 upload 框架记录的 SHA-256 哈希,供 Agent 对比本地缓存并按需拉取部署包(兼容旧路径)",
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -4533,7 +4533,7 @@ const docTemplate = `{
"AgentTokenAuth": [] "AgentTokenAuth": []
} }
], ],
"description": "流式下载指定部署的静态资源压缩包,供 Agent 边缘分发", "description": "流式下载指定部署的静态资源压缩包,供 Agent 边缘分发(兼容旧路径)",
"produces": [ "produces": [
"application/octet-stream" "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": { "/api/v1/agent/waf/ip-groups/sync": {
"post": { "post": {
"security": [ "security": [
@@ -8198,7 +8302,7 @@ const docTemplate = `{
"SessionCookie": [] "SessionCookie": []
} }
], ],
"description": "为指定项目上传 ZIP 部署包,需要管理员权限", "description": "为指定项目上传静态资源压缩包(zip/tar.gz/tar.xz/tar.bz2/tar/7z),需要管理员权限",
"consumes": [ "consumes": [
"multipart/form-data" "multipart/form-data"
], ],
@@ -8219,7 +8323,7 @@ const docTemplate = `{
}, },
{ {
"type": "file", "type": "file",
"description": "部署包 ZIP 文件", "description": "部署包文件",
"name": "package", "name": "package",
"in": "formData", "in": "formData",
"required": true "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": { "/api/v1/d/pages/{id}/deployments/{deployment_id}/activate": {
"post": { "post": {
"security": [ "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": { "github_com_Rain-kl_Wavelet_pkg_protocol.WAFIPGroup": {
"type": "object", "type": "object",
"properties": { "properties": {
@@ -16821,6 +17021,14 @@ const docTemplate = `{
} }
} }
}, },
"pages.UploadFromURLInput": {
"type": "object",
"properties": {
"url": {
"type": "string"
}
}
},
"pages.View": { "pages.View": {
"type": "object", "type": "object",
"properties": { "properties": {
+212 -4
View File
@@ -4468,7 +4468,7 @@
"AgentTokenAuth": [] "AgentTokenAuth": []
} }
], ],
"description": "返回 upload 框架记录的 SHA-256 哈希,供 Agent 对比本地缓存并按需拉取部署包", "description": "返回 upload 框架记录的 SHA-256 哈希,供 Agent 对比本地缓存并按需拉取部署包(兼容旧路径)",
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -4526,7 +4526,7 @@
"AgentTokenAuth": [] "AgentTokenAuth": []
} }
], ],
"description": "流式下载指定部署的静态资源压缩包,供 Agent 边缘分发", "description": "流式下载指定部署的静态资源压缩包,供 Agent 边缘分发(兼容旧路径)",
"produces": [ "produces": [
"application/octet-stream" "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": { "/api/v1/agent/waf/ip-groups/sync": {
"post": { "post": {
"security": [ "security": [
@@ -8191,7 +8295,7 @@
"SessionCookie": [] "SessionCookie": []
} }
], ],
"description": "为指定项目上传 ZIP 部署包,需要管理员权限", "description": "为指定项目上传静态资源压缩包(zip/tar.gz/tar.xz/tar.bz2/tar/7z),需要管理员权限",
"consumes": [ "consumes": [
"multipart/form-data" "multipart/form-data"
], ],
@@ -8212,7 +8316,7 @@
}, },
{ {
"type": "file", "type": "file",
"description": "部署包 ZIP 文件", "description": "部署包文件",
"name": "package", "name": "package",
"in": "formData", "in": "formData",
"required": true "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": { "/api/v1/d/pages/{id}/deployments/{deployment_id}/activate": {
"post": { "post": {
"security": [ "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": { "github_com_Rain-kl_Wavelet_pkg_protocol.WAFIPGroup": {
"type": "object", "type": "object",
"properties": { "properties": {
@@ -16814,6 +17014,14 @@
} }
} }
}, },
"pages.UploadFromURLInput": {
"type": "object",
"properties": {
"url": {
"type": "string"
}
}
},
"pages.View": { "pages.View": {
"type": "object", "type": "object",
"properties": { "properties": {
+131 -4
View File
@@ -778,6 +778,15 @@ definitions:
hash: hash:
type: string type: string
type: object 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: github_com_Rain-kl_Wavelet_pkg_protocol.WAFIPGroup:
properties: properties:
checksum: checksum:
@@ -2499,6 +2508,11 @@ definitions:
spa_fallback_path: spa_fallback_path:
type: string type: string
type: object type: object
pages.UploadFromURLInput:
properties:
url:
type: string
type: object
pages.View: pages.View:
properties: properties:
active_deployment: active_deployment:
@@ -6641,7 +6655,7 @@ paths:
- openflare-agent - openflare-agent
/api/v1/agent/pages/deployments/{deployment_id}/hash: /api/v1/agent/pages/deployments/{deployment_id}/hash:
get: get:
description: 返回 upload 框架记录的 SHA-256 哈希,供 Agent 对比本地缓存并按需拉取部署包 description: 返回 upload 框架记录的 SHA-256 哈希,供 Agent 对比本地缓存并按需拉取部署包(兼容旧路径)
parameters: parameters:
- description: 部署 ID - description: 部署 ID
in: path in: path
@@ -6675,7 +6689,7 @@ paths:
- openflare-agent - openflare-agent
/api/v1/agent/pages/deployments/{deployment_id}/package: /api/v1/agent/pages/deployments/{deployment_id}/package:
get: get:
description: 流式下载指定部署的静态资源压缩包,供 Agent 边缘分发 description: 流式下载指定部署的静态资源压缩包,供 Agent 边缘分发(兼容旧路径)
parameters: parameters:
- description: 部署 ID - description: 部署 ID
in: path in: path
@@ -6702,6 +6716,69 @@ paths:
summary: 下载 Pages 部署包 summary: 下载 Pages 部署包
tags: tags:
- openflare-agent - 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: /api/v1/agent/waf/ip-groups/sync:
post: post:
consumes: consumes:
@@ -8930,14 +9007,14 @@ paths:
post: post:
consumes: consumes:
- multipart/form-data - multipart/form-data
description: 为指定项目上传 ZIP 部署包,需要管理员权限 description: 为指定项目上传静态资源压缩包(zip/tar.gz/tar.xz/tar.bz2/tar/7z),需要管理员权限
parameters: parameters:
- description: 项目 ID - description: 项目 ID
in: path in: path
name: id name: id
required: true required: true
type: integer type: integer
- description: 部署包 ZIP 文件 - description: 部署包文件
in: formData in: formData
name: package name: package
required: true required: true
@@ -8975,6 +9052,56 @@ paths:
summary: 上传 Pages 部署包 summary: 上传 Pages 部署包
tags: tags:
- openflare-pages - 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: /api/v1/d/pages/{id}/update:
post: post:
consumes: consumes:
@@ -468,7 +468,8 @@ export function OpenFlareOpsSettings() {
/> />
</div> </div>
<p className='text-xs text-muted-foreground'> <p className='text-xs text-muted-foreground'>
每个项目最多保留 N 条部署:激活部署始终保留,其余按从新到旧填充;超出的非激活部署会在上传成功后自动清理。支持 每个项目最多保留 N
条部署:激活部署始终保留,其余按从新到旧填充;超出的非激活部署会在上传成功后自动清理。支持
zip、tar.gz、tar.xz、tar.bz2、tar、7z 格式。 zip、tar.gz、tar.xz、tar.bz2、tar、7z 格式。
</p> </p>
</CardContent> </CardContent>
@@ -2,7 +2,7 @@
import { useRef, useState } from 'react'; import { useRef, useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query'; 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 { toast } from 'sonner';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -17,6 +17,7 @@ import {
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
import { Progress } from '@/components/ui/progress'; import { Progress } from '@/components/ui/progress';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { PagesService } from '@/lib/services/openflare'; import { PagesService } from '@/lib/services/openflare';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
@@ -61,12 +62,15 @@ export function DeploymentUploadDialog({
}: DeploymentUploadDialogProps) { }: DeploymentUploadDialogProps) {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const fileInputRef = useRef<HTMLInputElement>(null); const fileInputRef = useRef<HTMLInputElement>(null);
const [mode, setMode] = useState<'file' | 'url'>('file');
const [file, setFile] = useState<File | null>(null); const [file, setFile] = useState<File | null>(null);
const [packageURL, setPackageURL] = useState('');
const [isDragActive, setIsDragActive] = useState(false); const [isDragActive, setIsDragActive] = useState(false);
const [uploadProgress, setUploadProgress] = useState<number | null>(null); const [uploadProgress, setUploadProgress] = useState<number | null>(null);
const resetForm = () => { const resetForm = () => {
setFile(null); setFile(null);
setPackageURL('');
setIsDragActive(false); setIsDragActive(false);
setUploadProgress(null); setUploadProgress(null);
if (fileInputRef.current) fileInputRef.current.value = ''; if (fileInputRef.current) fileInputRef.current.value = '';
@@ -77,7 +81,17 @@ export function DeploymentUploadDialog({
onOpenChange(nextOpen); 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: () => { mutationFn: () => {
if (!file) throw new Error('请选择部署包'); if (!file) throw new Error('请选择部署包');
return PagesService.uploadDeployment(projectId, { return PagesService.uploadDeployment(projectId, {
@@ -87,13 +101,7 @@ export function DeploymentUploadDialog({
}, },
onSuccess: async () => { onSuccess: async () => {
toast.success('部署包上传成功'); toast.success('部署包上传成功');
await Promise.all([ await invalidate();
queryClient.invalidateQueries({
queryKey: deploymentsQueryKey(projectId),
}),
queryClient.invalidateQueries({ queryKey: projectQueryKey(projectId) }),
queryClient.invalidateQueries({ queryKey: projectsQueryKey }),
]);
handleClose(false); handleClose(false);
}, },
onError: (error) => { 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) => { const handleFileSelect = (selected: File | null) => {
if (!selected) return; if (!selected) return;
if (!isSupportedPagesPackage(selected.name)) { if (!isSupportedPagesPackage(selected.name)) {
@@ -111,80 +140,129 @@ export function DeploymentUploadDialog({
setFile(selected); setFile(selected);
}; };
const handleSubmit = () => {
if (mode === 'file') {
uploadFileMutation.mutate();
return;
}
uploadURLMutation.mutate();
};
const canSubmit =
mode === 'file' ? Boolean(file) : packageURL.trim().length > 0;
return ( return (
<Dialog open={open} onOpenChange={handleClose}> <Dialog open={open} onOpenChange={handleClose}>
<DialogContent> <DialogContent className='sm:max-w-lg'>
<DialogHeader> <DialogHeader>
<DialogTitle>上传部署包</DialogTitle> <DialogTitle>上传部署包</DialogTitle>
<DialogDescription> <DialogDescription>
上传已构建的静态资源压缩包(zip / tar.gz / tar.xz / tar.bz2 / tar / 支持本地上传或从 URL 下载静态资源压缩包(zip / tar.gz / tar.xz /
7z),部署后可在列表中激活。 tar.bz2 / tar / 7z),创建部署后可在列表中激活。
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<div <Tabs
className={cn( value={mode}
'rounded-lg border border-dashed p-8 text-center transition', onValueChange={(value) => setMode(value as 'file' | 'url')}
isDragActive ? 'border-primary bg-primary/5' : 'bg-muted/20', className='w-full'
)}
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' /> <TabsList className='grid w-full grid-cols-2'>
<p className='mt-3 text-sm'>拖拽部署包到此处,或点击选择文件</p> <TabsTrigger value='file'>本地上传</TabsTrigger>
<p className='mt-1 text-xs text-muted-foreground'> <TabsTrigger value='url'>从 URL 下载</TabsTrigger>
支持 zip、tar.gz、tar.xz、tar.bz2、tar、7z </TabsList>
</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>
{file ? ( <TabsContent value='file' className='space-y-4 mt-4'>
<div className='rounded-lg border border-dashed px-4 py-3 text-sm'> <div
<p className='font-medium'>{file.name}</p> className={cn(
<p className='text-xs text-muted-foreground mt-1'> 'rounded-lg border border-dashed p-8 text-center transition',
{formatBytes(file.size)} isDragActive ? 'border-primary bg-primary/5' : 'bg-muted/20',
</p> )}
</div> onDragEnter={(e) => {
) : null} e.preventDefault();
setIsDragActive(true);
{uploadProgress !== null ? ( }}
<div className='space-y-1.5'> onDragOver={(e) => e.preventDefault()}
<div className='flex justify-between text-xs text-muted-foreground'> onDragLeave={(e) => {
<span>{uploadProgress >= 100 ? '服务端处理中' : '上传进度'}</span> e.preventDefault();
<span> setIsDragActive(false);
{uploadProgress >= 100 ? '请稍候' : `${uploadProgress}%`} }}
</span> 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> </div>
<Progress value={uploadProgress >= 100 ? 100 : uploadProgress} />
</div> {file ? (
) : null} <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'> <div className='space-y-1.5'>
<Label htmlFor='entryFile'>入口文件</Label> <Label htmlFor='entryFile'>入口文件</Label>
@@ -195,15 +273,14 @@ export function DeploymentUploadDialog({
<Button variant='outline' onClick={() => handleClose(false)}> <Button variant='outline' onClick={() => handleClose(false)}>
取消 取消
</Button> </Button>
<Button <Button onClick={handleSubmit} disabled={!canSubmit || isPending}>
onClick={() => uploadMutation.mutate()} {isPending ? (
disabled={!file || uploadMutation.isPending}
>
{uploadMutation.isPending ? (
<> <>
<Loader2 className='size-4 animate-spin mr-1' /> <Loader2 className='size-4 animate-spin mr-1' />
上传中... {mode === 'url' ? '下载中...' : '上传中...'}
</> </>
) : mode === 'url' ? (
'下载并创建部署'
) : ( ) : (
'上传并创建部署' '上传并创建部署'
)} )}
@@ -8,6 +8,7 @@ import { OpenFlareBaseService } from './base.service';
import type { import type {
PagesDeployment, PagesDeployment,
PagesDeploymentFile, PagesDeploymentFile,
PagesDeploymentUploadFromURLPayload,
PagesDeploymentUploadPayload, PagesDeploymentUploadPayload,
PagesProject, PagesProject,
PagesProjectPayload, 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( static activateDeployment(
projectId: number, projectId: number,
deploymentId: number, deploymentId: number,
+4
View File
@@ -469,6 +469,10 @@ export interface PagesDeploymentUploadPayload {
onProgress?: (percent: number) => void; onProgress?: (percent: number) => void;
} }
export interface PagesDeploymentUploadFromURLPayload {
url: string;
}
// ==================== Origins ==================== // ==================== Origins ====================
export interface OriginItem { 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)
}
+4
View File
@@ -14,6 +14,10 @@ const (
errPagesDeploymentMismatch = "pages 部署不属于该项目" errPagesDeploymentMismatch = "pages 部署不属于该项目"
errPagesDeleteActiveDeploy = "不能删除当前激活的 Pages 部署" errPagesDeleteActiveDeploy = "不能删除当前激活的 Pages 部署"
errPagesPackageMissing = "缺少 Pages 部署包" errPagesPackageMissing = "缺少 Pages 部署包"
errPagesPackageURLRequired = "请填写部署包下载链接"
errPagesPackageURLInvalid = "部署包下载链接无效,仅支持 http/https"
errPagesPackageURLDownloadFailed = "从链接下载部署包失败"
errPagesPackageURLTooLarge = "链接指向的部署包超过大小限制"
errPagesPackageNotZip = "pages 部署包必须是 .zip 文件" // legacy alias kept for tests errPagesPackageNotZip = "pages 部署包必须是 .zip 文件" // legacy alias kept for tests
errPagesPackageUnsupported = "pages 部署包仅支持 zip、tar.gz、tar.xz、tar.bz2、tar、7z 格式" errPagesPackageUnsupported = "pages 部署包仅支持 zip、tar.gz、tar.xz、tar.bz2、tar、7z 格式"
errPagesPackageInvalidZip = "pages 部署包不是有效 zip 文件" // legacy alias errPagesPackageInvalidZip = "pages 部署包不是有效 zip 文件" // legacy alias
+43 -9
View File
@@ -243,7 +243,7 @@ func ListDeploymentFiles(ctx context.Context, deploymentID uint) ([]DeploymentFi
return views, nil return views, nil
} }
// UploadDeployment 上传 Pages 部署包。 // UploadDeployment 上传 Pages 部署包(本地 multipart 文件)。
func UploadDeployment(ctx context.Context, projectID uint, fileHeader *multipart.FileHeader, createdBy string) (*DeploymentView, error) { func UploadDeployment(ctx context.Context, projectID uint, fileHeader *multipart.FileHeader, createdBy string) (*DeploymentView, error) {
project, err := model.GetPagesProjectByID(ctx, projectID) project, err := model.GetPagesProjectByID(ctx, projectID)
if err != nil { if err != nil {
@@ -253,16 +253,52 @@ func UploadDeployment(ctx context.Context, projectID uint, fileHeader *multipart
return nil, errors.New(errPagesPackageMissing) return nil, errors.New(errPagesPackageMissing)
} }
limits := resolvePagesLimits(ctx) 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) tempPath, checksum, _, format, err := persistPagesUploadTemp(fileHeader, limits.PackageBytes)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer func() { _ = os.Remove(tempPath) }() 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) manifest, err := inspectPagesPackage(tempPath, format, rootDir, entryFile, limits)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -272,7 +308,7 @@ func UploadDeployment(ctx context.Context, projectID uint, fileHeader *multipart
tempPath, tempPath,
checksum, checksum,
project.Slug, project.Slug,
fileHeader.Filename, fileName,
format, format,
) )
if err != nil { if err != nil {
@@ -321,8 +357,6 @@ func UploadDeployment(ctx context.Context, projectID uint, fileHeader *multipart
} }
ingestCommitted = true 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 { if pruneErr := pruneProjectDeploymentHistory(ctx, project.ID, limits.HistoryCount); pruneErr != nil {
logger.ErrorF(ctx, logger.ErrorF(ctx,
"[Pages] prune deployment history failed: project_id=%d keep=%d error=%v", "[Pages] prune deployment history failed: project_id=%d keep=%d error=%v",
+35 -2
View File
@@ -190,13 +190,13 @@ func ListDeploymentsHandler(c *gin.Context) {
// UploadDeploymentHandler 上传 Pages 部署包。 // UploadDeploymentHandler 上传 Pages 部署包。
// @Summary 上传 Pages 部署包 // @Summary 上传 Pages 部署包
// @Description 为指定项目上传 ZIP 部署包,需要管理员权限 // @Description 为指定项目上传静态资源压缩包(zip/tar.gz/tar.xz/tar.bz2/tar/7z),需要管理员权限
// @Tags openflare-pages // @Tags openflare-pages
// @Accept multipart/form-data // @Accept multipart/form-data
// @Produce json // @Produce json
// @Security SessionCookie // @Security SessionCookie
// @Param id path int true "项目 ID" // @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} "部署记录" // @Success 200 {object} response.Any{data=pages.DeploymentView} "部署记录"
// @Failure 400 {object} response.Any "参数错误" // @Failure 400 {object} response.Any "参数错误"
// @Failure 401 {object} response.Any "未登录" // @Failure 401 {object} response.Any "未登录"
@@ -221,6 +221,39 @@ func UploadDeploymentHandler(c *gin.Context) {
c.JSON(http.StatusOK, response.OK(deployment)) 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 部署。 // ActivateDeploymentHandler 激活 Pages 部署。
// @Summary 激活 Pages 部署 // @Summary 激活 Pages 部署
// @Description 将指定部署设为项目当前生效版本,需要管理员权限 // @Description 将指定部署设为项目当前生效版本,需要管理员权限
@@ -20,6 +20,7 @@ func registerPagesRoutes(apiGroup *gin.RouterGroup) {
pagesRoute.POST("/:id/delete", pages.DeleteProjectHandler) pagesRoute.POST("/:id/delete", pages.DeleteProjectHandler)
pagesRoute.GET("/:id/deployments", pages.ListDeploymentsHandler) pagesRoute.GET("/:id/deployments", pages.ListDeploymentsHandler)
pagesRoute.POST("/:id/deployments/upload", pages.UploadDeploymentHandler) 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/activate", pages.ActivateDeploymentHandler)
pagesRoute.POST("/:id/deployments/:deployment_id/delete", pages.DeleteDeploymentHandler) pagesRoute.POST("/:id/deployments/:deployment_id/delete", pages.DeleteDeploymentHandler)
pagesRoute.GET("/deployments/:deployment_id/files", pages.ListDeploymentFilesHandler) pagesRoute.GET("/deployments/:deployment_id/files", pages.ListDeploymentFilesHandler)