fix: 加固 Windows 发布脚本

This commit is contained in:
Nixevol
2026-07-16 12:16:00 +08:00
parent 4b548d9367
commit 8eeba3a83f
4 changed files with 216 additions and 36 deletions
+199 -34
View File
@@ -5,11 +5,11 @@
"""构建非 Docker 发布包(宝塔/1Panel 用 Node/PM2 部署)。
两种形态(代码 payload 相同,辅助文件/命名不同):
- 全新包(默认 / --fresh):含 .env.example 与 README-deploy.md,首次启动进入安装向导。
- 全新包(默认 / --fresh):含 .env.example、init.sh / init.ps1 与 README-deploy.md,首次启动进入安装向导。
- 升级包(--upgrade):不含配置示例,附 upgrade.sh / upgrade.ps1 与 README-upgrade.md,
就地替换代码,保留并不触碰服务器上的 config/ storage/ backups/。
就地替换代码,保留并不触碰服务器上的 .env / storage/ backups/。
配置/密钥/数据均在服务器的 config/ storage/ backups/ 与数据库中,发布包不写死这些内容。
配置/密钥/数据均在服务器的 .env / storage/ backups/ 与数据库中,发布包不写死这些内容。
"""
from __future__ import annotations
@@ -134,7 +134,32 @@ pnpm --dir apps/api exec prisma generate --schema ./prisma/schema.prisma
node migrate.cjs
"""
INSTALL_DEPS_PS1 = """$ErrorActionPreference = 'Stop'
INSTALL_DEPS_PS1 = r"""[CmdletBinding()]
param()
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
function Resolve-NativeCommand {
param([Parameter(Mandatory=$true)][string]$Name)
$command = Get-Command $Name -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
if ($null -eq $command) { return $null }
return $command.Source
}
function Invoke-NativeCommand {
param(
[Parameter(Mandatory=$true)][string]$FilePath,
[string[]]$Arguments = @(),
[string]$FailureMessage = ''
)
& $FilePath @Arguments
$exitCode = $LASTEXITCODE
if ($exitCode -ne 0) {
if ($FailureMessage) { throw "$FailureMessage(退出码 $exitCode)。" }
throw "原生命令执行失败(退出码 $exitCode):$FilePath"
}
}
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $root
$pnpmVersion = if ($env:PNPM_VERSION) { $env:PNPM_VERSION } else { '10.28.0' }
@@ -144,27 +169,85 @@ if (-not $env:npm_config_registry) { $env:npm_config_registry = $npmRegistry }
if (-not $env:PRISMA_ENGINES_MIRROR) {
$env:PRISMA_ENGINES_MIRROR = 'https://registry.npmmirror.com/-/binary/prisma'
}
if (-not (Get-Command node -ErrorAction SilentlyContinue)) {
$nodePath = Resolve-NativeCommand 'node'
if (-not $nodePath) {
throw '未找到 Node.js,请先安装 Node.js 24 LTS(最低 20.11.1)。'
}
if (-not (Get-Command pnpm -ErrorAction SilentlyContinue)) {
if (Get-Command corepack -ErrorAction SilentlyContinue) {
corepack enable
corepack prepare "pnpm@$pnpmVersion" --activate
$nodeVersion = [string](Invoke-NativeCommand -FilePath $nodePath -Arguments @('--version') | Select-Object -Last 1)
$nodeVersion = $nodeVersion.Trim()
if ($nodeVersion -notmatch '^v?(\d+)\.(\d+)\.(\d+)') {
throw "无法识别 Node.js 版本:$nodeVersion"
}
$nodeMajor = [int]$Matches[1]
$nodeMinor = [int]$Matches[2]
$nodePatch = [int]$Matches[3]
$nodeSupported = ($nodeMajor -gt 20) -or (
$nodeMajor -eq 20 -and ($nodeMinor -gt 11 -or ($nodeMinor -eq 11 -and $nodePatch -ge 1))
)
if (-not $nodeSupported) { throw 'Node.js 版本过低,最低需要 20.11.1。' }
$pnpmPath = Resolve-NativeCommand 'pnpm'
$actualPnpmVersion = ''
if ($pnpmPath) {
$versionOutput = & $pnpmPath --version
$versionExitCode = $LASTEXITCODE
if ($versionExitCode -eq 0) {
$actualPnpmVersion = ([string]($versionOutput | Select-Object -Last 1)).Trim()
} else {
throw '未找到 corepack 或 pnpm。'
Write-Host "[install] 当前 pnpm 无法运行(退出码 $versionExitCode),将尝试用 corepack 修复。"
}
}
$actualPnpmVersion = pnpm --version
if (-not $actualPnpmVersion.StartsWith('10.')) {
$corepackPath = Resolve-NativeCommand 'corepack'
if (-not $corepackPath) { throw '未找到可用的 pnpm 10 或 corepack。' }
Invoke-NativeCommand -FilePath $corepackPath -Arguments @('enable') -FailureMessage 'corepack enable 失败'
Invoke-NativeCommand -FilePath $corepackPath -Arguments @('prepare', "pnpm@$pnpmVersion", '--activate') -FailureMessage '准备 pnpm 失败'
$pnpmPath = Resolve-NativeCommand 'pnpm'
if (-not $pnpmPath) { throw 'corepack 执行后仍未找到 pnpm。' }
$actualPnpmVersion = [string](Invoke-NativeCommand -FilePath $pnpmPath -Arguments @('--version') | Select-Object -Last 1)
$actualPnpmVersion = $actualPnpmVersion.Trim()
}
if (-not $actualPnpmVersion.StartsWith('10.')) {
throw "需要 pnpm 10,当前版本为 $actualPnpmVersion。"
}
Write-Host "[install] Node $(node --version),pnpm $actualPnpmVersion"
Write-Host "[install] Node $nodeVersion,pnpm $actualPnpmVersion"
Write-Host "[install] npm 镜像:$env:npm_config_registry"
Write-Host "[install] Prisma 引擎镜像:$env:PRISMA_ENGINES_MIRROR"
pnpm install --prod --frozen-lockfile
pnpm --dir apps/api exec prisma generate --schema ./prisma/schema.prisma
node migrate.cjs
Invoke-NativeCommand -FilePath $pnpmPath -Arguments @('install', '--prod', '--frozen-lockfile') -FailureMessage '生产依赖安装失败'
Invoke-NativeCommand -FilePath $pnpmPath -Arguments @('--dir', 'apps/api', 'exec', 'prisma', 'generate', '--schema', './prisma/schema.prisma') -FailureMessage 'Prisma Client 生成失败'
Invoke-NativeCommand -FilePath $nodePath -Arguments @('migrate.cjs') -FailureMessage '数据库迁移失败'
"""
INIT_PS1 = r"""[CmdletBinding()]
param()
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $root
foreach ($required in @('package.json', 'pnpm-lock.yaml', 'install-deps.ps1', 'server.cjs', 'migrate.cjs')) {
$requiredPath = Join-Path $root $required
if (-not (Test-Path -LiteralPath $requiredPath -PathType Leaf)) {
throw "发布包不完整,缺少 $required。"
}
}
[System.IO.Directory]::CreateDirectory((Join-Path $root 'storage')) | Out-Null
[System.IO.Directory]::CreateDirectory((Join-Path $root 'backups')) | Out-Null
$envPath = Join-Path $root '.env'
if (Test-Path -LiteralPath $envPath) {
if (-not (Test-Path -LiteralPath $envPath -PathType Leaf)) { throw '.env 必须是文件。' }
Write-Host '[init] 检测到已有 .env,将原样保留。'
} else {
[System.IO.File]::WriteAllBytes($envPath, [byte[]]@())
Write-Host '[init] 已创建空 .env,首次启动后请在 /admin 完成安装向导。'
}
& (Join-Path $root 'install-deps.ps1')
if (-not $?) { throw '依赖初始化失败。' }
Write-Host '[init] 项目初始化完成。'
Write-Host "[init] 下一步:用 PM2 启动 $root/server.cjs,并访问 /admin 完成安装向导。"
"""
INIT_SH = """#!/usr/bin/env sh
@@ -241,7 +324,7 @@ for required in package.json server.cjs apps/api .env; do
fi
done
for required in apps packages server.cjs migrate.cjs ecosystem.config.cjs init.sh install-deps.sh install-deps.ps1 package.json pnpm-lock.yaml pnpm-workspace.yaml; do
for required in apps packages server.cjs migrate.cjs ecosystem.config.cjs init.sh init.ps1 install-deps.sh install-deps.ps1 package.json pnpm-lock.yaml pnpm-workspace.yaml; do
if [ ! -e "$SRC/$required" ]; then
echo "升级包不完整,缺少 $required。" >&2
exit 1
@@ -249,7 +332,7 @@ for required in apps packages server.cjs migrate.cjs ecosystem.config.cjs init.s
done
echo "[upgrade] 用 $SRC 的新代码升级 $TARGET(保留 .env / storage/ / backups/)"
for item in apps packages server.cjs migrate.cjs ecosystem.config.cjs init.sh install-deps.sh install-deps.ps1 package.json pnpm-lock.yaml pnpm-workspace.yaml; do
for item in apps packages server.cjs migrate.cjs ecosystem.config.cjs init.sh init.ps1 install-deps.sh install-deps.ps1 package.json pnpm-lock.yaml pnpm-workspace.yaml; do
rm -rf "$TARGET/$item"
cp -R "$SRC/$item" "$TARGET/$item"
done
@@ -259,23 +342,98 @@ echo "[upgrade] 完成。请重启 Node 服务(宝塔重启该 PM2 项目,
echo "[upgrade] .env / storage/ / backups/ 已原样保留。"
"""
UPGRADE_PS1 = """param([Parameter(Mandatory=$true)][string]$Target)
UPGRADE_PS1 = r"""[CmdletBinding()]
param([Parameter(Mandatory=$true)][string]$Target)
$ErrorActionPreference = 'Stop'
$src = Split-Path -Parent $MyInvocation.MyCommand.Path
if (-not (Test-Path $Target)) { throw "目标目录不存在: $Target" }
Write-Host "[upgrade] 用 $src 的新代码升级 $Target(保留 .env / storage/ / backups/)"
$items = @('apps','packages','server.cjs','migrate.cjs','ecosystem.config.cjs','init.sh','install-deps.sh','install-deps.ps1','package.json','pnpm-lock.yaml','pnpm-workspace.yaml')
foreach ($i in $items) {
$s = Join-Path $src $i
if (Test-Path $s) {
$d = Join-Path $Target $i
if (Test-Path $d) { Remove-Item -Recurse -Force $d }
Copy-Item -Recurse -Force $s $d
Set-StrictMode -Version Latest
function Normalize-FullPath {
param([Parameter(Mandatory=$true)][string]$Path)
$fullPath = [System.IO.Path]::GetFullPath($Path)
$rootPath = [System.IO.Path]::GetPathRoot($fullPath)
$separators = [char[]]@(
[System.IO.Path]::DirectorySeparatorChar,
[System.IO.Path]::AltDirectorySeparatorChar
)
$trimmed = $fullPath.TrimEnd($separators)
$rootTrimmed = $rootPath.TrimEnd($separators)
if ([string]::Equals($trimmed, $rootTrimmed, [System.StringComparison]::OrdinalIgnoreCase)) {
return $rootPath
}
return $trimmed
}
function Resolve-FileSystemDirectory {
param(
[Parameter(Mandatory=$true)][string]$Path,
[Parameter(Mandatory=$true)][string]$Label
)
if (-not (Test-Path -LiteralPath $Path -PathType Container)) { throw "$Label 不存在或不是目录: $Path" }
$resolved = Resolve-Path -LiteralPath $Path -ErrorAction Stop
if ($resolved.Provider.Name -ne 'FileSystem') { throw "$Label 必须位于本地文件系统: $Path" }
return Normalize-FullPath $resolved.ProviderPath
}
function Test-SameOrChildPath {
param(
[Parameter(Mandatory=$true)][string]$Parent,
[Parameter(Mandatory=$true)][string]$Candidate
)
if ([string]::Equals($Parent, $Candidate, [System.StringComparison]::OrdinalIgnoreCase)) { return $true }
$prefix = $Parent
$separator = [string][System.IO.Path]::DirectorySeparatorChar
if (-not $prefix.EndsWith($separator)) { $prefix += $separator }
return $Candidate.StartsWith($prefix, [System.StringComparison]::OrdinalIgnoreCase)
}
$src = Resolve-FileSystemDirectory (Split-Path -Parent $MyInvocation.MyCommand.Path) '升级包目录'
$targetPath = Resolve-FileSystemDirectory $Target '目标目录'
$targetRoot = Normalize-FullPath ([System.IO.Path]::GetPathRoot($targetPath))
if ([string]::Equals($targetPath, $targetRoot, [System.StringComparison]::OrdinalIgnoreCase)) {
throw '拒绝将文件系统根目录作为升级目标。'
}
if (Test-SameOrChildPath $targetPath $src) {
throw '升级包不能位于线上部署目录内部,请解压到其他目录后重试。'
}
if (Test-SameOrChildPath $src $targetPath) {
throw '线上部署目录不能与升级包目录相同,也不能位于升级包目录内部。'
}
foreach ($required in @('package.json', 'server.cjs', 'apps/api', '.env')) {
$requiredPath = Join-Path $targetPath $required
$expectedType = if ($required -eq 'apps/api') { 'Container' } else { 'Leaf' }
if (-not (Test-Path -LiteralPath $requiredPath -PathType $expectedType)) {
throw "目标目录不是完整的 Artveris 部署,缺少 ${required}: $targetPath"
}
}
Set-Location $Target
corepack enable 2>$null
& .\\install-deps.ps1
$items = @(
'apps', 'packages', 'server.cjs', 'migrate.cjs', 'ecosystem.config.cjs',
'init.sh', 'init.ps1', 'install-deps.sh', 'install-deps.ps1',
'package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml'
)
foreach ($item in $items) {
$sourcePath = Join-Path $src $item
if (-not (Test-Path -LiteralPath $sourcePath)) { throw "升级包不完整,缺少 $item。" }
}
Write-Host "[upgrade] 用 $src 的新代码升级 $targetPath(保留 .env / storage/ / backups/)"
foreach ($item in $items) {
$sourcePath = Join-Path $src $item
$destinationPath = Normalize-FullPath ([System.IO.Path]::GetFullPath((Join-Path $targetPath $item)))
if (-not (Test-SameOrChildPath $targetPath $destinationPath) -or
[string]::Equals($targetPath, $destinationPath, [System.StringComparison]::OrdinalIgnoreCase)) {
throw "拒绝操作目标目录之外的路径: $destinationPath"
}
if (Test-Path -LiteralPath $destinationPath) {
Remove-Item -LiteralPath $destinationPath -Recurse -Force
}
Copy-Item -LiteralPath $sourcePath -Destination $destinationPath -Recurse -Force
}
Set-Location $targetPath
& (Join-Path $targetPath 'install-deps.ps1')
if (-not $?) { throw '升级依赖安装失败。' }
Write-Host "[upgrade] 完成。请重启 Node 服务。.env / storage/ / backups/ 已保留。"
"""
@@ -310,7 +468,13 @@ cd /www/wwwroot/artveris
sh init.sh
```
`init.sh` 会自动准备项目要求的 pnpm 10、配置国内 npm/Prisma 镜像、安装生产依赖、生成 Prisma Client、执行已有数据库迁移,并准备 `.env`、`storage/`、`backups/` 与 `www` 用户权限。脚本可重复执行:已有 `.env` 不会被覆盖。默认运行用户为 `www`,其他环境可用 `APP_USER=实际用户 sh init.sh` 覆盖。
Windows PowerShell 部署执行:
```powershell
.\\init.ps1
```
`init.sh` / `init.ps1` 会自动准备项目要求的 pnpm 10、配置国内 npm/Prisma 镜像、安装生产依赖、生成 Prisma Client、执行已有数据库迁移,并准备 `.env`、`storage/`、`backups/`。脚本可重复执行:已有 `.env` 不会被覆盖。Linux 默认把运行目录授权给 `www`,其他环境可用 `APP_USER=实际用户 sh init.sh` 覆盖。
如果服务器没有 `corepack`,请在宝塔里安装 Node.js 24 LTS 后再执行;最低兼容版本为 20.11.1。海外服务器如需使用官方源,可在执行时覆盖 `NPM_REGISTRY` 与 `PRISMA_ENGINES_MIRROR`。
@@ -433,9 +597,9 @@ Windows:
## 手动升级
1. 后台先做一次系统备份,并停止 Node 服务。
2. 用本包内的 `apps/`、`packages/`、`server.cjs`、`migrate.cjs`、`ecosystem.config.cjs`、`init.sh`、`install-deps.*`、
2. 用本包内的 `apps/`、`packages/`、`server.cjs`、`migrate.cjs`、`ecosystem.config.cjs`、`init.*`、`install-deps.*`、
`package.json`、`pnpm-lock.yaml`、`pnpm-workspace.yaml` 覆盖线上同名文件;**不要动根目录 `.env`、`storage/`、`backups/`**。
3. 执行 `sh install-deps.sh`。
3. Linux 执行 `sh install-deps.sh`;Windows 执行 `.\\install-deps.ps1`。
4. 启动 Node 服务。
如需修改数据库/域名等配置,直接编辑根目录 `.env` 后重启;平台名/存储等也可在后台系统设置在线改。
@@ -463,6 +627,7 @@ def copy_code_payload(package_dir: Path) -> None:
shutil.copy2(ROOT / "scripts/migrate.cjs", package_dir / "migrate.cjs")
write_text(package_dir / "ecosystem.config.cjs", ECOSYSTEM_CJS)
write_text(package_dir / "init.sh", INIT_SH)
write_powershell(package_dir / "init.ps1", INIT_PS1)
write_text(package_dir / "install-deps.sh", INSTALL_DEPS_SH)
write_powershell(package_dir / "install-deps.ps1", INSTALL_DEPS_PS1)