TypeScript源码解析:权限系统与 OS 级沙箱
理论篇讲了六层防御链的设计思路,这篇带你走读 MewCode 的权限系统代码,看看
checker.ts怎么把六层防御链完整地搭起来。
模块概览
权限系统整个塞在一个文件里:
| 文件 | 职责 |
|---|---|
src/permissions/checker.ts |
全部:类型定义、危险命令检测、安全命令白名单、路径沙箱、规则引擎、模式矩阵、PermissionChecker 主类 |
单文件的好处是不需要跨文件跳转,从上到下读一遍就能看到完整的权限系统。代码的组织顺序是:先定义类型和常量,然后实现各个组件,最后用 PermissionChecker 类把它们串起来。
核心类型
Decision:权限判定结果
export type DecisionEffect = "allow" | "deny" | "ask";
export interface Decision {
effect: DecisionEffect;
reason: string;
}
DecisionEffect 是一个联合类型,TypeScript 编译器会在类型检查时确保只能赋值为这三个字符串之一。 Decision 接口包含两个字段: effect 表示判定结果, reason 记录原因。
interface 是纯类型约束,运行时完全消失。不需要 new,直接用对象字面量 { effect: "allow", reason: "..." } 就能创建。对象字面量本身就足够简洁,不需要额外的工厂方法。
PermissionMode:权限模式
export type PermissionMode = "default" | "acceptEdits" | "plan" | "bypassPermissions";
四种模式用联合类型定义,一行搞定。联合类型在编译期限制取值范围,运行时就是普通字符串。
模式矩阵
function modeDecide(
mode: PermissionMode,
category: "read" | "write" | "command"
): DecisionEffect {
switch (mode) {
case "bypassPermissions":
return "allow";
case "plan":
return category === "read" ? "allow" : "deny";
case "acceptEdits":
return category === "command" ? "ask" : "allow";
case "default":
default:
return category === "read" ? "allow" : "ask";
}
}
用 switch 语句实现,每种模式一个 case,内部用三元表达式处理不同的工具分类。
有一个值得注意的设计选择:的 Plan 模式对写操作和命令返回 deny 而不是 ask 。Plan 模式下只有读操作被放行,写操作和命令直接拒绝,不给用户手动确认的机会。这是一个比较严格的实现。
default 分支 fallthrough 到和 "default" 模式相同的逻辑,确保未知模式也能有兜底行为。
内容提取映射表
const CONTENT_FIELDS: Record<string, string> = {
Bash: "command",
ReadFile: "file_path",
WriteFile: "file_path",
EditFile: "file_path",
Glob: "pattern",
Grep: "pattern",
};
export function extractContent(toolName: string, args: Record<string, unknown>): string {
const field = CONTENT_FIELDS[toolName];
if (!field) return "";
const v = args[field];
return typeof v === "string" ? v : "";
}
Record<string, string> 定义了字符串到字符串的映射类型。 extractContent 的逻辑是:按工具名查字段名,从参数中取值,类型检查后返回。
主流程走读:check() 方法
PermissionChecker 的构造
export class PermissionChecker {
mode: PermissionMode;
planFilePath = "";
private sandbox: PathSandbox;
private ruleEngine: RuleEngine;
constructor(workDir: string, mode: PermissionMode = "default") {
this.mode = mode;
this.sandbox = new PathSandbox(workDir);
this.ruleEngine = new RuleEngine(workDir);
}
}
构造函数接收工作目录和权限模式,内部创建 PathSandbox 和 RuleEngine 。组件在构造函数里直接创建,不从外部注入。这样做更简单,调用方只需要传工作目录就行。
危险命令检测和安全命令检测都是模块级函数,不需要实例化。
check() 方法概览
的 check() 接收三个参数:工具名、工具分类、参数。不需要传入 Tool 对象,调用方自己负责提取分类信息。
check(
toolName: string,
category: "read" | "write" | "command",
args: Record<string, unknown>
): Decision {
const content = extractContent(toolName, args);
// Layer 1 → Layer 2 → Layer 3 → Layer 4 → Layer 5 → Layer 6
// ...
}
六层防御链
Layer 0:Plan Mode 例外
if (this.mode === "plan" && toolName === "WriteFile") {
const path = String(args.file_path ?? "");
if (path.includes(".mewcode/plans/")) {
return { effect: "allow", reason: "Plan file write allowed in plan mode" };
}
}
的 Plan Mode 例外比较简洁:只检查 WriteFile 工具对 .mewcode/plans/ 目录的写入。没有维护 Plan 模式工具白名单,也不检查 EditFile 。
匹配方式也最简单:路径包含 .mewcode/plans/ 就放行,没有绝对路径比较和文件名降级。
Layer 1:安全命令白名单
const SAFE_PREFIXES = [
"ls", "pwd", "echo", "cat", "head", "tail", "wc", "date",
"whoami", "uname", "hostname", "which", "type", "file",
"git status", "git log", "git diff", "git branch",
"git show", "git rev-parse", "git remote",
"bun test", "bun run", "npm test", "npm run",
"go test", "go build", "go vet",
"python -c", "node -e",
];
的白名单约 30 条,覆盖了常用的只读命令和开发工具命令。包含 bun test 、 bun run 、 npm test 、 npm run 等 Node.js/Bun 生态的命令,也包含 go test 、 go build 、 python -c 等跨生态的常用命令。
function isSafeCommand(command: string): boolean {
const trimmed = command.trim();
if (
trimmed.includes(">") || trimmed.includes("|") ||
trimmed.includes(";") || trimmed.includes("&&") ||
trimmed.includes("$(") || trimmed.includes("`")
) {
return false;
}
return SAFE_PREFIXES.some(
(prefix) =>
trimmed === prefix ||
trimmed.startsWith(prefix + " ") ||
trimmed.startsWith(prefix + "\t")
);
}
元字符检测和前缀匹配的逻辑很标准:先排除含管道/重定向/分号的命令,再做完整前缀匹配(包括 Tab 分隔的检查)。用 Array.some() 替代手动遍历循环,更符合 函数式风格。
Layer 2:危险命令黑名单
const DANGEROUS_PATTERNS = [
/rm\s+(-rf?|--recursive)\s+[\/~]/,
/rm\s+-rf?\s+*/,
/mkfs./,
/dd\s+if=/,
/>\s*\/dev\/sd/,
/chmod\s+-R?\s*777\s+\//,
/:(){\s*:\|\s*:\s*&\s*}\s*;/,
/curl\s+.*\|\s*(ba)?sh/,
/wget\s+.*\|\s*(ba)?sh/,
/git\s+push\s+.*--force/,
/git\s+reset\s+--hard/,
/git\s+clean\s+-f/,
/git\s+checkout\s+./,
/git\s+branch\s+-D/,
];
function detectDangerous(command: string): boolean {
return DANGEROUS_PATTERNS.some((p) => p.test(command));
}
的黑名单有 14 条。除了标准的破坏性系统命令,还拦截了 5 条危险的 Git 操作: git push --force 、 git reset --hard 、 git clean -f 、 git checkout . 、 git branch -D 。这些 Git 操作虽然不会损毁系统,但会造成代码丢失,拦截它们是一个更谨慎的选择。
正则用 JavaScript 的字面量语法直接定义。正则字面量在脚本解析时就编译好了,效果等同于预编译,不需要额外调用编译函数。
detectDangerous 只返回布尔值,不返回具体的拦截理由。理由在 check() 方法里用通用的 "Dangerous command blocked" 字符串代替。
Layer 3:路径沙箱
export class PathSandbox {
private allowedRoots: string[];
constructor(projectDir: string) {
this.allowedRoots = [resolve(projectDir), "/tmp"];
}
addRoot(root: string): void {
this.allowedRoots.push(resolve(root));
}
check(filePath: string): Decision | null {
const absolute = resolve(filePath);
for (const root of this.allowedRoots) {
if (absolute.startsWith(root)) return null;
}
return {
effect: "deny",
reason: `Path ${filePath} is outside allowed directories`,
};
}
}
返回 null 表示路径在沙箱内(通过),返回 Decision 表示被拦截。这个 API 设计的好处是调用方可以直接把返回值 return 出去,不用再包装。
用 Node.js 的 resolve 函数转绝对路径,然后做字符串 startsWith 比较。没有解析符号链接,只检查字面路径。 addRoot 方法可以在构造后动态添加额外的白名单目录。
沙箱只在文件类工具的 check 路径里被调用:
if ((category === "read" || category === "write") && filePath) {
const sandboxDecision = this.sandbox.check(filePath);
if (sandboxDecision) return sandboxDecision;
}
Layer 4:规则引擎
export class RuleEngine {
private userPath: string;
private projectPath: string;
private localPath: string;
constructor(workDir: string) {
this.userPath = join(homedir(), ".mewcode", "permissions.yaml");
this.projectPath = join(workDir, ".mewcode", "permissions.yaml");
this.localPath = join(workDir, ".mewcode", ".permissions.local.yaml");
}
}
注意 的本地配置文件名是 .permissions.local.yaml (前面多了一个点),在 Unix 系统上会被当作隐藏文件。
规则语法和匹配
自己实现了 glob 匹配函数,因为 Node.js 标准库没有现成的 glob 匹配工具函数:
function globMatch(pattern: string, content: string): boolean {
const re =
"^" +
pattern
.replace(/[.+^${}()|[]\]/g, "\$&")
.replace(/*/g, "[^/]*")
.replace(/\?/g, "[^/]") +
"$";
try {
return new RegExp(re).test(content);
} catch {
return false;
}
}
把 glob 模式转换成正则表达式来匹配。 * 转成 [^/]* (匹配任意非路径分隔符字符), ? 转成 [^/] (匹配单个非分隔符字符)。先转义正则特殊字符,避免 pattern 里的 . 、 ( 等字符被当作正则语法。
三层规则文件
evaluate(toolName: string, content: string): RuleEffect | null {
for (const path of [this.userPath, this.projectPath, this.localPath]) {
const rules = loadRulesFile(path);
for (let i = rules.length - 1; i >= 0; i--) {
const r = rules[i];
if (r.tool !== toolName && r.tool !== "*") continue;
if (globMatch(r.pattern, content)) return r.effect;
}
}
return null;
}
每次 evaluate 都重新读文件,没有做缓存,追加新规则后下次 check 自动生效。从后往前扫描,后定义的规则优先。有一个额外特性: r.tool !== "*" 这个检查说明 支持通配工具名 * ,可以写 *(pattern) 匹配所有工具的内容。
规则文件加载
function loadRulesFile(path: string): Rule[] {
let data: string;
try {
data = readFileSync(path, "utf-8");
} catch {
return [];
}
let parsed: unknown;
try {
parsed = yaml.load(data);
} catch {
return [];
}
if (!Array.isArray(parsed)) return [];
// ... 逐条解析 ...
}
用 js-yaml 库解析 YAML。容错策略是:文件读取失败、解析失败、格式不对都返回空数组。
动态追加规则
appendLocalRule(rule: Rule): void {
mkdirSync(dirname(this.localPath), { recursive: true });
const rules = loadRulesFile(this.localPath);
rules.push(rule);
const entries = rules.map((r) => ({ rule: `${r.tool}(${r.pattern})`, effect: r.effect }));
writeFileSync(this.localPath, yaml.dump(entries), "utf-8");
}
mkdirSync 带 recursive: true 确保目录链存在。流程是:读取现有规则、追加新规则、序列化、写回文件。
还提供了一个 allowAlways 便捷方法:
allowAlways(toolName: string, args: Record<string, unknown>): void {
const content = extractContent(toolName, args);
const pattern = content.length > 60 ? content.slice(0, 60) + "*" : content + "*";
this.ruleEngine.appendLocalRule({ tool: toolName, pattern, effect: "allow" });
}
自动从参数中提取内容,截断到 60 字符加通配符,构造规则并追加。这样 Agent Loop 里只需要调用 checker.allowAlways(toolName, args) 一行代码就行,不用自己构造 Rule 对象。
Layer 5:模式矩阵兜底
return {
effect: modeDecide(this.mode, category),
reason: `Mode: ${this.mode}`,
};
最后一层直接调用 modeDecide 查表。返回值可能是 allow 、 deny 或 ask 。如果是 ask ,Agent Loop 会触发 HITL 确认。
注意这里直接把 modeDecide 的结果作为 Decision 的 effect 返回,没有对 ask 做单独处理。这意味着 Plan 模式下写操作返回的是 deny 而不是 ask ,不会触发 HITL 确认,直接拒绝。
Agent Loop 里的集成
权限检查嵌在 agent.ts 的工具执行循环里:
const decision = this.checker.check(tu.toolName, category, tu.arguments);
if (decision.effect === "deny") {
events.push({
type: "tool_result",
output: `Permission denied: ${decision.reason}. 此操作已被安全策略拦截和阻止...`,
isError: true,
});
continue;
}
deny 返回一个 isError 的 tool_result 事件但不终止循环。注意 的 deny 消息额外加了中文提示「此操作已被安全策略拦截和阻止,请告知用户该命令被拒绝,不要描述该命令会做什么」,直接在 tool_result 里给模型下指令,避免模型在下一轮回复里描述被拒绝命令的具体内容。
if (decision.effect === "ask" && this.onPermissionRequest) {
const response = await this.onPermissionRequest(
tu.toolName,
tu.arguments,
decision
);
if (response === "deny") {
// ... 返回错误结果 ...
continue;
}
if (response === "allowAlways") {
this.checker.allowAlways(tu.toolName, tu.arguments);
}
}
的 HITL 通过回调函数 onPermissionRequest 实现。回调函数返回一个 Promise, await 等待用户回复。用户选「始终允许」时调用 checker.allowAlways 一行搞定。
OS 级沙箱
应用层的 PathSandbox 只管文件类工具,Bash 命令可以在 shell 里随意读写文件系统,它管不着。所以还需要一层 OS 级的沙箱,在操作系统层面限制进程的文件写入和网络访问。macOS 用 seatbelt( sandbox-exec ),Linux 用 bubblewrap( bwrap ),各写一个实现,通过统一接口对外暴露。
Sandbox 接口
export interface SandboxConfig {
allowWrite: string[]; // 允许写入的路径列表
denyWrite: string[]; // 始终只读的路径(优先级高于 allowWrite)
networkEnabled: boolean; // 是否允许网络访问
}
export interface Sandbox {
wrap(command: string, config: SandboxConfig): string;
available(): boolean;
}
SandboxConfig 描述沙箱的三个维度:哪些路径可写、哪些路径强制只读、网络是否放行。 Sandbox 接口只有两个方法: wrap 把原始命令包装成沙箱内执行的命令字符串, available 检查当前平台的沙箱工具是否可用。
工厂函数按平台返回对应实现:
export function createSandbox(): Sandbox | null {
const platform = os.platform();
if (platform === "darwin") {
const { SeatbeltSandbox } = require("./seatbelt");
return new SeatbeltSandbox();
}
if (platform === "linux") {
const { BwrapSandbox } = require("./bwrap");
return new BwrapSandbox();
}
return null;
}
不支持的平台返回 null ,调用方拿到 null 就知道没有沙箱可用,走降级逻辑。用 require 动态加载而不是顶层 import,是为了避免在不支持的平台上加载不必要的模块。
macOS:seatbelt 实现
macOS 的 sandbox-exec 接受一个 seatbelt profile 字符串来描述沙箱策略。核心在 buildProfile 函数,它根据 SandboxConfig 动态生成这个策略:
function buildProfile(config: SandboxConfig): string {
const lines: string[] = [];
lines.push("(version 1)");
lines.push("(deny default)");
// 允许进程执行、fork、读取系统信息、全盘可读
lines.push("(allow process-exec)");
lines.push("(allow process-fork)");
lines.push("(allow sysctl-read)");
lines.push('(allow file-read* (subpath "/"))');
// 按路径放行写入
for (const path of config.allowWrite) {
lines.push(`(allow file-write* (subpath "${path}"))`);
}
策略的思路是「默认全拒绝,再逐项放行」。先放行执行和读取(不然命令都跑不起来),再按配置的路径列表放行写入。
denyWrite 的处理有个细节:seatbelt profile 里后出现的规则优先级更高,所以 deny 规则放在 allow 之后,就能覆盖掉上面放行的路径。单文件用 literal 精确匹配,目录用 subpath 前缀匹配:
for (const path of config.denyWrite) {
const matcher = existsSync(path) && statSync(path).isDirectory()
? "subpath" : "literal";
lines.push(`(deny file-write* (${matcher} "${path}"))`);
}
sandbox-exec 的路径硬编码为 /usr/bin/sandbox-exec ,防止 PATH 注入攻击。 available 方法就是检查这个路径是否存在。
Linux:bubblewrap 实现
Linux 用 bubblewrap( bwrap )创建轻量级用户命名空间隔离。整个 wrap 方法就是在拼 bwrap 的命令行参数:
wrap(command: string, config: SandboxConfig): string {
const args: string[] = [];
// 隔离 user 和 pid namespace
args.push("bwrap", "--unshare-user", "--unshare-pid");
// 根文件系统只读挂载
args.push("--ro-bind", "/", "/");
// 按路径放行写入(可写绑定)
for (const path of config.allowWrite) {
args.push("--bind", path, path);
}
// 强制只读(覆盖根路径下的子路径)
for (const path of config.denyWrite) {
args.push("--ro-bind", path, path);
}
思路和 seatbelt 类似但用了不同的机制:先把根文件系统只读挂载,再用 --bind 把需要写入的路径重新可写绑定,最后用 --ro-bind 把 denyWrite 路径强制回只读。网络隔离通过 --unshare-net 实现, /proc 需要单独挂载。
available 方法通过 which bwrap 检查 bwrap 是否在 PATH 中, execSync 抛异常就说明没装。
敏感路径禁写(denyWrite)
OS 沙箱管的是进程级别的文件访问,但应用层也需要自己的防线。 PathSandbox 维护了一个 denyWritePaths 列表,专门保护敏感配置文件:
const DEFAULT_DENY_WRITE = [
".mewcode/config.yaml",
".mewcode/permissions.local.yaml",
".mewcode/skills/",
];
这三个路径的逻辑是: config.yaml 里有 API key 等敏感信息, permissions.local.yaml 是权限规则文件(改了它就能绕过权限检查), skills/ 目录放的是 skill 文件(改了能注入任意 prompt)。构造函数里把相对路径转成绝对路径:
constructor(projectDir: string) {
this.projectDir = resolve(projectDir);
this.allowedRoots = [this.projectDir, "/tmp"];
this.denyWritePaths = DEFAULT_DENY_WRITE.map(
(p) => join(this.projectDir, p)
);
}
checkDenyWrite 在 check() 方法里优先于 allowedRoots 的检查执行。即使路径在项目目录内(通过了 allowedRoots 检查),只要命中 denyWrite 列表就直接拒绝。这样应用层和 OS 层形成双重防护:应用层在文件工具的 check 路径里拦,OS 层在 Bash 命令的进程级别拦。
autoAllow 联动
沙箱开启后,命令类工具已经被 OS 沙箱隔离了,写入操作受到限制。这时候每条命令还要弹窗确认就太烦了,所以 PermissionChecker 支持 autoAllow 模式:
// PermissionChecker 中的两个标志位
sandboxEnabled = false;
sandboxAutoAllow = false;
在 check() 方法里,autoAllow 的判断插在危险命令检查之后、规则引擎之前:
// 沙箱自动放行:OS 沙箱已隔离写入,非危险命令可跳过人工确认
if (this.sandboxEnabled && this.sandboxAutoAllow && category === "command") {
return { effect: "allow", reason: "Sandbox auto-allow: OS sandbox active" };
}
注意位置:危险命令检查在它前面,所以 rm -rf / 这类命令不管沙箱开没开都会被拦住。autoAllow 只是跳过了后面的模式矩阵兜底(那里 default 模式会返回 ask),对显式的 deny 规则没有影响。
BashTool 集成
BashTool 类持有一个可选的 Sandbox 实例和对应的配置:
export class BashTool implements Tool {
sandbox: Sandbox | null = null;
sandboxConfig: SandboxConfig = {
allowWrite: [], denyWrite: [], networkEnabled: true,
};
在 execute 方法里,命令执行前检查沙箱是否可用,可用就包装一下:
let actualCommand = command;
if (this.sandbox?.available()) {
actualCommand = this.sandbox.wrap(command, this.sandboxConfig);
}
?. 可选链保证 sandbox 为 null 时不会报错。包装后的命令从 ls /tmp 变成类似 bwrap --unshare-user --unshare-pid --ro-bind / / ... -- bash -c 'ls /tmp' 的形式。沙箱不可用时(没装 bwrap、不是 macOS/Linux)就跑原始命令,降级到没有 OS 级隔离的状态。
/sandbox 斜杠命令
/sandbox 命令注册为 local_ui 类型,由 TUI 层处理状态切换:
registry.register({
name: "sandbox",
aliases: ["sb"],
type: "local_ui",
description: "Toggle OS sandbox mode for command execution",
handler: () => "sandbox",
});
handler 返回 "sandbox" 字符串,TUI 层收到后弹出选择菜单,提供三种模式:开启沙箱并自动放行命令、开启沙箱但保留常规权限确认、关闭沙箱。切换时 TUI 层同时更新 BashTool 的 sandbox/sandboxConfig 和 PermissionChecker 的 sandboxEnabled/sandboxAutoAllow 标志位。
小结
| 设计决策 | 实现方式 |
|---|---|
| 判定结果 | DecisionEffect 联合类型 + Decision 接口,对象字面量构造 |
| 权限模式 | PermissionMode 联合类型,四种模式 |
| 模式矩阵 | switch 语句 + 三元表达式,Plan 模式写操作返回 deny(非 ask) |
| 安全命令白名单 | string[] 数组(约 30 条), Array.some 前缀匹配 + 元字符检测 |
| 危险命令黑名单 | 14 条正则字面量(含 5 条 Git 操作), Array.some + test 匹配 |
| 路径沙箱 | resolve 转绝对路径 + 字符串 startsWith 匹配,不解析符号链接 |
| 规则语法和匹配 | ToolName(pattern) 格式,自实现 glob→正则 转换匹配,支持通配工具名 * |
| 规则文件加载 | 每次 evaluate 重新读文件,无缓存 |
| Plan Mode 例外 | 仅检查 WriteFile + 路径包含 .mewcode/plans/ |
| 防御链串联 | check() 六层顺序执行,首个明确判定即返回 |
| OS 沙箱接口 | Sandbox 接口 + createSandbox() 工厂,按平台动态加载实现 |
| macOS seatbelt | 动态生成 profile 字符串,deny default → 逐项 allow/deny,硬编码 sandbox-exec 路径 |
| Linux bubblewrap | 拼接 bwrap 命令行参数, --ro-bind / 全局只读 → --bind 可写 → --ro-bind 强制只读 |
| 敏感路径禁写 | PathSandbox.denyWritePaths 列表, checkDenyWrite 优先于 allowedRoots 检查 |
| autoAllow 联动 | sandboxEnabled + sandboxAutoAllow 双标志位,插在危险命令检查之后、规则引擎之前 |
| HITL 同步 | 回调函数 onPermissionRequest 返回 Promise |
| 架构选择 | 单文件,组件全部在文件内定义 |