typescript-security
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript / JavaScript Security Development Guide
TypeScript / JavaScript安全开发指南
Provide a structured approach to building secure TypeScript and JavaScript applications, covering the OWASP Top 10, secure coding patterns, and verification checklists. Apply these guidelines throughout the secure development lifecycle — from threat modeling through deployment. This guide covers both server-side (Node.js, Deno, Bun) and client-side (browser) contexts.
本文提供构建安全TypeScript和JavaScript应用的结构化方法,涵盖OWASP Top 10、安全编码模式及验证检查清单。在安全开发生命周期的各个阶段(从威胁建模到部署)均需遵循这些指南。本指南同时覆盖服务端(Node.js、Deno、Bun)和客户端(浏览器)场景。
Secure Development Lifecycle
安全开发生命周期
Phase 1: Threat Modeling and Secure Design
阶段1:威胁建模与安全设计
Before writing code, identify and mitigate threats at the design level:
- Identify trust boundaries — Map where untrusted data enters the system (HTTP requests, WebSocket messages, file uploads, database reads, environment variables, third-party APIs, , URL parameters, localStorage)
postMessage - Map data flows — Trace sensitive data (credentials, PII, tokens) through the system and verify protection at each stage
- Enumerate entry points — List all routes, endpoints, CLI arguments, message queue consumers, WebSocket handlers, and scheduled tasks
- Map attack surfaces to OWASP Top 10 — Cross-reference each entry point against the OWASP categories in the quick reference table below
Design with security controls built-in:
- Centralized authentication and authorization middleware — never scatter auth checks across handlers
- Input validation at every trust boundary — validate early, reject invalid data before processing
- Least-privilege database access — use read-only connections where writes are not needed
- Defense in depth — layer multiple controls (input validation + parameterized queries + WAF)
- Fail securely — deny by default, require explicit grants
- Server-side enforcement — never rely solely on client-side validation or access controls
编写代码前,需在设计层面识别并缓解威胁:
- 识别信任边界 — 绘制不可信数据进入系统的路径(HTTP请求、WebSocket消息、文件上传、数据库读取、环境变量、第三方API、、URL参数、localStorage)
postMessage - 映射数据流 — 追踪敏感数据(凭证、个人可识别信息PII、令牌)在系统中的流转,验证每个阶段的保护措施
- 枚举入口点 — 列出所有路由、端点、CLI参数、消息队列消费者、WebSocket处理器及定时任务
- 将攻击面映射到OWASP Top 10 — 将每个入口点与下方快速参考表中的OWASP类别交叉对照
设计时内置安全控制:
- 集中式身份验证与授权中间件 — 切勿在多个处理器中分散权限检查逻辑
- 在每个信任边界处进行输入验证 — 尽早验证,在处理前拒绝无效数据
- 数据库最小权限访问 — 无需写入操作时使用只读连接
- 纵深防御 — 多层控制叠加(输入验证 + 参数化查询 + Web应用防火墙WAF)
- 安全失败机制 — 默认拒绝,需显式授权
- 服务端强制执行 — 切勿仅依赖客户端验证或访问控制
Phase 2: Secure Implementation
阶段2:安全实现
Critical Prohibitions
关键禁止项
Never use these patterns. Violations are high-severity findings in any review.
| Never | Instead |
|---|---|
| |
| |
| String concatenation / template literals in SQL | Parameterized queries ( |
| |
| DOMPurify + explicit sanitization |
| |
| MD5 / SHA1 for password hashing | |
| |
| Validated schema (Zod, class-validator) + |
| Static imports with allowlisted modules |
| Hardcoded secrets in source code | Environment variables or secret manager (Vault, AWS SM) |
| Environment-specific configuration |
| Zod, io-ts, or class-validator after parsing |
| Escape user input or use a safe regex library |
| Isolated worker threads or dedicated sandbox |
Disabling TLS verification ( | Proper certificate management |
绝不能使用以下模式,任何违反情况在代码审查中均属于高严重性问题。
| 禁止使用 | 推荐替代方案 |
|---|---|
| |
| |
| SQL中使用字符串拼接/模板字面量 | 参数化查询( |
使用 | |
| DOMPurify + 显式净化处理 |
| |
| MD5 / SHA1用于密码哈希 | |
| |
| 验证模式(Zod、class-validator) + |
| 静态导入并使用白名单模块 |
| 源代码中硬编码密钥 | 环境变量或密钥管理器(Vault、AWS Secrets Manager) |
生产环境中保留 | 环境专属配置 |
| 解析后使用Zod、io-ts或class-validator验证 |
| 转义用户输入或使用安全正则库 |
| 隔离工作线程或专用沙箱 |
禁用TLS验证( | 规范证书管理 |
Secure Implementation References
安全实现参考
- For OWASP Top 10 details with vulnerable → secure code examples: See references/owasp-top-10.md
- For secure coding patterns organized by domain (input validation, auth, crypto, DOM security, subprocess, file I/O, web frameworks): See references/secure-coding.md
- 包含OWASP Top 10详细说明及漏洞代码→安全代码示例:查看references/owasp-top-10.md
- 按领域分类的安全编码模式(输入验证、权限、加密、DOM安全、子进程、文件I/O、Web框架):查看references/secure-coding.md
Phase 3: Security Verification
阶段3:安全验证
Apply a layered verification approach:
- Static Analysis — Detect common vulnerability patterns automatically
- — Node.js security linter rules
eslint-plugin-security - — Detect unsafe DOM manipulation
eslint-plugin-no-unsanitized - — Pattern-based analysis with OWASP and TypeScript/JavaScript rulesets
semgrep - — Type-aware linting for TypeScript
typescript-eslint
- Dependency Audit — Identify known vulnerabilities in third-party packages
- /
npm audit/yarn audit— Built-in package manager auditingpnpm audit - — Comprehensive vulnerability database and remediation advice
snyk - — Supply chain attack detection (typosquatting, install scripts)
socket.dev
- Secrets Detection — Find leaked credentials and API keys
- — Baseline-aware secrets scanner
detect-secrets - — Git-aware secrets scanning
gitleaks
- Code Review — Apply the security review workflow and checklists
- Security Testing — Write negative tests that verify rejection of malicious inputs; fuzz-test parsers and validators
Quick tool commands:
bash
undefined采用分层验证方法:
- 静态分析 — 自动检测常见漏洞模式
- — Node.js安全检查规则
eslint-plugin-security - — 检测不安全DOM操作
eslint-plugin-no-unsanitized - — 基于模式的分析,支持OWASP和TypeScript/JavaScript规则集
semgrep - — TypeScript类型感知代码检查
typescript-eslint
- 依赖审计 — 识别第三方包中的已知漏洞
- /
npm audit/yarn audit— 包管理器内置审计功能pnpm audit - — 全面漏洞数据库及修复建议
snyk - — 供应链攻击检测(仿冒包、安装脚本)
socket.dev
- 密钥检测 — 查找泄露的凭证和API密钥
- — 基于基线的密钥扫描工具
detect-secrets - — Git感知型密钥扫描工具
gitleaks
- 代码审查 — 遵循安全审查流程及检查清单
- 安全测试 — 编写负面测试验证恶意输入被拒绝;对解析器和验证器进行模糊测试
快速工具命令:
bash
undefinedESLint security plugins
ESLint安全插件
npm install --save-dev eslint-plugin-security eslint-plugin-no-unsanitized
npx eslint --ext .ts,.js,.tsx,.jsx src/
npm install --save-dev eslint-plugin-security eslint-plugin-no-unsanitized
npx eslint --ext .ts,.js,.tsx,.jsx src/
npm audit — dependency vulnerabilities
npm audit — 依赖漏洞检查
npm audit
npm audit --audit-level=high
npm audit
npm audit --audit-level=high
Snyk — comprehensive dependency and code scanning
Snyk — 全面依赖与代码扫描
npx snyk test
npx snyk code test
npx snyk test
npx snyk code test
detect-secrets — secrets scanning
detect-secrets — 密钥扫描
detect-secrets scan > .secrets.baseline
detect-secrets scan > .secrets.baseline
Semgrep — advanced pattern matching
Semgrep — 高级模式匹配
semgrep --config=p/javascript --config=p/typescript --config=p/owasp-top-ten src/
semgrep --config=p/javascript --config=p/typescript --config=p/owasp-top-ten src/
Socket.dev — supply chain security
Socket.dev — 供应链安全
npx socket npm info <package-name>
For complete verification checklists (code review, architecture review, dependency audit, deployment, testing, incident response): See [references/security-checklist.md](references/security-checklist.md)npx socket npm info <package-name>
完整验证检查清单(代码审查、架构审查、依赖审计、部署、测试、事件响应):查看[references/security-checklist.md](references/security-checklist.md)Phase 4: Dependency and Deployment Security
阶段4:依赖与部署安全
Dependency Management
依赖管理
- Use lockfiles (,
package-lock.json,yarn.lock) and commit thempnpm-lock.yaml - Run /
npm auditin CI/CD pipeline on every buildsnyk test - Enable for packages where postinstall scripts are not needed
--ignore-scripts - Monitor for typosquatting — verify package names carefully before installing
- Review new dependencies before adding — check maintainership, download counts, known issues
- Use or similar tools to detect supply chain attacks (install scripts, obfuscated code)
socket.dev - Prefer packages with provenance attestations ()
npm provenance
- 使用锁文件(、
package-lock.json、yarn.lock)并提交到版本库pnpm-lock.yaml - 在CI/CD流水线的每次构建中运行/
npm auditsnyk test - 对不需要postinstall脚本的包启用
--ignore-scripts - 警惕仿冒包 — 安装前仔细验证包名
- 添加新依赖前进行审查 — 检查维护状态、下载量、已知问题
- 使用或类似工具检测供应链攻击(安装脚本、混淆代码)
socket.dev - 优先选择带有来源证明的包()
npm provenance
Deployment Hardening
部署强化
- Container security — Scan images with ; use minimal base images (distroless, alpine); run as non-root user
trivy - HTTPS/TLS — Enforce TLS 1.2+ for all connections; redirect HTTP to HTTPS; set header
Strict-Transport-Security - Security headers — Configure ,
Content-Security-Policy,X-Content-Type-Options: nosniff,X-Frame-Options: DENYPermissions-Policy - Secrets at runtime — Inject secrets via environment variables or mounted volumes; never bake into images or bundles
- Least privilege — Run processes as non-root; use read-only filesystems where possible; limit network access
- Source maps — Never deploy source maps to production in public-facing applications
- Client-side — Enable Subresource Integrity (SRI) for CDN scripts; configure strict CSP; avoid inline scripts
- Logging — Use structured logging (JSON); never log passwords, tokens, PII, or full stack traces to users; log authentication events and access denials for audit
- 容器安全 — 使用扫描镜像;使用最小化基础镜像(distroless、alpine);以非root用户运行
trivy - HTTPS/TLS — 强制所有连接使用TLS 1.2+;将HTTP重定向到HTTPS;设置头部
Strict-Transport-Security - 安全头部 — 配置、
Content-Security-Policy、X-Content-Type-Options: nosniff、X-Frame-Options: DENYPermissions-Policy - 运行时密钥 — 通过环境变量或挂载卷注入密钥;切勿嵌入到镜像或打包文件中
- 最小权限 — 以非root用户运行进程;尽可能使用只读文件系统;限制网络访问
- Source maps — 面向公众的生产环境绝不部署source maps
- 客户端 — 为CDN脚本启用子资源完整性(SRI);配置严格的CSP;避免内联脚本
- 日志 — 使用结构化日志(JSON);绝不向用户记录密码、令牌、PII或完整堆栈跟踪;记录身份验证事件和访问拒绝情况用于审计
OWASP Top 10:2025 Quick Reference
OWASP Top 10:2025快速参考
Map each OWASP 2025 category to TypeScript/JavaScript-specific risks and primary mitigations:
| # | Category | TypeScript/JavaScript-Specific Risks | Primary Mitigation |
|---|---|---|---|
| A01 | Broken Access Control | Missing auth middleware, IDOR via sequential IDs, path traversal, SSRF via | Centralized auth middleware, object-level permissions, |
| A02 | Security Misconfiguration | | Environment-specific config, disable docs in prod, centralized error handler, explicit CORS, |
| A03 | Software Supply Chain Failures | Unpinned deps, typosquatting on npm, malicious postinstall scripts, no lockfile, unvetted transitive deps, CI/CD secrets exposure | |
| A04 | Cryptographic Failures | | |
| A05 | Injection | SQL via template literals, XSS via | Parameterized queries, DOM sanitization (DOMPurify), |
| A06 | Insecure Design | No rate limiting, missing input validation layer, no abuse case modeling, client-side enforcement of server-side security | Threat modeling, validation at boundaries (Zod/class-validator), rate limiting middleware, server-side enforcement |
| A07 | Authentication Failures | Weak session config, JWT | Secure session settings, explicit |
| A08 | Software or Data Integrity Failures | Prototype pollution, | Schema validation (Zod), |
| A09 | Security Logging and Alerting Failures | Logging passwords/tokens, | Structured logging (pino/winston) with field filtering, audit trail, alerting thresholds, honeytokens |
| A10 | Mishandling of Exceptional Conditions | Unhandled promise rejections, empty | Specific error types, |
For detailed vulnerable → secure code examples for each category: See references/owasp-top-10.md
将每个OWASP 2025类别映射到TypeScript/JavaScript特定风险及主要缓解措施:
| # | 类别 | TypeScript/JavaScript特定风险 | 主要缓解措施 |
|---|---|---|---|
| A01 | 访问控制失效 | 缺失权限中间件、通过连续ID的IDOR漏洞、路径遍历、通过 | 集中式权限中间件、对象级权限控制、 |
| A02 | 安全配置错误 | 生产环境设置 | 环境专属配置、生产环境禁用文档、集中式错误处理器、显式CORS配置、 |
| A03 | 软件供应链故障 | 未固定依赖版本、npm仿冒包、恶意postinstall脚本、无锁文件、未审核传递依赖、CI/CD密钥泄露 | CI中运行 |
| A04 | 加密失效 | | |
| A05 | 注入攻击 | 模板字面量拼接SQL、 | 参数化查询、DOM净化(DOMPurify)、带数组参数的 |
| A06 | 不安全设计 | 无速率限制、缺失输入验证层、未建模滥用场景、仅客户端执行服务端安全逻辑 | 威胁建模、边界处验证(Zod/class-validator)、速率限制中间件、服务端强制执行 |
| A07 | 身份验证失效 | 弱会话配置、JWT使用 | 安全会话设置、显式指定 |
| A08 | 软件或数据完整性失效 | 原型污染、 | 模式验证(Zod)、 |
| A09 | 安全日志与告警失效 | 记录密码/令牌、生产环境使用 | 带字段过滤的结构化日志(pino/winston)、审计追踪、告警阈值、蜜令牌 |
| A10 | 异常处理不当 | 未处理Promise拒绝、空 | 特定错误类型、 |
每个类别的详细漏洞代码→安全代码示例:查看references/owasp-top-10.md
Security Review Workflow
安全审查流程
Follow this procedure when reviewing TypeScript or JavaScript code for security:
- Scan for critical prohibitions — Check for any pattern in the "Critical Prohibitions" table above. Each match is an immediate high-severity finding.
- Check input validation — Verify every entry point (route handler, CLI argument, file parser, WebSocket handler, queue consumer) validates and sanitizes input before processing.
- Verify authentication and authorization — Confirm every endpoint requires authentication (unless explicitly public) and checks authorization for the specific resource being accessed.
- Review data handling — Trace how secrets, PII, and sensitive data flow through the system. Verify encryption at rest and in transit, proper key management, and secure deletion. Ensure no secrets are bundled into client-side code.
- Check error handling — Ensure errors do not leak stack traces, internal paths, database details, or configuration to users. Verify fail-secure behavior. Check for unhandled promise rejections.
- Audit dependencies — Run and
npm audit. Flag any unpatched dependencies or packages with known CVEs. Check for suspicious postinstall scripts.snyk test - Verify logging — Confirm no sensitive data (passwords, tokens, PII) appears in logs. Verify authentication events, authorization failures, and security-relevant actions are logged.
- Run static analysis — Execute ESLint with security plugins and review findings. Run with JavaScript/TypeScript and OWASP rulesets for deeper analysis.
semgrep - Check DOM security (client-side) — Verify no unsafe DOM manipulation (,
innerHTML). Check CSP configuration, SRI on external scripts, and proper sanitization of user content.document.write - Report findings — For each finding, document: severity (Critical/High/Medium/Low), location (file:line), vulnerable code snippet, explanation of the risk, and recommended fix with code example.
审查TypeScript或JavaScript代码安全性时遵循以下步骤:
- 扫描关键禁止项 — 检查是否存在上述“关键禁止项”表格中的任何模式,每一项匹配均为立即高严重性问题。
- 检查输入验证 — 验证每个入口点(路由处理器、CLI参数、文件解析器、WebSocket处理器、队列消费者)在处理前是否验证并净化输入。
- 验证身份验证与授权 — 确认每个端点均要求身份验证(除非明确公开),并检查对所访问特定资源的授权情况。
- 审查数据处理 — 追踪密钥、PII和敏感数据在系统中的流转,验证静态和传输中的加密、密钥管理及安全删除,确保密钥未嵌入客户端代码。
- 检查错误处理 — 确保错误不会向用户泄露堆栈跟踪、内部路径、数据库细节或配置,验证安全失败行为,检查未处理Promise拒绝。
- 审计依赖 — 运行和
npm audit,标记任何未修补的依赖或存在已知CVE的包,检查可疑postinstall脚本。snyk test - 验证日志 — 确认日志中无敏感数据(密码、令牌、PII),验证身份验证事件、授权失败及安全相关操作已被记录。
- 运行静态分析 — 执行带安全插件的ESLint并审查结果,运行带JavaScript/TypeScript和OWASP规则集的进行深度分析。
semgrep - 检查DOM安全(客户端) — 验证无不安全DOM操作(、
innerHTML),检查CSP配置、外部脚本的SRI及用户内容的正确净化。document.write - 报告问题 — 每个问题需记录:严重性(Critical/High/Medium/Low)、位置(文件:行号)、漏洞代码片段、风险说明及带代码示例的修复建议。
Security Hardening Quick Commands
安全强化快速命令
bash
undefinedbash
undefined=== Static Analysis ===
=== 静态分析 ===
npm install --save-dev eslint-plugin-security eslint-plugin-no-unsanitized
npx eslint --ext .ts,.js,.tsx,.jsx src/
semgrep --config=p/javascript --config=p/typescript --config=p/owasp-top-ten src/
npm install --save-dev eslint-plugin-security eslint-plugin-no-unsanitized
npx eslint --ext .ts,.js,.tsx,.jsx src/
semgrep --config=p/javascript --config=p/typescript --config=p/owasp-top-ten src/
=== Dependency Audit ===
=== 依赖审计 ===
npm audit --audit-level=high
npx snyk test
npm audit --audit-level=high
npx snyk test
=== Secrets Detection ===
=== 密钥检测 ===
detect-secrets scan > .secrets.baseline
gitleaks detect --source .
detect-secrets scan > .secrets.baseline
gitleaks detect --source .
=== Lock Dependencies ===
=== 锁定依赖 ===
npm ci # install from lockfile (CI/CD)
npm ci # 从锁文件安装(CI/CD环境)
=== Container Scanning ===
=== 容器扫描 ===
trivy image <image-name>
trivy image <image-name>
undefinedundefinedReference Files
参考文件
Consult these files for detailed guidance beyond this overview:
- references/owasp-top-10.md — Detailed OWASP Top 10 coverage with TypeScript/JavaScript-specific vulnerable → secure code examples for each category, including Express, Fastify, NestJS, Next.js, and React patterns
- references/secure-coding.md — Secure coding patterns organized by domain: input validation, authentication, cryptography, DOM security, subprocess execution, file operations, and web framework configuration (Express, Fastify, NestJS, Next.js, React)
- references/security-checklist.md — Actionable verification checklists for code review, architecture review, dependency audit, deployment hardening, security testing, and incident response
如需更详细指导,请查阅以下文件:
- references/owasp-top-10.md — 详细覆盖OWASP Top 10,包含每个类别的TypeScript/JavaScript特定漏洞代码→安全代码示例,涵盖Express、Fastify、NestJS、Next.js及React模式
- references/secure-coding.md — 按领域分类的安全编码模式:输入验证、身份验证、加密、DOM安全、子进程执行、文件操作及Web框架配置(Express、Fastify、NestJS、Next.js、React)
- references/security-checklist.md — 可执行的验证检查清单,涵盖代码审查、架构审查、依赖审计、部署强化、安全测试及事件响应