From e09414dfbe48ad05d0524a8c59d300cdecb88c50 Mon Sep 17 00:00:00 2001
From: 云 <2163098428@qq.com>
Date: 星期四, 19 十一月 2026 13:06:38 +0800
Subject: [PATCH] chore(deploy): 将部署脚本重构为PowerShell

---
 deploy.bat |  457 ---------------------------------------------
 deploy.ps1 |  124 ++++++++++++
 2 files changed, 131 insertions(+), 450 deletions(-)

diff --git a/deploy.bat b/deploy.bat
index fdb91fa..9df9891 100644
--- a/deploy.bat
+++ b/deploy.bat
@@ -1,451 +1,8 @@
 @echo off
-setlocal EnableExtensions EnableDelayedExpansion
-
-REM ============================================================
-REM Vue Frontend Deploy Script
-REM ============================================================
-
-REM =========================
-REM Configuration
-REM =========================
-
-set "COMPANY=TEST"
-
-set "REMOTE_USER=root"
-set "REMOTE_HOST=36.213.150.237"
-set "REMOTE_PORT=65022"
-
-set "PASSWORD=Sh@1008600"
-
-set "ZIP_FILE=dist.zip"
-set "REMOTE_DIR=/data/vue/mom/jssm/dist"
-
-set "SSH_OPTS=-o StrictHostKeyChecking=no -o ConnectTimeout=10 -o ServerAliveInterval=15 -o ServerAliveCountMax=3"
-
-set "RETRY_COUNT=3"
-
-set "SSHPASS_DIR=%~dp0bin"
-
-
-REM ============================================================
-REM Start
-REM ============================================================
-
-echo.
-echo ============================================================
-echo              Vue Dist Auto Deploy
-echo ============================================================
-echo.
-echo Company    : %COMPANY%
-echo Server     : %REMOTE_USER%@%REMOTE_HOST%
-echo Port       : %REMOTE_PORT%
-echo Remote Dir : %REMOTE_DIR%
-echo Package    : %ZIP_FILE%
-echo.
-
-
-REM ============================================================
-REM Check sshpass
-REM ============================================================
-
-echo [1/7] Checking sshpass...
-
-if exist "%SSHPASS_DIR%\sshpass.exe" (
-    set "PATH=%SSHPASS_DIR%;%PATH%"
-)
-
-where sshpass >nul 2>&1
-
-if not errorlevel 1 (
-    echo [OK] sshpass found.
-    goto CHECK_PNPM
-)
-
-echo [WARN] sshpass not found.
-
-if not exist "%SSHPASS_DIR%" (
-    mkdir "%SSHPASS_DIR%" >nul 2>&1
-)
-
-if exist "%SSHPASS_DIR%\sshpass.exe" (
-    set "PATH=%SSHPASS_DIR%;%PATH%"
-    echo [OK] sshpass found.
-    goto CHECK_PNPM
-)
-
-echo [INFO] Downloading sshpass...
-
-powershell -NoProfile -ExecutionPolicy Bypass -Command "$url='https://github.com/xhcoding/sshpass-win32/releases/download/v1.0.3/sshpass.exe'; $out='%SSHPASS_DIR%\sshpass.exe'; Invoke-WebRequest -Uri $url -OutFile $out"
-
-if errorlevel 1 (
-    echo [ERROR] Failed to download sshpass.
-    echo [ERROR] Please install sshpass manually.
-    goto ERROR_EXIT
-)
-
-set "PATH=%SSHPASS_DIR%;%PATH%"
-
-echo [OK] sshpass installed.
-
-
-REM ============================================================
-REM Check pnpm
-REM ============================================================
-
-:CHECK_PNPM
-
-echo.
-echo [2/7] Checking pnpm...
-
-where pnpm >nul 2>&1
-
-if errorlevel 1 (
-    echo [ERROR] pnpm not found.
-    echo [HINT] npm install -g pnpm
-    goto ERROR_EXIT
-)
-
-call pnpm --version
-
-if errorlevel 1 (
-    echo [ERROR] pnpm execution failed.
-    goto ERROR_EXIT
-)
-
-
-REM ============================================================
-REM Check node
-REM ============================================================
-
-echo.
-echo [3/7] Checking Node.js...
-
-where node >nul 2>&1
-
-if errorlevel 1 (
-    echo [ERROR] Node.js not found.
-    goto ERROR_EXIT
-)
-
-call node --version
-
-if errorlevel 1 (
-    echo [ERROR] Node.js execution failed.
-    goto ERROR_EXIT
-)
-
-
-REM ============================================================
-REM Check node_modules
-REM ============================================================
-
-if not exist "node_modules" (
-    echo.
-    echo [INFO] node_modules not found.
-    echo [INFO] Running pnpm install...
-
-    call pnpm install
-
-    if errorlevel 1 (
-        echo [ERROR] pnpm install failed.
-        goto ERROR_EXIT
-    )
-
-    echo [OK] pnpm install completed.
-) else (
-    echo [OK] node_modules exists.
-)
-
-
-REM ============================================================
-REM Build
-REM ============================================================
-
-echo.
-echo [4/7] Building project...
-
-if exist "%ZIP_FILE%" (
-    echo.
-    echo [WARN] %ZIP_FILE% already exists.
-    set "REBUILD="
-    set /p "REBUILD=Rebuild? Y/N (default Y): "
-
-    if /I "!REBUILD!"=="N" (
-        echo [INFO] Skip build.
-        goto CHECK_ZIP
-    )
-)
-
-echo [INFO] Company: %COMPANY%
-echo [INFO] Command: pnpm run build
-echo.
-
-set "VITE_COMPANY=%COMPANY%"
-
-call pnpm run build
-
-if errorlevel 1 (
-    echo.
-    echo [ERROR] Build failed.
-    goto ERROR_EXIT
-)
-
-echo.
-echo [OK] Build completed.
-
-
-REM ============================================================
-REM Check ZIP
-REM ============================================================
-
-:CHECK_ZIP
-
-echo.
-echo [5/7] Checking package...
-
-if not exist "%ZIP_FILE%" (
-    echo [ERROR] %ZIP_FILE% not found.
-    echo [HINT] Please check whether your build generates dist.zip.
-    goto ERROR_EXIT
-)
-
-for %%F in ("%ZIP_FILE%") do set "ZIP_BYTES=%%~zF"
-
-set /a ZIP_MB=ZIP_BYTES/1024/1024
-
-echo [OK] Package found.
-echo [INFO] File size: !ZIP_BYTES! bytes
-echo [INFO] File size: !ZIP_MB! MB
-
-
-REM ============================================================
-REM Set sshpass password
-REM ============================================================
-
-set "SSHPASS=%PASSWORD%"
-
-
-REM ============================================================
-REM Test SSH
-REM ============================================================
-
-echo.
-echo [6/7] Testing SSH connection...
-
-sshpass -e ssh -p %REMOTE_PORT% %SSH_OPTS% %REMOTE_USER%@%REMOTE_HOST% "echo SSH_OK"
-
-if errorlevel 1 (
-    echo [ERROR] SSH connection failed.
-    goto ERROR_EXIT
-)
-
-echo [OK] SSH connection successful.
-
-
-REM ============================================================
-REM Create remote directory
-REM ============================================================
-
-echo.
-echo [INFO] Creating remote directory...
-
-sshpass -e ssh -p %REMOTE_PORT% %SSH_OPTS% %REMOTE_USER%@%REMOTE_HOST% "mkdir -p '%REMOTE_DIR%'"
-
-if errorlevel 1 (
-    echo [ERROR] Failed to create remote directory.
-    goto ERROR_EXIT
-)
-
-echo [OK] Remote directory ready.
-
-
-REM ============================================================
-REM Upload temporary file
-REM ============================================================
-
-echo.
-echo [INFO] Uploading package...
-
-set "REMOTE_TMP=%REMOTE_DIR%/.dist.zip.uploading"
-
-sshpass -e ssh -p %REMOTE_PORT% %SSH_OPTS% %REMOTE_USER%@%REMOTE_HOST% "rm -f '%REMOTE_TMP%'"
-
-sshpass -e scp -P %REMOTE_PORT% %SSH_OPTS% "%ZIP_FILE%" %REMOTE_USER%@%REMOTE_HOST%:"%REMOTE_TMP%"
-
-if errorlevel 1 (
-    echo [ERROR] Upload failed.
-    goto ERROR_EXIT
-)
-
-echo [OK] Upload completed.
-
-
-REM ============================================================
-REM Check remote file
-REM ============================================================
-
-echo.
-echo [INFO] Checking remote package...
-
-sshpass -e ssh -p %REMOTE_PORT% %SSH_OPTS% %REMOTE_USER%@%REMOTE_HOST% "test -f '%REMOTE_TMP%'"
-
-if errorlevel 1 (
-    echo [ERROR] Remote package does not exist.
-    goto ERROR_EXIT
-)
-
-echo [OK] Remote package exists.
-
-
-REM ============================================================
-REM Compare file size
-REM ============================================================
-
-echo.
-echo [INFO] Checking package size...
-
-sshpass -e ssh -p %REMOTE_PORT% %SSH_OPTS% %REMOTE_USER%@%REMOTE_HOST% "stat -c %%s '%REMOTE_TMP%'"
-
-echo.
-
-
-REM ============================================================
-REM Rename temporary file
-REM ============================================================
-
-echo [INFO] Activating package...
-
-sshpass -e ssh -p %REMOTE_PORT% %SSH_OPTS% %REMOTE_USER%@%REMOTE_HOST% "mv -f '%REMOTE_TMP%' '%REMOTE_DIR%/%ZIP_FILE%'"
-
-if errorlevel 1 (
-    echo [ERROR] Failed to activate package.
-    goto ERROR_EXIT
-)
-
-echo [OK] Package activated.
-
-
-REM ============================================================
-REM Check unzip
-REM ============================================================
-
-echo.
-echo [INFO] Checking unzip...
-
-sshpass -e ssh -p %REMOTE_PORT% %SSH_OPTS% %REMOTE_USER%@%REMOTE_HOST% "command -v unzip"
-
-if errorlevel 1 (
-    echo [ERROR] unzip is not installed on server.
-    echo.
-    echo CentOS/RHEL:
-    echo yum install -y unzip
-    echo.
-    echo Ubuntu/Debian:
-    echo apt install -y unzip
-    goto ERROR_EXIT
-)
-
-echo [OK] unzip found.
-
-
-REM ============================================================
-REM Test ZIP
-REM ============================================================
-
-echo.
-echo [INFO] Testing remote ZIP...
-
-sshpass -e ssh -p %REMOTE_PORT% %SSH_OPTS% %REMOTE_USER%@%REMOTE_HOST% "cd '%REMOTE_DIR%' && unzip -t '%ZIP_FILE%'"
-
-if errorlevel 1 (
-    echo.
-    echo [ERROR] ZIP test failed.
-    echo [INFO] Remote ZIP has been kept.
-    goto ERROR_EXIT
-)
-
-echo [OK] ZIP test passed.
-
-
-REM ============================================================
-REM Extract
-REM ============================================================
-
-echo.
-echo [INFO] Extracting package...
-
-sshpass -e ssh -p %REMOTE_PORT% %SSH_OPTS% %REMOTE_USER%@%REMOTE_HOST% "cd '%REMOTE_DIR%' && unzip -o '%ZIP_FILE%'"
-
-if errorlevel 1 (
-    echo.
-    echo [ERROR] Remote unzip failed.
-    echo [INFO] Remote ZIP has been kept.
-    goto ERROR_EXIT
-)
-
-echo.
-echo [OK] Extract completed.
-
-
-REM ============================================================
-REM Remove ZIP
-REM ============================================================
-
-echo.
-echo [INFO] Removing remote ZIP...
-
-sshpass -e ssh -p %REMOTE_PORT% %SSH_OPTS% %REMOTE_USER%@%REMOTE_HOST% "rm -f '%REMOTE_DIR%/%ZIP_FILE%'"
-
-if errorlevel 1 (
-    echo [WARN] Failed to remove remote ZIP.
-) else (
-    echo [OK] Remote ZIP removed.
-)
-
-
-REM ============================================================
-REM Success
-REM ============================================================
-
-echo.
-echo ============================================================
-echo                 DEPLOY SUCCESS
-echo ============================================================
-echo.
-echo Company    : %COMPANY%
-echo Server     : %REMOTE_HOST%:%REMOTE_PORT%
-echo Remote Dir : %REMOTE_DIR%
-echo Package    : %ZIP_FILE%
-echo Size       : !ZIP_MB! MB
-echo.
-echo Deployment completed successfully.
-echo.
-
-goto END
-
-
-REM ============================================================
-REM Error
-REM ============================================================
-
-:ERROR_EXIT
-
-echo.
-echo ============================================================
-echo                  DEPLOY FAILED
-echo ============================================================
-echo.
-echo Please check the error message above.
-echo.
-
-goto END
-
-
-REM ============================================================
-REM End
-REM ============================================================
-
-:END
-
-pause
-endlocal
\ No newline at end of file
+setlocal
+pushd "%~dp0" || (echo [ERROR] Cannot open project directory. & exit /b 1)
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0deploy.ps1" %*
+set "DEPLOY_EXIT=%ERRORLEVEL%"
+popd
+if not "%DEPLOY_NO_PAUSE%"=="1" pause
+exit /b %DEPLOY_EXIT%
diff --git a/deploy.ps1 b/deploy.ps1
new file mode 100644
index 0000000..97a2120
--- /dev/null
+++ b/deploy.ps1
@@ -0,0 +1,124 @@
+# Frontend deployment for Windows. Run via deploy.bat.
+$ErrorActionPreference = 'Stop'
+Set-StrictMode -Version Latest
+
+# Override these values with DEPLOY_* environment variables when necessary.
+$company = if ($env:DEPLOY_COMPANY) { $env:DEPLOY_COMPANY } else { 'TEST' }
+$remoteUser = if ($env:DEPLOY_USER) { $env:DEPLOY_USER } else { 'root' }
+$remoteHost = if ($env:DEPLOY_HOST) { $env:DEPLOY_HOST } else { '36.213.150.237' }
+$remotePort = if ($env:DEPLOY_PORT) { $env:DEPLOY_PORT } else { '65022' }
+$remoteDir = if ($env:DEPLOY_DIR) { $env:DEPLOY_DIR.TrimEnd('/') } else { '/data/vue/mom/jssm/dist' }
+$projectDir = $PSScriptRoot
+$archive = $null
+$oldSshPass = $env:SSHPASS
+
+function Require-Command([string] $name) {
+    $command = Get-Command $name -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
+    if (-not $command) { throw "Required command '$name' not found in PATH." }
+    return $command.Source
+}
+function Invoke-Checked([string] $program, [string[]] $arguments, [string] $message) {
+    & $program @arguments
+    if ($LASTEXITCODE -ne 0) { throw "$message (exit code $LASTEXITCODE)." }
+}
+
+try {
+    if ($company -notmatch '^[A-Za-z0-9_-]+$' -or $remoteUser -notmatch '^[A-Za-z0-9_.-]+$' -or
+        $remoteHost -notmatch '^[A-Za-z0-9.-]+$' -or $remotePort -notmatch '^\d{1,5}$' -or
+        [int]$remotePort -lt 1 -or [int]$remotePort -gt 65535 -or
+        $remoteDir -notmatch '^/[A-Za-z0-9_./-]+$' -or $remoteDir -match '(^|/)\.\.?(/|$)') {
+        throw 'Invalid deployment settings. Check DEPLOY_COMPANY, USER, HOST, PORT and DIR.'
+    }
+    $ssh = Require-Command 'ssh.exe'
+    $scp = Require-Command 'scp.exe'
+    $pnpm = Require-Command 'pnpm.cmd'
+    $null = Require-Command 'node.exe'
+    $sshpass = Join-Path $projectDir 'bin\sshpass.exe'
+    $credentialFile = Join-Path $env:USERPROFILE '.ssh\mom_jssm_deploy.credential'
+    # A stored password is only used for the original target, never for overrides.
+    $useStoredPassword = $env:DEPLOY_USE_SSHPASS -ne '0' -and -not $env:DEPLOY_SSH_KEY -and
+        $remoteUser -eq 'root' -and $remoteHost -eq '36.213.150.237' -and $remotePort -eq '65022' -and
+        (Test-Path -LiteralPath $credentialFile -PathType Leaf)
+    $useSshpass = $env:DEPLOY_USE_SSHPASS -eq '1' -or $useStoredPassword
+    if ($useSshpass -and -not (Test-Path -LiteralPath $sshpass -PathType Leaf)) {
+        throw 'DEPLOY_USE_SSHPASS=1 but bin\sshpass.exe is missing. Use normal SSH authentication or install it yourself.'
+    }
+    if ($useSshpass -and -not $env:SSHPASS) {
+        $securePassword = if ($useStoredPassword) {
+            Get-Content -LiteralPath $credentialFile -Raw | ConvertTo-SecureString
+        } else {
+            Read-Host 'SSH password' -AsSecureString
+        }
+        $secretPtr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePassword)
+        try { $env:SSHPASS = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($secretPtr) }
+        finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($secretPtr) }
+    }
+    # This server only offers hmac-sha1. Append it without disabling stronger MACs.
+    $sshOptions = @('-o', 'StrictHostKeyChecking=accept-new', '-o', 'MACs=+hmac-sha1', '-o', 'ConnectTimeout=10', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=3')
+    if ($env:DEPLOY_SSH_KEY) {
+        if (-not (Test-Path -LiteralPath $env:DEPLOY_SSH_KEY -PathType Leaf)) { throw 'DEPLOY_SSH_KEY does not exist.' }
+        $sshOptions += @('-i', $env:DEPLOY_SSH_KEY)
+    }
+    $target = "$remoteUser@$remoteHost"
+    Write-Host "Target: $target`:$remotePort  Directory: $remoteDir  Company: $company"
+    if ($useStoredPassword) { Write-Host 'Using the current Windows user encrypted deployment password.' }
+    elseif (-not $useSshpass) { Write-Host 'SSH may prompt for authentication more than once.' }
+    function Invoke-Ssh([string] $command, [string] $message) {
+        # sshpass-win32 can alter quotes and return success after a remote failure.
+        # Encode the script and require an explicit marker from its final command.
+        $marker = 'MOM_DEPLOY_OK_' + [Guid]::NewGuid().ToString('N')
+        $script = "set -e`n$command`nprintf '%s\n' '$marker'"
+        $encoded = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($script))
+        $arguments = @('-p', $remotePort) + $sshOptions + @($target, "echo $encoded | base64 -d | sh")
+        if ($useSshpass) { $output = @(& $sshpass -e $ssh @arguments) }
+        else { $output = @(& $ssh @arguments) }
+        $result = $LASTEXITCODE
+        $output | ForEach-Object { Write-Host $_ }
+        if ($result -ne 0 -or -not (($output -join "`n") -match [regex]::Escape($marker))) {
+            throw "$message (SSH exit code $result)."
+        }
+    }
+
+    Write-Host '[1/4] Checking SSH and server prerequisites...'
+    Invoke-Ssh 'set -eu; command -v unzip >/dev/null; command -v sha256sum >/dev/null; command -v cp >/dev/null; echo SSH_OK' 'SSH connection or server prerequisite check failed; server needs unzip and sha256sum'
+
+    Write-Host '[2/4] Building frontend...'
+    Set-Location -LiteralPath $projectDir
+    if (-not (Test-Path -LiteralPath (Join-Path $projectDir 'node_modules') -PathType Container)) {
+        throw 'node_modules is missing. Run pnpm install in the frontend project first.'
+    }
+    $env:VITE_COMPANY = $company
+    $env:VITE_ARCHIVER = 'false'
+    $start = Get-Date
+    Invoke-Checked $pnpm @('run', 'build') 'Frontend build failed'
+    $dist = Join-Path $projectDir 'dist'
+    $index = Join-Path $dist 'index.html'
+    if (-not (Test-Path -LiteralPath $index -PathType Leaf) -or (Get-Item -LiteralPath $index).LastWriteTime -lt $start.AddSeconds(-2)) {
+        throw 'Build did not produce a fresh dist/index.html; deployment stopped.'
+    }
+    Add-Type -AssemblyName System.IO.Compression.FileSystem
+    $id = [Guid]::NewGuid().ToString('N')
+    $archive = Join-Path ([IO.Path]::GetTempPath()) "mom-frontend-$id.zip"
+    [IO.Compression.ZipFile]::CreateFromDirectory($dist, $archive, [IO.Compression.CompressionLevel]::Optimal, $false)
+    $hash = (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLowerInvariant()
+    $remoteArchive = "/tmp/mom-frontend-$id.zip"
+    $remoteStage = "/tmp/mom-frontend-$id"
+
+    Write-Host '[3/4] Uploading package...'
+    # -O supports servers that only provide SCP and have no SFTP subsystem.
+    $scpArguments = @('-O', '-P', $remotePort) + $sshOptions + @($archive, "${target}:$remoteArchive")
+    if ($useSshpass) { Invoke-Checked $sshpass (@('-e', $scp) + $scpArguments) 'SCP upload failed' }
+    else { Invoke-Checked $scp $scpArguments 'SCP upload failed' }
+
+    Write-Host '[4/4] Verifying and publishing...'
+    $remoteCommand = "set -eu; test -f '$remoteArchive'; actual=`$(sha256sum '$remoteArchive'); actual=`${actual%% *}; test `"`$actual`" = '$hash' || { echo 'ERROR: SHA-256 mismatch' >&2; exit 1; }; unzip -tq '$remoteArchive' >/dev/null; mkdir -p '$remoteStage'; unzip -oq '$remoteArchive' -d '$remoteStage'; test -f '$remoteStage/index.html'; mkdir -p '$remoteDir'; cp -a '$remoteStage/.' '$remoteDir/'; rm -rf -- '$remoteStage'; rm -f -- '$remoteArchive'; echo DEPLOY_OK"
+    Invoke-Ssh $remoteCommand "Verification or publishing failed; uploaded package remains at $remoteArchive"
+    Write-Host "Deployment completed: $target`:$remoteDir"
+    exit 0
+} catch {
+    Write-Error -ErrorAction Continue $_.Exception.Message
+    exit 1
+} finally {
+    if ($archive -and (Test-Path -LiteralPath $archive)) { Remove-Item -LiteralPath $archive -Force -ErrorAction SilentlyContinue }
+    $env:SSHPASS = $oldSshPass
+}

--
Gitblit v1.9.3