Bologu

管理 API 藏在你的 JavaScript 裡外洩:為什麼延遲載入沒用,該在哪裡修正

更新於 · Bologu 團隊

用 AI 打造的網站常只有一個 API 檔,例如 lib/api.ts,裡面同時放著顧客用的呼叫和管理後台的呼叫。每個頁面都 import 它, 建置時整個檔案就被送給每位訪客。任何人打開 DevTools 都能看到後台有哪些 API,以及哪些可以刪除資料或退款。

// lib/api.ts: imported by every page, so the whole file ships to every visitor
export const getProducts = () => fetch("/api/products");
export const checkout    = (cart) => fetch("/api/checkout", { method: "POST", ... });

export const admin = {
  users:     () => fetch("/api/admin/users"),
  refund:    (id) => fetch(`/api/admin/orders/${id}/refund`, { method: "POST" }),
  deleteAll: () => fetch("/api/admin/purge", { method: "DELETE" }),
};

我們在自己的網站上發現了這個問題

用檢查客戶網站的同樣方法檢查 bologu.com 時,我們發現首頁、價格頁等頁面送出了完整的管理 API 清單。我們的管理區另有登入保護,沒有人進得去, 但那份清單等於免費送出後台地圖。我們把管理程式碼移到只有管理頁使用的檔案,並在 CI 加了一個步驟:只要這些路徑再出現在公開頁面,建置就失敗。

為什麼這很重要

  • 隱藏按鈕不等於存取控制:OWASP 舉例說明,若網站只在瀏覽器的 JavaScript 檢查管理員權限,攻擊者直接對管理網址送出請求就能繞過。存取控制只有放在伺服器端才有效。
  • API 清單是攻擊的起點:找出管理頁面與 API 是 OWASP 測試指南中的早期步驟。如果你的 JS 已經寫明,來探索網站的人或 AI 就不必猜了。
  • 只要有任何一個管理 API 忘了在伺服器端檢查權限,它就能被直接呼叫,包括會刪除資料或退款的 API。

為什麼延遲載入(lazy load)沒用

常見的建議是把管理頁改成延遲載入(React.lazy 或 import())。這只是把管理程式碼移到另一個檔案,那個檔案仍然公開, 而且檔名就寫在主檔案裡。我們建置了一個小型 Vite 應用程式來驗證:

// main JS file after "vite build", with the admin page lazy-loaded:
...import("./admin-BcREgPCl.js")...
// anyone can open https://your-site/assets/admin-BcREgPCl.js
// and read /api/admin/users, /api/admin/orders/refund ...

真正能藏起來的方法有兩種:把管理應用程式放到需要先登入才能載入檔案的獨立子網域(例如放在 Cloudflare Access 後面), 或在 Next.js App Router 中只從 app/admin 底下 import 管理程式碼,讓管理檔名不會出現在公開頁面。

2 分鐘自己檢查

  1. 用無痕視窗打開首頁,按 F12 → Sources,再按 Ctrl+Shift+F 搜尋 /api/admin(或你的管理路徑)。
  2. 如果找到,在同一個無痕視窗(未登入)打開任一管理 API 網址,應該得到 401、403 或被導向登入頁。若拿到資料,請立刻修正。

依這個順序修正

  1. 每個管理端點都在伺服器端檢查權限:從 session 或資料庫讀取角色,絕不相信瀏覽器送來的值,預設拒絕。
  2. 把管理程式碼與公開頁面分開,方法如上。
  3. 防止再次發生:在 CI 建置後加一個步驟,若公開頁面的 JS 含有 /api/admin 就讓它失敗。

讓 AI 幫你修正的 prompt

My public pages ship JavaScript that names my admin API (e.g. /api/admin/...).
1. List every admin endpoint and show me the line on the SERVER that checks the caller is an
   admin (role read from the session or database, never from a value the browser sends).
   Add the check where it is missing; deny by default.
2. Move the admin API calls out of the module that public pages import. Next.js App Router:
   a module imported only under app/admin. React/Vite/Vue SPA: lazy-loading alone is NOT
   enough (the chunk stays public); serve the admin app from its own subdomain behind login.
3. Add a CI step after the production build that fails if a JS file loaded by a public page
   contains "/api/admin".
Show me every file you changed.

讓 Bologu 幫你檢查

網站掃描(免費)會讀取公開頁面載入的 JS,包括延遲載入的檔案,發現管理或內部 API 時會提醒。如果只做延遲載入, 這一項仍會出現,因為管理檔案還是下載得到。GitHub 程式碼掃描則能幫你找出伺服器端忘了檢查權限的 API。

資料來源