연습 - Node.js 프로젝트에서 종속성 업데이트 관리

완료됨

Tailwind Traders로부터 오래된 종속성이 있는 앱과 관련된 작업을 의뢰받았습니다. 앱은 작으며 몇 개의 종속성만 포함합니다. 코드를 업데이트하는 것은 간단해야 합니다. 앱을 업데이트하여 최신 기능을 활용할 수 있는지 알아보세요. 도중에 취약성을 발견하는 경우 해결해야 합니다.

시작하기

  1. 새 터미널 창(Ctrl + Shift + `)에서 이 연습을 위해 파일이 있는 폴더로 변경합니다.

    cd ../7-exercise-dependency-management
    
  2. 다음 명령을 실행하여 종속성을 설치합니다.

    npm install
    

    설치된 패키지와 취약성에 대한 출력이 표시되어야 합니다.

  3. package.json 파일을 열고 dependencies 섹션을 봅니다.

    "lodash": "^1.1.0",
    "node-fetch": "^1.0.2"
    

    패턴은 종속성을 지원하기 위해 부 버전에 대한 업데이트를 나타내는 삽입 (^) 문자를 지정합니다. 1.x.

  4. index.js 파일을 열어 앱에서 패키지 종속성이 사용되는 방식을 이해합니다.

    const fetch = require('node-fetch')
    const _ = require('lodash');
    const path = require('path');
    const fs = require('fs');
    
    async function run() {
      const response = await fetch("https://dev.to/api/articles?state=rising");
      const json = await response.json();
      const sorted = _.sortBy(json, ["public_reactions_count"], ['desc']);
      const top3 = _.take(sorted, 3);
    
      const filePrefix = new Date().toISOString().split('T')[0];
      fs.writeFileSync(path.join(__dirname, `${filePrefix}-feed.json`), JSON.stringify(top3, null, 2));
    }
    
    run();
    

    이 코드는 node-fetch 패키지를 사용하여 REST API에서 데이터를 가져옵니다. 데이터를 정렬하고 lodash 패키지를 사용하여 상위 3개 결과를 사용하여 응답을 처리합니다. 결과는 파일에 저장됩니다.

npm audit

취약성이 있는지 확인하려면 다음 명령을 실행합니다.

npm audit

다음 예시와 유사한 출력이 표시됩니다.

# npm audit report

lodash  <=4.17.20
Severity: critical
Regular Expression Denial of Service (ReDoS) in lodash - https://github.com/advisories/GHSA-x5rq-j2xg-h7qm
Prototype Pollution in lodash - https://github.com/advisories/GHSA-fvqr-27wr-82fm
Prototype Pollution in lodash - https://github.com/advisories/GHSA-jf85-cpcp-j695
Command Injection in lodash - https://github.com/advisories/GHSA-35jh-r3h4-6jhm
Prototype Pollution in lodash - https://github.com/advisories/GHSA-4xc9-xhrj-v574
Regular Expression Denial of Service (ReDoS) in lodash - https://github.com/advisories/GHSA-29mw-wpgm-hmr9
fix available via `npm audit fix --force`
Will install lodash@4.17.21, which is a breaking change
node_modules/lodash

node-fetch  <=2.6.6
Severity: high
The `size` option isn't honored after following a redirect in node-fetch - https://github.com/advisories/GHSA-w7rc-rwvf-8q5r
node-fetch forwards secure headers to untrusted sites - https://github.com/advisories/GHSA-r683-j2x4-v87g
fix available via `npm audit fix --force`
Will install node-fetch@3.3.2, which is a breaking change
node_modules/node-fetch

2 vulnerabilities (1 high, 1 critical)

To address all issues (including breaking changes), run:
npm audit fix --force

취약성과 문제를 해결하는 패키지 버전이 출력됩니다.

Will install lodash@4.17.21, which is a breaking change
Will install node-fetch@3.3.2, which is a breaking change

npm outdated

터미널에서 다음 명령을 실행하여 오래된 종속성을 확인합니다.

npm outdated

다음 예시와 유사한 출력이 표시됩니다.

Package     Current  Wanted   Latest  Location                 Depended by
lodash        1.3.1   1.3.1  4.17.21  node_modules/lodash      7-exercise-dependency-management
node-fetch    1.7.3   1.7.3    3.3.2  node_modules/node-fetch  7-exercise-dependency-management

현재 버전과 원하는 버전은 동일하지만 최신 버전이 다릅니다. package.json에 지정된 의미 체계 업데이트 전략이 충족되었지만 취약성이 여전히 존재합니다.

npm update

  1. 보다 중요한 패키지부터 시작하여 취약성을 편집하기 위한 주요 변경 내용을 명시적으로 허용하도록 package.json 파일을 편집합니다.

    "node-fetch": "^2.6.6"
    
  2. 업데이트가 어떤 작업을 수행하는지 확인하려면 다음 명령을 실행합니다.

    npm update --dry-run
    
    added 3 packages, removed 4 packages, and changed 1 package in 508ms
    
  3. 다음 명령을 실행하여 package.json을 기반으로 프로젝트를 업데이트합니다.

    npm update
    
  4. 다음 명령을 실행하여 node-fetch에 대한 취약성이 수정되었는지 확인합니다.

    npm audit
    
    # npm audit report
    
    lodash  <=4.17.20
    Severity: critical
    Regular Expression Denial of Service (ReDoS) in lodash - https://github.com/advisories/GHSA-x5rq-j2xg-h7qm
    Prototype Pollution in lodash - https://github.com/advisories/GHSA-fvqr-27wr-82fm
    Prototype Pollution in lodash - https://github.com/advisories/GHSA-jf85-cpcp-j695
    Command Injection in lodash - https://github.com/advisories/GHSA-35jh-r3h4-6jhm
    Prototype Pollution in lodash - https://github.com/advisories/GHSA-4xc9-xhrj-v574
    Regular Expression Denial of Service (ReDoS) in lodash - https://github.com/advisories/GHSA-29mw-wpgm-hmr9
    fix available via `npm audit fix --force`
    Will install lodash@4.17.21, which is a breaking change
    node_modules/lodash
    
    1 critical severity vulnerability
    
    To address all issues (including breaking changes), run:
      npm audit fix --force
    
  5. 프로젝트에 테스트가 있는 경우 이를 실행하여 업데이트로 인해 문제가 발생하지 않았는지 확인합니다.

  6. 동일한 단계에서 lo-dash를 취약성이 없는 4.17.20 버전으로 업데이트합니다.

    취약성은 수정되었지만 node-fetch 버전은 여전히 주 버전보다 뒤떨어져 있습니다. 모든 테스트가 통과하면 package.json 파일에 지정된 버전을 최신 버전으로 수정합니다.

    "node-fetch": "^3.3.2"
    
  7. 그리고 다음 명령을 실행하여 프로젝트를 업데이트합니다.

    npm update
    

    이제 프로젝트에 npm 취약성이 없으며 현재 주 버전에 있어야 합니다.

  8. package.jsonpackage-lock.json 파일을 체크 인합니다.

    축하합니다! 프로젝트의 종속성을 업데이트하고 취약성을 수정했습니다.

개발 컨테이너 정리

프로젝트를 완료한 후 개발 환경을 정리하거나 일반적인 상태로 되돌릴 수 있습니다.

GitHub Codespaces 환경을 삭제하면 계정에 대해 얻을 수 있는 코어당 무료 사용 권한을 최대화할 수 있습니다.

중요

GitHub 계정의 자격에 대한 자세한 내용은 GitHub Codespaces 월별 포함된 스토리지 및 코어 시간을 참조하세요.

  1. GitHub Codespaces 대시보드(https://github.com/codespaces)에 로그인합니다.

    Screenshot of all the running codespaces including their status and templates.

  2. codespace에 대한 상황에 맞는 메뉴를 열고 삭제를 선택합니다.

    Screenshot of the context menu for a single codespace with the delete option highlighted.