capacitor-security

capacitor-security

面向 Capacitor 应用的全面安全指南,使用 Capsec 扫描器。涵盖密钥、存储、网络、身份验证、密码学和特定平台漏洞等 63+ 条安全规则。当用户需要保障移动应用安全或执行安全审计时使用此 skill。

71Star
4Fork
更新于 2026/7/13
SKILL.md
只读
名称
capacitor-security
描述

面向 Capacitor 应用的全面安全指南,使用 Capsec 扫描器。涵盖密钥、存储、网络、身份验证、密码学和特定平台漏洞等 63+ 条安全规则。当用户需要保障移动应用安全或执行安全审计时使用此 skill。

使用 Capsec 保障 Capacitor 安全

面向 Capacitor 和 Ionic 应用的零配置安全扫描工具。

何时使用此 Skill

  • 用户想要保障其应用的安全
  • 用户咨询关于安全漏洞的问题
  • 用户需要运行安全审计
  • 用户代码中硬编码了密钥
  • 用户需要 CI/CD 安全扫描
  • 用户询问有关 OWASP 移动安全的问题

Capsec 快速上手

运行安全扫描

# 扫描当前目录(无需安装)
npx capsec scan

# 扫描特定路径
npx capsec scan ./my-app

# CI 模式(存在高危/严重问题时退出代码为 1)
npx capsec scan --ci

输出格式

# CLI 输出(默认)
npx capsec scan

# JSON 报告
npx capsec scan --output json --output-file report.json

# HTML 报告
npx capsec scan --output html --output-file security-report.html

过滤

# 仅严重(Critical)和高危(High)严重程度
npx capsec scan --severity high

# 特定类别
npx capsec scan --categories secrets,network,storage

# 排除测试文件
npx capsec scan --exclude "**/test/**,**/*.spec.ts"

安全规则参考

密钥检测 (SEC)

规则 严重程度 说明
SEC001 Critical 硬编码 API 密钥与秘密
SEC002 High 泄露的 .env 文件

Capsec 检测的内容:

  • AWS 访问密钥
  • Google API 密钥
  • Firebase 密钥
  • Stripe 密钥
  • GitHub 令牌
  • JWT 密钥
  • 数据库凭据
  • 30+ 种密钥模式

修复示例:

// 错误 - 硬编码的 API 密钥
const API_KEY = 'sk_live_abc123xyz';

// 正确 - 使用环境变量
import { Env } from '@capgo/capacitor-env';
const API_KEY = await Env.get({ key: 'API_KEY' });

存储安全 (STO)

规则 严重程度 说明
STO001 High Preferences 中存在未加密的敏感数据
STO002 High 将 localStorage 用于敏感数据
STO003 Medium SQLite 数据库未加密
STO004 Medium 文件系统存储敏感数据
STO005 Low 不安全的数据缓存
STO006 High 凭据未存入 Keychain/Keystore

修复示例:

// 错误 - 使用明文 preferences 存储 token
import { Preferences } from '@capacitor/preferences';
await Preferences.set({ key: 'auth_token', value: token });

// 正确 - 使用安全存储
import { NativeBiometric } from '@capgo/capacitor-native-biometric';
await NativeBiometric.setCredentials({
  username: email,
  password: token,
  server: 'api.myapp.com',
});

网络安全 (NET)

规则 严重程度 说明
NET001 Critical HTTP 明文传输
NET002 High 缺少 SSL/TLS 证书固定 (Certificate Pinning)
NET003 High 启用了 Capacitor 服务器明文传输
NET004 Medium 不安全的 WebSocket 连接
NET005 Medium CORS 通配符配置
NET006 Medium 不安全的 Deep Link 校验
NET007 Low 误用 Capacitor HTTP 插件
NET008 High URL 参数中传递敏感数据

修复示例:

// 错误 - 在生产环境使用 HTTP
const config: CapacitorConfig = {
  server: {
    cleartext: true,  // 切勿在生产环境开启!
  },
};

// 正确 - 仅限 HTTPS
const config: CapacitorConfig = {
  server: {
    cleartext: false,
    // 仅允许特定域名
    allowNavigation: ['https://api.myapp.com'],
  },
};

Capacitor 专属 (CAP)

规则 严重程度 说明
CAP001 High 启用了 WebView 调试模式
CAP002 Medium 不安全的插件配置
CAP003 Low 生产环境中输出冗长日志
CAP004 High 不安全的 allowNavigation
CAP005 Critical Native Bridge 暴露
CAP006 Critical 结合用户输入使用了 Eval
CAP007 Medium 缺少 Root/越狱检测
CAP008 Low 不安全的插件导入
CAP009 Medium 热更新 (Live Update) 安全性问题
CAP010 High 不安全的 postMessage 处理程序

修复示例:

// 错误 - 生产环境中开启调试模式
const config: CapacitorConfig = {
  ios: {
    webContentsDebuggingEnabled: true,  // 请在生产环境中移除!
  },
  android: {
    webContentsDebuggingEnabled: true,  // 请在生产环境中移除!
  },
};

// 正确 - 仅在开发环境开启
const config: CapacitorConfig = {
  ios: {
    webContentsDebuggingEnabled: process.env.NODE_ENV === 'development',
  },
};

Android 安全 (AND)

规则 严重程度 说明
AND001 High 允许 Android 明文传输
AND002 Medium 启用了 Android 调试模式
AND003 Medium 不安全的 Android 权限声明
AND004 Low 允许 Android 备份
AND005 High 导出组件未声明权限
AND006 Medium WebView JavaScript 启用但缺少保护措施
AND007 Critical 不安全的 WebView addJavascriptInterface
AND008 Critical 硬编码的签名密钥

修复 AndroidManifest.xml:

<!-- 错误 -->
<application android:usesCleartextTraffic="true">

<!-- 正确 -->
<application
    android:usesCleartextTraffic="false"
    android:allowBackup="false"
    android:networkSecurityConfig="@xml/network_security_config">

network_security_config.xml:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="false">
        <domain includeSubdomains="true">api.myapp.com</domain>
        <pin-set>
            <pin digest="SHA-256">your-pin-hash</pin>
        </pin-set>
    </domain-config>
</network-security-config>

iOS 安全 (IOS)

规则 严重程度 说明
IOS001 High 禁用了 App Transport Security (ATS)
IOS002 Medium 不安全的 Keychain 访问
IOS003 Medium URL Scheme 缺少校验
IOS004 Low iOS 剪贴板包含敏感数据
IOS005 Medium 不安全的 iOS Entitlements 配置
IOS006 Low 后台应用刷新暴露数据
IOS007 Medium 缺少 iOS 越狱检测
IOS008 Low 敏感页面未禁用截屏功能

修复 Info.plist:

<!-- 错误 - 禁用了 ATS -->
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

<!-- 正确 - 仅对特定域名设置例外 -->
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>legacy-api.example.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSExceptionMinimumTLSVersion</key>
            <string>TLSv1.2</string>
        </dict>
    </dict>
</dict>

身份验证 (AUTH)

规则 严重程度 说明
AUTH001 Critical 弱 JWT 校验
AUTH002 High 不安全的生物识别实现
AUTH003 High 弱随机数生成
AUTH004 Medium 缺少会话超时机理
AUTH005 High 缺少 OAuth State 参数
AUTH006 Critical 身份验证逻辑中硬编码凭据

修复示例:

// 错误 - 未进行 JWT 校验
const decoded = jwt.decode(token);

// 正确 - 验证 JWT 签名
const decoded = jwt.verify(token, publicKey, {
  algorithms: ['RS256'],
  issuer: 'https://auth.myapp.com',
  audience: 'myapp',
});

WebView 安全 (WEB)

规则 严重程度 说明
WEB001 Critical WebView JavaScript 注入漏洞
WEB002 Medium 不安全的 iframe 配置
WEB003 Medium 加载外部脚本
WEB004 Medium 缺少内容安全策略 (CSP)
WEB005 Low Target _blank 未配置 noopener

修复 - 添加 CSP:

<!-- index.html -->
<meta http-equiv="Content-Security-Policy" content="
  default-src 'self';
  script-src 'self';
  style-src 'self' 'unsafe-inline';
  img-src 'self' data: https:;
  connect-src 'self' https://api.myapp.com;
  font-src 'self';
  frame-ancestors 'none';
">

密码学 (CRY)

规则 严重程度 说明
CRY001 Critical 使用弱加密算法
CRY002 Critical 硬编码加密密钥
CRY003 High 不安全的随机 IV 生成
CRY004 High 弱密码哈希算法

修复示例:

// 错误 - 弱算法
const encrypted = CryptoJS.DES.encrypt(data, key);

// 正确 - 强算法
const encrypted = CryptoJS.AES.encrypt(data, key, {
  mode: CryptoJS.mode.GCM,
  padding: CryptoJS.pad.Pkcs7,
});

// 错误 - 硬编码密钥
const key = 'my-secret-key-123';

// 正确 - 派生密钥
const key = await crypto.subtle.deriveKey(
  { name: 'PBKDF2', salt, iterations: 100000, hash: 'SHA-256' },
  baseKey,
  { name: 'AES-GCM', length: 256 },
  false,
  ['encrypt', 'decrypt']
);

日志记录 (LOG)

规则 严重程度 说明
LOG001 High 控制台日志包含敏感数据
LOG002 Low 生产环境中保留控制台日志

修复示例:

// 错误 - 打印敏感数据
console.log('User password:', password);
console.log('Token:', authToken);

// 正确 - 脱敏敏感数据
console.log('User authenticated:', userId);
// 使用条件日志
if (process.env.NODE_ENV === 'development') {
  console.debug('Debug info:', data);
}

CI/CD 集成

GitHub Actions

name: Security Scan

on: [push, pull_request]

jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4

      - name: Run Capsec Security Scan
        run: npx capsec scan --ci --output json --output-file security-report.json

      - name: Upload Security Report
        uses: actions/upload-artifact@v4
        if: always()
        with:
          name: security-report
          path: security-report.json

GitLab CI

security-scan:
  image: node:20
  script:
    - npx capsec scan --ci
  artifacts:
    reports:
      security: security-report.json
  only:
    - merge_requests
    - main

配置

capsec.config.json

{
  "exclude": [
    "**/node_modules/**",
    "**/dist/**",
    "**/*.test.ts",
    "**/*.spec.ts"
  ],
  "severity": "low",
  "categories": [],
  "rules": {
    "LOG002": {
      "enabled": false
    },
    "SEC001": {
      "severity": "critical"
    }
  }
}

初始化配置

npx capsec init

Root/越狱检测

import { IsRoot } from '@capgo/capacitor-is-root';

async function checkDeviceSecurity() {
  const { isRooted } = await IsRoot.isRooted();

  if (isRooted) {
    // 选项 1: 警告用户
    showWarning('设备存在安全风险');

    // 选项 2: 限制功能
    disableSensitiveFeatures();

    // 选项 3: 阻止使用应用(适用于高安全级别应用)
    blockApp();
  }
}

安全检查清单

发布前

  • [ ] 运行 npx capsec scan --severity high
  • [ ] 移除所有 console.log 语句
  • [ ] 禁用 WebView 调试
  • [ ] 移除开发环境地址/URL
  • [ ] 确认没有硬编码的密钥秘密
  • [ ] 启用证书固定 (Certificate Pinning)
  • [ ] 实现 Root/越狱检测
  • [ ] 添加内容安全策略 (CSP)
  • [ ] 使用安全存储保存凭据
  • [ ] 启用 ProGuard (Android)
  • [ ] 检查并确认 ATS 设置 (iOS)

日常维护

  • [ ] 在 CI/CD 中定期运行安全扫描
  • [ ] 监控新的安全漏洞
  • [ ] 定期更新依赖包
  • [ ] 审查第三方插件
  • [ ] 审计身份验证流程

相关资源