Skip to content

Commit 069105f

Browse files
author
Eason
committed
feat: 重構與完善靜態發佈/安全掃描腳本,調整路徑
將 publish-browser-hosted.ps1、 scan-static-artifacts.ps1 移至 scripts/ 目錄, 並同步更新所有文件與 CI workflow 路徑。 完整實作兩腳本: 支援 deterministic 靜態發佈 (含 CSP、base href、SWA config)、 靜態 artefact secrets 掃描。 新增 generate-pwa-icons.ps1。 提升自動化、驗證與部署一致性。
1 parent b86de39 commit 069105f

9 files changed

Lines changed: 326 additions & 24 deletions

File tree

.github/workflows/deploy-azure-swa.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@ jobs:
2525
- name: Publish (Azure SWA)
2626
shell: pwsh
2727
run: |
28-
./specs/001-add-wasm-hosting/scripts/publish-browser-hosted.ps1 \
29-
-Platform azure-swa \
28+
./scripts/publish-browser-hosted.ps1 `
29+
-Platform azure-swa `
3030
-Configuration Release
3131
3232
- name: Deploy to Azure Static Web Apps

.github/workflows/deploy-gh-pages.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@ jobs:
3131
- name: Publish (GitHub Pages)
3232
shell: pwsh
3333
run: |
34-
./specs/001-add-wasm-hosting/scripts/publish-browser-hosted.ps1 \
35-
-Platform github-pages \
36-
-BasePath "/${{ github.event.repository.name }}/" \
34+
./scripts/publish-browser-hosted.ps1 `
35+
-Platform github-pages `
36+
-BasePath "/${{ github.event.repository.name }}/" `
3737
-Configuration Release
3838
3939
- name: Upload Pages artifact

README.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,13 +101,13 @@ Server host 啟動後會自動開啟預設瀏覽器(現況 `Program.cs`)。W
101101

102102
本 repo 提供可重複、可驗證(deterministic hashes)的 publish script,用於產出可直接部署到 static hosting 的 artefacts:
103103

104-
- Script: `specs/001-add-wasm-hosting/scripts/publish-browser-hosted.ps1`
104+
- Script: `scripts/publish-browser-hosted.ps1`
105105
- Output root: `ReleaseDownload/browser-hosted/{platform}/{configuration}/wwwroot/`
106106

107107
#### Publish: GitHub Pages
108108

109109
```powershell
110-
powershell -NoProfile -ExecutionPolicy Bypass -File specs/001-add-wasm-hosting/scripts/publish-browser-hosted.ps1 -Platform github-pages -BasePath "/CovenantPromptKey/" -Configuration Release
110+
powershell -NoProfile -ExecutionPolicy Bypass -File scripts/publish-browser-hosted.ps1 -Platform github-pages -BasePath "/CovenantPromptKey/" -Configuration Release
111111
```
112112

113113
Notes:
@@ -117,7 +117,7 @@ Notes:
117117
#### Publish: Azure Static Web Apps
118118

119119
```powershell
120-
powershell -NoProfile -ExecutionPolicy Bypass -File specs/001-add-wasm-hosting/scripts/publish-browser-hosted.ps1 -Platform azure-swa -Configuration Release
120+
powershell -NoProfile -ExecutionPolicy Bypass -File scripts/publish-browser-hosted.ps1 -Platform azure-swa -Configuration Release
121121
```
122122

123123
Notes:
@@ -195,7 +195,7 @@ CovenantPromptKey/
195195
Validation(可重複驗證)
196196
- Malicious input corpus: `specs/001-add-wasm-hosting/security/malicious-input-cases.md`
197197
- Static artefact secrets scan:
198-
- `powershell -NoProfile -ExecutionPolicy Bypass -File specs/001-add-wasm-hosting/scripts/scan-static-artifacts.ps1 -PublishRoot "ReleaseDownload/browser-hosted/github-pages/Release/wwwroot"`
198+
- `powershell -NoProfile -ExecutionPolicy Bypass -File scripts/scan-static-artifacts.ps1 -PublishRoot "ReleaseDownload/browser-hosted/github-pages/Release/wwwroot"`
199199

200200
---
201201

scripts/generate-pwa-icons.ps1

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
param(
2+
[Parameter(Mandatory = $true)]
3+
[string]$SourcePng,
4+
5+
[Parameter(Mandatory = $true)]
6+
[string]$Dest192Png,
7+
8+
[Parameter(Mandatory = $true)]
9+
[string]$Dest512Png
10+
)
11+
12+
Set-StrictMode -Version Latest
13+
$ErrorActionPreference = 'Stop'
14+
15+
Add-Type -AssemblyName System.Drawing
16+
17+
$img = [System.Drawing.Image]::FromFile($SourcePng)
18+
try {
19+
$bmp192 = New-Object System.Drawing.Bitmap 192, 192
20+
$g192 = [System.Drawing.Graphics]::FromImage($bmp192)
21+
try {
22+
$g192.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
23+
$g192.DrawImage($img, 0, 0, 192, 192)
24+
$bmp192.Save($Dest192Png, [System.Drawing.Imaging.ImageFormat]::Png)
25+
}
26+
finally {
27+
$g192.Dispose()
28+
$bmp192.Dispose()
29+
}
30+
31+
$bmp512 = New-Object System.Drawing.Bitmap 512, 512
32+
$g512 = [System.Drawing.Graphics]::FromImage($bmp512)
33+
try {
34+
$g512.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
35+
$g512.DrawImage($img, 0, 0, 512, 512)
36+
$bmp512.Save($Dest512Png, [System.Drawing.Imaging.ImageFormat]::Png)
37+
}
38+
finally {
39+
$g512.Dispose()
40+
$bmp512.Dispose()
41+
}
42+
}
43+
finally {
44+
$img.Dispose()
45+
}
46+
47+
Write-Host "Generated: $Dest192Png"
48+
Write-Host "Generated: $Dest512Png"

scripts/publish-browser-hosted.ps1

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
<#
2+
.SYNOPSIS
3+
Publish browser-hosted (Blazor WebAssembly) output for free static hosting targets.
4+
5+
.DESCRIPTION
6+
Produces deterministic validation output (paths, hashes, base href) and prepares
7+
publish artefacts for GitHub Pages / Azure Static Web Apps.
8+
9+
.NOTES
10+
Keep minimal-change; do not modify publish output manually.
11+
#>
12+
13+
[CmdletBinding()]
14+
param(
15+
[Parameter(Mandatory = $true)]
16+
[ValidateSet('github-pages', 'azure-swa')]
17+
[string] $Platform,
18+
19+
[string] $BasePath,
20+
21+
[ValidateSet('Debug', 'Release')]
22+
[string] $Configuration = 'Release'
23+
)
24+
25+
Set-StrictMode -Version Latest
26+
$ErrorActionPreference = 'Stop'
27+
28+
function Normalize-BasePath {
29+
param([Parameter(Mandatory = $true)][string] $Value)
30+
31+
$v = $Value.Trim()
32+
if (-not $v.StartsWith('/')) { $v = '/' + $v }
33+
if (-not $v.EndsWith('/')) { $v = $v + '/' }
34+
return $v
35+
}
36+
37+
function Replace-BaseHrefInFile {
38+
param(
39+
[Parameter(Mandatory = $true)][string] $FilePath,
40+
[Parameter(Mandatory = $true)][string] $NewBaseHref
41+
)
42+
43+
if (-not (Test-Path -LiteralPath $FilePath)) {
44+
return
45+
}
46+
47+
$content = Get-Content -LiteralPath $FilePath -Raw
48+
$replacement = '<base href="' + $NewBaseHref + '" />'
49+
$updated = $content -replace '<base\s+href="[^"]*"\s*/>', $replacement
50+
Set-Content -LiteralPath $FilePath -Value $updated -NoNewline
51+
}
52+
53+
function Upsert-CspMetaInFile {
54+
param(
55+
[Parameter(Mandatory = $true)][string] $FilePath,
56+
[Parameter(Mandatory = $true)][string] $Csp
57+
)
58+
59+
if (-not (Test-Path -LiteralPath $FilePath)) {
60+
return
61+
}
62+
63+
$content = Get-Content -LiteralPath $FilePath -Raw
64+
65+
$metaRegex = '<meta\s+http-equiv="Content-Security-Policy"\s+content="[^"]*"\s*/?>'
66+
$metaReplacement = '<meta http-equiv="Content-Security-Policy" content="' + $Csp + '" />'
67+
68+
if ($content -match $metaRegex) {
69+
$updated = $content -replace $metaRegex, $metaReplacement
70+
Set-Content -LiteralPath $FilePath -Value $updated -NoNewline
71+
return
72+
}
73+
74+
# Insert CSP meta before the first <base ...> (or as first element inside <head> if <base> not found).
75+
if ($content -match '<base\s+href=') {
76+
$updated = $content -replace '(<base\s+href=)', ($metaReplacement + "`r`n " + '$1')
77+
Set-Content -LiteralPath $FilePath -Value $updated -NoNewline
78+
return
79+
}
80+
81+
if ($content -match '<head\s*>') {
82+
$updated = $content -replace '(<head\s*>)', ('$1' + "`r`n " + $metaReplacement)
83+
Set-Content -LiteralPath $FilePath -Value $updated -NoNewline
84+
return
85+
}
86+
}
87+
88+
Write-Host "[publish-browser-hosted] Platform=$Platform Configuration=$Configuration"
89+
90+
$repoRoot = Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')
91+
$wasmProject = Join-Path $repoRoot 'CovenantPromptKeyWebAssembly'
92+
$wasmProject = Join-Path $wasmProject 'CovenantPromptKeyWebAssembly.csproj'
93+
94+
if (-not (Test-Path -LiteralPath $wasmProject)) {
95+
throw "WASM project not found: $wasmProject"
96+
}
97+
98+
$outputDir = Join-Path $repoRoot 'ReleaseDownload'
99+
$outputDir = Join-Path $outputDir 'browser-hosted'
100+
$outputDir = Join-Path $outputDir $Platform
101+
$outputDir = Join-Path $outputDir $Configuration
102+
New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
103+
104+
Write-Host "[publish-browser-hosted] Publishing: $wasmProject"
105+
dotnet publish $wasmProject -c $Configuration -o $outputDir | Out-Host
106+
107+
$wwwrootDir = Join-Path $outputDir 'wwwroot'
108+
if (-not (Test-Path -LiteralPath $wwwrootDir)) {
109+
throw "Publish output missing wwwroot: $wwwrootDir"
110+
}
111+
112+
$cspBaseline = "default-src 'self'; base-uri 'self'; object-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self';"
113+
114+
Upsert-CspMetaInFile -FilePath (Join-Path $wwwrootDir 'index.html') -Csp $cspBaseline
115+
Upsert-CspMetaInFile -FilePath (Join-Path $wwwrootDir '404.html') -Csp $cspBaseline
116+
117+
if ($Platform -eq 'github-pages') {
118+
if ([string]::IsNullOrWhiteSpace($BasePath)) {
119+
throw "BasePath is required for github-pages (e.g. '/CovenantPromptKey/')"
120+
}
121+
122+
$baseHref = Normalize-BasePath -Value $BasePath
123+
Replace-BaseHrefInFile -FilePath (Join-Path $wwwrootDir 'index.html') -NewBaseHref $baseHref
124+
Replace-BaseHrefInFile -FilePath (Join-Path $wwwrootDir '404.html') -NewBaseHref $baseHref
125+
}
126+
127+
if ($Platform -eq 'azure-swa') {
128+
$swaConfigSrc = Join-Path $repoRoot 'CovenantPromptKeyWebAssembly'
129+
$swaConfigSrc = Join-Path $swaConfigSrc 'staticwebapp.config.json'
130+
$swaConfigDst = Join-Path $wwwrootDir 'staticwebapp.config.json'
131+
Copy-Item -LiteralPath $swaConfigSrc -Destination $swaConfigDst -Force
132+
}
133+
134+
$indexPath = Join-Path $wwwrootDir 'index.html'
135+
$swAssetsPath = Join-Path $wwwrootDir 'service-worker-assets.js'
136+
137+
$indexHash = if (Test-Path -LiteralPath $indexPath) { (Get-FileHash -Algorithm SHA256 -LiteralPath $indexPath).Hash } else { '' }
138+
$swAssetsHash = if (Test-Path -LiteralPath $swAssetsPath) { (Get-FileHash -Algorithm SHA256 -LiteralPath $swAssetsPath).Hash } else { '' }
139+
140+
Write-Host "[publish-browser-hosted] OutputDir=$outputDir"
141+
Write-Host "[publish-browser-hosted] WwwrootDir=$wwwrootDir"
142+
Write-Host "[publish-browser-hosted] IndexHtmlSha256=$indexHash"
143+
Write-Host "[publish-browser-hosted] ServiceWorkerAssetsSha256=$swAssetsHash"
144+
145+
exit 0

scripts/scan-static-artifacts.ps1

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
<#
2+
.SYNOPSIS
3+
Scan published static artifacts for secrets or dangerous patterns.
4+
5+
.DESCRIPTION
6+
Scans a publish directory and fails if token/secret-like patterns match.
7+
8+
.NOTES
9+
This is a client-side artefact scan; it does not replace proper secret management.
10+
#>
11+
12+
[CmdletBinding()]
13+
param(
14+
[Parameter(Mandatory = $true)]
15+
[Alias('Path')]
16+
[string] $PublishRoot
17+
)
18+
19+
Set-StrictMode -Version Latest
20+
$ErrorActionPreference = 'Stop'
21+
22+
if (-not (Test-Path -LiteralPath $PublishRoot)) {
23+
throw "PublishRoot does not exist: $PublishRoot"
24+
}
25+
26+
Write-Host "[scan-static-artifacts] PublishRoot=$PublishRoot"
27+
28+
function Get-MaskedValue {
29+
param(
30+
[Parameter(Mandatory = $true)]
31+
[string] $Value
32+
)
33+
34+
if ($Value.Length -le 12) {
35+
return ('*' * $Value.Length)
36+
}
37+
38+
return ($Value.Substring(0, 4) + '...' + $Value.Substring($Value.Length - 4))
39+
}
40+
41+
# Token patterns (keep this list explicit and local to the script)
42+
$patterns = @(
43+
@{ Name = 'GitHub classic PAT (ghp_)'; Regex = 'ghp_[A-Za-z0-9]{36}' },
44+
@{ Name = 'GitHub fine-grained PAT (github_pat_)'; Regex = 'github_pat_[A-Za-z0-9_]{20,120}' },
45+
@{ Name = 'Slack token (xoxb/xoxp/xoxa)'; Regex = 'xox[baprs]-[A-Za-z0-9-]{10,200}' },
46+
@{ Name = 'Stripe secret key (sk_live/sk_test)'; Regex = 'sk_(live|test)_[A-Za-z0-9]{16,200}' },
47+
@{ Name = 'Google API key (AIza)'; Regex = 'AIza[0-9A-Za-z\-_]{30,50}' },
48+
@{ Name = 'OAuth access token (ya29.)'; Regex = 'ya29\.[0-9A-Za-z\-_]+' },
49+
@{ Name = 'JWT-like token (eyJ...\..+\..+)'; Regex = 'eyJ[0-9A-Za-z\-_]+\.[0-9A-Za-z\-_]+\.[0-9A-Za-z\-_]+' },
50+
@{ Name = 'Private key block'; Regex = '-----BEGIN( [A-Z0-9]+)? PRIVATE KEY-----' }
51+
)
52+
53+
$textExtensions = @(
54+
'.html', '.htm',
55+
'.js', '.mjs',
56+
'.css',
57+
'.json', '.map',
58+
'.txt', '.md',
59+
'.xml',
60+
'.yml', '.yaml',
61+
'.webmanifest',
62+
'.config'
63+
)
64+
65+
$files = Get-ChildItem -LiteralPath $PublishRoot -Recurse -File |
66+
Where-Object { $textExtensions -contains $_.Extension.ToLowerInvariant() } |
67+
Sort-Object -Property FullName
68+
69+
Write-Host "[scan-static-artifacts] FilesToScan=$($files.Count)"
70+
71+
$findings = New-Object System.Collections.Generic.List[object]
72+
73+
foreach ($file in $files) {
74+
try {
75+
$bytes = [System.IO.File]::ReadAllBytes($file.FullName)
76+
$content = [System.Text.Encoding]::UTF8.GetString($bytes)
77+
}
78+
catch {
79+
Write-Host "[scan-static-artifacts] WARN: Failed to read file: $($file.FullName) ($($_.Exception.Message))"
80+
continue
81+
}
82+
83+
foreach ($pattern in $patterns) {
84+
$regex = [regex]::new($pattern.Regex)
85+
$match = $regex.Match($content)
86+
87+
if ($match.Success) {
88+
$findings.Add([pscustomobject]@{
89+
File = $file.FullName
90+
Pattern = $pattern.Name
91+
Match = (Get-MaskedValue -Value $match.Value)
92+
})
93+
}
94+
}
95+
}
96+
97+
if ($findings.Count -gt 0) {
98+
Write-Host "[scan-static-artifacts] FAIL: Potential secret patterns detected."
99+
$findings |
100+
Sort-Object -Property File, Pattern |
101+
Format-Table -AutoSize |
102+
Out-String |
103+
Write-Host
104+
105+
exit 1
106+
}
107+
108+
Write-Host "[scan-static-artifacts] PASS: No secret patterns detected."
109+
exit 0

0 commit comments

Comments
 (0)