示例工程 44-threat-model

44-threat-model/demo-01-navigation-policy/nav.ts

typescript · 1.8 KB

import path from "node:path";

type Verdict = { allowed: boolean; reason: string };

const NAV_HOSTS = new Set(["docs.xwrt.dev", "www.electronjs.org"]);

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" };
}

function resolveInside(root: string, candidate: string): Verdict {
  const base = path.resolve(root);
  const target = path.resolve(base, candidate);
  const relative = path.relative(base, target);
  if (relative.startsWith("..") || path.isAbsolute(relative)) {
    return { allowed: false, reason: "PATH_ESCAPE" };
  }
  return { allowed: true, reason: "INSIDE" };
}

const nav = {
  docs: isAllowedNavigation("https://docs.xwrt.dev/security"),
  electron: isAllowedNavigation("https://www.electronjs.org/docs"),
  javascript: isAllowedNavigation("javascript:alert(1)"),
  file: isAllowedNavigation("file:///etc/passwd"),
  evil: isAllowedNavigation("https://evil.example/"),
  http: isAllowedNavigation("http://docs.xwrt.dev/"),
};

const paths = {
  inside: resolveInside("/tmp/workspace", "notes/readme.md"),
  dotdot: resolveInside("/tmp/workspace", "../../etc/passwd"),
  absolute: resolveInside("/tmp/workspace", "/etc/passwd"),
};

const ok =
  nav.docs.allowed &&
  nav.electron.allowed &&
  !nav.javascript.allowed &&
  !nav.file.allowed &&
  !nav.evil.allowed &&
  !nav.http.allowed &&
  paths.inside.allowed &&
  !paths.dotdot.allowed &&
  !paths.absolute.allowed;

console.log(JSON.stringify({ evt: "smoke", ok, nav, paths }));