示例工程 62-workspace-shell-sandbox

62-workspace-shell-sandbox/demo-01-path-guard/paths.ts

typescript · 1.8 KB

const ROOT = "/Users/demo/work";
const SYMLINKS: Record<string, string> = {
  "link-out": "/Users/demo/private/key",
  "link-in": "/Users/demo/work/src/real.ts",
};

function normalize(input: string): string {
  const parts: string[] = [];
  for (const part of input.split("/")) {
    if (!part || part === ".") continue;
    if (part === "..") {
      parts.pop();
      continue;
    }
    parts.push(part);
  }
  return `/${parts.join("/")}`;
}

function resolve(input: string): { code: string; resolved: string } {
  const root = normalize(ROOT);
  const raw = input.trim();
  if (!raw) return { code: "EMPTY", resolved: "" };
  if (raw.startsWith("/") || raw.startsWith("~")) {
    return { code: "ABSOLUTE", resolved: raw };
  }
  const first = raw.split("/")[0] ?? "";
  const link = SYMLINKS[first];
  if (link) {
    const target = normalize(`${link}${raw.slice(first.length)}`);
    return {
      code:
        target === root || target.startsWith(`${root}/`)
          ? "OK"
          : "SYMLINK_ESCAPE",
      resolved: target,
    };
  }
  const candidate = normalize(`${root}/${raw}`);
  return {
    code:
      candidate === root || candidate.startsWith(`${root}/`) ? "OK" : "OUTSIDE",
    resolved: candidate,
  };
}

const inside = resolve("src/app.ts");
const outside = resolve("../secrets.env");
const absolute = resolve("/etc/passwd");
const escape = resolve("link-out");
const insideLink = resolve("link-in");

const ok =
  inside.code === "OK" &&
  inside.resolved === "/Users/demo/work/src/app.ts" &&
  outside.code === "OUTSIDE" &&
  absolute.code === "ABSOLUTE" &&
  escape.code === "SYMLINK_ESCAPE" &&
  insideLink.code === "OK";

console.log(
  JSON.stringify({
    evt: "smoke",
    ok,
    inside,
    outside,
    absolute,
    escape,
    insideLink,
  }),
);

export {};