示例工程 62-workspace-shell-sandbox

62-workspace-shell-sandbox/demo-02-shell-policy/shell.ts

typescript · 1.4 KB

const ALLOW = ["pnpm test", "git status", "ls", "cat", "echo"];

function inspect(command: string): { code: string; detail: string } {
  const raw = command.trim();
  if (!raw) return { code: "EMPTY", detail: "EMPTY_COMMAND" };
  if (raw.length > 200) return { code: "TOO_LONG", detail: "COMMAND_TOO_LONG" };
  if (/[;&|<>$`\n\r]/.test(raw)) {
    return { code: "SHELL_METACHAR", detail: "SHELL_METACHAR" };
  }
  const tokens = raw.split(/\s+/).filter(Boolean);
  const first = tokens[0] ?? "";
  const allowed = ALLOW.some(
    (entry) => raw === entry || raw.startsWith(`${entry} `),
  );
  if (!allowed) {
    return { code: "COMMAND_NOT_ALLOWED", detail: `BLOCKED:${first}` };
  }
  if (tokens.some((token) => token.startsWith("/") || token.includes(".."))) {
    return { code: "PATH_OUTSIDE", detail: "ARG_OUTSIDE_WORKSPACE" };
  }
  return { code: "OK", detail: "ALLOWED" };
}

const tests = inspect("pnpm test");
const status = inspect("git status");
const blocked = inspect("rm -rf /");
const metachar = inspect("ls; rm -rf /");
const outside = inspect("cat ../secrets.env");

const ok =
  tests.code === "OK" &&
  status.code === "OK" &&
  blocked.code === "COMMAND_NOT_ALLOWED" &&
  metachar.code === "SHELL_METACHAR" &&
  outside.code === "PATH_OUTSIDE";

console.log(
  JSON.stringify({
    evt: "smoke",
    ok,
    tests,
    status,
    blocked,
    metachar,
    outside,
  }),
);

export {};