匠人学院 JR Academy
  • Position

    Where am I now, and where should I go?

    How your job is changing, where your experience can take you and what you still need for a target role, worked out from what you have actually done. Free, and the full result needs no sign-up.

    Analyse my career and skills

    Look up a career

    Will AI replace my job?AI impact and transition paths for common careersNew jobs in the AI eraWhat they do, what they need, how to move in

    Focused tools

    AI Engineer interview readiness30 timed questions on what you still need before interviewsCareer personality testDirections that suit how you workReturning to China checkJob prospects in China by school, major and graduation date

    AI coach

    Talk to your AI coachStill unsure after your result? Talk through what is holding you back
  • Core courses

    AI Engineer BootcampEngineering bootcamp from LLM apps to agentsAI Engineer Full-Stack Project Class16 weeks · RAG and full-stack AI projectsVibe Coding Masterclass8 weeks · direct agents to build and ship a productAI Essentials10 hours · use AI for email, reports, data and copyAI Office Automation Course8 weeks · help a whole company adopt AIOne-Person Company (OPC) Bootcamp15 weeks in person · build a one-person company with AIAll courses →

    AI engineering

    Machine Learning & Data Engineering Full-Stack ClassAI Agent & MCP Project BootcampAI Engineer Core TechniquesAI Engineer FoundationsAI Engineer Advanced: RAG to Agents and TuningClaude Code TasterAll AI engineering courses →

    AI at work

    AI Coding for everyoneClaude Code One-Day Masterclass (Non-Technical)Enterprise AI Automation BootcampAI Marketing BootcampAI Risk, Governance and Audit CourseOpenClaw 4-Week Personal AI Assistant BootcampAll AI-at-work courses →

    Career development

    AI Product Manager (BA) Bootcamp + InternshipAustralia IT Interview BootcampAustralia IT Technical Interview BootcampAustralia IT Resume BootcampAustralia Big Tech Job Search BootcampAustralia IT Career Planning BootcampAll career courses →

    Learn free first

    Vibe CodingAI for office workPrompt MasterAI EngineerAI data analysisResource centerInstructorsAll learning paths →
  • Evidence

    What will convince an employer?

    Certifications, projects, team work and competition entries, collected into one portfolio.

    See the portfolio

    Certifications

    Cert Master · all certificationsPrep and mock exams for AWS, Azure, GCP, Claude and moreAWS CLF-C02Entry-level AWS cloud certificationAWS SAA-C03Entry certification for cloud architectsClaude certificationsAnthropic Claude certification seriesAll certifications →

    Projects and team work

    P3 team projectsBuild a project with real teammates in a simulated team workflowP3 project experienceThe parts of a P3 project that go on your resumeDemo DayProject showcaseP3 certificatesProof once a project is completeAll of P3 →

    Competitions and work

    HackathonsBuild something against the clockSubmit your workAdd your project to the showcaseCareerOS portfolioDo tasks in the desktop app; your results become portfolio pieces
    Cert MasterBrowser extension, app and mini programScreenshot a question for analysis and practise anywhereAbout Cert Master
  • Connect

    How do I get myself in front of employers?

    Resume, interviews, referrals and mentors. See how far you are from the target role first, then decide what to fix.

    Start with Jobpin

    Resume and openings

    Graduate careersGraduate preparation across Australia, China, Malaysia, Singapore, the US and UKJobpinAI job search workspace: resume, roles, applicationsAI resumeRewrite your resume against a job descriptionReferralsRoles shared by students and mentorsOpportunitiesInternships, projects and collaborationsOffer boardOffers students have received

    Interviews

    AI Engineer interview guideSeven areas, with worked examplesFDE interview guideFive rounds, from scoping to the customer roundAI mock interviewPractise by text or voice and see the gapsInterview storiesReal interview experiencesSystem Design handbookPrepare for system design interviewsAll interview prep →

    Mentors

    1:1 mentorsBook AI, career and technical mentors by the hourGroup tutoringShare a tutor with a few others and pay less eachCareer coachingResume, interview and direction packages
    Jobpin desktopOne workspace for the whole job searchOrganise real experience and refine resume versions for target roles on macOS or Windows.About Jobpin
BusinessMembershipDownload CareerOS
0
匠人学院 JR Academy

Follow Us

linkedinfacebooktwitterinstagramyoutube

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png
Airbotix · AI learning & creation for kids Another Life · AI story game
Products46

CareerOS and tools

  • CareerOS
  • Cert Master
  • Jobpin
  • Jobpin web
  • Jobpin report
  • Jobpin desktop download
  • My job search reports
  • Buy report credits
  • Jobpin billing
  • AI Toolbox
  • AI Skill Marketplace

Membership

  • Membership
  • AI membership

Courses

  • Bootcamps
  • Training Camp
  • Kanban learning
  • AI Builder course
  • MCP course
  • NotebookLM workshop
  • Business Analyst course
  • Web Full-Stack Bootcamp
  • DevOps Bootcamp
  • Data Engineering Bootcamp
  • Data Analysis Bootcamp
  • Coding for Beginners
  • Algorithm Bootcamp

Career services

  • Graduate careers
  • Graduate careers in Australia
  • Graduate careers in China
  • Graduate careers in Malaysia
  • Graduate careers in Singapore
  • Graduate careers in the US
  • Graduate careers in the UK
  • 1:1 coaching
  • Career coaching
  • AI Engineer VIP
  • BA & PM Internship
  • Data Science Internship
  • Data Analysis Internship
  • Marketing Internship
  • Resume Review
  • Interview Coaching
  • Job Application Service
  • Job Monitoring
  • LinkedIn Management
  • LinkedIn Networking
Library57

Learning paths

  • All Learning Paths
  • AI Engineer
  • Context Engineering
  • Vibe Coding
  • Prompt Master
  • AI Builder
  • AI Product Manager
  • Python Basics
  • AI Productivity
  • AI Data Analysis
  • AI Finance
  • AI Content Creation
  • AI Image Creation
  • Frontend Development
  • Hermes Agent
  • OpenClaw Local Agent

Interactive labs

  • Prompt Lab
  • Frontend Lab
  • JavaScript Lab
  • Python Lab
  • AWS Lab
  • Azure Lab
  • LLM Lab
  • Git Lab

Reference and guides

  • Resources
  • Wiki
  • Cheat sheets
  • Roadmaps
  • AI roadmaps
  • Videos
  • Ebooks
  • Blog
  • Interview handbook
  • Mock exams
  • Free resources

Cities

  • Sydney
  • Melbourne
  • Brisbane
  • Adelaide
  • Singapore
  • Kuala Lumpur
  • London
  • New York
  • San Francisco
  • Los Angeles
  • Seattle
  • Toronto
  • Vancouver

Immigration

  • Australia Immigration
  • Skilled Visa 189/190/491
  • Employer Sponsored 482/186/494
  • Business Visa 188/888
  • UK Immigration
  • US Immigration
  • Canada Immigration
  • Singapore immigration
  • Malaysia immigration
Business20

For business

  • AI for Business
  • Business portal sign-in
  • Corporate Training
  • Internship Partnership
  • Recruitment Partnership
  • Enterprise (EN)

Metatree AI Lab

  • Metatree AI Lab (Chinese)
  • AI solutions (Chinese)
  • Digital employees (Chinese)
  • Case studies (Chinese)
  • Metatree AI Lab
  • AI services
  • Digital employees
  • Case studies

AI education for kids

  • Airbotix — AI Learning & Creation for Kids
  • AU Family Resource Hub
  • NAPLAN Report Guide
  • My School Data Guide
  • Sydney Private School Fees 2026
  • Kids Coding Programs
About15

Company

  • About Us
  • Our Mentors
  • Become a Mentor
  • Metaverse Classroom
  • JR Careers
  • Another Life — AI Story Game
  • Contact Us

Help and policies

  • FAQs
  • Terms & Conditions
  • Privacy Policy
  • Cancellation & Refund Policy
  • Site map

Friend links

  • CS Browser

Contact

  • hello@jiangren.com.au
  • 0421-672-555

Offices

Level 10b, 144 Edward Street, Brisbane CBD (Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
45A13, Block B, Oriental Hope Tianxiang Plaza, 500 Tianfu Avenue Middle Section, Wuhou District, Chengdu, Sichuan, China
Business Hub, 155 Waymouth St, Adelaide SA 5000
Disclaimer
footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

All content on the JR Academy website, including course materials, logos, and information provided, is protected under Australian intellectual property laws. Unauthorized use, sale, distribution, reproduction, or modification is strictly prohibited. Violations may result in legal action. By accessing our website, you agree to respect our intellectual property. JR Academy Pty Ltd reserves all rights, including patents, trademarks, and copyrights. Any infringement will be subject to legal prosecution. View Terms of Service

© 2017-2026 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572

HomeLearnCoursesCerts
  1. Home
  2. Learn
  3. Blog
  4. npm 发布安全指南:从 Claude Code 源码泄露学到的 5 个教训
JR Academy · BlogCareer insights

npm 发布安全指南:从 Claude Code 源码泄露学到的 5 个教训

Anthropic Claude Code 512K 行源码因 npm 打包失误泄露。本文分析泄露原因,提供 npm 发布安全检查清单、.npmignore 配置、package.json files 字段最佳实践,帮你避免同样的错误。

Published2026-04-05
Reading time2 min
Author

Contents

  • npm 包发布安全:一个配置失误的代价
  • 为什么你应该关注 npm 发布安全
  • 实操指南:5 步加固你的 npm 发布流程
  • 第 1 步:用 files 字段做白名单,而不是用 .npmignore 做黑名单
  • 第 2 步:发布前用 npm pack --dry-run 检查
  • 第 3 步:显式禁用 source map 生成
  • 第 4 步:添加 prepublishOnly 钩子做自动检查
  • 第 5 步:在 CI 中加入发布内容审计
  • 常见问题
  • .npmignore 和 package.json 的 files 字段冲突时谁优先?
  • 我的 npm 包已经发布了敏感文件怎么办?
  • source map 到底会暴露什么?
  • JR Academy 相关资源

npm 包发布安全与 Claude Code 源码泄露分析

npm 包发布安全:一个配置失误的代价

3 月 31 日,Anthropic 的 Claude Code——一个月活数百万的 AI 编程助手——的完整源码被发现公开在了 npm 公共仓库上。512,000 行 TypeScript 代码,1,906 个文件,包含 44 个未发布功能的 feature flag 和内部模型代号。原因?发布时漏了一个 .npmignore 配置。

这不是什么高深的供应链攻击,也不是零日漏洞。就是一个工程师忘了排除 source map 文件。但后果是 GitHub 历史上增长最快的 repo——2 小时内 5 万星。

如果 Anthropic 这种级别的公司都会犯这个错,你的项目也有可能。这篇文章不是要嘲笑谁,而是帮你检查自己的发布流程有没有同样的漏洞。


为什么你应该关注 npm 发布安全

npm 生态每天处理超过 20 亿次下载。你发布到 npm 的任何东西都是永久公开的——即使你在几分钟内 unpublish,自动化爬虫和镜像已经抓走了。

常见的泄露内容:

  • Source map 文件(.map):完整的原始源码,包括注释
  • 环境变量文件(.env、.env.local):API 密钥、数据库密码
  • 构建产物和缓存(.next/、dist/debug/):可能包含调试信息
  • 测试文件和 fixtures:可能包含真实数据
  • 内部文档:架构设计、安全审计报告

Claude Code 泄露的核心链条是:Bun 构建 → 默认生成 .map 文件 → .map 引用 R2 上的 zip → zip 包含完整源码 → npm publish 没排除 .map → 全球可见。


实操指南:5 步加固你的 npm 发布流程

第 1 步:用 files 字段做白名单,而不是用 .npmignore 做黑名单

Claude Code 泄露的根本原因是黑名单思维——"我要排除哪些文件"。但你永远无法列举所有不该发布的文件。

正确做法:在 package.json 里用 files 字段做白名单,只包含你明确知道该发布的文件:

{
  "name": "your-package",
  "files": [
    "dist/**/*.js",
    "dist/**/*.d.ts",
    "README.md",
    "LICENSE"
  ]
}

注意:files 字段不会排除 package.json、README.md、LICENSE 和 CHANGELOG.md——这些永远会被包含。但其他所有文件默认被排除。

第 2 步:发布前用 npm pack --dry-run 检查

这是最简单也最容易被忽略的一步。在 npm publish 之前,先看看到底会发布什么:

# 列出所有会被打包的文件
npm pack --dry-run

# 或者生成 tarball 然后手动检查
npm pack
tar -tzf your-package-1.0.0.tgz

把这个命令加入你的 CI/CD 流程,用脚本自动检查是否有敏感文件:

#!/bin/bash
# scripts/check-publish.sh
SENSITIVE_PATTERNS=("*.map" "*.env" ".env*" "*.pem" "*.key" "*secret*" "*credentials*")

FILES=$(npm pack --dry-run 2>&1)

for pattern in "${SENSITIVE_PATTERNS[@]}"; do
  if echo "$FILES" | grep -q "$pattern"; then
    echo "❌ 发现敏感文件: $pattern"
    exit 1
  fi
done

echo "✅ 发布内容检查通过"

第 3 步:显式禁用 source map 生成

不管你用什么构建工具,生产发布时都应该显式关闭 source map:

// webpack.config.js
module.exports = {
  mode: 'production',
  devtool: false, // 不要用 'source-map' 或 'hidden-source-map'
};

// vite.config.ts
export default defineConfig({
  build: {
    sourcemap: false,
  },
});

// tsconfig.json
{
  "compilerOptions": {
    "sourceMap": false,
    "declarationMap": false
  }
}

如果你用 Bun(Claude Code 的构建工具):

# bun build 默认生成 source map,必须显式关闭
bun build --no-sourcemap ./src/index.ts --outdir ./dist

第 4 步:添加 prepublishOnly 钩子做自动检查

在 package.json 里加一个发布前的自动检查脚本:

{
  "scripts": {
    "prepublishOnly": "npm run build && npm run test && node scripts/check-no-secrets.js"
  }
}
// scripts/check-no-secrets.js
const { execSync } = require('child_process');

const output = execSync('npm pack --dry-run 2>&1', { encoding: 'utf8' });
const lines = output.split('\n');

const forbidden = ['.map', '.env', '.pem', '.key', 'secret', 'credential', '.DS_Store'];
const violations = [];

for (const line of lines) {
  for (const pattern of forbidden) {
    if (line.toLowerCase().includes(pattern)) {
      violations.push(line.trim());
    }
  }
}

if (violations.length > 0) {
  console.error('🚫 以下文件不应该被发布:');
  violations.forEach(v => console.error(`  - ${v}`));
  process.exit(1);
}

console.log('✅ npm 包内容安全检查通过');

第 5 步:在 CI 中加入发布内容审计

GitHub Actions 示例:

# .github/workflows/publish-audit.yml
name: Publish Audit
on:
  pull_request:
    paths:
      - 'package.json'
      - '.npmignore'
      - 'tsconfig.json'

jobs:
  audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npm run build
      - name: Check publish contents
        run: |
          npm pack --dry-run 2>&1 | tee pack-contents.txt
          if grep -E '\.(map|env|pem|key)$' pack-contents.txt; then
            echo "::error::发现不应发布的敏感文件"
            exit 1
          fi

常见问题

.npmignore 和 package.json 的 files 字段冲突时谁优先?

如果 files 字段存在,它的优先级最高。.npmignore 只在没有 files 字段时生效。最佳实践是只用 files,不用 .npmignore——白名单永远比黑名单安全。

我的 npm 包已经发布了敏感文件怎么办?

  1. 立即 npm unpublish your-package@affected-version(72 小时内可操作)
  2. 轮换所有可能泄露的密钥和凭证
  3. 检查 npm 镜像和 CDN 缓存(unpkg、jsDelivr 等)是否仍有缓存
  4. 修复配置后发布新版本

注意:npm 的 unpublish 政策是 72 小时内可以撤回,但自动化爬虫可能在几分钟内就已经备份了你的包。预防永远比补救重要。

source map 到底会暴露什么?

Source map 是构建产物到原始源码的完整映射。一个 .map 文件通常包含:

  • 完整的原始源代码(包括注释)
  • 文件路径和目录结构
  • 变量名、函数名(即使代码被混淆了)
  • 有时还包含内联的 source content

Claude Code 的情况更极端——source map 指向了一个外部 zip 包,里面是未经任何处理的完整 TypeScript 源码。


JR Academy 相关资源

  • Claude Code 工作流指南 — 了解 Claude Code 的正确打开方式
  • JR Academy DevOps 课程 — 系统学习 CI/CD、安全发布流程和云原生部署
  • Gemma 4 开发者指南 — 用开源模型构建你的 AI 应用

这篇文章由 Claude Code 源码泄露事件启发。安全不是事后补救的东西,是发布流程的一部分。花 10 分钟检查你的 npm 发布配置,总好过花 10 天做危机公关。

Author
Share or copy the link

Related certifications

Start with a few sample questions or a free chapter. The exam guide covers what the exam tests; the question bank lets you practise by exam domain.

Foundational

Claude Certified Architect – Foundations

CCAR-F

Sample questionsExam guide
Foundational

Claude Certified Developer – Foundations

CCDV-F

Question bankExam guide
Associate

Claude Certified Associate – Foundations

CCAO-F

Question bankExam guide

Related learning resources

  • Vibe Coding Hub
  • Prompt engineering
← Previous article推荐一个老板和高管会喜欢的OpenClaw私享会Next article →AI 日报 2026-04-06:Claude Mythos 万亿参数模型曝光,GPT-5.4 首次超越人类基准

Related articles

🇦🇺测一下:袋鼠国码农能当FDE吗?

2026-12-01

Monash 研究:肠道酸度是膳食纤维降血压的关键;AI 搬运新闻冲击维州选举信息;MPAC 公布 2027 演出季

2026-12-01

Adelaide 物理学家获 $250,000 总理科学奖;全球葡萄酒消费六十年降四分之一;残障师范生实习障碍研究

2026-12-01

DVA-C03今日上线首发 · Google Cloud AI Agent认证完整解析 · AZ-401本月GA替代AZ-400

2026-12-01

Anthropic推迟下一代模型并调百人做安全,AWS推出AI办公三件套,Google让用户单独关掉AI训练

2026-12-01

GitHub Copilot 实战指南 — Copilot AI Code Review:30 秒让 AI 帮你审 PR,三档深度随需切换

2026-11-30
View all articles →

Done reading? Next steps

Not sure what to learn next? Tell us where you are

Tell us what you do now and where you want to go. See your gaps in skills, evidence, experience, expression and positioning, and what to work on first. No sign-in needed.

Compare with my situation
  • SkillAI Engineer Bootcamp13 weeks, 12 Theory + 13 Practice live classes. You build one Agent system across Context, RAG, Tools, Memory and production Evals. Built for Applied AI and Agent Engineer roles.See the program →
  • PositioningLearning roadmaps by roleFrontend, backend, data, AI and more, laid out stage by stage in the order to learn them.All roadmaps →
  • ExpressionTry an AI mock interviewPick a role and run a mock interview to practise explaining your experience and projects.Practise now →

Not sure what to do next?

Take this page's topic with you and see where your gaps are.

Compare with my situation
JR Academy
AI learning for the global Chinese community
BootcampsFree resourcesLearn AICareer coaching
精选推荐
AI Career Impact Map
Assess career exposure and explore transition paths and learning options
Popular tool
AI & Data Bootcamps
Build your skills through structured courses and hands-on projects
Popular courses
1:1 Career Coaching
Work with an experienced mentor on your resume and interview preparation
Career coaching
Custom Corporate Training
AI training tailored to your team
Business services
Popular tags
Vibe CodingAI codingCursorClaudeJob searchPromptFrontend developmentBackend development
Subscribe to updates

Receive AI learning resources, technical tutorials and career advice by email.

We respect your privacy and do not send spam.