附录 III:运行时安全与治理

安全不是功能,是约束——它必须在每个层次上都存在,而不是事后补丁。


附录 III-A:LSP 集成(实时代码诊断)

功能描述

Claude Code 通过 Language Server Protocol (LSP) 与编程语言的类型检查器、Linter 等工具实时通信,获取诊断信息(类型错误、警告等),并将其作为上下文自动注入对话。

核心价值:Agent 修改代码后,无需等待用户反馈,LSP 会立即推送编译错误,Agent 可主动修复。

架构

LSP Server(TypeScript/Python/...)
    │  标准 stdio JSON-RPC(LSP 协议)
    ▼
LSPClient(每个 server 对应一个)
    │
    ├─ textDocument/publishDiagnostics(异步推送)
    │       ↓
    │   passiveFeedback.ts → registerPendingLSPDiagnostic()
    │       ↓
    │   LSPDiagnosticRegistry(LRU 缓存)
    │       ↓
    │   getAttachments() → 自动注入下一轮对话上下文
    │
    └─ textDocument/definition 等同步请求
            ↓
        LSPTool(LLM 主动调用)

核心文件

文件 作用
src/services/lsp/LSPServerManager.ts 多语言 Server 管理器(按文件扩展名路由)
src/services/lsp/LSPServerInstance.ts 单个 LSP Server 进程封装(stdio JSON-RPC)
src/services/lsp/LSPClient.ts LSP 协议客户端(请求/通知发送)
src/services/lsp/LSPDiagnosticRegistry.ts 诊断缓存(LRU),去重 + 限流
src/services/lsp/passiveFeedback.ts 将 LSP 推送的诊断转换为 Claude attachment 格式
src/services/lsp/config.ts LSP Server 配置加载(支持用户自定义)
src/tools/LSPTool/ LLM 主动调用的诊断查询工具

限流保护

// LSPDiagnosticRegistry.ts
const MAX_DIAGNOSTICS_PER_FILE = 10   // 每个文件最多 10 条诊断
const MAX_TOTAL_DIAGNOSTICS = 30       // 全局最多 30 条诊断(防止大型项目淹没上下文)
const MAX_DELIVERED_FILES = 500        // 追踪去重的文件数上限(防内存泄漏)

严重级别映射

// passiveFeedback.ts:LSP 标准 severity → Claude 内部格式
// LSP DiagnosticSeverity: 1=Error, 2=Warning, 3=Information, 4=Hint
function mapLSPSeverity(lspSeverity: number | undefined): 'Error' | 'Warning' | 'Info' | 'Hint'

文件生命周期同步

LSP Server 需要感知文件的打开/修改/保存/关闭事件,LSPServerManager 暴露对应接口:

manager.openFile(filePath, content)    // 发送 didOpen 通知
manager.changeFile(filePath, content)  // 发送 didChange 通知
manager.saveFile(filePath)             // 发送 didSave 通知(触发诊断刷新)
manager.closeFile(filePath)            // 发送 didClose 通知

文件保存(saveFile)后,LSP Server 通常重新检查类型,并通过 publishDiagnostics 推送最新结果——这是 passiveFeedback.ts 的主要触发场景。


附录 III-B:OAuth 认证流程

功能描述

Claude Code 支持 OAuth 2.0 Authorization Code Flow + PKCE,允许用户通过 Claude.ai 账号登录(而非仅靠 API Key),享受 Pro/Max 订阅权益。

核心文件src/services/oauth/(5 个文件)

认证流程

claude /login
    │
    ├─ 1. 生成 PKCE code_verifier(随机 32 字节,base64url 编码)
    │       code_challenge = SHA-256(code_verifier)
    │
    ├─ 2. 启动本地 HTTP 服务器(AuthCodeListener)
    │       监听 localhost:<random-port>/oauth/callback
    │
    ├─ 3. 构建 Authorization URL:
    │       https://claude.ai/oauth/authorize?
    │         client_id=...&
    │         code_challenge=<SHA256>&
    │         code_challenge_method=S256&
    │         redirect_uri=http://localhost:<port>/oauth/callback&
    │         state=<random>&
    │         response_type=code
    │
    ├─ 4a. 自动流程:openBrowser(authUrl) → 用户登录 → 浏览器回调 localhost
    │   4b. 手动流程(无浏览器环境):展示 URL,等待用户粘贴 code
    │
    ├─ 5. 收到 authorization code
    │       POST /oauth/token(带 code + code_verifier)
    │       → 获得 access_token + refresh_token
    │
    └─ 6. 存储 token(系统 Keychain 或加密文件)

核心文件

文件 作用
src/services/oauth/index.ts OAuthService 类:完整 OAuth 流程编排
src/services/oauth/client.ts HTTP 请求(授权 URL 构建、token 交换、刷新)
src/services/oauth/crypto.ts PKCE 工具(generateCodeVerifiergenerateCodeChallengegenerateState
src/services/oauth/auth-code-listener.ts AuthCodeListener:本地临时 HTTP 服务器,接收 OAuth 回调
src/services/oauth/getOauthProfile.ts 用 access_token 查询用户订阅类型(RateLimitTierSubscriptionType

安全特性

  • PKCE(Proof Key for Code Exchange):防止 authorization code 截获攻击——即使攻击者拿到 code,没有 code_verifier 也无法换取 token
  • state 参数:防 CSRF(Cross-Site Request Forgery)攻击
  • 随机端口:本地回调 HTTP 服务器使用随机端口,避免端口冲突或预测攻击
  • 双模式支持skipBrowserOpen 选项支持 SDK 控制协议场景(IDE 插件接管浏览器打开)

附录 III-C:企业策略管理(Remote Managed Settings)

功能描述

企业 IT 管理员通过 Anthropic 管理控制台推送策略配置,覆盖用户的本地 Claude Code 设置。员工打开 Claude Code 时自动同步企业策略(无需用户主动操作),且用户无法绕过强制策略。

适用场景

  • 禁用特定工具(如禁止 BashTool 在生产环境运行)
  • 限制可访问的目录(合规需求)
  • 强制启用诊断日志
  • 限制允许的 AI 模型范围

核心文件src/services/remoteManagedSettings/(5 个文件)

策略加载流程

Claude Code 启动
    │
    ├─ isRemoteManagedSettingsEligible() 检查资格
    │   ├─ Console 用户(API Key):全部符合资格
    │   └─ OAuth 用户:仅 Enterprise / C4E / Team 订阅用户符合资格
    │
    ├─ 从本地缓存(syncCache)读取上次同步的策略
    │   └─ 立即应用缓存策略(避免阻塞启动)
    │
    ├─ 后台 fetch 最新策略(10 秒超时,最多重试 5 次)
    │   GET /api/remote-settings(带 checksum,增量拉取)
    │
    ├─ checkManagedSettingsSecurity():
    │   ├─ 新策略含"危险设置"(如 allowedPaths)且与缓存不同?
    │   │       ↓ 是
    │   │   展示阻塞确认对话框(ManagedSettingsSecurityDialog)
    │   │   用户拒绝 → 不应用新策略
    │   └─ 否 → 静默应用
    │
    └─ 每小时轮询更新(POLLING_INTERVAL_MS = 60 * 60 * 1000)

核心文件

文件 作用
src/services/remoteManagedSettings/index.ts 主逻辑:fetch、缓存、轮询
src/services/remoteManagedSettings/syncCache.ts 本地缓存管理(checksum + 内容)
src/services/remoteManagedSettings/syncCacheState.ts 缓存路径与 session 级缓存读写
src/services/remoteManagedSettings/securityCheck.tsx 危险设置检测 + 用户确认对话框
src/services/remoteManagedSettings/types.ts 策略协议类型(RemoteManagedSettingsResponseSchema

优先级(高→低)

CLI 参数(--dangerously-skip-permissions 等)
    ↓
Remote Managed Settings(企业策略)   ← 覆盖用户设置
    ↓
用户本地 settings.json
    ↓
默认值

失效安全(Fail Open)

网络请求失败时,继续使用缓存策略(或无策略)正常运行,不阻塞用户使用——企业策略不作为硬性依赖。


附录 III-D:自动更新

功能描述

Claude Code 启动时自动检查 npm registry 最新版本,根据配置决定是自动安装还是仅提示。

核心文件src/cli/update.tssrc/utils/autoUpdater.ts

更新流程

claude update(或启动时后台检查)
    │
    ├─ getLatestVersion():查询 npm registry(或配置的 channel)
    │   channel 来自 settings.autoUpdatesChannel(默认 'latest')
    │
    ├─ 版本比较:gte(currentVersion, latestVersion)?
    │   ├─ 已是最新 → 退出
    │   └─ 有新版本 → 继续
    │
    ├─ 检测安装方式(installationType):
    │   ├─ npm global → installGlobalPackage()
    │   ├─ local install → installOrUpdateClaudePackage()
    │   └─ native → installLatestNative()(系统包管理器)
    │
    └─ 更新完成后 regenerateCompletionCache()(刷新 shell 补全缓存)

多安装检测

// update.ts:发现多个 Claude Code 安装时告警
if (diagnostic.multipleInstallations.length > 1) {
  writeToStdout(chalk.yellow('Warning: Multiple installations found'))
  // 提示用户清理,避免版本混用
}

配置项

配置 说明
settings.autoUpdatesChannel 更新渠道(latest / beta 等)
settings.autoUpdate 是否自动安装(否则仅提示)

附录 III 源码快速导航

运行时安全与治理
├── LSP 实时诊断
│   └── src/services/lsp/
│       ├── LSPServerManager.ts    ← 多语言 Server 路由
│       ├── LSPServerInstance.ts   ← 单个 Server 进程封装
│       ├── LSPDiagnosticRegistry.ts ← 诊断 LRU 缓存(去重+限流)
│       ├── passiveFeedback.ts     ← 文件保存后自动推送诊断
│       └── config.ts              ← 语言服务器配置
│
├── OAuth 2.0 + PKCE 认证
│   └── src/services/oauth/
│       ├── index.ts               ← OAuthService:完整流程编排
│       ├── client.ts              ← HTTP 请求(授权URL + token 交换)
│       ├── crypto.ts              ← PKCE 工具函数
│       ├── auth-code-listener.ts  ← 本地回调 HTTP 服务器
│       └── getOauthProfile.ts     ← 查询用户订阅类型
│
├── 企业策略(Remote Managed Settings)
│   └── src/services/remoteManagedSettings/
│       ├── index.ts               ← fetch + 缓存 + 轮询主逻辑
│       ├── syncCache.ts           ← checksum 本地缓存
│       ├── securityCheck.tsx      ← 危险设置变更确认对话框
│       └── types.ts               ← RemoteManagedSettingsResponseSchema
│
└── 自动更新
    ├── src/cli/update.ts          ← update 命令主逻辑
    └── src/utils/autoUpdater.ts   ← 版本检查 + 安装执行

附录 IV:自动化与调度