示例工程 28-project-approval-panel

28-project-approval-panel/demo-01-policy/policy.ts

typescript · 2.7 KB

type Decision = "allow" | "deny" | "always";
type Outcome = Decision | "expired";

type PendingRequest = {
  id: string;
  tool: string;
  risk: string;
  createdAt: number;
  expiresAt: number;
};

type AuditRecord = {
  id: string;
  tool: string;
  outcome: Outcome;
  at: number;
  auto: boolean;
};

type State = {
  pending: PendingRequest[];
  history: AuditRecord[];
  policies: string[];
};

function empty(): State {
  return { pending: [], history: [], policies: [] };
}

function record(
  state: State,
  request: PendingRequest,
  outcome: Outcome,
  at: number,
  auto: boolean,
): State {
  return {
    ...state,
    history: [
      { id: request.id, tool: request.tool, outcome, at, auto },
      ...state.history,
    ],
  };
}

function enqueue(
  state: State,
  tool: string,
  now: number,
  ttlMs = 10_000,
): State {
  if (state.policies.includes(tool)) {
    return record(
      state,
      { id: `auto-${now}`, tool, risk: "read", createdAt: now, expiresAt: now },
      "allow",
      now,
      true,
    );
  }
  const request: PendingRequest = {
    id: `req-${now}`,
    tool,
    risk: "read",
    createdAt: now,
    expiresAt: now + ttlMs,
  };
  return { ...state, pending: [...state.pending, request] };
}

function decide(
  state: State,
  id: string,
  decision: Decision,
  now: number,
): State {
  const request = state.pending.find((item) => item.id === id);
  if (!request) return state;
  const pending = state.pending.filter((item) => item.id !== id);
  const policies =
    decision === "always"
      ? [...new Set([...state.policies, request.tool])]
      : state.policies;
  return record({ ...state, pending, policies }, request, decision, now, false);
}

function expire(state: State, id: string, now: number): State {
  const request = state.pending.find((item) => item.id === id);
  if (!request) return state;
  return record(
    { ...state, pending: state.pending.filter((item) => item.id !== id) },
    request,
    "expired",
    now,
    false,
  );
}

let state = empty();
state = enqueue(state, "read_file", 1000);
const firstId = state.pending[0]?.id ?? "";
state = decide(state, firstId, "always", 1100);
const policySet = state.policies.includes("read_file");

state = enqueue(state, "read_file", 1200);
const auto = state.history[0];

state = enqueue(state, "run_shell", 1300, 500);
const shellId = state.pending[0]?.id ?? "";
state = expire(state, shellId, 1900);

console.log(
  JSON.stringify({
    evt: "smoke",
    ok:
      firstId !== "" &&
      policySet &&
      auto?.auto === true &&
      auto.outcome === "allow" &&
      state.history[0]?.outcome === "expired" &&
      state.pending.length === 0 &&
      state.history.length === 3,
    policySet,
    auto,
    history: state.history,
  }),
);