code-safety-scanner
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCode Safety Scanner
代码安全扫描工具
<!-- dual-compat-start -->
<!-- dual-compat-start -->
Use When
适用场景
- Scan any codebase for 14 critical safety issues across security vulnerabilities, server stability (500 errors), and payment misconfigurations. Use when auditing code before deployment, reviewing AI-generated code for production readiness, or...
- The task needs reusable judgment, domain constraints, or a proven workflow rather than ad hoc advice.
- 扫描任意代码库,检测14类关键安全问题,涵盖安全漏洞、服务器稳定性(500错误)以及支付配置错误场景。适用于部署前的代码审计、AI生成代码的生产就绪性评审等场景...
- 任务需要可复用的判断逻辑、领域约束或成熟的工作流,而非临时建议。
Do Not Use When
不适用场景
- The task is unrelated to or would be better handled by a more specific companion skill.
code-safety-scanner - The request only needs a trivial answer and none of this skill's constraints or references materially help.
- 任务与无关,或更适合由其他更专业的配套工具处理。
code-safety-scanner - 请求仅需要简单答案,本工具的约束条件或参考内容无法提供实质性帮助。
Required Inputs
必要输入
- Gather relevant project context, constraints, and the concrete problem to solve; load only as needed.
references - Confirm the desired deliverable: design, code, review, migration plan, audit, or documentation.
- 收集相关项目背景、约束条件以及具体需要解决的问题;仅在必要时加载内容。
references - 确认期望的交付成果:设计方案、代码、评审报告、迁移计划、审计报告或文档。
Workflow
工作流
- Read this first, then load only the referenced deep-dive files that are necessary for the task.
SKILL.md - Apply the ordered guidance, checklists, and decision rules in this skill instead of cherry-picking isolated snippets.
- Produce the deliverable with assumptions, risks, and follow-up work made explicit when they matter.
- 首先阅读本文件,仅加载完成任务所需的参考深度文件。
SKILL.md - 应用本工具中的有序指导、检查清单和决策规则,而非随意选取孤立的片段内容。
- 交付成果中需明确标注假设条件、风险点以及后续工作(若相关)。
Quality Standards
质量标准
- Keep outputs execution-oriented, concise, and aligned with the repository's baseline engineering standards.
- Preserve compatibility with existing project conventions unless the skill explicitly requires a stronger standard.
- Prefer deterministic, reviewable steps over vague advice or tool-specific magic.
- 输出内容需以执行为导向、简洁明了,并与代码库的基线工程标准保持一致。
- 除非工具明确要求更高标准,否则需与现有项目约定保持兼容。
- 优先采用可确定、可评审的步骤,而非模糊建议或工具特定的“魔法操作”。
Anti-Patterns
反模式
- Treating examples as copy-paste truth without checking fit, constraints, or failure modes.
- Loading every reference file by default instead of using progressive disclosure.
- 将示例内容直接复制粘贴,而不检查是否适配当前场景、约束条件或失败模式。
- 默认加载所有参考文件,而非按需逐步披露内容。
Outputs
输出成果
- A concrete result that fits the task: implementation guidance, review findings, architecture decisions, templates, or generated artifacts.
- Clear assumptions, tradeoffs, or unresolved gaps when the task cannot be completed from available context alone.
- References used, companion skills, or follow-up actions when they materially improve execution.
- 符合任务需求的具体结果:实施指导、评审发现、架构决策、模板或生成的工件。
- 当仅靠现有上下文无法完成任务时,需明确标注假设条件、权衡方案或未解决的缺口。
- 若能显著提升执行效果,需列出使用的参考内容、配套工具或后续行动。
Evidence Produced
生成的证据
| Category | Artifact | Format | Example |
|---|---|---|---|
| Security | Codebase safety scan report | Markdown doc covering the 14 critical safety findings (security, stability, payment) per scan run | |
| 分类 | 工件 | 格式 | 示例 |
|---|---|---|---|
| 安全 | 代码库安全扫描报告 | Markdown文档,涵盖每次扫描检测到的14类关键安全问题(安全、稳定性、支付) | |
References
参考内容
- Use the directory for deep detail after reading the core workflow below.
references/
Systematic 14-point safety scan for web applications. Covers security, stability, and payment safety across PHP, Node.js/JS/TS, and Python stacks.
- 阅读以下核心工作流后,如需详细内容可查看目录。
references/
针对Web应用的系统化14项安全扫描,涵盖PHP、Node.js/JS/TS以及Python技术栈的安全、稳定性和支付安全检测。
Two Modes
两种模式
Automated Scan (default): Run all 14 checks, produce structured report.
Checklist Mode: Reference checks passively during code review. State which mode at start.
Automated Scan(默认):运行全部14项检查,生成结构化报告。
Checklist Mode:代码评审过程中被动参考检查项。开始时需说明使用的模式。
Scan Procedure
扫描流程
Step 1: Detect Stack
步骤1:检测技术栈
Identify the project's tech stack by checking for:
- /
composer.json= PHP*.php - /
package.json/*.js= Node.js/JS/TS*.ts - /
requirements.txt= Python*.py - Frontend files: ,
*.html,*.jsx,*.tsx,*.vue*.svelte
Load the appropriate scan patterns from references/ based on detected stack.
通过以下文件识别项目技术栈:
- /
composer.json= PHP*.php - /
package.json/*.js= Node.js/JS/TS*.ts - /
requirements.txt= Python*.py - 前端文件:,
*.html,*.jsx,*.tsx,*.vue*.svelte
根据检测到的技术栈,从references/加载对应的扫描规则。
Step 2: Run All 14 Checks
步骤2:运行全部14项检查
Execute checks in order. For each check, use Grep/Glob to find patterns, then analyze context to confirm true positives. Rate each finding:
| Severity | Meaning |
|---|---|
| CRITICAL | Exploitable now, data loss or unauthorized access possible |
| HIGH | Likely exploitable, requires specific conditions |
| MEDIUM | Defense-in-depth gap, not immediately exploitable |
| LOW | Best practice violation, minimal risk |
| PASS | No issues found for this check |
按顺序执行检查。对于每项检查,使用Grep/Glob查找匹配模式,然后分析上下文确认真阳性结果。为每个检测结果评级:
| 严重程度 | 说明 |
|---|---|
| CRITICAL | 当前可被利用,可能导致数据丢失或未授权访问 |
| HIGH | 可能被利用,需满足特定条件 |
| MEDIUM | 纵深防御缺口,无法立即被利用 |
| LOW | 违反最佳实践,风险极低 |
| PASS | 未发现问题 |
Step 3: Generate Report
步骤3:生成报告
Use this exact format:
markdown
undefined使用以下固定格式:
markdown
undefinedCode Safety Scan Report
代码安全扫描报告
Project: [name] | Date: [date] | Stack: [detected]
项目: [名称] | 日期: [日期] | 技术栈: [检测结果]
Category A: Security Vulnerabilities
分类A:安全漏洞
| # | Check | Severity | Findings |
|---|---|---|---|
| 1 | Hardcoded API Keys | ... | ... |
| 2 | Inverted Auth Logic | ... | ... |
| 3 | Open Admin Endpoints | ... | ... |
| 4 | Missing Signup/Login Auth | ... | ... |
| 5 | Missing Row-Level Security | ... | ... |
| 序号 | 检查项 | 严重程度 | 检测结果 |
|---|---|---|---|
| 1 | 硬编码API密钥 | ... | ... |
| 2 | 反转的认证逻辑 | ... | ... |
| 3 | 开放的管理员端点 | ... | ... |
| 4 | 缺失注册/登录认证 | ... | ... |
| 5 | 缺失行级安全控制 | ... | ... |
Category B: Server Stability (500 Error Risks)
分类B:服务器稳定性(500错误风险)
| # | Check | Severity | Findings |
|---|---|---|---|
| 6 | Unhandled Runtime Exceptions | ... | ... |
| 7 | Misconfigured Env Variables | ... | ... |
| 8 | Misconfigured File Paths | ... | ... |
| 9 | Database Connection Problems | ... | ... |
| 10 | Infinite Loops/Recursion | ... | ... |
| 11 | Memory Leaks | ... | ... |
| 12 | Concurrency Issues | ... | ... |
| 13 | Data Race Conditions | ... | ... |
| 序号 | 检查项 | 严重程度 | 检测结果 |
|---|---|---|---|
| 6 | 未处理的运行时异常 | ... | ... |
| 7 | 配置错误的环境变量 | ... | ... |
| 8 | 配置错误的文件路径 | ... | ... |
| 9 | 数据库连接问题 | ... | ... |
| 10 | 无限循环/递归 | ... | ... |
| 11 | 内存泄漏 | ... | ... |
| 12 | 并发问题 | ... | ... |
| 13 | 数据竞争条件 | ... | ... |
Category C: Payment Safety
分类C:支付安全
| # | Check | Severity | Findings |
|---|---|---|---|
| 14 | Duplicate Charge Risk | ... | ... |
| 序号 | 检查项 | 严重程度 | 检测结果 |
|---|---|---|---|
| 14 | 重复扣费风险 | ... | ... |
Summary
总结
- CRITICAL: X | HIGH: X | MEDIUM: X | LOW: X | PASS: X
- Top Priority Fixes: [numbered list of most urgent items]
undefined- CRITICAL: X | HIGH: X | MEDIUM: X | LOW: X | PASS: X
- 最高优先级修复项: [最紧急问题的编号列表]
undefinedThe 14 Checks
14项检查内容
Category A: Security Vulnerabilities
分类A:安全漏洞
Check 1 - Hardcoded API Keys in Frontend
Scan frontend files for exposed secrets: API keys, tokens, connection strings.
Grep patterns: in , , , , , , ,
(sk_live|sk_test|pk_live|STRIPE|SUPABASE|apiKey|api_key|secret|token|password|firebase|AWS_)*.js*.ts*.jsx*.tsx*.vue*.svelte*.html*.env.localRed flags:
- Any ,
sk_live_prefixed strings in client codesk_test_ - Supabase key in frontend (anon key is OK)
service_role - Firebase config with database rules set to for all
true - with hardcoded token values
Authorization: Bearer - files committed to git (check
.env).gitignore
For detailed patterns per stack, see references/security-scans.md.
Remediation: Cross-ref vibe-security-skill (Section 4).
Check 2 - Inverted Authentication Logic
Scan auth middleware/guards for logic that accidentally inverts access control.
Look for:
- granting access instead of blocking
if (!authenticated) - allowing admin routes
if (role !== 'admin') - Middleware that calls in the rejection branch
next() - Auth checks that return on failure
true - /
allowListlogic reverseddenyList
Read every auth middleware file fully. Trace the logic path for both authenticated and unauthenticated users.
For detailed patterns, see references/security-scans.md.
Remediation: Cross-ref web-app-security-audit (Layer 3).
Check 3 - Open Admin Endpoints
Scan for routes/endpoints with admin functionality that lack auth middleware.
Grep patterns: in route files.
(admin|dashboard|bulk|delete-all|manage|users/list|export-all|import|migrate|seed|reset)Check each matched route for:
- Missing auth middleware attachment
- Missing role/permission check
- Public accessibility (no session/token requirement)
Remediation: Cross-ref web-app-security-audit (Layer 3).
Check 4 - Missing User Auth on Signup/Login
Scan auth endpoints for missing verification and validation.
Check for:
- Email verification missing after signup
- No rate limiting on login/signup endpoints
- No CAPTCHA or bot protection
- Password stored without hashing (check for plaintext storage)
- No input validation on email/username fields
- Missing CSRF protection on auth forms
- No account lockout after failed attempts
Remediation: Cross-ref vibe-security-skill (Section 2).
Check 5 - Missing Row-Level Security
Scan database queries for missing tenant/user isolation.
Grep patterns: in query files, then check for:
(SELECT|UPDATE|DELETE|INSERT)- Queries without or
WHERE user_id =WHERE tenant_id = - Direct use of user-supplied IDs without ownership validation
- API endpoints that accept record IDs without verifying ownership
- Missing RLS policies (Supabase: check )
alter table...enable row level security - Bulk operations without scope filtering
For detailed ORM patterns, see references/security-scans.md.
Remediation: Cross-ref vibe-security-skill (Section 6).
检查1 - 前端硬编码API密钥
扫描前端文件中的暴露密钥:API密钥、令牌、连接字符串。
Grep匹配模式:,涉及文件:, , , , , , ,
(sk_live|sk_test|pk_live|STRIPE|SUPABASE|apiKey|api_key|secret|token|password|firebase|AWS_)*.js*.ts*.jsx*.tsx*.vue*.svelte*.html*.env.local危险信号:
- 客户端代码中存在任何以、
sk_live_为前缀的字符串sk_test_ - 前端使用Supabase的密钥(anon密钥是安全的)
service_role - Firebase配置中数据库规则设置为对所有请求开放()
true - 头中包含硬编码令牌值
Authorization: Bearer - 文件被提交到git仓库(检查
.env配置).gitignore
如需各技术栈的详细匹配模式,请查看references/security-scans.md。
修复方案:参考vibe-security-skill(第4节)。
检查2 - 反转的认证逻辑
扫描认证middleware/guards中是否存在意外反转访问控制的逻辑。
查找以下情况:
- 允许访问而非拒绝
if (!authenticated) - 允许管理员路由访问
if (role !== 'admin') - Middleware在拒绝分支中调用
next() - 认证检查失败时返回
true - /
allowList逻辑被反转denyList
完整阅读所有认证middleware文件,跟踪已认证和未认证用户的逻辑路径。
如需详细匹配模式,请查看references/security-scans.md。
修复方案:参考web-app-security-audit(第3层)。
检查3 - 开放的管理员端点
扫描包含管理员功能的路由/端点,检查是否缺失认证middleware。
Grep匹配模式:,涉及路由文件。
(admin|dashboard|bulk|delete-all|manage|users/list|export-all|import|migrate|seed|reset)检查每个匹配路由:
- 未附加认证middleware
- 缺失角色/权限检查
- 可公开访问(无需会话/令牌)
修复方案:参考web-app-security-audit(第3层)。
检查4 - 注册/登录缺失认证验证
扫描认证端点,检查是否缺失验证机制。
查找以下情况:
- 注册后缺失邮箱验证
- 登录/注册端点未做速率限制
- 缺失CAPTCHA或机器人防护
- 密码未经过哈希存储(检查是否明文存储)
- 邮箱/用户名字段缺失输入验证
- 认证表单缺失CSRF防护
- 登录失败后未锁定账户
修复方案:参考vibe-security-skill(第2节)。
检查5 - 缺失行级安全控制
扫描数据库查询,检查是否缺失租户/用户隔离。
Grep匹配模式:,涉及查询文件,然后检查:
(SELECT|UPDATE|DELETE|INSERT)- 查询语句中缺失或
WHERE user_id =条件WHERE tenant_id = - 直接使用用户提供的ID而未验证所有权
- API端点接受记录ID但未验证所有权
- 缺失RLS策略(Supabase:检查配置)
alter table...enable row level security - 批量操作未做范围过滤
如需详细ORM匹配模式,请查看references/security-scans.md。
修复方案:参考vibe-security-skill(第6节)。
Category B: Server Stability (500 Error Risks)
分类B:服务器稳定性(500错误风险)
For all detailed scan patterns per stack, see references/stability-scans.md.
Check 6 - Unhandled Runtime Exceptions
Scan for code paths that can throw without catch/error handling:
- JSON parsing without try-catch (,
JSON.parse,json_decode)json.loads - File operations without error handling
- External API calls without try-catch
- Missing global error handler / uncaught exception handler
- Null/undefined access on optional data (missing null checks)
- Type coercion errors (PHP loose comparisons, JS type juggling)
Check 7 - Misconfigured Environment Variables
Scan for env var usage without validation:
- /
process.env.X/$_ENV['X']used without fallback or validationos.environ['X'] - Missing file documenting required variables
.env.example - No startup validation that required env vars are present
- Hardcoded fallback values that mask missing config (e.g., )
|| 'localhost' - Different env var names between code and
.env.example
Check 8 - Misconfigured File Paths
Scan for fragile file path references:
- Hardcoded absolute paths (,
/home/user/)C:\Users\ - Relative paths that assume CWD (,
./uploads/)../config/ - Missing existence checks before file operations
- Path construction without /
path.join/realpathos.path.join - User-supplied paths without sanitization (path traversal risk)
Check 9 - Database Connection Problems
Scan for connection pool and lifecycle issues:
- Missing connection pooling (new connection per request)
- No connection limit configuration
- Missing connection error handling / retry logic
- Connections opened but never closed (missing / destructor)
finally - No connection timeout configured
- Multiple database connections created in loops
Check 10 - Infinite Loops/Recursion
Scan for unbounded iteration:
- /
while(true)without break conditionswhile(1) - Recursive functions without base case or depth limit
- Retry logic without max attempt cap
- Event listeners that trigger themselves
- without
setIntervalclearInterval - Recursive database queries (e.g., tree traversal without depth limit)
Check 11 - Memory Leaks
Scan for resource accumulation patterns:
- Growing arrays/lists in long-running processes
- Event listeners added but never removed
- Cache without size limits or TTL
- Large file reads into memory without streaming
- Unclosed streams, cursors, or connections
- Global variable accumulation in request handlers
Check 12 - Concurrency Issues
Analyze for concurrent access problems:
- Shared mutable state across requests (global variables in web servers)
- File writes without locking
- Counter increments without atomic operations (in concurrent context)
count++ - Session data modified by parallel requests
- Missing database transaction isolation
Check 13 - Data Race Conditions
Analyze for specific race condition patterns:
- Read-then-write without atomicity (check balance then deduct)
- TOCTOU (time-of-check-to-time-of-use) on file or DB operations
- Optimistic updates without version checking
- Missing on read-modify-write sequences
SELECT ... FOR UPDATE - Async operations sharing mutable variables
Cross-ref mysql-best-practices (references/transaction-locking.md) for DB-level fixes.
如需各技术栈的详细扫描模式,请查看references/stability-scans.md。
检查6 - 未处理的运行时异常
扫描可能抛出异常但未捕获/处理的代码路径:
- JSON解析未使用try-catch(,
JSON.parse,json_decode)json.loads - 文件操作未做错误处理
- 外部API调用未使用try-catch
- 缺失全局错误处理器/未捕获异常处理器
- 可选数据上的空/未定义访问(缺失空值检查)
- 类型转换错误(PHP宽松比较、JS类型隐式转换)
检查7 - 配置错误的环境变量
扫描未做验证的环境变量使用情况:
- 使用/
process.env.X/$_ENV['X']时未设置默认值或验证os.environ['X'] - 缺失文件记录所需变量
.env.example - 启动时未验证必要环境变量是否存在
- 硬编码默认值掩盖缺失的配置(例如:)
|| 'localhost' - 代码与中的环境变量名称不一致
.env.example
检查8 - 配置错误的文件路径
扫描脆弱的文件路径引用:
- 硬编码绝对路径(,
/home/user/)C:\Users\ - 依赖当前工作目录的相对路径(,
./uploads/)../config/ - 文件操作前未检查路径是否存在
- 未使用/
path.join/realpath构造路径os.path.join - 用户提供的路径未做 sanitization(路径遍历风险)
检查9 - 数据库连接问题
扫描连接池和生命周期问题:
- 缺失连接池(每个请求创建新连接)
- 未配置连接限制
- 缺失连接错误处理/重试逻辑
- 打开连接后未关闭(缺失/ 析构函数)
finally - 未配置连接超时
- 循环中创建多个数据库连接
检查10 - 无限循环/递归
扫描无边界的迭代逻辑:
- /
while(true)无终止条件while(1) - 递归函数无基线条件或深度限制
- 重试逻辑无最大尝试次数限制
- 触发自身的事件监听器
- 未搭配
setInterval使用clearInterval - 无深度限制的递归数据库查询(例如:树遍历)
检查11 - 内存泄漏
扫描资源累积模式:
- 长运行进程中持续增长的数组/列表
- 添加后未移除的事件监听器
- 无大小限制或TTL的缓存
- 未使用流处理的大文件内存读取
- 未关闭的流、游标或连接
- 请求处理器中的全局变量累积
检查12 - 并发问题
分析并发访问问题:
- 请求间共享可变状态(Web服务器中的全局变量)
- 文件写入未加锁
- 并发场景中的计数器增量操作非原子化()
count++ - 并行请求修改会话数据
- 缺失数据库事务隔离
检查13 - 数据竞争条件
分析特定的竞争条件模式:
- 无原子性的读-写操作(检查余额后扣费)
- 文件或数据库操作中的TOCTOU(检查时间与使用时间不一致)
- 无版本检查的乐观更新
- 读-改-写序列中缺失
SELECT ... FOR UPDATE - 共享可变变量的异步操作
参考mysql-best-practices(references/transaction-locking.md)获取数据库层面的修复方案。
Category C: Payment Safety
分类C:支付安全
For detailed patterns, see references/payment-scans.md.
Check 14 - Duplicate Charge Risk
Scan payment flows for double-charge vulnerabilities:
- Missing idempotency key on payment API calls
- No client-side button disable after click
- No server-side deduplication (same amount + user + time window)
- Missing payment status check before creating new charge
- No webhook deduplication (processing same event twice)
- Stripe: missing parameter
idempotency_key - Missing database transaction around payment + order creation
- No loading/spinner state preventing resubmit
如需详细匹配模式,请查看references/payment-scans.md。
检查14 - 重复扣费风险
扫描支付流程中的重复扣费漏洞:
- 支付API调用缺失幂等键
- 客户端点击后未禁用按钮
- 服务端未做去重(相同金额+用户+时间窗口)
- 创建新扣费前未检查支付状态
- Webhook未做去重(重复处理同一事件)
- Stripe:缺失参数
idempotency_key - 支付与订单创建过程中缺失数据库事务
- 缺失加载/ spinner状态防止重复提交
Cross-Reference Skills
参考配套工具
For deeper remediation guidance on Category A findings:
| Check | Skill | Section |
|---|---|---|
| Hardcoded API Keys | vibe-security-skill | Section 4: Hardcoded secrets |
| Inverted Auth | web-app-security-audit | Layer 3: Authorization |
| Open Endpoints | web-app-security-audit | Layer 3: Access Control |
| Missing Auth | vibe-security-skill | Section 2: Authentication |
| Missing RLS | vibe-security-skill | Section 6: Row-Level Security |
| Race Conditions | mysql-best-practices | references/transaction-locking.md |
针对分类A检测结果的深度修复指导:
| 检查项 | 工具 | 章节 |
|---|---|---|
| 硬编码API密钥 | vibe-security-skill | 第4节:硬编码密钥 |
| 反转的认证逻辑 | web-app-security-audit | 第3层:授权 |
| 开放的管理员端点 | web-app-security-audit | 第3层:访问控制 |
| 缺失注册/登录认证 | vibe-security-skill | 第2节:认证 |
| 缺失行级安全控制 | vibe-security-skill | 第6节:行级安全 |
| 数据竞争条件 | mysql-best-practices | references/transaction-locking.md |
Checklist Mode
Checklist Mode使用指南
When used passively during code review, check each file against relevant items:
- Route files -> Checks 2, 3, 4
- Frontend files -> Check 1
- Database queries -> Checks 5, 9, 12, 13
- API handlers -> Checks 6, 7, 8
- Payment code -> Check 14
- Long-running processes -> Checks 10, 11
- Async/concurrent code -> Checks 12, 13
代码评审过程中被动使用时,根据文件类型检查对应项:
- 路由文件 → 检查2、3、4
- 前端文件 → 检查1
- 数据库查询文件 → 检查5、9、12、13
- API处理器文件 → 检查6、7、8
- 支付代码 → 检查14
- 长运行进程文件 → 检查10、11
- 异步/并发代码 → 检查12、13