Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

9.0 KB
Raw Blame
/**
 * Policies service layer.
 *
 * The portal calls the real Stirling policy API (`/api/v1/policies`);
 * Storybook and tests intercept the same calls with MSW handlers.
 *
 * The flat `WirePolicy[]` + `PolicyRunView[]` responses are assembled into the
 * decorated catalogue client-side by the shared `assemblePolicies()`.
 */

import type { TFunction } from "i18next";
import { apiClient } from "@processor/api/http";
import { policyInputs, toWirePolicy } from "@editor/policies/codec";
import { assemblePolicies } from "@editor/policies/overview";
export { assemblePolicies };
import {
  policyStepFromWire,
  type PolicyToolId,
} from "@editor/policies/operations";
import { HttpError } from "@processor/api/http";
import type { Policy } from "@processor/api/pipelines";
import type { PolicyRunView, WirePolicy } from "@editor/policies/types";

export type { PolicyRunView, WirePolicy } from "@editor/policies/types";

/* Catalogue model + definitions live in @editor/policies/catalog - shared with the
   editor's folder-processing setup - and are re-exported here for the portal. */
export * from "@editor/policies/catalog";
import {
  POLICY_CATEGORIES,
  POLICY_CONFIG,
  type CatalogueEntry,
  type PolicySetupResult,
} from "@editor/policies/catalog";

/** GET /api/v1/policies — the flat stored-policy records. */
export function fetchPoliciesList(): Promise<WirePolicy[]> {
  return apiClient.local.json<WirePolicy[]>("/api/v1/policies");
}

/**
 * GET /api/v1/policies/runs.
 *
 * <p>Only a 404 means "this backend has no run history", which is the case worth treating as an
 * empty list. Swallowing every failure made an unreachable or forbidden endpoint render exactly
 * like a policy that has never run, so a missing activity list could not be told from a broken one.
 */
export function fetchPolicyRuns(): Promise<PolicyRunView[]> {
  return apiClient.local
    .json<PolicyRunView[]>("/api/v1/policies/runs")
    .catch((e: unknown) => {
      if (e instanceof HttpError && e.status === 404) {
        return [] as PolicyRunView[];
      }
      throw e;
    });
}

/**
 * Whether `inner` appears in `outer` in order (no reordering), each used once. The wizard renders
 * a category's capabilities in a fixed order, so a policy whose enabled tools are a subsequence of
 * the template's canonical chain round-trips; any other order cannot be shown simply.
 */
function isOrderedSubset<T>(inner: T[], outer: T[]): boolean {
  let cursor = 0;
  for (const item of inner) {
    const at = outer.indexOf(item, cursor);
    if (at === -1) return false;
    cursor = at + 1;
  }
  return true;
}

/**
 * The CatalogueEntry that seeds the simple wizard for a policy, or null if the wizard can't express
 * it losslessly. Unsupported triggers, multiple locations, extra tools and reordered chains
 * stay in the full builder.
 */
export function parseSimplePolicy(
  policy: Policy,
  runs: PolicyRunView[],
): CatalogueEntry | null {
  const rawCategory = policy.output?.options?.categoryId;
  const categoryId = typeof rawCategory === "string" ? rawCategory : "";
  if (!categoryId) return null;
  const category = POLICY_CATEGORIES.find((c) => c.id === categoryId);
  const config = POLICY_CONFIG[categoryId];
  if (!category || !config) return null;

  if ((policy.inputs?.length ?? 0) > 1 || (policy.outputIds?.length ?? 0) > 1)
    return null;
  if (policy.output?.type && policy.output.type !== "inline") return null;
  if (policy.editor?.allowed && policy.inputs?.length) return null;

  const trigger = policy.inputs?.[0]?.trigger;
  if (trigger) {
    if (!["schedule", "folder-watch"].includes(trigger.type)) return null;
    const options = trigger.options ?? {};
    if (trigger.type === "folder-watch" && Object.keys(options).length > 0)
      return null;
    if (trigger.type === "schedule") {
      const schedule = options.schedule as
        | { type?: string; unit?: string; count?: number }
        | undefined;
      if (
        Object.keys(options).some((key) => key !== "schedule") ||
        schedule?.type !== "every" ||
        !["MINUTES", "HOURS", "DAYS"].includes(schedule.unit ?? "") ||
        Object.keys(schedule).some(
          (key) => !["type", "unit", "count"].includes(key),
        )
      )
        return null;
    }
  }

  // Every step must be one of this template's capabilities, and they must stay in canonical order.
  const canonical = config.defaultOperations.map((op) => op.toolId);
  const toolIds: PolicyToolId[] = [];
  for (const step of policy.steps) {
    const parsed = policyStepFromWire(step);
    if (!parsed || !canonical.includes(parsed.toolId)) return null;
    toolIds.push(parsed.toolId);
  }
  if (!isOrderedSubset(toolIds, canonical)) return null;

  const wire: WirePolicy = {
    id: policy.id ?? "",
    name: policy.name,
    icon: policy.icon,
    enabled: policy.enabled,
    required: policy.required,
    inputs: policy.inputs ?? [],
    outputIds: policy.outputIds ?? [],
    routingRules: policy.routingRules ?? [],
    steps: policy.steps,
    // The options bag is untyped on the pipeline record; the codec reads it defensively.
    output: {
      type: "inline",
      options: policy.output?.options ?? {},
    },
    editor: policy.editor,
  };
  const decorated = assemblePolicies([wire], runs).catalogue.find(
    (entry) => entry.category.id === categoryId,
  )?.policy;
  if (!decorated) return null;

  return {
    category,
    config,
    policy: {
      ...decorated,
      state: {
        ...decorated.state,
        name: policy.name,
        icon: policy.icon,
        inputs: policy.inputs ?? [],
        outputIds: policy.outputIds ?? [],
      },
    },
  };
}

/**
 * POST /api/v1/policies — create (blank id) or update (matched id). The
 * backend stamps owner + teamId server-side and returns the stored record.
 */
export async function savePolicy(wire: WirePolicy): Promise<WirePolicy> {
  return apiClient.local.json<WirePolicy>("/api/v1/policies", {
    method: "POST",
    body: wire,
  });
}

/** DELETE /api/v1/policies/{id} */
export async function deletePolicy(id: string): Promise<void> {
  await apiClient.local.json<void>(
    `/api/v1/policies/${encodeURIComponent(id)}`,
    {
      method: "DELETE",
    },
  );
}

/**
 * DELETE /api/v1/policies/{id}/processed-history — forget which source files
 * the policy has processed, so its next sweep reprocesses everything present.
 */
export async function clearProcessedHistory(id: string): Promise<void> {
  await apiClient.local.json<void>(
    `/api/v1/policies/${encodeURIComponent(id)}/processed-history`,
    {
      method: "DELETE",
    },
  );
}

// ── Wire-build helpers (so Policies.tsx doesn't need codec knowledge) ────────

// Catalogue policy bodies carry categoryId at the top level so the pipelines
// mock handler can discriminate them from raw pipeline saves on the shared
// POST /api/v1/policies endpoint. The real backend ignores unknown fields.
type CatalogueWireBody = WirePolicy & { categoryId: string; icon?: string };

/**
 * The persisted policy name derived from its category, e.g. "Security Policy".
 * `category.label` is an i18n key, so translate it before building the name;
 * otherwise the raw key is persisted and surfaces in the UI (e.g. the Sources
 * "Used by" pill).
 */
export function policyDisplayName(entry: CatalogueEntry, t: TFunction): string {
  return t("portal.policies.defaultName", {
    category: t(entry.category.label),
  });
}

/** Build a wire policy from a setup wizard result. */
export function buildWireFromSetup(
  entry: CatalogueEntry,
  result: PolicySetupResult,
  t: TFunction,
  enabled = true,
): CatalogueWireBody {
  const stored = entry.policy?.state;
  return {
    categoryId: entry.category.id,
    ...toWirePolicy({
      id: stored?.backendId ?? "",
      name: stored?.name ?? policyDisplayName(entry, t),
      icon: stored?.icon,
      enabled,
      required: result.required,
      extraOptions: result.extraOptions,
      policyKey: entry.category.id,
      inputs:
        result.trigger !== undefined
          ? policyInputs(result.sources, result.trigger)
          : (result.inputs ?? stored?.inputs ?? []),
      trigger: result.trigger ?? null,
      routingRules: result.routingRules ?? stored?.routingRules ?? [],
      sources: result.sources,
      outputIds: result.outputIds ?? stored?.outputIds ?? [],
      runsOnEditor: result.runsOnEditor,
      scopeTypes: result.scopeTypes,
      reviewerEmail: result.reviewerEmail,
      fieldValues: result.fieldValues,
      runOn: result.runOn,
      outputMode: result.outputMode,
      outputName: result.outputName,
      outputNamePosition: result.outputNamePosition,
      maxRetries: result.maxRetries,
      retryDelayMinutes: result.retryDelayMinutes,
      steps: result.steps,
    }),
  };
}

/**
 * POST /api/v1/policies/{id}/run — trigger a stored policy immediately. The
 * real endpoint is multipart; the portal sends no files, relying on whatever
 * the backend has queued for this policy.
 */
export async function runPolicy(id: string): Promise<{ runId: string }> {
  return apiClient.local.json<{ runId: string }>(
    `/api/v1/policies/${encodeURIComponent(id)}/run`,
    { method: "POST" },
  );
}