示例工程 44-threat-model
44-threat-model/app/shared/policy.ts
import path from "node:path";
export type Verdict = {
allowed: boolean;
reason: string;
};
const NAV_HOSTS = new Set(["docs.xwrt.dev", "www.electronjs.org"]);
export function isAllowedNavigation(raw: string): Verdict {
let url: URL;
try {
url = new URL(raw);
} catch {
return { allowed: false, reason: "BAD_URL" };
}
if (url.protocol !== "https:") {
return { allowed: false, reason: `BAD_SCHEME:${url.protocol}` };
}
if (!NAV_HOSTS.has(url.hostname)) {
return { allowed: false, reason: `HOST_NOT_ALLOWED:${url.hostname}` };
}
return { allowed: true, reason: "ALLOWED_HOST" };
}
export function resolveInsideWorkspace(
root: string,
candidate: string,
): { ok: boolean; path: string; reason: string } {
if (
typeof candidate !== "string" ||
candidate.length === 0 ||
candidate.length > 4096 ||
candidate.includes("\0")
) {
return { ok: false, path: "", reason: "BAD_PATH" };
}
const base = path.resolve(root);
const target = path.resolve(base, candidate);
const relative = path.relative(base, target);
if (relative.startsWith("..") || path.isAbsolute(relative)) {
return { ok: false, path: "", reason: "PATH_ESCAPE" };
}
return { ok: true, path: target, reason: "INSIDE" };
}
function compareVersion(a: string, b: string): number {
const left = a.split(".").map(Number);
const right = b.split(".").map(Number);
for (let index = 0; index < 3; index += 1) {
const l = left[index] ?? 0;
const r = right[index] ?? 0;
if (l !== r) return l - r;
}
return 0;
}
export function verifyUpdate(input: {
current: string;
next: string;
hash: string;
expectedHash: string;
signed: boolean;
}): Verdict {
if (compareVersion(input.next, input.current) <= 0) {
return { allowed: false, reason: "NOT_NEWER" };
}
if (!input.signed) return { allowed: false, reason: "UNSIGNED" };
if (input.hash !== input.expectedHash) {
return { allowed: false, reason: "HASH_MISMATCH" };
}
return { allowed: true, reason: "VERIFIED" };
}
export function pluginAllowed(input: {
bundled: boolean;
signed: boolean;
path: string;
}): Verdict {
if (!input.bundled) return { allowed: false, reason: "NOT_BUNDLED" };
if (!input.signed) return { allowed: false, reason: "UNSIGNED" };
if (/userData/i.test(input.path)) {
return { allowed: false, reason: "USER_WRITABLE_PATH" };
}
return { allowed: true, reason: "BUNDLED_SIGNED" };
}