在傳統網站開發中,安全檢測 往往需要人工反覆檢查:
這些工作不但耗時,而且容易遺漏。
因此,我們示範如何用 AI Agent 當資安顧問,做到:
server.js
建立一個模擬 APIagent.js
呼叫 API,收集 Response Headers + Bodyagent.js
把資料交給 Gemini 模型import express from "express";
import bodyParser from "body-parser";
const app = express();
const PORT = 3000;
app.use(bodyParser.json());
// 模擬一個不安全的登入 API
app.post("/login", (req, res) => {
const { username, password } = req.body;
// 這裡故意寫得很不安全 (只要帳密正確就回傳)
if (username === "admin" && password === "1234") {
res.cookie("session", "abc123", {
httpOnly: false, // 沒有 HttpOnly → JS 可以讀取
secure: false, // 沒有 Secure → HTTP 明文也會傳
});
return res.status(200).send("Login success (但 Cookie 設定不安全)");
}
return res.status(401).send("Login failed");
});
app.listen(PORT, () => {
console.log(`測試伺服器啟動:http://localhost:${PORT}`);
});
async function callServer() {
const res = await fetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: "admin", password: "1234" }),
});
const headers = Object.fromEntries(res.headers.entries());
const body = await res.text();
return { status: res.status, headers, body };
}
async function analyzeResponse(response) {
const prompt = `
你是一個資安顧問 AI。
以下是伺服器的回應,請檢查是否存在資安問題,並提供修正建議:
狀態碼: ${response.status}
Headers: ${JSON.stringify(response.headers, null, 2)}
Body: ${response.body}
輸出格式:
- 問題
- 原因
- 修正建議
`;
const result = await model.generateContent(prompt);
console.log("AI Agent 分析結果:\n");
console.log(result.response.text());
}
(async () => {
const response = await callServer();
await analyzeResponse(response);
})();