Communitygithub.com

Git 洩密防範

預防敏感檔案、密鑰和建置產物被推送至 GitHub。掃描、偵測並自動修復 .gitignore。

Git 洩密防範 是什麼?

Git 洩密防範技能會掃描 Git 倉儲,找出不應被推送至 GitHub 的敏感檔案、密鑰與建置產物。它能自動更新 .gitignore、從追蹤中移除已提交的敏感檔案,並在偵測到已暴露的密鑰時發出警告。此技能在 TypeScript、React 等開發環境中特別有用,因為這些專案常包含 .env、node_modules 或 dist 等目錄。支援 Windows PowerShell 或命令提示字元,透過 `git ls-files` 和 ripgrep 進行掃描,最後產出一份清晰的資安報告,列出風險項目、自動修復內容以及使用者應採取的後續行動。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add bilals2008/bilal-skills

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Git 洩密防範 是做什麼的?

目的

防止敏感檔案、密鑰和建置產物被推送至 GitHub。掃描、偵測並自動修復 .gitignore。

操作說明

步驟 1 — 掃描敏感檔案

執行以下命令,找出不該出現在 GitHub 上的檔案:

git ls-files | findstr /i ".env .env.local .env.production .env.staging node_modules dist build releases *.key *.pem *.p12 secrets"

在 PowerShell 上:

git ls-files | Select-String -Pattern "\.env|node_modules|dist|build|releases|\.key$|\.pem$|\.p12$|secrets|\.log$|\.cache$"

同時檢查未追蹤的敏感檔案:

git status --porcelain

步驟 2 — 檢查常見的敏感模式

在已追蹤的檔案中尋找以下模式:

模式風險行動
.env / .env.*API 金鑰、資料庫密碼從 Git 移除 + 加入 .gitignore
node_modules/相依套件(龐大,不需要)移除 + .gitignore
dist/ / build/編譯輸出移除 + .gitignore
releases/二進位發行檔移除 + .gitignore
*.key / *.pem私密金鑰移除 + .gitignore
*.p12 / *.pfx憑證移除 + .gitignore
.DS_StoremacOS 中繼資料.gitignore
Thumbs.dbWindows 中繼資料.gitignore
*.log日誌檔案.gitignore
.cache/快取資料夾.gitignore
coverage/測試涵蓋率.gitignore
.turbo/ / .next/建置快取.gitignore
*.sql資料庫傾印(有時包含密鑰)檢查內容

步驟 3 — 檢查程式碼中的密鑰

在已追蹤的檔案中搜尋硬編碼的密鑰:

rg -i "(api[_-]?key|secret|password|token|private[_-]?key)\s*[:=]\s*['\x22]" --type-add 'code:*.{ts,tsx,js,jsx,json,yaml,yml,env,config}' -t code

尋找以下模式:

  • API_KEY=sk-...
  • SECRET=...
  • PASSWORD=...
  • PRIVATE_KEY-----BEGIN
  • token: "eyJ..."

步驟 4 — 自動修復 .gitignore

如果發現敏感檔案,自動更新 .gitignore:

# 檢查目前的 .gitignore
cat .gitignore

加入遺漏的項目。Web 專案的標準 .gitignore:

# 環境檔案
.env
.env.local
.env.production
.env.staging
.env.development

# 相依套件
node_modules/

# 建置輸出
dist/
build/
release/
releases/

# 密鑰
*.key
*.pem
*.p12
*.pfx

# IDE
.vscode/settings.json
.idea/

# 作業系統
.DS_Store
Thumbs.db

# 日誌
*.log
npm-debug.log*

# 快取
.cache/
.turbo/
.next/
.nuxt/

# 涵蓋率
coverage/

# 其他
*.swp
*.swo

步驟 5 — 從 Git 追蹤中移除敏感檔案(如果已追蹤)

如果敏感檔案已被追蹤:

# 從追蹤中移除,但保留在本機
git rm --cached .env
git rm --cached -r node_modules/
git rm --cached -r dist/
git rm --cached -r build/

# 然後加入 .gitignore

警告: 如果密鑰已被推送至 GitHub,則表示已遭洩漏。使用者應:

  1. 立即輪換所有暴露的金鑰/密鑰
  2. 永不重複使用相同的密鑰

步驟 6 — 向使用者顯示報告

清晰地呈現調查結果:

🔍 安全性掃描報告

有風險的檔案:
  ❌ .env — 已被追蹤(包含密鑰)
  ❌ node_modules/ — 已被追蹤(應被忽略)
  ⚠️ dist/ — 已被追蹤(建置輸出)

已採取的行動:
  ✅ 已將 .env 加入 .gitignore
  ✅ 已將 node_modules/ 加入 .gitignore
  ✅ 已將 dist/ 加入 .gitignore
  ✅ 已從 Git 追蹤中移除 .env(保留在本機)

⚠️ 如果 .env 包含真實密鑰,請立即輪換它們。
   GitHub 歷史紀錄中仍留有舊版本。

步驟 7 — 提交修復

git add .gitignore
git commit -m "chore(security): 更新 gitignore 以防止密鑰洩漏"

禁止事項

  • ❌ 切勿在報告中顯示實際密鑰值(應遮罩:sk-****...****)
  • ❌ 切勿提交 .env 或密鑰,即使是「暫時性」原因
  • ❌ 切勿忽略已推送密鑰的警告
  • ❌ 切勿略過檢查 git ls-files — 未追蹤的檔案沒問題,已追蹤的才是風險

預期輸出

一份清晰的安全性報告,顯示:

  1. 發現了哪些風險
  2. 自動修復了哪些問題
  3. 使用者需要手動處理的事項(輪換金鑰)

相關技能