Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
improvement: refactor cert profile policy creation to be inline
Scott Wilson5d2f156d1982
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsxindex d390485e19..143aeccaaf 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/CreatePolicyModal.tsx@@ -1,5 +1,5 @@/* eslint-disable no-nested-ternary */-import { ReactNode, useEffect, useState } from "react";+import { forwardRef, ReactNode, useEffect, useImperativeHandle, useRef, useState } from "react";import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { Info, Plus, ShieldCheck, Trash2 } from "lucide-react";@@ -90,6 +90,23 @@ interface Props {onComplete?: (policy: TCertificatePolicy) => void;}+export type CertificatePolicyWizardHandle = {+ goNext: () => Promise<void>;+ submit: () => Promise<void>;+};++interface WizardProps {+ policy?: TCertificatePolicy;+ mode?: "create" | "edit";+ onComplete?: (policy: TCertificatePolicy) => void | Promise<void>;+ onFinish?: () => void;+ step: number;+ onStepChange: (step: number) => void;+ banner?: ReactNode;+ defaultName?: string;+ nameDescription?: ReactNode;+}+const ATTRIBUTE_TYPE_LABELS: Record<(typeof SUBJECT_ATTRIBUTE_TYPE_OPTIONS)[number], string> = {common_name: "Common Name (CN)",organization: "Organization (O)",@@ -243,6 +260,8 @@ const STEPS = [}] as const;+export const CERTIFICATE_POLICY_STEPS = STEPS;+const SUBJECT_INCLUDE_VERBS: Record<CertSubjectAttributeInclude, string> = {[CertSubjectAttributeInclude.REQUIRED]: "Requires",[CertSubjectAttributeInclude.OPTIONAL]: "Allows",@@ -415,677 +434,1226 @@ const SectionToggle = ({</div>);-export const CreatePolicyModal = ({- isOpen,- onClose,- policy,- mode = "create",- onComplete-}: Props) => {- const { currentProject } = useProject();- const { subscription } = useSubscription();- const createPolicy = useCreateCertificatePolicy();- const updatePolicy = useUpdateCertificatePolicy();-- const isEdit = mode === "edit" && policy;-- const [step, setStep] = useState(0);- const currentStep = STEPS[step];- const isLast = step === STEPS.length - 1;-- const [restrictSubject, setRestrictSubject] = useState(false);- const [restrictSans, setRestrictSans] = useState(false);- const [restrictSignature, setRestrictSignature] = useState(false);- const [restrictKeyAlg, setRestrictKeyAlg] = useState(false);- const [restrictKeyUsages, setRestrictKeyUsages] = useState(false);- const [restrictExtendedKeyUsages, setRestrictExtendedKeyUsages] = useState(false);- const [restrictValidity, setRestrictValidity] = useState(false);- const [configureBasicConstraints, setConfigureBasicConstraints] = useState(false);-- const [errors, setErrors] = useState<Record<string, string>>({});- const clearError = (key: string) =>- setErrors((prev) => {- if (!prev[key]) return prev;- const next = { ...prev };- delete next[key];- return next;- });-- const goBack = () => {- if (step > 0) setStep((s) => s - 1);- };+export const CertificatePolicyWizard = forwardRef<CertificatePolicyWizardHandle, WizardProps>(+ (+ {+ policy,+ mode = "create",+ onComplete,+ onFinish,+ step,+ onStepChange,+ banner,+ defaultName,+ nameDescription+ },+ ref+ ) => {+ const { currentProject } = useProject();+ const { subscription } = useSubscription();+ const createPolicy = useCreateCertificatePolicy();+ const updatePolicy = useUpdateCertificatePolicy();++ const isEdit = mode === "edit" && policy;++ const currentStep = STEPS[step];+ const setStep = (next: number) => onStepChange(Math.min(Math.max(next, 0), STEPS.length - 1));++ const [restrictSubject, setRestrictSubject] = useState(false);+ const [restrictSans, setRestrictSans] = useState(false);+ const [restrictSignature, setRestrictSignature] = useState(false);+ const [restrictKeyAlg, setRestrictKeyAlg] = useState(false);+ const [restrictKeyUsages, setRestrictKeyUsages] = useState(false);+ const [restrictExtendedKeyUsages, setRestrictExtendedKeyUsages] = useState(false);+ const [restrictValidity, setRestrictValidity] = useState(false);+ const [configureBasicConstraints, setConfigureBasicConstraints] = useState(false);++ const [errors, setErrors] = useState<Record<string, string>>({});+ const clearError = (key: string) =>+ setErrors((prev) => {+ if (!prev[key]) return prev;+ const next = { ...prev };+ delete next[key];+ return next;+ });- const toAttributeRows = (- type: CertSubjectAttributeType,- values: string[] | undefined,- include: CertSubjectAttributeInclude- ): AttributeRow[] =>- Array.isArray(values) ? values.map((value) => ({ type, include, value: [value] })) : [];-- const convertApiToUiFormat = (policyData: TCertificatePolicy): FormData => {- const attributes: FormData["attributes"] = Array.isArray(policyData.subject)- ? policyData.subject.flatMap((subj) => {- const type = subj.type as CertSubjectAttributeType;- return [- ...toAttributeRows(type, subj.required, CertSubjectAttributeInclude.REQUIRED),- ...toAttributeRows(type, subj.allowed, CertSubjectAttributeInclude.OPTIONAL),- ...toAttributeRows(type, subj.denied, CertSubjectAttributeInclude.PROHIBIT)- ];- })- : [];-- const subjectAlternativeNames: FormData["subjectAlternativeNames"] = [];- if (policyData.sans && Array.isArray(policyData.sans)) {- policyData.sans.forEach((san) => {- if (san.required && Array.isArray(san.required)) {- san.required.forEach((requiredValue) => {- subjectAlternativeNames.push({- type: san.type as CertSubjectAlternativeNameType,- include: CertSanInclude.MANDATORY,- value: [requiredValue]+ const toAttributeRows = (+ type: CertSubjectAttributeType,+ values: string[] | undefined,+ include: CertSubjectAttributeInclude+ ): AttributeRow[] =>+ Array.isArray(values) ? values.map((value) => ({ type, include, value: [value] })) : [];++ const convertApiToUiFormat = (policyData: TCertificatePolicy): FormData => {+ const attributes: FormData["attributes"] = Array.isArray(policyData.subject)+ ? policyData.subject.flatMap((subj) => {+ const type = subj.type as CertSubjectAttributeType;+ return [+ ...toAttributeRows(type, subj.required, CertSubjectAttributeInclude.REQUIRED),+ ...toAttributeRows(type, subj.allowed, CertSubjectAttributeInclude.OPTIONAL),+ ...toAttributeRows(type, subj.denied, CertSubjectAttributeInclude.PROHIBIT)+ ];+ })+ : [];++ const subjectAlternativeNames: FormData["subjectAlternativeNames"] = [];+ if (policyData.sans && Array.isArray(policyData.sans)) {+ policyData.sans.forEach((san) => {+ if (san.required && Array.isArray(san.required)) {+ san.required.forEach((requiredValue) => {+ subjectAlternativeNames.push({+ type: san.type as CertSubjectAlternativeNameType,+ include: CertSanInclude.MANDATORY,+ value: [requiredValue]+ });});- });- }- if (san.allowed && Array.isArray(san.allowed)) {- san.allowed.forEach((allowedValue) => {- subjectAlternativeNames.push({- type: san.type as CertSubjectAlternativeNameType,- include: CertSanInclude.OPTIONAL,- value: [allowedValue]+ }+ if (san.allowed && Array.isArray(san.allowed)) {+ san.allowed.forEach((allowedValue) => {+ subjectAlternativeNames.push({+ type: san.type as CertSubjectAlternativeNameType,+ include: CertSanInclude.OPTIONAL,+ value: [allowedValue]+ });});- });- }- if (san.denied && Array.isArray(san.denied)) {- san.denied.forEach((deniedValue) => {- subjectAlternativeNames.push({- type: san.type as CertSubjectAlternativeNameType,- include: CertSanInclude.PROHIBIT,- value: [deniedValue]+ }+ if (san.denied && Array.isArray(san.denied)) {+ san.denied.forEach((deniedValue) => {+ subjectAlternativeNames.push({+ type: san.type as CertSubjectAlternativeNameType,+ include: CertSanInclude.PROHIBIT,+ value: [deniedValue]+ });});- });- }- });- }+ }+ });+ }++ const keyUsages = {+ requiredUsages: (policyData.keyUsages?.required || []) as CertKeyUsageType[],+ optionalUsages: (policyData.keyUsages?.allowed || []) as CertKeyUsageType[]+ };++ const extendedKeyUsages = {+ requiredUsages: (policyData.extendedKeyUsages?.required ||+ []) as CertExtendedKeyUsageType[],+ optionalUsages: (policyData.extendedKeyUsages?.allowed || []) as CertExtendedKeyUsageType[]+ };++ const validity = policyData.validity?.max+ ? (() => {+ const maxValue = policyData.validity.max;+ if (maxValue.length < 2)+ return { maxDuration: { value: 365, unit: CertDurationUnit.DAYS } };++ const lastChar = maxValue.slice(-1);+ const numberPart = maxValue.slice(0, -1);+ const value = parseInt(numberPart, 10);++ if (Number.isNaN(value) || value <= 0 || numberPart !== value.toString()) {+ return { maxDuration: { value: 365, unit: CertDurationUnit.DAYS } };+ }++ let unit: CertDurationUnit = CertDurationUnit.DAYS;+ if (lastChar === "h") {+ unit = CertDurationUnit.HOURS;+ } else if (lastChar === "d") {+ unit = CertDurationUnit.DAYS;+ } else if (lastChar === "m") {+ unit = CertDurationUnit.MONTHS;+ } else if (lastChar === "y") {+ unit = CertDurationUnit.YEARS;+ }- const keyUsages = {- requiredUsages: (policyData.keyUsages?.required || []) as CertKeyUsageType[],- optionalUsages: (policyData.keyUsages?.allowed || []) as CertKeyUsageType[]+ return { maxDuration: { value, unit } };+ })()+ : { maxDuration: { value: 365, unit: CertDurationUnit.DAYS } };++ const signatureAlgorithm = {+ allowedAlgorithms: policyData.algorithms?.signature || []+ };++ const keyAlgorithm = {+ allowedKeyTypes: policyData.algorithms?.keyAlgorithm || []+ };++ const basicConstraints: FormData["basicConstraints"] = {+ isCA: (policyData.basicConstraints?.isCA as CertPolicyState) || CertPolicyState.DENIED,+ maxPathLength: policyData.basicConstraints?.maxPathLength ?? undefined+ };++ return {+ preset: POLICY_PRESET_IDS.CUSTOM,+ name: policyData.name || "",+ description: policyData.description || "",+ attributes,+ subjectAlternativeNames,+ keyUsages,+ extendedKeyUsages,+ validity,+ signatureAlgorithm,+ keyAlgorithm,+ basicConstraints+ };};- const extendedKeyUsages = {- requiredUsages: (policyData.extendedKeyUsages?.required || []) as CertExtendedKeyUsageType[],- optionalUsages: (policyData.extendedKeyUsages?.allowed || []) as CertExtendedKeyUsageType[]+ const getDefaultValues = (): FormData & { preset: PolicyPresetId } => {+ return {+ preset: POLICY_PRESET_IDS.CUSTOM,+ name: defaultName ?? "",+ description: "",+ basicConstraints: {+ isCA: CertPolicyState.DENIED,+ maxPathLength: undefined+ },+ attributes: [],+ keyUsages: { requiredUsages: [], optionalUsages: [] },+ extendedKeyUsages: { requiredUsages: [], optionalUsages: [] },+ subjectAlternativeNames: [],+ validity: {+ maxDuration: { value: 365, unit: CertDurationUnit.DAYS }+ },+ signatureAlgorithm: {+ allowedAlgorithms: []+ },+ keyAlgorithm: {+ allowedKeyTypes: []+ }+ };};- const validity = policyData.validity?.max- ? (() => {- const maxValue = policyData.validity.max;- if (maxValue.length < 2)- return { maxDuration: { value: 365, unit: CertDurationUnit.DAYS } };+ const { control, handleSubmit, reset, watch, setValue, trigger } = useForm<+ FormData & { preset: PolicyPresetId }+ >({+ resolver: zodResolver(policySchema),+ defaultValues: getDefaultValues(),+ mode: "onChange",+ reValidateMode: "onChange",+ criteriaMode: "all"+ });- const lastChar = maxValue.slice(-1);- const numberPart = maxValue.slice(0, -1);- const value = parseInt(numberPart, 10);+ const resetToggles = (source?: TCertificatePolicy) => {+ setRestrictSubject(Boolean(source?.subject));+ setRestrictSans(Boolean(source?.sans));+ setRestrictSignature(Boolean(source?.algorithms?.signature?.length));+ setRestrictKeyAlg(Boolean(source?.algorithms?.keyAlgorithm?.length));+ setRestrictKeyUsages(Boolean(source?.keyUsages));+ setRestrictExtendedKeyUsages(Boolean(source?.extendedKeyUsages));+ setRestrictValidity(Boolean(source?.validity?.max));+ setConfigureBasicConstraints(Boolean(source?.basicConstraints?.isCA));+ setErrors({});+ };- if (Number.isNaN(value) || value <= 0 || numberPart !== value.toString()) {- return { maxDuration: { value: 365, unit: CertDurationUnit.DAYS } };- }+ useEffect(() => {+ if (isEdit && policy) {+ const convertedData = convertApiToUiFormat(policy);+ reset({ ...convertedData, preset: POLICY_PRESET_IDS.CUSTOM });+ resetToggles(policy);+ } else if (!isEdit) {+ reset(getDefaultValues());+ resetToggles();+ }+ setStep(0);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [isEdit, policy, reset]);++ const watchedAttributes = watch("attributes") || [];+ const watchedSans = watch("subjectAlternativeNames") || [];+ const watchedKeyUsages = watch("keyUsages") || { requiredUsages: [], optionalUsages: [] };+ const watchedExtendedKeyUsages = watch("extendedKeyUsages") || {+ requiredUsages: [],+ optionalUsages: []+ };+ const watchedPreset = watch("preset") || POLICY_PRESET_IDS.CUSTOM;+ const watchedSignatureAlgs = watch("signatureAlgorithm")?.allowedAlgorithms || [];+ const watchedKeyAlgs = watch("keyAlgorithm")?.allowedKeyTypes || [];+ const watchedIsCAPolicy = watch("basicConstraints.isCA") || CertPolicyState.DENIED;++ const markCustomPreset = () => {+ if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {+ setValue("preset", POLICY_PRESET_IDS.CUSTOM);+ }+ };- let unit: CertDurationUnit = CertDurationUnit.DAYS;- if (lastChar === "h") {- unit = CertDurationUnit.HOURS;- } else if (lastChar === "d") {- unit = CertDurationUnit.DAYS;- } else if (lastChar === "m") {- unit = CertDurationUnit.MONTHS;- } else if (lastChar === "y") {- unit = CertDurationUnit.YEARS;- }+ const handlePresetChange = async (presetId: PolicyPresetId) => {+ setValue("preset", presetId);- return { maxDuration: { value, unit } };- })()- : { maxDuration: { value: 365, unit: CertDurationUnit.DAYS } };+ if (presetId === POLICY_PRESET_IDS.CUSTOM) {+ await trigger();+ return;+ }- const signatureAlgorithm = {- allowedAlgorithms: policyData.algorithms?.signature || []- };+ const selectedPreset = CERTIFICATE_POLICY_PRESETS.find((p) => p.id === presetId);+ if (selectedPreset) {+ const { formData } = selectedPreset;+ if (formData.keyUsages) setValue("keyUsages", formData.keyUsages);+ if (formData.extendedKeyUsages) setValue("extendedKeyUsages", formData.extendedKeyUsages);+ if (formData.attributes) setValue("attributes", formData.attributes);+ if (formData.subjectAlternativeNames)+ setValue("subjectAlternativeNames", formData.subjectAlternativeNames);+ if (formData.signatureAlgorithm)+ setValue("signatureAlgorithm", formData.signatureAlgorithm);+ if (formData.keyAlgorithm) setValue("keyAlgorithm", formData.keyAlgorithm);+ if (formData.basicConstraints) setValue("basicConstraints", formData.basicConstraints);+ if (formData.validity) setValue("validity", formData.validity);++ setRestrictSubject(Boolean(formData.attributes?.length));+ setRestrictSans(Boolean(formData.subjectAlternativeNames?.length));+ setRestrictSignature(Boolean(formData.signatureAlgorithm?.allowedAlgorithms?.length));+ setRestrictKeyAlg(Boolean(formData.keyAlgorithm?.allowedKeyTypes?.length));+ setRestrictKeyUsages(+ Boolean(+ formData.keyUsages?.requiredUsages?.length || formData.keyUsages?.optionalUsages?.length+ )+ );+ setRestrictExtendedKeyUsages(+ Boolean(+ formData.extendedKeyUsages?.requiredUsages?.length ||+ formData.extendedKeyUsages?.optionalUsages?.length+ )+ );+ setRestrictValidity(Boolean(formData.validity?.maxDuration));+ setConfigureBasicConstraints(+ Boolean(+ formData.basicConstraints?.isCA &&+ formData.basicConstraints.isCA !== CertPolicyState.DENIED+ )+ );- const keyAlgorithm = {- allowedKeyTypes: policyData.algorithms?.keyAlgorithm || []+ await trigger();+ }};- const basicConstraints: FormData["basicConstraints"] = {- isCA: (policyData.basicConstraints?.isCA as CertPolicyState) || CertPolicyState.DENIED,- maxPathLength: policyData.basicConstraints?.maxPathLength ?? undefined- };+ const mergeRuleValues = (+ existing: string[] | undefined,+ incoming: string[] | undefined+ ): string[] => Array.from(new Set([...(existing || []), ...(incoming || [])]));++ const consolidateByType = <+ T extends {+ type: string;+ allowed?: string[];+ required?: string[];+ denied?: string[];+ }+ >(+ items: T[]+ ): T[] => {+ const consolidated = new Map<string, T>();++ items.forEach((item) => {+ const existing = consolidated.get(item.type);+ if (existing) {+ const mergedItem = {+ ...item,+ allowed: mergeRuleValues(existing.allowed, item.allowed),+ required: mergeRuleValues(existing.required, item.required),+ denied: mergeRuleValues(existing.denied, item.denied)+ } as T;++ if (mergedItem.allowed?.length === 0) delete mergedItem.allowed;+ if (mergedItem.required?.length === 0) delete mergedItem.required;+ if (mergedItem.denied?.length === 0) delete mergedItem.denied;++ consolidated.set(item.type, mergedItem);+ } else {+ consolidated.set(item.type, item);+ }+ });- return {- preset: POLICY_PRESET_IDS.CUSTOM,- name: policyData.name || "",- description: policyData.description || "",- attributes,- subjectAlternativeNames,- keyUsages,- extendedKeyUsages,- validity,- signatureAlgorithm,- keyAlgorithm,- basicConstraints+ return Array.from(consolidated.values());};- };- const getDefaultValues = (): FormData & { preset: PolicyPresetId } => {- return {- preset: POLICY_PRESET_IDS.CUSTOM,- name: "",- description: "",- basicConstraints: {- isCA: CertPolicyState.DENIED,- maxPathLength: undefined- },- attributes: [],- keyUsages: { requiredUsages: [], optionalUsages: [] },- extendedKeyUsages: { requiredUsages: [], optionalUsages: [] },- subjectAlternativeNames: [],- validity: {- maxDuration: { value: 365, unit: CertDurationUnit.DAYS }- },- signatureAlgorithm: {- allowedAlgorithms: []- },- keyAlgorithm: {- allowedKeyTypes: []- }- };- };+ const transformToApiFormat = (data: FormData) => {+ const subjectRaw =+ data.attributes?.map((attr): AttributeTransform => {+ const ruleKey = SUBJECT_INCLUDE_RULE_KEYS[attr.include];++ const values = attr.value || [];+ return {+ type: attr.type,+ ...(values.length > 0 ? { [ruleKey]: values } : {})+ } as AttributeTransform;+ }) || [];++ const sansRaw =+ data.subjectAlternativeNames?.map((san) => {+ const result: SanTransform = { type: san.type };+ if (san.include === CertSanInclude.MANDATORY && san.value && san.value.length > 0) {+ result.required = san.value;+ } else if (san.include === CertSanInclude.OPTIONAL && san.value && san.value.length > 0) {+ result.allowed = san.value;+ } else if (san.include === CertSanInclude.PROHIBIT && san.value && san.value.length > 0) {+ result.denied = san.value;+ }+ return result;+ }) || [];- const { control, handleSubmit, reset, watch, setValue, trigger } = useForm<- FormData & { preset: PolicyPresetId }- >({- resolver: zodResolver(policySchema),- defaultValues: getDefaultValues(),- mode: "onChange",- reValidateMode: "onChange",- criteriaMode: "all"- });-- const resetToggles = (source?: TCertificatePolicy) => {- setRestrictSubject(Boolean(source?.subject));- setRestrictSans(Boolean(source?.sans));- setRestrictSignature(Boolean(source?.algorithms?.signature?.length));- setRestrictKeyAlg(Boolean(source?.algorithms?.keyAlgorithm?.length));- setRestrictKeyUsages(Boolean(source?.keyUsages));- setRestrictExtendedKeyUsages(Boolean(source?.extendedKeyUsages));- setRestrictValidity(Boolean(source?.validity?.max));- setConfigureBasicConstraints(Boolean(source?.basicConstraints?.isCA));- setErrors({});- };+ const subject = restrictSubject ? consolidateByType(subjectRaw) : null;+ const sans = restrictSans ? consolidateByType(sansRaw) : null;- useEffect(() => {- if (isEdit && policy) {- const convertedData = convertApiToUiFormat(policy);- reset({ ...convertedData, preset: POLICY_PRESET_IDS.CUSTOM });- resetToggles(policy);- } else if (!isEdit) {- reset(getDefaultValues());- resetToggles();- }- setStep(0);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [isEdit, policy, reset, isOpen]);-- const watchedAttributes = watch("attributes") || [];- const watchedSans = watch("subjectAlternativeNames") || [];- const watchedKeyUsages = watch("keyUsages") || { requiredUsages: [], optionalUsages: [] };- const watchedExtendedKeyUsages = watch("extendedKeyUsages") || {- requiredUsages: [],- optionalUsages: []- };- const watchedPreset = watch("preset") || POLICY_PRESET_IDS.CUSTOM;- const watchedSignatureAlgs = watch("signatureAlgorithm")?.allowedAlgorithms || [];- const watchedKeyAlgs = watch("keyAlgorithm")?.allowedKeyTypes || [];- const watchedIsCAPolicy = watch("basicConstraints.isCA") || CertPolicyState.DENIED;-- const markCustomPreset = () => {- if (watchedPreset !== POLICY_PRESET_IDS.CUSTOM) {- setValue("preset", POLICY_PRESET_IDS.CUSTOM);- }- };+ const keyUsages: KeyUsagesTransform | null = restrictKeyUsages+ ? {+ required: data.keyUsages?.requiredUsages ?? [],+ allowed: data.keyUsages?.optionalUsages ?? []+ }+ : null;- const handlePresetChange = async (presetId: PolicyPresetId) => {- setValue("preset", presetId);+ const extendedKeyUsages: ExtendedKeyUsagesTransform | null = restrictExtendedKeyUsages+ ? {+ required: data.extendedKeyUsages?.requiredUsages ?? [],+ allowed: data.extendedKeyUsages?.optionalUsages ?? []+ }+ : null;- if (presetId === POLICY_PRESET_IDS.CUSTOM) {- await trigger();- return;- }+ const algorithms: AlgorithmsTransform = {};+ if (restrictSignature && data.signatureAlgorithm?.allowedAlgorithms?.length) {+ algorithms.signature = data.signatureAlgorithm+ .allowedAlgorithms as NonNullable<AlgorithmsTransform>["signature"];+ }+ if (restrictKeyAlg && data.keyAlgorithm?.allowedKeyTypes?.length) {+ algorithms.keyAlgorithm = data.keyAlgorithm+ .allowedKeyTypes as NonNullable<AlgorithmsTransform>["keyAlgorithm"];+ }- const selectedPreset = CERTIFICATE_POLICY_PRESETS.find((p) => p.id === presetId);- if (selectedPreset) {- const { formData } = selectedPreset;- if (formData.keyUsages) setValue("keyUsages", formData.keyUsages);- if (formData.extendedKeyUsages) setValue("extendedKeyUsages", formData.extendedKeyUsages);- if (formData.attributes) setValue("attributes", formData.attributes);- if (formData.subjectAlternativeNames)- setValue("subjectAlternativeNames", formData.subjectAlternativeNames);- if (formData.signatureAlgorithm) setValue("signatureAlgorithm", formData.signatureAlgorithm);- if (formData.keyAlgorithm) setValue("keyAlgorithm", formData.keyAlgorithm);- if (formData.basicConstraints) setValue("basicConstraints", formData.basicConstraints);- if (formData.validity) setValue("validity", formData.validity);-- setRestrictSubject(Boolean(formData.attributes?.length));- setRestrictSans(Boolean(formData.subjectAlternativeNames?.length));- setRestrictSignature(Boolean(formData.signatureAlgorithm?.allowedAlgorithms?.length));- setRestrictKeyAlg(Boolean(formData.keyAlgorithm?.allowedKeyTypes?.length));- setRestrictKeyUsages(- Boolean(- formData.keyUsages?.requiredUsages?.length || formData.keyUsages?.optionalUsages?.length- )- );- setRestrictExtendedKeyUsages(- Boolean(- formData.extendedKeyUsages?.requiredUsages?.length ||- formData.extendedKeyUsages?.optionalUsages?.length- )- );- setRestrictValidity(Boolean(formData.validity?.maxDuration));- setConfigureBasicConstraints(- Boolean(- formData.basicConstraints?.isCA &&- formData.basicConstraints.isCA !== CertPolicyState.DENIED- )- );+ const validity: ValidityTransform = {};+ if (restrictValidity && data.validity?.maxDuration) {+ let unit = "d";+ if (data.validity.maxDuration.unit === CertDurationUnit.HOURS) {+ unit = "h";+ } else if (data.validity.maxDuration.unit === CertDurationUnit.DAYS) {+ unit = "d";+ } else if (data.validity.maxDuration.unit === CertDurationUnit.MONTHS) {+ unit = "m";+ } else {+ unit = "y";+ }+ validity.max = `${data.validity.maxDuration.value}${unit}`;+ }- await trigger();- }- };+ const basicConstraints = configureBasicConstraints+ ? {+ isCA: data.basicConstraints?.isCA ?? CertPolicyState.DENIED,+ maxPathLength:+ data.basicConstraints?.isCA && data.basicConstraints.isCA !== CertPolicyState.DENIED+ ? (data.basicConstraints.maxPathLength ?? undefined)+ : undefined+ }+ : null;++ return {+ name: data.name,+ description: data.description,+ subject,+ sans,+ keyUsages,+ extendedKeyUsages,+ algorithms: algorithms.signature || algorithms.keyAlgorithm ? algorithms : null,+ validity: validity.max ? validity : null,+ basicConstraints+ };+ };- const mergeRuleValues = (- existing: string[] | undefined,- incoming: string[] | undefined- ): string[] => Array.from(new Set([...(existing || []), ...(incoming || [])]));-- const consolidateByType = <- T extends {- type: string;- allowed?: string[];- required?: string[];- denied?: string[];- }- >(- items: T[]- ): T[] => {- const consolidated = new Map<string, T>();-- items.forEach((item) => {- const existing = consolidated.get(item.type);- if (existing) {- const mergedItem = {- ...item,- allowed: mergeRuleValues(existing.allowed, item.allowed),- required: mergeRuleValues(existing.required, item.required),- denied: mergeRuleValues(existing.denied, item.denied)- } as T;-- if (mergedItem.allowed?.length === 0) delete mergedItem.allowed;- if (mergedItem.required?.length === 0) delete mergedItem.required;- if (mergedItem.denied?.length === 0) delete mergedItem.denied;-- consolidated.set(item.type, mergedItem);- } else {- consolidated.set(item.type, item);- }- });+ const onFormSubmit = async (data: FormData) => {+ if (!currentProject?.id && !isEdit) return;- return Array.from(consolidated.values());- };+ const hasEmptyAttributeValues =+ restrictSubject &&+ data.attributes?.some(+ (attr) => !attr.value || attr.value.length === 0 || attr.value.some((v) => !v.trim())+ );- const transformToApiFormat = (data: FormData) => {- const subjectRaw =- data.attributes?.map((attr): AttributeTransform => {- const ruleKey = SUBJECT_INCLUDE_RULE_KEYS[attr.include];-- const values = attr.value || [];- return {- type: attr.type,- ...(values.length > 0 ? { [ruleKey]: values } : {})- } as AttributeTransform;- }) || [];-- const sansRaw =- data.subjectAlternativeNames?.map((san) => {- const result: SanTransform = { type: san.type };- if (san.include === CertSanInclude.MANDATORY && san.value && san.value.length > 0) {- result.required = san.value;- } else if (san.include === CertSanInclude.OPTIONAL && san.value && san.value.length > 0) {- result.allowed = san.value;- } else if (san.include === CertSanInclude.PROHIBIT && san.value && san.value.length > 0) {- result.denied = san.value;- }- return result;- }) || [];+ const hasEmptySanValues =+ restrictSans &&+ data.subjectAlternativeNames?.some(+ (san) => !san.value || san.value.length === 0 || san.value.some((v) => !v.trim())+ );- const subject = restrictSubject ? consolidateByType(subjectRaw) : null;- const sans = restrictSans ? consolidateByType(sansRaw) : null;+ if (hasEmptyAttributeValues || hasEmptySanValues) {+ createNotification({+ text: "All configured subject or SAN values must be non-empty. Use wildcards (*) if needed.",+ type: "error"+ });+ return;+ }- const keyUsages: KeyUsagesTransform | null = restrictKeyUsages- ? {- required: data.keyUsages?.requiredUsages ?? [],- allowed: data.keyUsages?.optionalUsages ?? []- }- : null;+ const hasInvalidDomainComponentSequence =+ restrictSubject &&+ data.attributes?.some(+ (attr) =>+ attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT &&+ attr.value?.some((value) => !isValidDomainComponentSequence(value))+ );- const extendedKeyUsages: ExtendedKeyUsagesTransform | null = restrictExtendedKeyUsages- ? {- required: data.extendedKeyUsages?.requiredUsages ?? [],- allowed: data.extendedKeyUsages?.optionalUsages ?? []- }- : null;+ if (hasInvalidDomainComponentSequence) {+ createNotification({+ text: "Every domain component in a sequence must be non-empty, for example corp,example,com.",+ type: "error"+ });+ return;+ }- const algorithms: AlgorithmsTransform = {};- if (restrictSignature && data.signatureAlgorithm?.allowedAlgorithms?.length) {- algorithms.signature = data.signatureAlgorithm- .allowedAlgorithms as NonNullable<AlgorithmsTransform>["signature"];- }- if (restrictKeyAlg && data.keyAlgorithm?.allowedKeyTypes?.length) {- algorithms.keyAlgorithm = data.keyAlgorithm- .allowedKeyTypes as NonNullable<AlgorithmsTransform>["keyAlgorithm"];- }+ const transformedData = transformToApiFormat(data);- const validity: ValidityTransform = {};- if (restrictValidity && data.validity?.maxDuration) {- let unit = "d";- if (data.validity.maxDuration.unit === CertDurationUnit.HOURS) {- unit = "h";- } else if (data.validity.maxDuration.unit === CertDurationUnit.DAYS) {- unit = "d";- } else if (data.validity.maxDuration.unit === CertDurationUnit.MONTHS) {- unit = "m";+ if (isEdit) {+ await updatePolicy.mutateAsync({ policyId: policy.id, ...transformedData });} else {- unit = "y";+ if (!currentProject?.id) {+ throw new Error("Project ID is required for creating a policy");+ }+ const createdPolicy = await createPolicy.mutateAsync({+ projectId: currentProject.id,+ ...transformedData+ });+ await onComplete?.(createdPolicy);}- validity.max = `${data.validity.maxDuration.value}${unit}`;- }- const basicConstraints = configureBasicConstraints- ? {- isCA: data.basicConstraints?.isCA ?? CertPolicyState.DENIED,- maxPathLength:- data.basicConstraints?.isCA && data.basicConstraints.isCA !== CertPolicyState.DENIED- ? (data.basicConstraints.maxPathLength ?? undefined)- : undefined- }- : null;-- return {- name: data.name,- description: data.description,- subject,- sans,- keyUsages,- extendedKeyUsages,- algorithms: algorithms.signature || algorithms.keyAlgorithm ? algorithms : null,- validity: validity.max ? validity : null,- basicConstraints+ createNotification({+ text: `Certificate policy ${isEdit ? "updated" : "created"} successfully`,+ type: "success"+ });++ reset();+ onFinish?.();};- };- const onFormSubmit = async (data: FormData) => {- if (!currentProject?.id && !isEdit) return;+ const addAttribute = () => {+ setValue("attributes", [+ ...watchedAttributes,+ {+ type: SUBJECT_ATTRIBUTE_TYPE_OPTIONS[0],+ include: SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS[1],+ value: []+ }+ ]);+ clearError("subject");+ markCustomPreset();+ };- const hasEmptyAttributeValues =- restrictSubject &&- data.attributes?.some(- (attr) => !attr.value || attr.value.length === 0 || attr.value.some((v) => !v.trim())+ const removeAttribute = (index: number) => {+ setValue(+ "attributes",+ watchedAttributes.filter((_, i) => i !== index));+ markCustomPreset();+ };++ const addSan = () => {+ setValue("subjectAlternativeNames", [+ ...watchedSans,+ { type: SAN_TYPE_OPTIONS[0], include: SAN_INCLUDE_OPTIONS[1], value: [] }+ ]);+ clearError("sans");+ markCustomPreset();+ };- const hasEmptySanValues =- restrictSans &&- data.subjectAlternativeNames?.some(- (san) => !san.value || san.value.length === 0 || san.value.some((v) => !v.trim())+ const removeSan = (index: number) => {+ setValue(+ "subjectAlternativeNames",+ watchedSans.filter((_, i) => i !== index));+ markCustomPreset();+ };- if (hasEmptyAttributeValues || hasEmptySanValues) {- createNotification({- text: "All configured subject or SAN values must be non-empty. Use wildcards (*) if needed.",- type: "error"- });- return;- }+ const keyUsagePolicyOf = (usage: CertKeyUsageType): UsagePolicy => {+ if (watchedKeyUsages.requiredUsages.includes(usage)) return "require";+ if (watchedKeyUsages.optionalUsages.includes(usage)) return "allow";+ return "deny";+ };- const hasInvalidDomainComponentSequence =- restrictSubject &&- data.attributes?.some(- (attr) =>- attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT &&- attr.value?.some((value) => !isValidDomainComponentSequence(value))- );+ const setKeyUsagePolicy = (usage: CertKeyUsageType, policyValue: UsagePolicy) => {+ const required = watchedKeyUsages.requiredUsages.filter((u) => u !== usage);+ const optional = watchedKeyUsages.optionalUsages.filter((u) => u !== usage);+ if (policyValue === "require") required.push(usage);+ else if (policyValue === "allow") optional.push(usage);+ setValue("keyUsages", { requiredUsages: required, optionalUsages: optional });+ clearError("keyUsages");+ markCustomPreset();+ };- if (hasInvalidDomainComponentSequence) {- createNotification({- text: "Every domain component in a sequence must be non-empty, for example corp,example,com.",- type: "error"- });- return;- }+ const extendedKeyUsagePolicyOf = (usage: CertExtendedKeyUsageType): UsagePolicy => {+ if (watchedExtendedKeyUsages.requiredUsages.includes(usage)) return "require";+ if (watchedExtendedKeyUsages.optionalUsages.includes(usage)) return "allow";+ return "deny";+ };- const transformedData = transformToApiFormat(data);+ const setExtendedKeyUsagePolicy = (+ usage: CertExtendedKeyUsageType,+ policyValue: UsagePolicy+ ) => {+ const required = watchedExtendedKeyUsages.requiredUsages.filter((u) => u !== usage);+ const optional = watchedExtendedKeyUsages.optionalUsages.filter((u) => u !== usage);+ if (policyValue === "require") required.push(usage);+ else if (policyValue === "allow") optional.push(usage);+ setValue("extendedKeyUsages", { requiredUsages: required, optionalUsages: optional });+ clearError("extendedKeyUsages");+ markCustomPreset();+ };- if (isEdit) {- await updatePolicy.mutateAsync({ policyId: policy.id, ...transformedData });- } else {- if (!currentProject?.id) {- throw new Error("Project ID is required for creating a policy");- }- const createdPolicy = await createPolicy.mutateAsync({- projectId: currentProject.id,- ...transformedData- });- onComplete?.(createdPolicy);- }+ const toggleAlgorithm = (+ fieldName: "signatureAlgorithm" | "keyAlgorithm",+ key: "allowedAlgorithms" | "allowedKeyTypes",+ current: string[],+ value: string,+ checked: boolean+ ) => {+ const next = checked ? [...current, value] : current.filter((v) => v !== value);+ setValue(fieldName, { [key]: next } as never);+ clearError(fieldName === "signatureAlgorithm" ? "signature" : "keyAlgorithm");+ markCustomPreset();+ };- createNotification({- text: `Certificate policy ${isEdit ? "updated" : "created"} successfully`,- type: "success"- });+ const validateStep = (): boolean => {+ const stepErrors: Record<string, string> = {};- reset();- onClose();- };+ if (step === 1) {+ if (restrictSubject && watchedAttributes.some((a) => !a.value?.[0]?.trim())) {+ stepErrors.subject = "Every subject attribute needs a value (use * for any).";+ }+ if (restrictSans && watchedSans.some((s) => !s.value?.[0]?.trim())) {+ stepErrors.sans = "Every subject alternative name needs a value (use * for any).";+ }+ }- const addAttribute = () => {- setValue("attributes", [- ...watchedAttributes,- {- type: SUBJECT_ATTRIBUTE_TYPE_OPTIONS[0],- include: SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS[1],- value: []+ if (step === 2) {+ if (restrictSignature && !watchedSignatureAlgs.length) {+ stepErrors.signature =+ "Select at least one signature algorithm, or turn off the restriction.";+ }+ if (restrictKeyAlg && !watchedKeyAlgs.length) {+ stepErrors.keyAlgorithm =+ "Select at least one key algorithm, or turn off the restriction.";+ }}- ]);- clearError("subject");- markCustomPreset();- };- const removeAttribute = (index: number) => {- setValue(- "attributes",- watchedAttributes.filter((_, i) => i !== index)- );- markCustomPreset();- };+ setErrors(stepErrors);+ return Object.keys(stepErrors).length === 0;+ };- const addSan = () => {- setValue("subjectAlternativeNames", [- ...watchedSans,- { type: SAN_TYPE_OPTIONS[0], include: SAN_INCLUDE_OPTIONS[1], value: [] }- ]);- clearError("sans");- markCustomPreset();- };+ const goNext = async () => {+ if (step === 0) {+ const ok = await trigger(["name"]);+ if (!ok) return;+ }+ if (!validateStep()) return;+ setStep(step + 1);+ };- const removeSan = (index: number) => {- setValue(- "subjectAlternativeNames",- watchedSans.filter((_, i) => i !== index)+ const renderUsageGrid = (+ options: readonly string[],+ policyOf: (u: never) => UsagePolicy,+ onChange: (u: never, p: UsagePolicy) => void,+ formatter: (u: never) => string+ ) => (+ <div className="grid grid-cols-2 gap-x-6 gap-y-3">+ {options.map((usage) => (+ <div key={usage} className="flex items-center justify-between gap-2">+ <span className="text-sm leading-tight text-balance text-foreground">+ {formatter(usage as never)}+ </span>+ <Select+ value={policyOf(usage as never)}+ onValueChange={(value) => onChange(usage as never, value as UsagePolicy)}+ >+ <SelectTrigger className="w-24 shrink-0">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ {USAGE_POLICY_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ ))}+ </div>);- markCustomPreset();- };- const keyUsagePolicyOf = (usage: CertKeyUsageType): UsagePolicy => {- if (watchedKeyUsages.requiredUsages.includes(usage)) return "require";- if (watchedKeyUsages.optionalUsages.includes(usage)) return "allow";- return "deny";- };-- const setKeyUsagePolicy = (usage: CertKeyUsageType, policyValue: UsagePolicy) => {- const required = watchedKeyUsages.requiredUsages.filter((u) => u !== usage);- const optional = watchedKeyUsages.optionalUsages.filter((u) => u !== usage);- if (policyValue === "require") required.push(usage);- else if (policyValue === "allow") optional.push(usage);- setValue("keyUsages", { requiredUsages: required, optionalUsages: optional });- clearError("keyUsages");- markCustomPreset();- };+ const renderAlgorithmGrid = (+ options: readonly string[],+ selected: string[],+ fieldName: "signatureAlgorithm" | "keyAlgorithm",+ key: "allowedAlgorithms" | "allowedKeyTypes"+ ) => (+ <div className="grid grid-cols-2 gap-3">+ {options.map((alg) => {+ const isSelected = selected.includes(alg);+ const isPqcGated = isPqcAlgorithm(alg) && !subscription?.pkiPqc;+ return (+ <div key={alg} className="flex items-center gap-3">+ <Checkbox+ id={`${fieldName}-${alg}`}+ variant="project"+ isChecked={isSelected}+ isDisabled={isPqcGated}+ onCheckedChange={(checked) =>+ toggleAlgorithm(fieldName, key, selected, alg, Boolean(checked))+ }+ />+ <label+ htmlFor={`${fieldName}-${alg}`}+ className="flex cursor-pointer items-center gap-2 text-sm text-foreground"+ >+ {alg}+ {isPqcGated && <Badge variant="info">Enterprise</Badge>}+ </label>+ </div>+ );+ })}+ </div>+ );- const extendedKeyUsagePolicyOf = (usage: CertExtendedKeyUsageType): UsagePolicy => {- if (watchedExtendedKeyUsages.requiredUsages.includes(usage)) return "require";- if (watchedExtendedKeyUsages.optionalUsages.includes(usage)) return "allow";- return "deny";- };+ useImperativeHandle(ref, () => ({+ goNext,+ submit: () => handleSubmit(onFormSubmit)()+ }));- const setExtendedKeyUsagePolicy = (usage: CertExtendedKeyUsageType, policyValue: UsagePolicy) => {- const required = watchedExtendedKeyUsages.requiredUsages.filter((u) => u !== usage);- const optional = watchedExtendedKeyUsages.optionalUsages.filter((u) => u !== usage);- if (policyValue === "require") required.push(usage);- else if (policyValue === "allow") optional.push(usage);- setValue("extendedKeyUsages", { requiredUsages: required, optionalUsages: optional });- clearError("extendedKeyUsages");- markCustomPreset();- };+ return (+ <div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">+ {banner}+ <div className="mb-6">+ <h2 className="text-lg font-semibold text-foreground">{currentStep.title}</h2>+ <p className="mt-1 text-sm text-muted">{currentStep.subtitle}</p>+ </div>- const toggleAlgorithm = (- fieldName: "signatureAlgorithm" | "keyAlgorithm",- key: "allowedAlgorithms" | "allowedKeyTypes",- current: string[],- value: string,- checked: boolean- ) => {- const next = checked ? [...current, value] : current.filter((v) => v !== value);- setValue(fieldName, { [key]: next } as never);- clearError(fieldName === "signatureAlgorithm" ? "signature" : "keyAlgorithm");- markCustomPreset();- };+ {step === 0 && (+ <FieldGroup>+ <Controller+ control={control}+ name="name"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Policy Name <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Input {...field} placeholder="e.g. tls-server" isError={Boolean(error)} />+ {nameDescription ? (+ <FieldDescription>{nameDescription}</FieldDescription>+ ) : null}+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="description"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Description</FieldLabel>+ <FieldContent>+ <TextArea+ {...field}+ value={field.value ?? ""}+ placeholder="What this policy enforces."+ rows={3}+ isError={Boolean(error)}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="preset"+ render={({ field }) => (+ <Field>+ <FieldLabel>Policy Preset</FieldLabel>+ <FieldContent>+ <Select value={field.value} onValueChange={handlePresetChange}>+ <SelectTrigger className="w-full">+ <SelectValue placeholder="Select a preset" />+ </SelectTrigger>+ <SelectContent position="popper">+ <SelectItem value={POLICY_PRESET_IDS.CUSTOM}>Custom</SelectItem>+ {CERTIFICATE_POLICY_PRESETS.map((preset) => (+ <SelectItem key={preset.id} value={preset.id}>+ {preset.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldDescription>+ Apply a preset to populate every step with a recommended baseline, then review+ and tailor each one to your requirements. Select Custom to start from scratch.+ </FieldDescription>+ </FieldContent>+ </Field>+ )}+ />+ </FieldGroup>+ )}++ {step === 1 && (+ <div className="space-y-8">+ <SectionToggle+ title="Restrict subject attributes"+ description="Only allow the subject attributes (CN, O, OU, ...) you configure here."+ enabled={restrictSubject}+ error={errors.subject}+ onChange={(enabled) => {+ setRestrictSubject(enabled);+ if (!enabled) setValue("attributes", []);+ clearError("subject");+ markCustomPreset();+ }}+ >+ <div className="space-y-4">+ {watchedAttributes.length === 0 && (+ <p className="text-xs text-muted">+ No attributes configured. Certificates issued under this policy cannot include+ any subject attributes. Turn this off to allow any subject attribute.+ </p>+ )}+ {watchedAttributes.map((attr, index) => (+ // eslint-disable-next-line react/no-array-index-key+ <div key={`attr-${index}`}>+ <div className="flex items-center gap-2">+ <Select+ value={attr.type}+ onValueChange={(value) => {+ const next = [...watchedAttributes];+ next[index] = { ...attr, type: value as CertSubjectAttributeType };+ setValue("attributes", next);+ markCustomPreset();+ }}+ >+ <SelectTrigger className="w-18 shrink-0" aria-label="Attribute type">+ {ATTRIBUTE_TYPE_ABBREVIATIONS[attr.type]}+ </SelectTrigger>+ <SelectContent position="popper">+ {SUBJECT_ATTRIBUTE_TYPE_OPTIONS.map((type) => (+ <SelectItem key={type} value={type}>+ {ATTRIBUTE_TYPE_LABELS[type]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Select+ value={attr.include}+ onValueChange={(value) => {+ const next = [...watchedAttributes];+ next[index] = {+ ...attr,+ include: value as (typeof SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS)[number]+ };+ setValue("attributes", next);+ markCustomPreset();+ }}+ >+ <SelectTrigger className="w-24 shrink-0">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ {SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS.map((type) => (+ <SelectItem key={type} value={type}>+ {SUBJECT_ATTRIBUTE_LABELS[type]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <InputGroup className="min-w-0 flex-1">+ <InputGroupInput+ placeholder={ATTRIBUTE_TYPE_PLACEHOLDERS[attr.type]}+ value={attr.value?.[0] || ""}+ onChange={(e) => {+ const next = [...watchedAttributes];+ next[index] = {+ ...attr,+ value: e.target.value.trim() ? [e.target.value.trim()] : []+ };+ setValue("attributes", next);+ markCustomPreset();+ }}+ />+ {attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT && (+ <InputGroupAddon align="inline-end">+ <DomainComponentHelp+ isDenyRule={attr.include === CertSubjectAttributeInclude.PROHIBIT}+ />+ </InputGroupAddon>+ )}+ </InputGroup>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="shrink-0"+ onClick={() => removeAttribute(index)}+ >+ <Trash2 className="size-4" />+ </Button>+ </div>+ <AttributeRulePreview+ type={attr.type}+ include={attr.include}+ value={attr.value?.[0] || ""}+ />+ </div>+ ))}+ <Button type="button" variant="outline" size="sm" onClick={addAttribute}>+ <Plus className="size-4" /> Add attribute+ </Button>+ </div>+ </SectionToggle>++ <SectionToggle+ title="Restrict subject alternative names"+ description="Only allow the SAN types and values you configure here."+ enabled={restrictSans}+ error={errors.sans}+ onChange={(enabled) => {+ setRestrictSans(enabled);+ if (!enabled) setValue("subjectAlternativeNames", []);+ clearError("sans");+ markCustomPreset();+ }}+ >+ <div className="space-y-3">+ {watchedSans.length === 0 && (+ <p className="text-xs text-muted">+ No SANs configured. Certificates issued under this policy cannot include any+ subject alternative names. Turn this off to allow any SAN.+ </p>+ )}+ {watchedSans.map((san, index) => (+ // eslint-disable-next-line react/no-array-index-key+ <div key={`san-${index}`} className="flex items-start gap-2">+ <Select+ value={san.type}+ onValueChange={(value) => {+ const next = [...watchedSans];+ next[index] = {+ ...san,+ type: value as CertSubjectAlternativeNameType+ };+ setValue("subjectAlternativeNames", next);+ markCustomPreset();+ }}+ >+ <SelectTrigger className="w-40">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ {SAN_TYPE_OPTIONS.map((type) => (+ <SelectItem key={type} value={type}>+ {SAN_TYPE_LABELS[type]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Select+ value={san.include}+ onValueChange={(value) => {+ const next = [...watchedSans];+ next[index] = {+ ...san,+ include: value as (typeof SAN_INCLUDE_OPTIONS)[number]+ };+ setValue("subjectAlternativeNames", next);+ markCustomPreset();+ }}+ >+ <SelectTrigger className="w-28">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ {SAN_INCLUDE_OPTIONS.map((type) => (+ <SelectItem key={type} value={type}>+ {SAN_INCLUDE_LABELS[type]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Input+ placeholder={SAN_TYPE_PLACEHOLDERS[san.type]}+ value={san.value?.[0] || ""}+ onChange={(e) => {+ const next = [...watchedSans];+ next[index] = {+ ...san,+ value: e.target.value.trim() ? [e.target.value.trim()] : []+ };+ setValue("subjectAlternativeNames", next);+ markCustomPreset();+ }}+ className="flex-1"+ />+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() => removeSan(index)}+ >+ <Trash2 className="size-4" />+ </Button>+ </div>+ ))}+ <Button type="button" variant="outline" size="sm" onClick={addSan}>+ <Plus className="size-4" /> Add SAN+ </Button>+ </div>+ </SectionToggle>+ </div>+ )}++ {step === 2 && (+ <div className="space-y-8">+ <SectionToggle+ title="Restrict signature algorithms"+ description="Only allow the signature algorithms you select."+ enabled={restrictSignature}+ error={errors.signature}+ onChange={(enabled) => {+ setRestrictSignature(enabled);+ if (!enabled) setValue("signatureAlgorithm", { allowedAlgorithms: [] });+ clearError("signature");+ markCustomPreset();+ }}+ >+ {renderAlgorithmGrid(+ SIGNATURE_ALGORITHMS,+ watchedSignatureAlgs,+ "signatureAlgorithm",+ "allowedAlgorithms"+ )}+ </SectionToggle>++ <SectionToggle+ title="Restrict key algorithms"+ description="Only allow the key algorithms you select."+ enabled={restrictKeyAlg}+ error={errors.keyAlgorithm}+ onChange={(enabled) => {+ setRestrictKeyAlg(enabled);+ if (!enabled) setValue("keyAlgorithm", { allowedKeyTypes: [] });+ clearError("keyAlgorithm");+ markCustomPreset();+ }}+ >+ {renderAlgorithmGrid(+ KEY_ALGORITHMS,+ watchedKeyAlgs,+ "keyAlgorithm",+ "allowedKeyTypes"+ )}+ </SectionToggle>+ </div>+ )}++ {step === 3 && (+ <div className="space-y-8">+ <SectionToggle+ title="Restrict key usages"+ description="Require, allow, or deny individual key usages."+ enabled={restrictKeyUsages}+ error={errors.keyUsages}+ onChange={(enabled) => {+ setRestrictKeyUsages(enabled);+ if (!enabled) setValue("keyUsages", { requiredUsages: [], optionalUsages: [] });+ clearError("keyUsages");+ markCustomPreset();+ }}+ >+ {renderUsageGrid(+ KEY_USAGE_OPTIONS,+ keyUsagePolicyOf as (u: never) => UsagePolicy,+ setKeyUsagePolicy as (u: never, p: UsagePolicy) => void,+ formatKeyUsage as (u: never) => string+ )}+ </SectionToggle>++ <SectionToggle+ title="Restrict extended key usages"+ description="Require, allow, or deny individual extended key usages."+ enabled={restrictExtendedKeyUsages}+ error={errors.extendedKeyUsages}+ onChange={(enabled) => {+ setRestrictExtendedKeyUsages(enabled);+ if (!enabled)+ setValue("extendedKeyUsages", { requiredUsages: [], optionalUsages: [] });+ clearError("extendedKeyUsages");+ markCustomPreset();+ }}+ >+ {renderUsageGrid(+ EXTENDED_KEY_USAGE_OPTIONS,+ extendedKeyUsagePolicyOf as (u: never) => UsagePolicy,+ setExtendedKeyUsagePolicy as (u: never, p: UsagePolicy) => void,+ formatExtendedKeyUsage as (u: never) => string+ )}+ </SectionToggle>+ </div>+ )}++ {step === 4 && (+ <div className="space-y-8">+ <SectionToggle+ title="Set maximum validity"+ description="Cap how long issued certificates can remain valid."+ enabled={restrictValidity}+ onChange={(enabled) => {+ setRestrictValidity(enabled);+ markCustomPreset();+ }}+ >+ <div className="flex items-end gap-3">+ <Controller+ control={control}+ name="validity.maxDuration.value"+ render={({ field, fieldState: { error } }) => (+ <DurationInput field={field} error={error} onCustomPreset={markCustomPreset} />+ )}+ />+ <Controller+ control={control}+ name="validity.maxDuration.unit"+ render={({ field }) => (+ <Field className="flex-1">+ <FieldLabel>Unit</FieldLabel>+ <FieldContent>+ <Select+ value={field.value}+ onValueChange={(value) => {+ field.onChange(value);+ markCustomPreset();+ }}+ >+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ <SelectItem value={CertDurationUnit.HOURS}>Hours</SelectItem>+ <SelectItem value={CertDurationUnit.DAYS}>Days</SelectItem>+ <SelectItem value={CertDurationUnit.MONTHS}>Months</SelectItem>+ <SelectItem value={CertDurationUnit.YEARS}>Years</SelectItem>+ </SelectContent>+ </Select>+ </FieldContent>+ </Field>+ )}+ />+ </div>+ </SectionToggle>++ <SectionToggle+ title="Configure basic constraints"+ description="Control whether issued certificates can act as a CA. Off allows any."+ enabled={configureBasicConstraints}+ onChange={(enabled) => {+ setConfigureBasicConstraints(enabled);+ markCustomPreset();+ }}+ >+ <div className="space-y-4">+ <Controller+ control={control}+ name="basicConstraints.isCA"+ render={({ field }) => (+ <Field>+ <FieldLabel>CA certificate (isCA)</FieldLabel>+ <FieldContent>+ <Select+ value={field.value}+ onValueChange={(value) => {+ field.onChange(value);+ if (value === CertPolicyState.DENIED) {+ setValue("basicConstraints.maxPathLength", undefined);+ }+ markCustomPreset();+ }}+ >+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ <SelectItem value={CertPolicyState.DENIED}>Deny</SelectItem>+ <SelectItem value={CertPolicyState.ALLOWED}>Allow</SelectItem>+ <SelectItem value={CertPolicyState.REQUIRED}>Require</SelectItem>+ </SelectContent>+ </Select>+ </FieldContent>+ </Field>+ )}+ />+ {watchedIsCAPolicy !== CertPolicyState.DENIED && (+ <Controller+ control={control}+ name="basicConstraints.maxPathLength"+ render={({ field }) => (+ <Field>+ <FieldLabel>Maximum path length</FieldLabel>+ <FieldContent>+ <Input+ type="number"+ min={0}+ placeholder="Leave empty for no limit"+ value={field.value ?? ""}+ onChange={(e) => {+ field.onChange(+ e.target.value === "" ? null : parseInt(e.target.value, 10)+ );+ markCustomPreset();+ }}+ />+ <FieldDescription>+ How many sub-CA levels can exist below this certificate.+ </FieldDescription>+ </FieldContent>+ </Field>+ )}+ />+ )}+ </div>+ </SectionToggle>+ </div>+ )}+ </div>+ );+ }+);- const validateStep = (): boolean => {- const stepErrors: Record<string, string> = {};+CertificatePolicyWizard.displayName = "CertificatePolicyWizard";- if (step === 1) {- if (restrictSubject && watchedAttributes.some((a) => !a.value?.[0]?.trim())) {- stepErrors.subject = "Every subject attribute needs a value (use * for any).";- }- if (restrictSans && watchedSans.some((s) => !s.value?.[0]?.trim())) {- stepErrors.sans = "Every subject alternative name needs a value (use * for any).";- }- }+export const CreatePolicyModal = ({+ isOpen,+ onClose,+ policy,+ mode = "create",+ onComplete+}: Props) => {+ const [step, setStep] = useState(0);+ const [isSubmitting, setIsSubmitting] = useState(false);+ const wizardRef = useRef<CertificatePolicyWizardHandle>(null);- if (step === 2) {- if (restrictSignature && !watchedSignatureAlgs.length) {- stepErrors.signature =- "Select at least one signature algorithm, or turn off the restriction.";- }- if (restrictKeyAlg && !watchedKeyAlgs.length) {- stepErrors.keyAlgorithm = "Select at least one key algorithm, or turn off the restriction.";- }- }+ const isEdit = mode === "edit" && policy;+ const currentStep = STEPS[step];+ const isLast = step === STEPS.length - 1;- setErrors(stepErrors);- return Object.keys(stepErrors).length === 0;+ const goBack = () => {+ if (step > 0) setStep(step - 1);};- const goNext = async () => {- if (step === 0) {- const ok = await trigger(["name"]);- if (!ok) return;+ const goNext = () => wizardRef.current?.goNext();++ const handleSubmit = async () => {+ setIsSubmitting(true);+ try {+ await wizardRef.current?.submit();+ } finally {+ setIsSubmitting(false);}- if (!validateStep()) return;- setStep((s) => Math.min(s + 1, STEPS.length - 1));};- const isSubmitting = isEdit ? updatePolicy.isPending : createPolicy.isPending;-- const renderUsageGrid = (- options: readonly string[],- policyOf: (u: never) => UsagePolicy,- onChange: (u: never, p: UsagePolicy) => void,- formatter: (u: never) => string- ) => (- <div className="grid grid-cols-2 gap-x-6 gap-y-3">- {options.map((usage) => (- <div key={usage} className="flex items-center justify-between gap-2">- <span className="text-sm leading-tight text-balance text-foreground">- {formatter(usage as never)}- </span>- <Select- value={policyOf(usage as never)}- onValueChange={(value) => onChange(usage as never, value as UsagePolicy)}- >- <SelectTrigger className="w-24 shrink-0">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- {USAGE_POLICY_OPTIONS.map((option) => (- <SelectItem key={option.value} value={option.value}>- {option.label}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- ))}- </div>- );-- const renderAlgorithmGrid = (- options: readonly string[],- selected: string[],- fieldName: "signatureAlgorithm" | "keyAlgorithm",- key: "allowedAlgorithms" | "allowedKeyTypes"- ) => (- <div className="grid grid-cols-2 gap-3">- {options.map((alg) => {- const isSelected = selected.includes(alg);- const isPqcGated = isPqcAlgorithm(alg) && !subscription?.pkiPqc;- return (- <div key={alg} className="flex items-center gap-3">- <Checkbox- id={`${fieldName}-${alg}`}- variant="project"- isChecked={isSelected}- isDisabled={isPqcGated}- onCheckedChange={(checked) =>- toggleAlgorithm(fieldName, key, selected, alg, Boolean(checked))- }- />- <label- htmlFor={`${fieldName}-${alg}`}- className="flex cursor-pointer items-center gap-2 text-sm text-foreground"- >- {alg}- {isPqcGated && <Badge variant="info">Enterprise</Badge>}- </label>- </div>- );- })}- </div>- );-return (<Sheetopen={isOpen}onOpenChange={(open) => {if (!open) {- reset();- resetToggles();setStep(0);}onClose();@@ -1139,518 +1707,15 @@ export const CreatePolicyModal = ({</Stepper></aside>- <div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">- <div className="mb-6">- <h2 className="text-lg font-semibold text-foreground">{currentStep.title}</h2>- <p className="mt-1 text-sm text-muted">{currentStep.subtitle}</p>- </div>-- {step === 0 && (- <FieldGroup>- <Controller- control={control}- name="name"- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel>- Policy Name <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <Input- {...field}- placeholder="e.g. tls-server"- isError={Boolean(error)}- />- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}- />- <Controller- control={control}- name="description"- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel>Description</FieldLabel>- <FieldContent>- <TextArea- {...field}- value={field.value ?? ""}- placeholder="What this policy enforces."- rows={3}- isError={Boolean(error)}- />- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}- />- <Controller- control={control}- name="preset"- render={({ field }) => (- <Field>- <FieldLabel>Policy Preset</FieldLabel>- <FieldContent>- <Select value={field.value} onValueChange={handlePresetChange}>- <SelectTrigger className="w-full">- <SelectValue placeholder="Select a preset" />- </SelectTrigger>- <SelectContent position="popper">- <SelectItem value={POLICY_PRESET_IDS.CUSTOM}>Custom</SelectItem>- {CERTIFICATE_POLICY_PRESETS.map((preset) => (- <SelectItem key={preset.id} value={preset.id}>- {preset.name}- </SelectItem>- ))}- </SelectContent>- </Select>- <FieldDescription>- Apply a preset to populate every step with a recommended baseline, then- review and tailor each one to your requirements. Select Custom to start- from scratch.- </FieldDescription>- </FieldContent>- </Field>- )}- />- </FieldGroup>- )}-- {step === 1 && (- <div className="space-y-8">- <SectionToggle- title="Restrict subject attributes"- description="Only allow the subject attributes (CN, O, OU, ...) you configure here."- enabled={restrictSubject}- error={errors.subject}- onChange={(enabled) => {- setRestrictSubject(enabled);- if (!enabled) setValue("attributes", []);- clearError("subject");- markCustomPreset();- }}- >- <div className="space-y-4">- {watchedAttributes.length === 0 && (- <p className="text-xs text-muted">- No attributes configured. Certificates issued under this policy cannot- include any subject attributes. Turn this off to allow any subject- attribute.- </p>- )}- {watchedAttributes.map((attr, index) => (- // eslint-disable-next-line react/no-array-index-key- <div key={`attr-${index}`}>- <div className="flex items-center gap-2">- <Select- value={attr.type}- onValueChange={(value) => {- const next = [...watchedAttributes];- next[index] = { ...attr, type: value as CertSubjectAttributeType };- setValue("attributes", next);- markCustomPreset();- }}- >- <SelectTrigger className="w-18 shrink-0" aria-label="Attribute type">- {ATTRIBUTE_TYPE_ABBREVIATIONS[attr.type]}- </SelectTrigger>- <SelectContent position="popper">- {SUBJECT_ATTRIBUTE_TYPE_OPTIONS.map((type) => (- <SelectItem key={type} value={type}>- {ATTRIBUTE_TYPE_LABELS[type]}- </SelectItem>- ))}- </SelectContent>- </Select>- <Select- value={attr.include}- onValueChange={(value) => {- const next = [...watchedAttributes];- next[index] = {- ...attr,- include:- value as (typeof SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS)[number]- };- setValue("attributes", next);- markCustomPreset();- }}- >- <SelectTrigger className="w-24 shrink-0">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- {SUBJECT_ATTRIBUTE_INCLUDE_OPTIONS.map((type) => (- <SelectItem key={type} value={type}>- {SUBJECT_ATTRIBUTE_LABELS[type]}- </SelectItem>- ))}- </SelectContent>- </Select>- <InputGroup className="min-w-0 flex-1">- <InputGroupInput- placeholder={ATTRIBUTE_TYPE_PLACEHOLDERS[attr.type]}- value={attr.value?.[0] || ""}- onChange={(e) => {- const next = [...watchedAttributes];- next[index] = {- ...attr,- value: e.target.value.trim() ? [e.target.value.trim()] : []- };- setValue("attributes", next);- markCustomPreset();- }}- />- {attr.type === CertSubjectAttributeType.DOMAIN_COMPONENT && (- <InputGroupAddon align="inline-end">- <DomainComponentHelp- isDenyRule={- attr.include === CertSubjectAttributeInclude.PROHIBIT- }- />- </InputGroupAddon>- )}- </InputGroup>- <Button- type="button"- variant="ghost"- size="sm"- className="shrink-0"- onClick={() => removeAttribute(index)}- >- <Trash2 className="size-4" />- </Button>- </div>- <AttributeRulePreview- type={attr.type}- include={attr.include}- value={attr.value?.[0] || ""}- />- </div>- ))}- <Button type="button" variant="outline" size="sm" onClick={addAttribute}>- <Plus className="size-4" /> Add attribute- </Button>- </div>- </SectionToggle>-- <SectionToggle- title="Restrict subject alternative names"- description="Only allow the SAN types and values you configure here."- enabled={restrictSans}- error={errors.sans}- onChange={(enabled) => {- setRestrictSans(enabled);- if (!enabled) setValue("subjectAlternativeNames", []);- clearError("sans");- markCustomPreset();- }}- >- <div className="space-y-3">- {watchedSans.length === 0 && (- <p className="text-xs text-muted">- No SANs configured. Certificates issued under this policy cannot include- any subject alternative names. Turn this off to allow any SAN.- </p>- )}- {watchedSans.map((san, index) => (- // eslint-disable-next-line react/no-array-index-key- <div key={`san-${index}`} className="flex items-start gap-2">- <Select- value={san.type}- onValueChange={(value) => {- const next = [...watchedSans];- next[index] = {- ...san,- type: value as CertSubjectAlternativeNameType- };- setValue("subjectAlternativeNames", next);- markCustomPreset();- }}- >- <SelectTrigger className="w-40">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- {SAN_TYPE_OPTIONS.map((type) => (- <SelectItem key={type} value={type}>- {SAN_TYPE_LABELS[type]}- </SelectItem>- ))}- </SelectContent>- </Select>- <Select- value={san.include}- onValueChange={(value) => {- const next = [...watchedSans];- next[index] = {- ...san,- include: value as (typeof SAN_INCLUDE_OPTIONS)[number]- };- setValue("subjectAlternativeNames", next);- markCustomPreset();- }}- >- <SelectTrigger className="w-28">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- {SAN_INCLUDE_OPTIONS.map((type) => (- <SelectItem key={type} value={type}>- {SAN_INCLUDE_LABELS[type]}- </SelectItem>- ))}- </SelectContent>- </Select>- <Input- placeholder={SAN_TYPE_PLACEHOLDERS[san.type]}- value={san.value?.[0] || ""}- onChange={(e) => {- const next = [...watchedSans];- next[index] = {- ...san,- value: e.target.value.trim() ? [e.target.value.trim()] : []- };- setValue("subjectAlternativeNames", next);- markCustomPreset();- }}- className="flex-1"- />- <Button- type="button"- variant="ghost"- size="sm"- onClick={() => removeSan(index)}- >- <Trash2 className="size-4" />- </Button>- </div>- ))}- <Button type="button" variant="outline" size="sm" onClick={addSan}>- <Plus className="size-4" /> Add SAN- </Button>- </div>- </SectionToggle>- </div>- )}-- {step === 2 && (- <div className="space-y-8">- <SectionToggle- title="Restrict signature algorithms"- description="Only allow the signature algorithms you select."- enabled={restrictSignature}- error={errors.signature}- onChange={(enabled) => {- setRestrictSignature(enabled);- if (!enabled) setValue("signatureAlgorithm", { allowedAlgorithms: [] });- clearError("signature");- markCustomPreset();- }}- >- {renderAlgorithmGrid(- SIGNATURE_ALGORITHMS,- watchedSignatureAlgs,- "signatureAlgorithm",- "allowedAlgorithms"- )}- </SectionToggle>-- <SectionToggle- title="Restrict key algorithms"- description="Only allow the key algorithms you select."- enabled={restrictKeyAlg}- error={errors.keyAlgorithm}- onChange={(enabled) => {- setRestrictKeyAlg(enabled);- if (!enabled) setValue("keyAlgorithm", { allowedKeyTypes: [] });- clearError("keyAlgorithm");- markCustomPreset();- }}- >- {renderAlgorithmGrid(- KEY_ALGORITHMS,- watchedKeyAlgs,- "keyAlgorithm",- "allowedKeyTypes"- )}- </SectionToggle>- </div>- )}-- {step === 3 && (- <div className="space-y-8">- <SectionToggle- title="Restrict key usages"- description="Require, allow, or deny individual key usages."- enabled={restrictKeyUsages}- error={errors.keyUsages}- onChange={(enabled) => {- setRestrictKeyUsages(enabled);- if (!enabled)- setValue("keyUsages", { requiredUsages: [], optionalUsages: [] });- clearError("keyUsages");- markCustomPreset();- }}- >- {renderUsageGrid(- KEY_USAGE_OPTIONS,- keyUsagePolicyOf as (u: never) => UsagePolicy,- setKeyUsagePolicy as (u: never, p: UsagePolicy) => void,- formatKeyUsage as (u: never) => string- )}- </SectionToggle>-- <SectionToggle- title="Restrict extended key usages"- description="Require, allow, or deny individual extended key usages."- enabled={restrictExtendedKeyUsages}- error={errors.extendedKeyUsages}- onChange={(enabled) => {- setRestrictExtendedKeyUsages(enabled);- if (!enabled)- setValue("extendedKeyUsages", { requiredUsages: [], optionalUsages: [] });- clearError("extendedKeyUsages");- markCustomPreset();- }}- >- {renderUsageGrid(- EXTENDED_KEY_USAGE_OPTIONS,- extendedKeyUsagePolicyOf as (u: never) => UsagePolicy,- setExtendedKeyUsagePolicy as (u: never, p: UsagePolicy) => void,- formatExtendedKeyUsage as (u: never) => string- )}- </SectionToggle>- </div>- )}-- {step === 4 && (- <div className="space-y-8">- <SectionToggle- title="Set maximum validity"- description="Cap how long issued certificates can remain valid."- enabled={restrictValidity}- onChange={(enabled) => {- setRestrictValidity(enabled);- markCustomPreset();- }}- >- <div className="flex items-end gap-3">- <Controller- control={control}- name="validity.maxDuration.value"- render={({ field, fieldState: { error } }) => (- <DurationInput- field={field}- error={error}- onCustomPreset={markCustomPreset}- />- )}- />- <Controller- control={control}- name="validity.maxDuration.unit"- render={({ field }) => (- <Field className="flex-1">- <FieldLabel>Unit</FieldLabel>- <FieldContent>- <Select- value={field.value}- onValueChange={(value) => {- field.onChange(value);- markCustomPreset();- }}- >- <SelectTrigger className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- <SelectItem value={CertDurationUnit.HOURS}>Hours</SelectItem>- <SelectItem value={CertDurationUnit.DAYS}>Days</SelectItem>- <SelectItem value={CertDurationUnit.MONTHS}>Months</SelectItem>- <SelectItem value={CertDurationUnit.YEARS}>Years</SelectItem>- </SelectContent>- </Select>- </FieldContent>- </Field>- )}- />- </div>- </SectionToggle>-- <SectionToggle- title="Configure basic constraints"- description="Control whether issued certificates can act as a CA. Off allows any."- enabled={configureBasicConstraints}- onChange={(enabled) => {- setConfigureBasicConstraints(enabled);- markCustomPreset();- }}- >- <div className="space-y-4">- <Controller- control={control}- name="basicConstraints.isCA"- render={({ field }) => (- <Field>- <FieldLabel>CA certificate (isCA)</FieldLabel>- <FieldContent>- <Select- value={field.value}- onValueChange={(value) => {- field.onChange(value);- if (value === CertPolicyState.DENIED) {- setValue("basicConstraints.maxPathLength", undefined);- }- markCustomPreset();- }}- >- <SelectTrigger className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- <SelectItem value={CertPolicyState.DENIED}>Deny</SelectItem>- <SelectItem value={CertPolicyState.ALLOWED}>Allow</SelectItem>- <SelectItem value={CertPolicyState.REQUIRED}>Require</SelectItem>- </SelectContent>- </Select>- </FieldContent>- </Field>- )}- />- {watchedIsCAPolicy !== CertPolicyState.DENIED && (- <Controller- control={control}- name="basicConstraints.maxPathLength"- render={({ field }) => (- <Field>- <FieldLabel>Maximum path length</FieldLabel>- <FieldContent>- <Input- type="number"- min={0}- placeholder="Leave empty for no limit"- value={field.value ?? ""}- onChange={(e) => {- field.onChange(- e.target.value === "" ? null : parseInt(e.target.value, 10)- );- markCustomPreset();- }}- />- <FieldDescription>- How many sub-CA levels can exist below this certificate.- </FieldDescription>- </FieldContent>- </Field>- )}- />- )}- </div>- </SectionToggle>- </div>- )}- </div>+ <CertificatePolicyWizard+ ref={wizardRef}+ policy={policy}+ mode={mode}+ onComplete={onComplete}+ onFinish={onClose}+ step={step}+ onStepChange={setStep}+ /><aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex"><div className="mb-auto">@@ -1686,7 +1751,7 @@ export const CreatePolicyModal = ({variant="project"isPending={isSubmitting}isDisabled={isSubmitting}- onClick={handleSubmit(onFormSubmit)}+ onClick={handleSubmit}>{isEdit ? "Save Changes" : "Create Policy"}</Button>diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsxindex 651fc76d27..bcffa212d0 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx@@ -1,10 +1,10 @@-import { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { Control, Controller, useForm } from "react-hook-form";import { SingleValue } from "react-select";import { zodResolver } from "@hookform/resolvers/zod";import { useQueryClient } from "@tanstack/react-query";import { Link, useParams } from "@tanstack/react-router";-import { FileBadge } from "lucide-react";+import { Check, ChevronRight, FileBadge, ShieldCheck } from "lucide-react";import { z } from "zod";import { createNotification } from "@app/components/notifications";@@ -32,12 +32,12 @@ import {StepperStep,TextArea} from "@app/components/v3";+import { cn } from "@app/components/v3/utils";import { useProject, useProjectPermission } from "@app/context";import {ProjectPermissionCertificatePolicyActions,ProjectPermissionSub} from "@app/context/ProjectPermissionContext/types";-import { usePopUp } from "@app/hooks";import { CaType } from "@app/hooks/api/ca/enums";import {useGetAdcsTemplates,@@ -75,7 +75,11 @@ import {} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";import { PkiDocsUrls } from "../../../pki-docs-urls";-import { CreatePolicyModal } from "../CertificatePoliciesTab/CreatePolicyModal";+import {+ CERTIFICATE_POLICY_STEPS,+ CertificatePolicyWizard,+ CertificatePolicyWizardHandle+} from "../CertificatePoliciesTab/CreatePolicyModal";import { PolicyConstraints, ProfileDefaultsStep } from "./CreateProfileModal/ProfileDefaultsStep";import { CertificatePolicyOption } from "./CertificatePolicyOption";@@ -459,6 +463,49 @@ const buildFormValuesFromProfile = (defaults: convertDefaultsToForm(sourceProfile.defaults)});+const getSubStepStatus = (index: number, activeStep: number) => {+ if (index < activeStep) return "complete";+ if (index === activeStep) return "current";+ return "pending";+};++const PolicySubSteps = ({ activeStep, onCancel }: { activeStep: number; onCancel: () => void }) => (+ <li className="-mt-6 mb-8 ml-3.5 border-l border-border pl-5">+ <p className="mb-3 text-[10px] font-medium tracking-wider text-muted uppercase">New policy</p>+ <ol className="flex flex-col gap-y-2.5">+ {CERTIFICATE_POLICY_STEPS.map((s, i) => {+ const status = getSubStepStatus(i, activeStep);+ return (+ <li key={s.name} className="flex items-center gap-2.5">+ <span+ className={cn(+ "flex size-5 shrink-0 items-center justify-center rounded-full border text-[10px] font-medium",+ status === "complete" && "border-success bg-success/10 text-success",+ status === "current" && "border-warning bg-warning/10 text-warning",+ status === "pending" && "border-border bg-mineshaft-800 text-muted"+ )}+ >+ {status === "complete" ? <Check className="size-2.5" strokeWidth={3} /> : i + 1}+ </span>+ <span+ className={cn("text-xs", status === "pending" ? "text-muted" : "text-foreground")}+ >+ {s.name}+ </span>+ </li>+ );+ })}+ </ol>+ <button+ type="button"+ onClick={onCancel}+ className="mt-4 cursor-pointer text-left text-xs text-muted underline-offset-2 hover:text-foreground hover:underline"+ >+ Use an existing policy+ </button>+ </li>+);+interface Props {isOpen: boolean;onClose: () => void;@@ -480,7 +527,9 @@ export const CreateProfileModal = ({orgId?: string;projectId?: string;};- const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp(["createPolicy"] as const);+ const [policyStepIndex, setPolicyStepIndex] = useState<number | null>(null);+ const [isPolicySubmitting, setIsPolicySubmitting] = useState(false);+ const policyWizardRef = useRef<CertificatePolicyWizardHandle>(null);const queryClient = useQueryClient();const [selectedStepIndex, setSelectedStepIndex] = useState(0);@@ -548,6 +597,7 @@ export const CreateProfileModal = ({}});+ const watchedSlug = watch("slug");const watchedIssuerType = watch("issuerType");const watchedCertificateAuthorityId = watch("certificateAuthorityId");const watchedPolicyId = watch("certificatePolicyId");@@ -845,7 +895,7 @@ export const CreateProfileModal = ({};const handleClose = () => {- handlePopUpToggle("createPolicy", false);+ setPolicyStepIndex(null);reset();setSelectedStepIndex(0);onClose();@@ -853,6 +903,35 @@ export const CreateProfileModal = ({const isSubmitting = createProfile.isPending || updateProfile.isPending;+ const isPolicyWizardOpen = policyStepIndex !== null;+ const isFinalPolicyStep = policyStepIndex === CERTIFICATE_POLICY_STEPS.length - 1;+ const activePolicyStep = isPolicyWizardOpen ? CERTIFICATE_POLICY_STEPS[policyStepIndex] : null;+ const draftPolicyName = watchedSlug ? `${watchedSlug}-policy` : "";+ const goBackInPolicy = () => {+ setPolicyStepIndex((prev) => (prev === null || prev === 0 ? null : prev - 1));+ };++ const goNextInPolicy = async () => {+ if (!isFinalPolicyStep) {+ await policyWizardRef.current?.goNext();+ return;+ }+ setIsPolicySubmitting(true);+ try {+ await policyWizardRef.current?.submit();+ } finally {+ setIsPolicySubmitting(false);+ }+ };++ const handlePolicyCreated = async (createdPolicy: TCertificatePolicy) => {+ await queryClient.refetchQueries({+ queryKey: ["list-certificate-policies", currentProject?.id]+ });+ setValue("certificatePolicyId", createdPolicy.id, { shouldValidate: true });+ setPolicyStepIndex(null);+ };+return (<Sheetopen={isOpen}@@ -862,7 +941,7 @@ export const CreateProfileModal = ({}}}>- <SheetContent className="flex h-full max-h-full flex-col gap-y-0 p-0 sm:max-w-[1100px]">+ <SheetContent className="flex h-full max-h-full flex-col gap-y-0 p-0 sm:max-w-[1260px]"><SheetHeader className="border-b border-border"><SheetTitle><div className="flex w-full items-start gap-2">@@ -879,14 +958,22 @@ export const CreateProfileModal = ({: "Create Certificate Profile"}<DocumentationLinkBadge href={PkiDocsUrls.settings.profiles} /></div>- <p className="text-sm leading-4 text-muted">- {/* eslint-disable-next-line no-nested-ternary */}- {isEdit- ? `Update configuration for ${profile?.slug}`- : isClone- ? `Create a new profile based on ${profile?.slug}`- : "Define the CA and policy used to issue certificates from this profile"}- </p>+ {isPolicyWizardOpen ? (+ <p className="flex items-center gap-1 text-sm leading-4 font-normal text-muted">+ <span>{currentStep.name}</span>+ <ChevronRight className="h-3 w-3 shrink-0" />+ <span>New certificate policy</span>+ </p>+ ) : (+ <p className="text-sm leading-4 text-muted">+ {/* eslint-disable-next-line no-nested-ternary */}+ {isEdit+ ? `Update configuration for ${profile?.slug}`+ : isClone+ ? `Create a new profile based on ${profile?.slug}`+ : "Define the CA and policy used to issue certificates from this profile"}+ </p>+ )}</div></div></SheetTitle>@@ -902,262 +989,306 @@ export const CreateProfileModal = ({activeStep={selectedStepIndex}orientation="vertical"onStepChange={(i) => {- if (i < selectedStepIndex) setSelectedStepIndex(i);+ if (!isPolicyWizardOpen && i < selectedStepIndex) setSelectedStepIndex(i);}}><StepperList>- {steps.map((s, i) => (- <StepperStep- key={s.key}- index={i}- title={s.name}- description={s.shortDescription}- />- ))}+ {steps.flatMap((s, i) => {+ const stepNode = (+ <StepperStep+ key={s.key}+ index={i}+ title={s.name}+ description={s.shortDescription}+ />+ );++ if (!isPolicyWizardOpen || s.key !== "issuer") return [stepNode];++ return [+ stepNode,+ <PolicySubSteps+ key="policy-sub-steps"+ activeStep={policyStepIndex}+ onCancel={() => setPolicyStepIndex(null)}+ />+ ];+ })}</StepperList></Stepper></aside>- <div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">- <div className="mb-6">- <h2 className="text-lg font-semibold text-foreground">{currentStep.title}</h2>- <p className="mt-1 text-sm text-muted">{currentStep.subtitle}</p>- </div>-- {currentStep.key === "details" && (- <div className="space-y-5">- <Controller- control={control}- name="slug"- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel>- Name <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <Input- {...field}- placeholder="your-profile-name"- isError={Boolean(error)}- />- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}- />-- <Controller- control={control}- name="description"- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel>Description</FieldLabel>- <FieldContent>- <TextArea- {...field}- value={field.value ?? ""}- placeholder="Enter profile description"- rows={3}- isError={Boolean(error)}- />- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}- />+ {isPolicyWizardOpen ? (+ <CertificatePolicyWizard+ ref={policyWizardRef}+ step={policyStepIndex}+ onStepChange={setPolicyStepIndex}+ onComplete={handlePolicyCreated}+ defaultName={draftPolicyName}+ nameDescription="Pre-filled from the profile name. Edit if this policy will be shared."+ banner={+ <div className="mb-4 flex items-center gap-2 text-xs text-muted">+ <ShieldCheck className="size-3.5 shrink-0" />+ <span>+ Defining the policy for <span className="text-accent">{watchedSlug}</span>+ </span>+ </div>+ }+ />+ ) : (+ <div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">+ <div className="mb-6">+ <h2 className="text-lg font-semibold text-foreground">{currentStep.title}</h2>+ <p className="mt-1 text-sm text-muted">{currentStep.subtitle}</p></div>- )}- {currentStep.key === "issuer" && (- <div className="space-y-5">- <Controller- control={control}- name="issuerType"- render={({ field: { onChange, value }, fieldState: { error } }) => (- <Field>- <FieldLabel>- Issuer Type <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <Select- value={value}- onValueChange={(next) => {- if (next === IssuerType.SELF_SIGNED) {- setValue("certificateAuthorityId", "");- setValue("externalConfigs", undefined);- }- onChange(next);- }}- >- <SelectTrigger className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- <SelectItem value={IssuerType.CA}>Certificate Authority</SelectItem>- <SelectItem value={IssuerType.SELF_SIGNED}>Self-Signed</SelectItem>- </SelectContent>- </Select>- <FieldDescription>- Certificate Authority issues from an existing CA in your organization,- which is the standard path for production use. Self-Signed produces- standalone certificates with no CA chain, suitable for testing or- one-off identities only.- </FieldDescription>- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}- />+ {currentStep.key === "details" && (+ <div className="space-y-5">+ <Controller+ control={control}+ name="slug"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Name <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Input+ {...field}+ placeholder="your-profile-name"+ isError={Boolean(error)}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />- {watchedIssuerType === IssuerType.CA && (<Controllercontrol={control}- name="certificateAuthorityId"- render={({ field: { onChange, value }, fieldState: { error } }) => {- const hasCas = certificateAuthorities.length > 0;- return (- <Field>- <FieldLabel>- Certificate Authority <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <FilterableSelect- value={certificateAuthorities.find((ca) => ca.id === value) || null}- onChange={(selectedCaValue) => {- let nextCaId = "";- if (Array.isArray(selectedCaValue)) {- nextCaId = selectedCaValue[0]?.id || "";- } else if (- selectedCaValue &&- typeof selectedCaValue === "object" &&- "id" in selectedCaValue- ) {- nextCaId = selectedCaValue.id || "";- }- if (nextCaId !== value) {- // Templates are per-CA; a stale hidden template would- // fail step validation for non-ADCS issuers.- setValue("externalConfigs", undefined);- }- onChange(nextCaId);- }}- getOptionLabel={(ca) => ca.name}- getOptionValue={(ca) => ca.id}- options={certificateAuthorities}- groupBy={hasCas ? "groupType" : undefined}- getGroupHeaderLabel={hasCas ? getGroupHeaderLabel : undefined}- placeholder="Select a certificate authority"- isError={Boolean(error)}- className="w-full"- />- <FieldError errors={[error]} />- {!hasCas && (- <FieldDescription className="text-yellow-500">- No certificate authorities available.{" "}- <Link- to="/organizations/$orgId/projects/cert-manager/$projectId/certificate-authorities"- params={{ orgId: orgId ?? "", projectId: projectId ?? "" }}- className="underline hover:text-yellow-400"- >- Create one in Certificate Authorities- </Link>- </FieldDescription>- )}- </FieldContent>- </Field>- );- }}+ name="description"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Description</FieldLabel>+ <FieldContent>+ <TextArea+ {...field}+ value={field.value ?? ""}+ placeholder="Enter profile description"+ rows={3}+ isError={Boolean(error)}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}/>- )}+ </div>+ )}- {isAzureAdcsCa && (- <ExternalCaTemplateSelect+ {currentStep.key === "issuer" && (+ <div className="space-y-5">+ <Controllercontrol={control}- templates={azureAdcsTemplatesData?.templates || []}- valueKey="id"- placeholder="Select an Azure ADCS certificate template"+ name="issuerType"+ render={({ field: { onChange, value }, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Issuer Type <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Select+ value={value}+ onValueChange={(next) => {+ if (next === IssuerType.SELF_SIGNED) {+ setValue("certificateAuthorityId", "");+ setValue("externalConfigs", undefined);+ }+ onChange(next);+ }}+ >+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ <SelectItem value={IssuerType.CA}>Certificate Authority</SelectItem>+ <SelectItem value={IssuerType.SELF_SIGNED}>Self-Signed</SelectItem>+ </SelectContent>+ </Select>+ <FieldDescription>+ Certificate Authority issues from an existing CA in your organization,+ which is the standard path for production use. Self-Signed produces+ standalone certificates with no CA chain, suitable for testing or+ one-off identities only.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}/>- )}- {isAdcsCa && (- <ExternalCaTemplateSelect+ {watchedIssuerType === IssuerType.CA && (+ <Controller+ control={control}+ name="certificateAuthorityId"+ render={({ field: { onChange, value }, fieldState: { error } }) => {+ const hasCas = certificateAuthorities.length > 0;+ return (+ <Field>+ <FieldLabel>+ Certificate Authority <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <FilterableSelect+ value={+ certificateAuthorities.find((ca) => ca.id === value) || null+ }+ onChange={(selectedCaValue) => {+ let nextCaId = "";+ if (Array.isArray(selectedCaValue)) {+ nextCaId = selectedCaValue[0]?.id || "";+ } else if (+ selectedCaValue &&+ typeof selectedCaValue === "object" &&+ "id" in selectedCaValue+ ) {+ nextCaId = selectedCaValue.id || "";+ }+ if (nextCaId !== value) {+ // Templates are per-CA; a stale hidden template would+ // fail step validation for non-ADCS issuers.+ setValue("externalConfigs", undefined);+ }+ onChange(nextCaId);+ }}+ getOptionLabel={(ca) => ca.name}+ getOptionValue={(ca) => ca.id}+ options={certificateAuthorities}+ groupBy={hasCas ? "groupType" : undefined}+ getGroupHeaderLabel={hasCas ? getGroupHeaderLabel : undefined}+ placeholder="Select a certificate authority"+ isError={Boolean(error)}+ className="w-full"+ />+ <FieldError errors={[error]} />+ {!hasCas && (+ <FieldDescription className="text-yellow-500">+ No certificate authorities available.{" "}+ <Link+ to="/organizations/$orgId/projects/cert-manager/$projectId/certificate-authorities"+ params={{ orgId: orgId ?? "", projectId: projectId ?? "" }}+ className="underline hover:text-yellow-400"+ >+ Create one in Certificate Authorities+ </Link>+ </FieldDescription>+ )}+ </FieldContent>+ </Field>+ );+ }}+ />+ )}++ {isAzureAdcsCa && (+ <ExternalCaTemplateSelect+ control={control}+ templates={azureAdcsTemplatesData?.templates || []}+ valueKey="id"+ placeholder="Select an Azure ADCS certificate template"+ />+ )}++ {isAdcsCa && (+ <ExternalCaTemplateSelect+ control={control}+ templates={adcsTemplatesData?.templates || []}+ valueKey="name"+ placeholder="Select an ADCS certificate template"+ />+ )}++ <Controllercontrol={control}- templates={adcsTemplatesData?.templates || []}- valueKey="name"- placeholder="Select an ADCS certificate template"+ name="certificatePolicyId"+ render={({ field: { onChange, value }, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Certificate Policy <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <FilterableSelect+ value={certificatePolicies.find((p) => p.id === value) ?? null}+ onChange={(newValue) => {+ const selected = newValue as SingleValue<PolicyOption>;+ if (selected?.id === "_create") {+ setPolicyStepIndex(0);+ return;+ }+ onChange(selected?.id || "");++ setValue("defaults", undefined);+ }}+ options={policyOptions}+ getOptionLabel={(option) => option.name}+ getOptionValue={(option) => option.id}+ placeholder={+ certificatePolicies.length === 0 && !canCreatePolicy+ ? "No certificate policies available"+ : "Select a certificate policy"+ }+ isError={Boolean(error)}+ components={{ Option: CertificatePolicyOption }}+ className="w-full"+ />+ <FieldDescription>+ The rules that govern certificates issued from this profile: allowed+ key/signature algorithms, key usages, TTL bounds, and subject+ constraints.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}/>- )}+ </div>+ )}- <Controller+ {currentStep.key === "certificate-defaults" && (+ <ProfileDefaultsStepcontrol={control}- name="certificatePolicyId"- render={({ field: { onChange, value }, fieldState: { error } }) => (- <Field>- <FieldLabel>- Certificate Policy <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <FilterableSelect- value={certificatePolicies.find((p) => p.id === value) ?? null}- onChange={(newValue) => {- const selected = newValue as SingleValue<PolicyOption>;- if (selected?.id === "_create") {- handlePopUpOpen("createPolicy");- return;- }- onChange(selected?.id || "");-- setValue("defaults", undefined);- }}- options={policyOptions}- getOptionLabel={(option) => option.name}- getOptionValue={(option) => option.id}- placeholder={- certificatePolicies.length === 0 && !canCreatePolicy- ? "No certificate policies available"- : "Select a certificate policy"- }- isError={Boolean(error)}- components={{ Option: CertificatePolicyOption }}- className="w-full"- />- <FieldDescription>- The rules that govern certificates issued from this profile: allowed- key/signature algorithms, key usages, TTL bounds, and subject- constraints.- </FieldDescription>- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}+ watch={watch}+ setValue={setValue}+ policyConstraints={policyConstraints}+ isAwsAcmPublicCa={isAwsAcmPublicCa}+ isExternalAdcsCa={isAzureAdcsCa || isAdcsCa}+ caKeyAlgorithm={caKeyAlgorithm}/>- </div>- )}-- {currentStep.key === "certificate-defaults" && (- <ProfileDefaultsStep- control={control}- watch={watch}- setValue={setValue}- policyConstraints={policyConstraints}- isAwsAcmPublicCa={isAwsAcmPublicCa}- isExternalAdcsCa={isAzureAdcsCa || isAdcsCa}- caKeyAlgorithm={caKeyAlgorithm}- />- )}- </div>+ )}+ </div>+ )}<aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex"><div className="mb-auto"><div className="flex items-center justify-between gap-2"><p className="text-[11px] font-medium tracking-wider text-muted uppercase">- Step {selectedStepIndex + 1} · {currentStep.rightLabel}+ {activePolicyStep+ ? `Step ${selectedStepIndex + 1}.${(policyStepIndex ?? 0) + 1} · ${activePolicyStep.rightLabel}`+ : `Step ${selectedStepIndex + 1} · ${currentStep.rightLabel}`}</p>- <DocumentationLinkBadge href={PkiDocsUrls.settings.profiles} />+ <DocumentationLinkBadge+ href={+ activePolicyStep+ ? PkiDocsUrls.settings.policies+ : PkiDocsUrls.settings.profiles+ }+ /></div><p className="mt-4 text-sm font-semibold text-foreground">What this step does</p><p className="mt-2 text-sm leading-relaxed text-muted">- {currentStep.rightDescription}+ {activePolicyStep+ ? activePolicyStep.rightDescription+ : currentStep.rightDescription}</p></div></aside>@@ -1167,14 +1298,32 @@ export const CreateProfileModal = ({<span className="text-xs text-muted" /><div className="flex items-center gap-3"><span className="text-xs text-muted">- Step {selectedStepIndex + 1} of {steps.length}+ {isPolicyWizardOpen+ ? `Profile step ${selectedStepIndex + 1} · policy ${(policyStepIndex ?? 0) + 1} of ${CERTIFICATE_POLICY_STEPS.length}`+ : `Step ${selectedStepIndex + 1} of ${steps.length}`}</span>- {selectedStepIndex > 0 && (- <Button type="button" variant="outline" onClick={goBack}>+ {(selectedStepIndex > 0 || isPolicyWizardOpen) && (+ <Button+ type="button"+ variant="outline"+ onClick={isPolicyWizardOpen ? goBackInPolicy : goBack}+ >Back</Button>)}- {isFinalStep ? (+ {/* eslint-disable-next-line no-nested-ternary */}+ {isPolicyWizardOpen ? (+ <Button+ key="policy-cta"+ type="button"+ variant="project"+ isPending={isPolicySubmitting}+ isDisabled={isPolicySubmitting}+ onClick={goNextInPolicy}+ >+ {isFinalPolicyStep ? "Create Policy" : "Continue"}+ </Button>+ ) : isFinalStep ? (<Buttonkey="submit-cta"type="button"@@ -1204,18 +1353,6 @@ export const CreateProfileModal = ({</div></form></SheetContent>-- <CreatePolicyModal- isOpen={popUp.createPolicy.isOpen}- onClose={() => handlePopUpToggle("createPolicy", false)}- onComplete={async (createdPolicy) => {- await queryClient.refetchQueries({- queryKey: ["list-certificate-policies", currentProject?.id]- });- setValue("certificatePolicyId", createdPolicy.id, { shouldValidate: true });- handlePopUpToggle("createPolicy", false);- }}- /></Sheet>);};