示例工程 28-project-approval-panel

28-project-approval-panel/app/shared/ipc.ts

typescript · 2.1 KB

export const CH = {
  get: "approval:get",
  decide: "approval:decide",
  request: "approval:request",
  reset: "approval:reset",
  changed: "approval:changed",
} as const;

export type Risk = "read" | "write" | "exec";
export type Decision = "allow" | "deny" | "always";
export type Outcome = Decision | "expired";

export type Tool = "read_file" | "write_file" | "run_shell" | "http_get";

export type ApprovalRequest = {
  id: string;
  tool: Tool;
  risk: Risk;
  detail: string;
  createdAt: number;
  expiresAt: number;
};

export type ApprovalRecord = {
  id: string;
  tool: Tool;
  risk: Risk;
  outcome: Outcome;
  at: number;
  auto: boolean;
};

export type ApprovalState = {
  pending: ApprovalRequest[];
  history: ApprovalRecord[];
  policies: Tool[];
  now: number;
};

export const TOOLS: Tool[] = [
  "read_file",
  "write_file",
  "run_shell",
  "http_get",
];

const RISKS: Risk[] = ["read", "write", "exec"];
const DECISIONS: Decision[] = ["allow", "deny", "always"];

export function assertDecideReq(
  value: unknown,
): asserts value is { id: string; decision: Decision } {
  if (typeof value !== "object" || value === null) {
    throw new Error("BAD_DECIDE_REQ");
  }
  const { id, decision } = value as { id?: unknown; decision?: unknown };
  if (
    typeof id !== "string" ||
    id.length === 0 ||
    id.length > 64 ||
    !DECISIONS.includes(decision as Decision)
  ) {
    throw new Error("BAD_DECIDE_REQ");
  }
}

export function assertRequestReq(value: unknown): asserts value is {
  tool: Tool;
  risk: Risk;
  detail: string;
  ttlMs: number;
} {
  if (typeof value !== "object" || value === null) {
    throw new Error("BAD_REQUEST_REQ");
  }
  const { tool, risk, detail, ttlMs } = value as {
    tool?: unknown;
    risk?: unknown;
    detail?: unknown;
    ttlMs?: unknown;
  };
  if (
    !TOOLS.includes(tool as Tool) ||
    !RISKS.includes(risk as Risk) ||
    typeof detail !== "string" ||
    detail.length > 200 ||
    typeof ttlMs !== "number" ||
    !Number.isFinite(ttlMs) ||
    ttlMs < 200 ||
    ttlMs > 60_000
  ) {
    throw new Error("BAD_REQUEST_REQ");
  }
}