示例工程 12-ipc-anti-patterns
12-ipc-anti-patterns/app/main/audit.ts
import path from "node:path";
import type {
AuditReport,
BridgeAudit,
EnvAudit,
PathAudit,
WildcardAudit,
} from "../shared/ipc";
const WORKSPACE = "/tmp/workspace";
const ALLOWLIST = ["notes:list", "notes:read"];
const SECRET_KEYS = ["API_KEY", "DB_PASSWORD"];
function wildcardAudit(channels: string[]): WildcardAudit {
return {
// 反模式:一个入口接受任何通道名。
wildcardAccepted: channels.filter((channel) => channel.length > 0),
// 正确:精确匹配白名单。
allowlistAccepted: channels.filter((channel) =>
ALLOWLIST.includes(channel),
),
allowlistRejected: channels.filter(
(channel) => !ALLOWLIST.includes(channel),
),
};
}
function isInsideWorkspace(candidate: string): boolean {
const resolved = path.resolve(WORKSPACE, candidate);
const relative = path.relative(WORKSPACE, resolved);
return (
relative.length > 0 &&
!relative.startsWith("..") &&
!path.isAbsolute(relative)
);
}
function pathAudit(candidates: string[]): PathAudit {
return {
workspace: WORKSPACE,
// 反模式:直接 path.join + readFile,任何路径都接受。
unsafeAccepted: candidates.filter((candidate) => candidate.length > 0),
// 正确:解析后必须仍在工作区内。
safeAccepted: candidates.filter((candidate) =>
isInsideWorkspace(candidate),
),
safeRejected: candidates.filter(
(candidate) => !isInsideWorkspace(candidate),
),
};
}
function bridgeAudit(): BridgeAudit {
return {
// 反模式:把整个 ipcRenderer 交给页面。
rawMethods: [
"send",
"sendSync",
"invoke",
"on",
"once",
"removeListener",
"postMessage",
],
// 正确:只暴露具体方法。
safeMethods: ["listNotes", "readNote", "writeNote"],
};
}
function envAudit(): EnvAudit {
// 用假 env 演示,避免把真实进程环境写进页面与截图。
const env: Record<string, string> = {
PATH: "/usr/bin:/bin",
HOME: "/Users/alice",
API_KEY: "sk-live-123",
DB_PASSWORD: "hunter2",
NODE_ENV: "production",
LANG: "zh_CN.UTF-8",
};
const safeKeys = ["NODE_ENV", "LANG"];
const unsafeKeys = Object.keys(env);
return {
unsafeKeys,
safeKeys,
secretKeys: SECRET_KEYS.filter((key) => key in env),
};
}
export function runAudit(requestId: string): AuditReport {
const wildcard = wildcardAudit([
"notes:list",
"notes:read",
"env:dump",
"fs:read-anything",
]);
const pathResult = pathAudit([
"notes/welcome.md",
"../../etc/passwd",
"/etc/passwd",
]);
const bridge = bridgeAudit();
const env = envAudit();
const safeEnv = env.safeKeys;
return {
wildcard,
path: pathResult,
bridge,
env,
safeSecretsLeaked: env.secretKeys.filter((key) => safeEnv.includes(key))
.length,
requestId,
};
}