보안 헤더
Coddy Node.js 여정의 인증과 보안 섹션에 포함된 레슨. 17개 중 15번째.
브라우저는 기본적으로 추측하고 공유합니다. 텍스트 답변을 스크립트로 취급하고, 페이지가 링크한 모든 사이트에 페이지 주소를 보내며, 어디서든 스크립트를 실행할 수 있습니다. 몇 가지 응답 헤더로 이를 끌 수 있습니다.
X-Content-Type-Options: nosniff:Content-Type을 신뢰하고 절대 추측하지 않습니다.Referrer-Policy: no-referrer: 다른 사이트에 해당 사이트로 연결한 페이지가 무엇인지 알리지 않습니다.Content-Security-Policy: default-src 'self': 이 사이트에서만 스크립트, 스타일, 이미지를 불러옵니다.
Express는 공격자에게 무엇을 시도해야 할지 알려 주는 X-Powered-By: Express도 추가합니다. app.disable('x-powered-by')를 사용하면 이를 제거합니다. 미들웨어 하나로 모든 응답에 헤더를 설정할 수 있습니다.
app.use((req, res, next) => {
res.set('Strict-Transport-Security', 'max-age=31536000');
res.set('Permissions-Policy', 'camera=(), microphone=()');
next();
});챌린지
쉬움- 모든 응답에는
X-Content-Type-Options: nosniff와Referrer-Policy: no-referrer가 있습니다. - 페이지에는
Content-Security-Policy: default-src 'self'도 있습니다. 이 정책을 모든 응답에 설정해도 괜찮습니다. - 어떤 응답에도
X-Powered-By가 없습니다.
GET /notes를 보내고 Headers를 여세요. 로그인한 다음 GET /에 대해서도 똑같이 하세요.
직접 해보기
import express from 'express';
import { ObjectId } from 'mongodb';
import { randomBytes } from 'node:crypto';
import { parseCookies } from './cookies.js';
import { notes, sessions, users } from './db.js';
import { hashPassword, verifyPassword } from './passwords.js';
const app = express();
app.use(express.json());
// 유일한 관리자 계정입니다. 비밀번호는 환경 변수에서 가져옵니다.
await users.insertOne({ username: 'admin', role: 'admin', passwordHash: await hashPassword(process.env.ADMIN_PASSWORD) });
app.post('/signup', async (req, res) => {
const username = String(req.body.username ?? '').trim().toLowerCase();
const password = String(req.body.password ?? '');
if (!username || password.length < 8) {
return res.status(400).json({ error: 'Pick a username and a password of at least 8 characters' });
}
if (await users.findOne({ username })) {
return res.status(409).json({ error: 'That username is taken' });
}
await users.insertOne({ username, role: 'member', passwordHash: await hashPassword(password) });
res.status(201).json({ username });
});
app.post('/login', async (req, res) => {
const username = String(req.body.username ?? '').trim().toLowerCase();
const user = await users.findOne({ username });
if (!user || !(await verifyPassword(String(req.body.password ?? ''), user.passwordHash))) {
return res.status(401).json({ error: 'Wrong username or password' });
}
const sid = randomBytes(24).toString('base64url');
await sessions.insertOne({ _id: sid, userId: user._id, createdAt: new Date() });
res.cookie('sid', sid, {
httpOnly: true,
sameSite: 'lax',
secure: true,
maxAge: 24 * 60 * 60 * 1000,
});
res.json({ username: user.username });
});
// 세션 쿠키에 해당하는 사용자를 찾거나 401을 반환합니다.
async function requireUser(req, res, next) {
const { sid } = parseCookies(req.get('cookie'));
const session = sid && (await sessions.findOne({ _id: sid }));
const user = session && (await users.findOne({ _id: session.userId }));
if (!user) {
return res.status(401).json({ error: 'Log in first' });
}
req.user = { id: user._id.toHexString(), username: user.username, role: user.role };
next();
}
// 로그인한 사용자에게 이 역할이 없으면 403을 반환합니다.
function requireRole(role) {
return (req, res, next) => {
if (req.user.role !== role) {
return res.status(403).json({ error: 'Not allowed' });
}
next();
};
}
app.get('/me', requireUser, (req, res) => {
res.json({ username: req.user.username });
});
app.post('/logout', async (req, res) => {
const { sid } = parseCookies(req.get('cookie'));
if (sid) {
await sessions.deleteOne({ _id: sid });
}
res.clearCookie('sid');
res.status(204).end();
});
// 내 메모를 페이지로 보여줍니다.
app.get('/', requireUser, async (req, res) => {
const list = await notes.find({ owner: req.user.id }).toArray();
const items = list.map((note) => `<li>${note.text}</li>`).join('');
res.send(`<!doctype html><title>Vault</title><h1>${req.user.username}'s notes</h1><ul>${items}</ul>`);
});
// 메모: 각 사용자는 자신의 메모만 읽고 씁니다.
app.get('/notes', requireUser, async (req, res) => {
res.json(await notes.find({ owner: req.user.id }).toArray());
});
app.post('/notes', requireUser, async (req, res) => {
const note = { owner: req.user.id, text: String(req.body.text ?? '') };
await notes.insertOne(note);
res.status(201).json(note);
});
app.get('/notes/:id', requireUser, async (req, res) => {
if (!ObjectId.isValid(req.params.id)) {
return res.status(404).json({ error: 'Note not found' });
}
const note = await notes.findOne({ _id: new ObjectId(req.params.id), owner: req.user.id });
if (!note) {
return res.status(404).json({ error: 'Note not found' });
}
res.json(note);
});
app.delete('/notes/:id', requireUser, async (req, res) => {
if (!ObjectId.isValid(req.params.id)) {
return res.status(404).json({ error: 'Note not found' });
}
const { deletedCount } = await notes.deleteOne({ _id: new ObjectId(req.params.id), owner: req.user.id });
if (!deletedCount) {
return res.status(404).json({ error: 'Note not found' });
}
res.status(204).end();
});
// 관리자용: 계정이 몇 개 있는지 보여줍니다.
app.get('/admin', requireUser, requireRole('admin'), async (req, res) => {
res.json({ users: await users.countDocuments() });
});
app.listen(3000, () => {
console.log('Vault is running on port 3000');
});
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.