사용자가 입력한 정보를 외부로 출력할 때, 오염된 정보 소독하기
- html에서 script 태그 사용으로 오염된 정보 유출 예시
<script> location.href='http://example.com'; </script>
- script 태그로 인해 사용자가 html 페이지 접속시 다른 사이트로 이동해버림
▶ script 태그 비활성화하는 작업 진행 - 살균,소독(sanitize)
npm을 통해 sanitize-html 모듈 사용
https://www.npmjs.com/package/sanitize-html?activeTab=readme
sanitize-html
Clean up user-submitted HTML, preserving allowlisted elements and allowlisted attributes on a per-element basis. Latest version: 2.8.1, last published: a month ago. Start using sanitize-html in your project by running `npm i sanitize-html`. There are 1477
www.npmjs.com
npm init
- 기본 값으로 [Enter] 계속 클릭하여 진행
- 프로젝트에 package.json 파일이 생성 됨
npm install -S sanitize-html
- 다운로드 진행
* -g : pm2를 컴퓨터 전역에서 사용할 수 있는 독립된 프로그램으로 설치
* -S : 현재 진행하는 프로젝트에서 사용할 부품으로써의 프로그램 설치
- 프로젝트에 node_module 디렉토리 생성 됨
기본 사용
var sanitizeHtml = require('sanitize-html');
// 오염될 수 있는 정보인 dirty
var dirty = 'some really tacky HTML';
// 살균하기
var clean = sanitizeHtml(dirty);
사용 예제 적용
var sanitizeHtml = require('sanitize-html');
fs.readFile(`data/${filteredId}`, 'utf8', function(err, description){
// 오염될 수 있는 정보인 title, description 살균하기
var sanitizedTitle = sanitizeHtml(title);
var sanitizedDescription = sanitizeHtml(description);
});
- html에서 script 태그(예민한 태그) 살균
* 다른 특정 태그 허용하기
var sanitizeHtml = require('sanitize-html');
fs.readFile(`data/${filteredId}`, 'utf8', function(err, description){
// 오염될 수 있는 정보인 title, description 살균하기
var sanitizedTitle = sanitizeHtml(title);
var sanitizedDescription = sanitizeHtml((description, {
allowedTags:['h1'] // h1 태그 허용
});
});
- h1 태그는 허용하여 살려둠
* 생활코딩 WEB2-Node.js-47.1, WEB2-Node.js-47.2 ,WEB2-Node.js-47.3 강의 기반으로 작성됨
'JavaScript > Node.js' 카테고리의 다른 글
[Node.js] 쿠키(Cookie) 사용하기 (0) | 2023.02.21 |
---|---|
[Node.js] 파일 쓰기(fs.writeFile), 파일 삭제하기(fs.unlink) (0) | 2023.01.16 |
[Node.js] 동기(Syncronous)와 비동기(Asyncronous) (0) | 2023.01.14 |
[Node.js] 파일 읽기(fs.readFile), 파일 목록 알아내기(fs.readdir) (0) | 2023.01.11 |