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(cert-manager): migrate application and approval consumers to v3 (#8858)
Andrew Huang9ed91bb0392f
diff --git a/frontend/src/components/approvals/PolicyApprovalSteps.tsx b/frontend/src/components/approvals/PolicyApprovalSteps.tsxindex e110f2c873..d3439873cb 100644--- a/frontend/src/components/approvals/PolicyApprovalSteps.tsx+++ b/frontend/src/components/approvals/PolicyApprovalSteps.tsx@@ -1,11 +1,10 @@import { useId, useMemo } from "react";import { Controller, useFieldArray, useFormContext } from "react-hook-form";-import { MultiValue } from "react-select";import { PlusIcon, TrashIcon } from "lucide-react";-import { FilterableSelect } from "@app/components/v2";import {Button,+ Combobox,Field,FieldContent,FieldDescription,@@ -189,7 +188,7 @@ export const PolicyApprovalSteps = ({ applicationId }: Props = {}) => {<Controllercontrol={control}name={`steps.${index}.approvers`}- render={({ field: { value, onChange }, fieldState: { error } }) => {+ render={({ field: { value, onChange, onBlur, ref }, fieldState: { error } }) => {const userApprovers = value.filter((a) => a.type === ApproverType.User);const groupApprovers = value.filter((a) => a.type === ApproverType.Group);const approversError =@@ -204,22 +203,19 @@ export const PolicyApprovalSteps = ({ applicationId }: Props = {}) => {User Approvers</FieldLabel><FieldContent>- <FilterableSelect- inputId={`${fieldIdPrefix}-${index}-user-approvers`}- isMulti+ <Combobox+ id={`${fieldIdPrefix}-${index}-user-approvers`}+ ref={ref}+ onBlur={onBlur}+ multiple+ isError={Boolean(approversError)}placeholder="Select users..."options={memberOptions}getOptionValue={(option) => option.id}getOptionLabel={(option) => userLabel(option.id)}value={userApprovers}- onChange={(selected) => {- const newApprovers = [- ...((selected as MultiValue<{- type: ApproverType;- id: string;- }>) || []),- ...groupApprovers- ];+ onValueChange={(selected) => {+ const newApprovers = [...selected, ...groupApprovers];onChange(newApprovers);}}/>@@ -232,22 +228,18 @@ export const PolicyApprovalSteps = ({ applicationId }: Props = {}) => {Group Approvers</FieldLabel><FieldContent>- <FilterableSelect- inputId={`${fieldIdPrefix}-${index}-group-approvers`}- isMulti+ <Combobox+ id={`${fieldIdPrefix}-${index}-group-approvers`}+ onBlur={onBlur}+ multiple+ isError={Boolean(approversError)}placeholder="Select groups..."options={groupOptions}getOptionValue={(option) => option.id}getOptionLabel={(option) => groupLabel(option.id)}value={groupApprovers}- onChange={(selected) => {- const newApprovers = [- ...userApprovers,- ...((selected as MultiValue<{- type: ApproverType;- id: string;- }>) || [])- ];+ onValueChange={(selected) => {+ const newApprovers = [...userApprovers, ...selected];onChange(newApprovers);}}/>diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/AddApplicationMemberModal.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/AddApplicationMemberModal.tsxindex 119ba4b655..85050a35ca 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/AddApplicationMemberModal.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/AddApplicationMemberModal.tsx@@ -3,20 +3,21 @@ import { useQueries } from "@tanstack/react-query";import { HardDriveIcon, UserIcon, UsersIcon } from "lucide-react";import { createNotification } from "@app/components/notifications";-import { RoleOption } from "@app/components/roles";import {Button,ButtonGroup,+ Combobox,Dialog,+ DialogBody,DialogContent,DialogDescription,DialogFooter,DialogHeader,DialogTitle,+ DiscardChangesAlertDialog,Field,FieldLabel} from "@app/components/v3";-import { FilterableSelect } from "@app/components/v3/generic/ReactSelect";import { apiRequest } from "@app/config/request";import { useProject } from "@app/context";import {@@ -27,6 +28,7 @@ import {import { useListProjectIdentityMemberships } from "@app/hooks/api/projectIdentityMembership";import { useGetWorkspaceUsers, useListWorkspaceGroups } from "@app/hooks/api/projects/queries";import { ProjectType } from "@app/hooks/api/projects/types";+import { useDiscardChangesGuard } from "@app/hooks/useDiscardChangesGuard";type ActorType = "user" | "identity" | "group";@@ -59,12 +61,6 @@ const APP_ROLES: AppRoleOption[] = [}];-const formatMemberOptionLabel = (option: Option, meta: { context: "menu" | "value" }) => (- <span className={meta.context === "value" ? "block max-w-[22rem] truncate" : "block truncate"}>- {option.label}- </span>-);-const runSequential = async <T,>(items: T[], fn: (item: T) => Promise<void>): Promise<void> => {await items.reduce<Promise<void>>(async (prev, item) => {await prev;@@ -272,123 +268,158 @@ export const AddApplicationMemberModal = ({group: selectedGroups.length};const selectedCount = selectedByType[type];+ const { requestDiscard, confirmDiscard, isDiscardDialogOpen, setIsDiscardDialogOpen } =+ useDiscardChangesGuard({+ isDirty: selectedCount > 0 || role !== "operator",+ onDiscard: () => handleClose(false)+ });return (- <Dialog open={isOpen} onOpenChange={handleClose}>- <DialogContent className="max-w-2xl">- <DialogHeader>- <DialogTitle>Add Member</DialogTitle>- <DialogDescription>- Grant access to this Application. Select existing members, identities, or groups to- attach. New members must first be granted access from the Access Control page.- </DialogDescription>- </DialogHeader>-- <div className="space-y-4">- <ButtonGroup className="w-full">- {TYPE_OPTIONS.map((opt) => {- const Icon = opt.icon;- const active = type === opt.value;- return (- <Button- key={opt.value}- type="button"- variant={active ? "project" : "outline"}- size="sm"- className="flex-1"- onClick={() => handleTypeChange(opt.value)}- aria-pressed={active}- >- <Icon />- {opt.label}- </Button>- );- })}- </ButtonGroup>-- {type === "user" && (- <Field>- <FieldLabel htmlFor={memberSelectId}>Users</FieldLabel>- <FilterableSelect- inputId={memberSelectId}- isMulti- isLoading={usersQuery.isPending}- options={userOptions}- value={selectedUsers}- onChange={(v) => setSelectedUsers((v ?? []) as Option[])}- placeholder="Select existing members…"- formatOptionLabel={formatMemberOptionLabel}- noOptionsMessage={NoUserOptions}- />- </Field>- )}-- {type === "identity" && (- <Field>- <FieldLabel htmlFor={memberSelectId}>Machine Identities</FieldLabel>- <FilterableSelect- inputId={memberSelectId}- isMulti- isLoading={identitiesQuery.isPending}- options={identityOptions}- value={selectedIdentities}- onChange={(v) => setSelectedIdentities((v ?? []) as Option[])}- placeholder="Select existing identities…"- formatOptionLabel={formatMemberOptionLabel}- noOptionsMessage={NoIdentityOptions}- />- </Field>- )}-- {type === "group" && (- <Field>- <FieldLabel htmlFor={memberSelectId}>Groups</FieldLabel>- <FilterableSelect- inputId={memberSelectId}- isMulti- isLoading={groupsQuery.isPending}- options={groupOptions}- value={selectedGroups}- onChange={(v) => setSelectedGroups((v ?? []) as Option[])}- placeholder="Select groups…"- formatOptionLabel={formatMemberOptionLabel}- noOptionsMessage={NoGroupOptions}- />- </Field>- )}-- <Field>- <FieldLabel htmlFor={roleSelectId}>Role</FieldLabel>- <FilterableSelect- inputId={roleSelectId}- options={APP_ROLES}- value={APP_ROLES.find((r) => r.slug === role) ?? null}- onChange={(v) => {- const next = v as AppRoleOption | null;- if (next) setRole(next.slug);- }}- getOptionValue={(option) => option.slug}- getOptionLabel={(option) => option.name}- components={{ Option: RoleOption }}- isClearable={false}- />- </Field>- </div>-- <DialogFooter>- <Button variant="ghost" onClick={() => handleClose(false)}>- Cancel- </Button>- <Button- variant="project"- isDisabled={selectedCount === 0 || submitting}- isPending={submitting}- onClick={handleSubmit}+ <>+ <Dialog+ open={isOpen}+ onOpenChange={(open) => {+ if (open) handleClose(true);+ else requestDiscard();+ }}+ >+ <DialogContent isPending={submitting}>+ <DialogHeader>+ <DialogTitle>Add Member</DialogTitle>+ <DialogDescription>+ Grant access to this Application. Select existing members, identities, or groups to+ attach. New members must first be granted access from the Access Control page.+ </DialogDescription>+ </DialogHeader>++ <form+ className="flex min-h-0 flex-1 flex-col gap-6"+ onSubmit={(event) => {+ event.preventDefault();+ if (selectedCount > 0 && !submitting) handleSubmit();+ }}>- Add Member{selectedCount > 1 ? "s" : ""}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>+ <DialogBody>+ <fieldset disabled={submitting} className="min-w-0 space-y-4">+ <ButtonGroup className="w-full">+ {TYPE_OPTIONS.map((opt) => {+ const Icon = opt.icon;+ const active = type === opt.value;+ return (+ <Button+ key={opt.value}+ type="button"+ variant={active ? "project" : "outline"}+ size="sm"+ className="flex-1"+ onClick={() => handleTypeChange(opt.value)}+ aria-pressed={active}+ >+ <Icon />+ {opt.label}+ </Button>+ );+ })}+ </ButtonGroup>++ {type === "user" && (+ <Field>+ <FieldLabel htmlFor={memberSelectId}>Users</FieldLabel>+ <Combobox+ id={memberSelectId}+ multiple+ isLoading={usersQuery.isPending}+ options={userOptions}+ value={selectedUsers}+ onValueChange={setSelectedUsers}+ getOptionValue={(option) => option.value}+ getOptionLabel={(option) => option.label}+ placeholder="Select existing members…"+ emptyMessage={<NoUserOptions />}+ />+ </Field>+ )}++ {type === "identity" && (+ <Field>+ <FieldLabel htmlFor={memberSelectId}>Machine Identities</FieldLabel>+ <Combobox+ id={memberSelectId}+ multiple+ isLoading={identitiesQuery.isPending}+ options={identityOptions}+ value={selectedIdentities}+ onValueChange={setSelectedIdentities}+ getOptionValue={(option) => option.value}+ getOptionLabel={(option) => option.label}+ placeholder="Select existing identities…"+ emptyMessage={<NoIdentityOptions />}+ />+ </Field>+ )}++ {type === "group" && (+ <Field>+ <FieldLabel htmlFor={memberSelectId}>Groups</FieldLabel>+ <Combobox+ id={memberSelectId}+ multiple+ isLoading={groupsQuery.isPending}+ options={groupOptions}+ value={selectedGroups}+ onValueChange={setSelectedGroups}+ getOptionValue={(option) => option.value}+ getOptionLabel={(option) => option.label}+ placeholder="Select groups…"+ emptyMessage={<NoGroupOptions />}+ />+ </Field>+ )}++ <Field>+ <FieldLabel htmlFor={roleSelectId}>Role</FieldLabel>+ <Combobox+ id={roleSelectId}+ options={APP_ROLES}+ value={APP_ROLES.find((r) => r.slug === role) ?? null}+ onValueChange={(next) => setRole(next.slug)}+ getOptionValue={(option) => option.slug}+ getOptionLabel={(option) => option.name}+ renderOption={(option) => (+ <div className="flex flex-col gap-1">+ <span>{option.name}</span>+ <span className="text-xs text-muted">{option.description}</span>+ </div>+ )}+ isClearable={false}+ />+ </Field>+ </fieldset>+ </DialogBody>++ <DialogFooter>+ <Button variant="ghost" isDisabled={submitting} onClick={requestDiscard}>+ Cancel+ </Button>+ <Button+ variant="project"+ isDisabled={selectedCount === 0 || submitting}+ isPending={submitting}+ type="submit"+ >+ Add Member{selectedCount > 1 ? "s" : ""}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Member Changes?"+ description="Your pending member selection will be lost."+ />+ </>);};diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsxindex 9a38ee3b65..af71227836 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx@@ -1,5 +1,5 @@-import { ReactNode, useCallback, useMemo, useState } from "react";-import { components, MenuListProps } from "react-select";+import { ReactNode, useId, useMemo, useState } from "react";+import { subject } from "@casl/ability";import { faPlus } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { useQuery } from "@tanstack/react-query";@@ -29,13 +29,16 @@ import {CardDescription,CardHeader,CardTitle,+ Combobox,ConfirmationAlertDialog,Dialog,+ DialogBody,DialogContent,DialogDescription,DialogFooter,DialogHeader,DialogTitle,+ DiscardChangesAlertDialog,DocumentationLinkBadge,DropdownMenu,DropdownMenuContent,@@ -45,7 +48,8 @@ import {EmptyDescription,EmptyHeader,EmptyTitle,- FilterableSelect,+ Field,+ FieldLabel,IconButton,Skeleton,Table,@@ -82,10 +86,12 @@ import {useDetachPkiApplicationProfile,useGetPkiApplicationPermissions} from "@app/hooks/api/pkiApplications";+import { useDiscardChangesGuard } from "@app/hooks/useDiscardChangesGuard";import { PolicyModal } from "@app/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicyModal";import { CertificateAlertsCard } from "@app/pages/cert-manager/components/CertificateAlerts/CertificateAlertsCard";import { CertificateAlertScopeKind } from "@app/pages/cert-manager/components/CertificateAlerts/types";import { CreateProfileModal } from "@app/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal";+import { useProfileCreation } from "@app/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/useProfileCreation";import { PkiDocsUrls } from "../../pki-docs-urls";import {@@ -325,6 +331,19 @@ export const ApplicationSettingsTab = ({ application, profiles }: Props) => {const [isAttachOpen, setIsAttachOpen] = useState(false);const [isCreateProfileOpen, setIsCreateProfileOpen] = useState(false);const [profilesToAttach, setProfilesToAttach] = useState<TProfileOption[]>([]);+ const profileInputId = useId();+ const closeAttach = () => {+ setIsAttachOpen(false);+ setProfilesToAttach([]);+ };+ const { requestDiscard, confirmDiscard, isDiscardDialogOpen, setIsDiscardDialogOpen } =+ useDiscardChangesGuard({ isDirty: profilesToAttach.length > 0, onDiscard: closeAttach });+ const profileCreation = useProfileCreation((createdProfile) =>+ setProfilesToAttach((previous) => [+ ...previous,+ { value: createdProfile.id, label: createdProfile.slug }+ ])+ );const [profileToDetach, setProfileToDetach] = useState<TPkiApplicationProfile | null>(null);const [profileToConfigure, setProfileToConfigure] = useState<TPkiApplicationProfile | null>(null);const [enrollmentMethodToOpen, setEnrollmentMethodToOpen] = useState<EnrollmentMethod>();@@ -335,10 +354,26 @@ export const ApplicationSettingsTab = ({ application, profiles }: Props) => {};const { permission } = useProjectPermission();- const canCreateProfile = permission.can(- ProjectPermissionCertificateProfileActions.Create,- ProjectPermissionSub.CertificateProfiles- );+ const canCreateAndAttachProfile =+ permission.can(+ ProjectPermissionCertificateProfileActions.Create,+ ProjectPermissionSub.CertificateProfiles+ ) &&+ permission.can(+ ProjectPermissionCertificateProfileActions.ManageApplicationAttachments,+ ProjectPermissionSub.CertificateProfiles+ );+ const validateCreatedProfileSlug = (slug: string) => {+ const profileSubject = subject(ProjectPermissionSub.CertificateProfiles, { slug });+ return canManageProfileAttachments &&+ permission.can(ProjectPermissionCertificateProfileActions.Create, profileSubject) &&+ permission.can(+ ProjectPermissionCertificateProfileActions.ManageApplicationAttachments,+ profileSubject+ )+ ? undefined+ : "You don't have permission to create and attach a profile with this name. Choose an allowed name.";+ };const { data: profileList } = useListCertificateProfiles({ limit: 100 });const attachMutation = useAttachPkiApplicationProfiles();@@ -396,37 +431,13 @@ export const ApplicationSettingsTab = ({ application, profiles }: Props) => {const totalProfileCount = profileList?.totalCount ?? 0;const hasAttachableProfiles = totalProfileCount > profiles.length;let attachDisabledReason: ReactNode | null = null;- if (!hasAttachableProfiles && !canCreateProfile) {+ if (!hasAttachableProfiles && !canCreateAndAttachProfile) {attachDisabledReason =totalProfileCount === 0- ? "No certificate profiles exist yet, and you do not have permission to create one."+ ? "No certificate profiles exist yet, and you do not have permission to create and attach one.": "All certificate profiles are already attached.";}- // Pinned above the scrolling option list, so creating a profile is not a selectable option- // masquerading as one.- const ProfileMenuList = useCallback(- (menuProps: MenuListProps<TProfileOption, true>) => (- <>- {canCreateProfile ? (- <Button- type="button"- variant="ghost"- size="sm"- isFullWidth- className="justify-start"- onClick={() => setIsCreateProfileOpen(true)}- >- <PlusIcon />- Add Certificate Profile- </Button>- ) : null}- <components.MenuList {...menuProps} />- </>- ),- [canCreateProfile]- );-const handleAttach = async () => {if (profilesToAttach.length === 0) return;try {@@ -696,42 +707,69 @@ export const ApplicationSettingsTab = ({ application, profiles }: Props) => {<Dialogopen={isAttachOpen}onOpenChange={(open) => {- setIsAttachOpen(open);- if (!open) setProfilesToAttach([]);+ if (open) setIsAttachOpen(true);+ else requestDiscard();}}>- <DialogContent className="max-w-md">+ <DialogContent isPending={attachMutation.isPending}><DialogHeader><DialogTitle>Attach Profiles</DialogTitle><DialogDescription>Select one or more profiles to attach to this application.</DialogDescription></DialogHeader>- <div className="py-2">- <FilterableSelect- isMulti- value={profilesToAttach}- onChange={(val) => setProfilesToAttach((val ?? []) as TProfileOption[])}- options={availableProfiles}- components={{ MenuList: ProfileMenuList }}- placeholder="Select profiles..."- />- </div>- <DialogFooter>- <Button variant="outline" onClick={() => setIsAttachOpen(false)}>- Cancel- </Button>- <Button- variant="project"- onClick={handleAttach}- isDisabled={profilesToAttach.length === 0 || attachMutation.isPending}- isPending={attachMutation.isPending}- >- Attach- </Button>- </DialogFooter>+ <form+ className="flex min-h-0 flex-1 flex-col gap-6"+ onSubmit={(event) => {+ event.preventDefault();+ if (profilesToAttach.length && !attachMutation.isPending) handleAttach();+ }}+ >+ <DialogBody>+ <fieldset disabled={attachMutation.isPending} className="min-w-0">+ <Field>+ <FieldLabel htmlFor={profileInputId}>Certificate Profiles</FieldLabel>+ <Combobox+ id={profileInputId}+ multiple+ value={profilesToAttach}+ onValueChange={setProfilesToAttach}+ getOptionValue={(option) => option.value}+ getOptionLabel={(option) => option.label}+ options={availableProfiles}+ creation={profileCreation}+ placeholder="Select profiles..."+ />+ </Field>+ </fieldset>+ </DialogBody>+ <DialogFooter>+ <Button+ variant="ghost"+ isDisabled={attachMutation.isPending}+ onClick={requestDiscard}+ >+ Cancel+ </Button>+ <Button+ variant="project"+ type="submit"+ isDisabled={profilesToAttach.length === 0 || attachMutation.isPending}+ isPending={attachMutation.isPending}+ >+ Attach+ </Button>+ </DialogFooter>+ </form></DialogContent></Dialog>+ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Profile Selection?"+ description="Your pending profile attachments will be lost."+ /><ConfirmationAlertDialogisOpen={Boolean(profileToDetach)}@@ -747,19 +785,20 @@ export const ApplicationSettingsTab = ({ application, profiles }: Props) => {<CreateProfileModalisOpen={isCreateProfileOpen}onClose={() => setIsCreateProfileOpen(false)}- onComplete={(createdProfile) => {- setIsCreateProfileOpen(false);- // Created from inside the attach dialog: add it to the pending selection so it is- // attached alongside whatever else was picked. Created straight from the card, there is- // no selection to submit, so attach it now.- if (isAttachOpen) {- setProfilesToAttach((prev) => [- ...prev,- { value: createdProfile.id, label: createdProfile.slug }- ]);- return;+ validateSlug={validateCreatedProfileSlug}+ onComplete={async (createdProfile) => {+ if (+ !canManageProfileAttachments ||+ !permission.can(+ ProjectPermissionCertificateProfileActions.ManageApplicationAttachments,+ subject(ProjectPermissionSub.CertificateProfiles, { slug: createdProfile.slug })+ )+ ) {+ throw new Error(+ "The profile was created, but you no longer have permission to attach it to this application."+ );}- attachMutation.mutate({+ await attachMutation.mutateAsync({applicationId: application.id,profileIds: [createdProfile.id]});diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsxindex b8620d4641..8c7d51c9d6 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsx@@ -1,6 +1,5 @@-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { Controller, useForm } from "react-hook-form";-import { SingleValue } from "react-select";import { faCheck, faCopy, faDownload } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import {@@ -12,7 +11,6 @@ import {RotateCwIcon} from "lucide-react";-import { AppConnectionOption } from "@app/components/app-connections";import {CertificateEnrollmentUpgradeIntent,useUpgradeGate@@ -20,7 +18,6 @@ import {import { createNotification } from "@app/components/notifications";import {AlertDialog,- AlertDialogAction,AlertDialogCancel,AlertDialogContent,AlertDialogDescription,@@ -30,11 +27,13 @@ import {AlertDialogTitle,Badge,Button,- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,+ Card,+ CardAction,+ CardContent,+ CardHeader,+ CardTitle,+ Combobox,+ DiscardChangesAlertDialog,DropdownMenu,DropdownMenuContent,DropdownMenuItem,@@ -48,7 +47,6 @@ import {FieldDescription,FieldError,FieldLabel,- FilterableSelect,Input,InputGroup,InputGroupAddon,@@ -60,6 +58,12 @@ import {SelectItem,SelectTrigger,SelectValue,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,Spinner,Tabs,TabsContent,@@ -79,7 +83,7 @@ import {} from "@app/context";import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";import { downloadFile } from "@app/helpers/download";-import { usePopUp, useToggle } from "@app/hooks";+import { useDiscardChangesGuard, useToggle } from "@app/hooks";import { useListAvailableAppConnections } from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";import { isScepRaCaSigningSupported } from "@app/hooks/api/ca/capabilities";@@ -98,14 +102,12 @@ import {useSetPkiApplicationScepEnrollment} from "@app/hooks/api/pkiApplications/mutations";import { ScepChallengeType, TPkiApplicationProfile } from "@app/hooks/api/pkiApplications/types";-import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";+import { useConnectionCreation } from "@app/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/useConnectionCreation";import { PkiDocsUrls } from "../../pki-docs-urls";const COPY_RESET_MS = 1000;-const CREATE_CONNECTION_ID = "_create";-type Props = {isOpen: boolean;onOpenChange: (open: boolean) => void;@@ -114,9 +116,6 @@ type Props = {initialMethod?: EnrollmentMethod;};-const errorText = (err: unknown, fallback: string) =>- err instanceof Error ? err.message : fallback;-const SectionCard = ({title,actions,@@ -128,15 +127,15 @@ const SectionCard = ({children: React.ReactNode;className?: string;}) => (- <section- className={`rounded-md border border-border bg-foreground/[0.02] ${className ?? ""}`.trim()}- >- <header className="flex items-center justify-between gap-3 border-b border-border px-4 py-2.5">- <h3 className="text-sm font-normal text-foreground">{title}</h3>- {actions ? <div className="flex items-center gap-2">{actions}</div> : null}- </header>- <div className="space-y-4 px-4 py-4">{children}</div>- </section>+ <Card className={className}>+ <CardHeader>+ <CardTitle role="heading" aria-level={3}>+ {title}+ </CardTitle>+ {actions ? <CardAction className="flex items-center gap-2">{actions}</CardAction> : null}+ </CardHeader>+ <CardContent className="space-y-4">{children}</CardContent>+ </Card>);const CopyableField = ({@@ -182,12 +181,24 @@ const DisableEnrollmentButton = ({isPending: boolean;}) => {const [isOpen, setIsOpen] = useState(false);+ const [isConfirming, setIsConfirming] = useState(false);+ const isActionPending = isPending || isConfirming;return (<>- <Button variant="outline" onClick={() => setIsOpen(true)} isPending={isPending}>+ <Button+ type="button"+ variant="outline"+ onClick={() => setIsOpen(true)}+ isDisabled={isActionPending}+ >Disable</Button>- <AlertDialog open={isOpen} onOpenChange={setIsOpen}>+ <AlertDialog+ open={isOpen}+ onOpenChange={(open) => {+ if (!isActionPending) setIsOpen(open);+ }}+ ><AlertDialogContent><AlertDialogHeader><AlertDialogMedia>@@ -200,10 +211,27 @@ const DisableEnrollmentButton = ({</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction variant="danger" isPending={isPending} onClick={onConfirmed}>- Disable enrollment- </AlertDialogAction>+ <AlertDialogCancel isDisabled={isActionPending}>Cancel</AlertDialogCancel>+ <Button+ type="button"+ variant="danger"+ isPending={isActionPending}+ isDisabled={isActionPending}+ onClick={async () => {+ if (isActionPending) return;+ setIsConfirming(true);+ try {+ await onConfirmed();+ setIsOpen(false);+ } catch {+ return;+ } finally {+ setIsConfirming(false);+ }+ }}+ >+ Disable Enrollment+ </Button></AlertDialogFooter></AlertDialogContent></AlertDialog>@@ -230,13 +258,15 @@ const ApiPanel = ({enabled,initial,onCancelPending,- onDirtyChange+ onDirtyChange,+ onPendingChange}: {applicationId: string;profileId: string;enabled: boolean;onCancelPending: () => void;- onDirtyChange: (isDirty: boolean) => void;+ onDirtyChange: (method: EnrollmentMethod, isDirty: boolean) => void;+ onPendingChange: (method: EnrollmentMethod, isPending: boolean) => void;initial: { autoRenew: boolean; renewBeforeDays: number | null } | null;}) => {const setMutation = useSetPkiApplicationApiEnrollment();@@ -246,7 +276,7 @@ const ApiPanel = ({handleSubmit,watch,reset,- formState: { isDirty }+ formState: { isDirty, isSubmitting }} = useForm<ApiForm>({defaultValues: {autoRenew: initial?.autoRenew ?? false,@@ -263,35 +293,37 @@ const ApiPanel = ({const autoRenew = watch("autoRenew");+ const isPending = setMutation.isPending || clearMutation.isPending || isSubmitting;useEffect(() => {- onDirtyChange(isDirty);+ onDirtyChange("api", isDirty);}, [isDirty, onDirtyChange]);+ useEffect(() => {+ onPendingChange("api", isPending);+ }, [isPending, onPendingChange]);+ useEffect(+ () => () => {+ onDirtyChange("api", false);+ onPendingChange("api", false);+ },+ [onDirtyChange, onPendingChange]+ );const onSave = handleSubmit(async (values) => {- try {- await setMutation.mutateAsync({- applicationId,- profileId,- autoRenew: values.autoRenew,- renewBeforeDays: values.autoRenew ? (values.renewBeforeDays ?? undefined) : undefined- });- reset(values);- createNotification({ type: "success", text: "API enrollment saved" });- } catch (err) {- createNotification({ type: "error", text: errorText(err, "Failed to save API enrollment") });- }+ if (setMutation.isPending || clearMutation.isPending) return;+ await setMutation.mutateAsync({+ applicationId,+ profileId,+ autoRenew: values.autoRenew,+ renewBeforeDays: values.autoRenew ? (values.renewBeforeDays ?? undefined) : undefined+ });+ reset(values);+ createNotification({ type: "success", text: "API enrollment saved" });});const onDisable = async () => {- try {- await clearMutation.mutateAsync({ applicationId, profileId });- createNotification({ type: "success", text: "API enrollment disabled" });- } catch (err) {- createNotification({- type: "error",- text: errorText(err, "Failed to disable API enrollment")- });- }+ await clearMutation.mutateAsync({ applicationId, profileId });++ createNotification({ type: "success", text: "API enrollment disabled" });};const apiEndpointUrl =@@ -300,98 +332,107 @@ const ApiPanel = ({: "/api/v1/cert-manager/certificates";return (- <div className="space-y-5">- <SectionCard title="Endpoint">- <CopyableField- label="API endpoint URL"- value={apiEndpointUrl}- helper={- <>- POST to this endpoint with <code className="font-mono">applicationId</code>,{" "}- <code className="font-mono">profileId</code>, and an{" "}- <code className="font-mono">attributes</code> object (commonName, ttl, etc.) in the- body to issue a certificate.{" "}- <a- href="https://infisical.com/docs/api-reference/endpoints/certificates/create-certificate"- target="_blank"- rel="noreferrer"- className="font-medium text-project"- >- View API reference- </a>- </>- }- />- </SectionCard>- <SectionCard title="Renewal">- <Controller- control={control}- name="autoRenew"- render={({ field }) => (- <Field orientation="horizontal">- <FieldContent>- <Label>Auto-renew</Label>- <FieldDescription>- Automatically renew certificates issued via this profile before they expire.- </FieldDescription>- </FieldContent>- <Toggle- variant="project"- id="api-auto-renew"- checked={field.value}- onCheckedChange={field.onChange}- />- </Field>- )}- />- {autoRenew && (+ <form className="contents" onSubmit={(event) => onSave(event).catch(() => undefined)}>+ <fieldset+ disabled={isPending}+ className="min-h-0 thin-scrollbar flex-1 space-y-5 overflow-y-auto p-4"+ >+ <SectionCard title="Endpoint">+ <CopyableField+ label="API endpoint URL"+ value={apiEndpointUrl}+ helper={+ <>+ POST to this endpoint with <code className="font-mono">applicationId</code>,{" "}+ <code className="font-mono">profileId</code>, and an{" "}+ <code className="font-mono">attributes</code> object (commonName, ttl, etc.) in the+ body to issue a certificate.{" "}+ <a+ href="https://infisical.com/docs/api-reference/endpoints/certificates/create-certificate"+ target="_blank"+ rel="noreferrer"+ className="font-medium text-project"+ >+ View API reference+ </a>+ </>+ }+ />+ </SectionCard>+ <SectionCard title="Renewal"><Controllercontrol={control}- name="renewBeforeDays"- rules={{- validate: (value) =>- value === null || (value >= 1 && value <= 365) || "Must be between 1 and 365"- }}- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel>Renew before (days)</FieldLabel>+ name="autoRenew"+ render={({ field }) => (+ <Field orientation="horizontal"><FieldContent>- <Input- type="number"- inputMode="numeric"- value={field.value ?? ""}- onChange={handleOptionalIntChange(field.onChange)}- placeholder="30"- isError={Boolean(error)}- />+ <Label>Auto-renew</Label>+ <FieldDescription>+ Automatically renew certificates issued via this profile before they expire.+ </FieldDescription></FieldContent>- {error ? (- <FieldError>{error.message ?? "Must be between 1 and 365"}</FieldError>- ) : null}- <FieldDescription>How many days before expiry to trigger renewal.</FieldDescription>+ <Toggle+ variant="project"+ id="api-auto-renew"+ checked={field.value}+ onCheckedChange={field.onChange}+ /></Field>)}/>- )}- </SectionCard>- <div className="flex justify-end gap-2 pt-2">- {!enabled && (- <Button variant="outline" onClick={onCancelPending}>- Cancel- </Button>- )}+ {autoRenew && (+ <Controller+ control={control}+ name="renewBeforeDays"+ rules={{+ validate: (value) =>+ value === null || (value >= 1 && value <= 365) || "Must be between 1 and 365"+ }}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Renew before (days)</FieldLabel>+ <FieldContent>+ <Input+ ref={field.ref}+ name={field.name}+ onBlur={field.onBlur}+ type="number"+ inputMode="numeric"+ value={field.value ?? ""}+ onChange={handleOptionalIntChange(field.onChange)}+ placeholder="30"+ isError={Boolean(error)}+ />+ </FieldContent>+ {error ? (+ <FieldError>{error.message ?? "Must be between 1 and 365"}</FieldError>+ ) : null}+ <FieldDescription>+ How many days before expiry to trigger renewal.+ </FieldDescription>+ </Field>+ )}+ />+ )}+ </SectionCard>+ </fieldset>+ <SheetFooter className="justify-end border-t">{enabled && (- <DisableEnrollmentButton- method="API"- onConfirmed={onDisable}- isPending={clearMutation.isPending}- />+ <DisableEnrollmentButton method="API" onConfirmed={onDisable} isPending={isPending} />)}- <Button variant="project" onClick={onSave} isPending={setMutation.isPending}>+ <Button type="button" variant="ghost" onClick={onCancelPending} isDisabled={isPending}>+ Cancel+ </Button>+ <Button+ type="submit"+ variant="project"+ isPending={setMutation.isPending || isSubmitting}+ isDisabled={isPending}+ >{enabled ? "Save" : "Enable"}</Button>- </div>- </div>+ </SheetFooter>+ </form>);};@@ -403,13 +444,15 @@ const EstPanel = ({enabled,initial,onCancelPending,- onDirtyChange+ onDirtyChange,+ onPendingChange}: {applicationId: string;profileId: string;enabled: boolean;onCancelPending: () => void;- onDirtyChange: (isDirty: boolean) => void;+ onDirtyChange: (method: EnrollmentMethod, isDirty: boolean) => void;+ onPendingChange: (method: EnrollmentMethod, isPending: boolean) => void;initial: { disableBootstrapCaValidation: boolean; estEndpointUrl: string } | null;}) => {const setMutation = useSetPkiApplicationEstEnrollment();@@ -418,7 +461,7 @@ const EstPanel = ({control,handleSubmit,reset,- formState: { isDirty }+ formState: { isDirty, isSubmitting }} = useForm<EstForm>({defaultValues: {passphrase: "",@@ -435,140 +478,151 @@ const EstPanel = ({});}, [initial?.disableBootstrapCaValidation, reset]);+ const isPending = setMutation.isPending || clearMutation.isPending || isSubmitting;useEffect(() => {- onDirtyChange(isDirty);+ onDirtyChange("est", isDirty);}, [isDirty, onDirtyChange]);+ useEffect(() => {+ onPendingChange("est", isPending);+ }, [isPending, onPendingChange]);+ useEffect(+ () => () => {+ onDirtyChange("est", false);+ onPendingChange("est", false);+ },+ [onDirtyChange, onPendingChange]+ );const onSave = handleSubmit(async (values) => {- try {- await setMutation.mutateAsync({- applicationId,- profileId,- passphrase: values.passphrase,- disableBootstrapCaValidation: values.disableBootstrapCaValidation,- caChain: values.caChain || undefined- });- reset({- passphrase: "",- disableBootstrapCaValidation: values.disableBootstrapCaValidation,- caChain: values.caChain- });- createNotification({ type: "success", text: "EST enrollment saved" });- } catch (err) {- createNotification({ type: "error", text: errorText(err, "Failed to save EST enrollment") });- }+ if (setMutation.isPending || clearMutation.isPending) return;+ await setMutation.mutateAsync({+ applicationId,+ profileId,+ passphrase: values.passphrase,+ disableBootstrapCaValidation: values.disableBootstrapCaValidation,+ caChain: values.caChain || undefined+ });+ reset({+ passphrase: "",+ disableBootstrapCaValidation: values.disableBootstrapCaValidation,+ caChain: values.caChain+ });+ createNotification({ type: "success", text: "EST enrollment saved" });});const onDisable = async () => {- try {- await clearMutation.mutateAsync({ applicationId, profileId });- createNotification({ type: "success", text: "EST enrollment disabled" });- } catch (err) {- createNotification({- type: "error",- text: errorText(err, "Failed to disable EST enrollment")- });- }+ await clearMutation.mutateAsync({ applicationId, profileId });++ createNotification({ type: "success", text: "EST enrollment disabled" });};return (- <div className="space-y-5">- {enabled && initial?.estEndpointUrl ? (- <SectionCard title="Endpoint">- <CopyableField- label="EST endpoint base URL"- value={initial.estEndpointUrl}- helper={- <>- Append <code className="font-mono">/simpleenroll</code>,{" "}- <code className="font-mono">/simplereenroll</code>, or{" "}- <code className="font-mono">/cacerts</code> depending on the operation.- </>- }+ <form className="contents" onSubmit={(event) => onSave(event).catch(() => undefined)}>+ <fieldset+ disabled={isPending}+ className="min-h-0 thin-scrollbar flex-1 space-y-5 overflow-y-auto p-4"+ >+ {enabled && initial?.estEndpointUrl ? (+ <SectionCard title="Endpoint">+ <CopyableField+ label="EST endpoint base URL"+ value={initial.estEndpointUrl}+ helper={+ <>+ Append <code className="font-mono">/simpleenroll</code>,{" "}+ <code className="font-mono">/simplereenroll</code>, or{" "}+ <code className="font-mono">/cacerts</code> depending on the operation.+ </>+ }+ />+ </SectionCard>+ ) : null}+ <SectionCard title="Authentication">+ <Controller+ control={control}+ name="passphrase"+ rules={{ required: !enabled, minLength: 8 }}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>{enabled ? "New passphrase" : "Passphrase"}</FieldLabel>+ <FieldContent>+ <Input+ type="password"+ {...field}+ placeholder="••••••••"+ isError={Boolean(error)}+ />+ </FieldContent>+ <FieldDescription>+ {enabled+ ? "Leave blank to keep the current passphrase."+ : "Minimum 8 characters. EST clients authenticate with this passphrase."}+ </FieldDescription>+ {error ? <FieldError>Minimum 8 characters</FieldError> : null}+ </Field>+ )}+ />+ <Controller+ control={control}+ name="caChain"+ render={({ field }) => (+ <Field>+ <FieldLabel>CA chain (optional)</FieldLabel>+ <FieldContent>+ <TextArea+ {...field}+ rows={4}+ placeholder={+ "-----BEGIN CERTIFICATE-----\nMIIDdzCCAl+gAwIBAgIUJrK4...\n-----END CERTIFICATE-----"+ }+ className="font-mono text-xs"+ />+ </FieldContent>+ <FieldDescription>PEM-encoded chain returned by the EST endpoint.</FieldDescription>+ </Field>+ )}/></SectionCard>- ) : null}- <SectionCard title="Authentication">- <Controller- control={control}- name="passphrase"- rules={{ required: !enabled, minLength: 8 }}- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel>{enabled ? "New passphrase" : "Passphrase"}</FieldLabel>- <FieldContent>- <Input type="password" {...field} placeholder="••••••••" isError={Boolean(error)} />- </FieldContent>- <FieldDescription>- {enabled- ? "Leave blank to keep the current passphrase."- : "Minimum 8 characters. EST clients authenticate with this passphrase."}- </FieldDescription>- {error ? <FieldError>Minimum 8 characters</FieldError> : null}- </Field>- )}- />- <Controller- control={control}- name="caChain"- render={({ field }) => (- <Field>- <FieldLabel>CA chain (optional)</FieldLabel>- <FieldContent>- <TextArea- {...field}- rows={4}- placeholder={- "-----BEGIN CERTIFICATE-----\nMIIDdzCCAl+gAwIBAgIUJrK4...\n-----END CERTIFICATE-----"- }- className="font-mono text-xs"+ <SectionCard title="Advanced options">+ <Controller+ control={control}+ name="disableBootstrapCaValidation"+ render={({ field }) => (+ <Field orientation="horizontal">+ <FieldContent>+ <Label>Disable bootstrap CA validation</Label>+ <FieldDescription>+ Allow EST clients to skip server-certificate validation during enrollment.+ </FieldDescription>+ </FieldContent>+ <Toggle+ variant="project"+ id="est-disable-bootstrap"+ checked={field.value}+ onCheckedChange={field.onChange}/>- </FieldContent>- <FieldDescription>PEM-encoded chain returned by the EST endpoint.</FieldDescription>- </Field>- )}- />- </SectionCard>- <SectionCard title="Advanced options">- <Controller- control={control}- name="disableBootstrapCaValidation"- render={({ field }) => (- <Field orientation="horizontal">- <FieldContent>- <Label>Disable bootstrap CA validation</Label>- <FieldDescription>- Allow EST clients to skip server-certificate validation during enrollment.- </FieldDescription>- </FieldContent>- <Toggle- variant="project"- id="est-disable-bootstrap"- checked={field.value}- onCheckedChange={field.onChange}- />- </Field>- )}- />- </SectionCard>- <div className="flex justify-end gap-2 pt-2">- {!enabled && (- <Button variant="outline" onClick={onCancelPending}>- Cancel- </Button>- )}- {enabled && (- <DisableEnrollmentButton- method="EST"- onConfirmed={onDisable}- isPending={clearMutation.isPending}+ </Field>+ )}/>+ </SectionCard>+ </fieldset>+ <SheetFooter className="justify-end border-t">+ {enabled && (+ <DisableEnrollmentButton method="EST" onConfirmed={onDisable} isPending={isPending} />)}- <Button variant="project" onClick={onSave} isPending={setMutation.isPending}>+ <Button type="button" variant="ghost" onClick={onCancelPending} isDisabled={isPending}>+ Cancel+ </Button>+ <Button+ type="submit"+ variant="project"+ isPending={setMutation.isPending || isSubmitting}+ isDisabled={isPending}+ >{enabled ? "Save" : "Enable"}</Button>- </div>- </div>+ </SheetFooter>+ </form>);};@@ -580,13 +634,15 @@ const AcmePanel = ({enabled,initial,onCancelPending,- onDirtyChange+ onDirtyChange,+ onPendingChange}: {applicationId: string;profileId: string;enabled: boolean;onCancelPending: () => void;- onDirtyChange: (isDirty: boolean) => void;+ onDirtyChange: (method: EnrollmentMethod, isDirty: boolean) => void;+ onPendingChange: (method: EnrollmentMethod, isPending: boolean) => void;initial: {skipDnsOwnershipVerification: boolean;skipEabBinding: boolean;@@ -606,7 +662,7 @@ const AcmePanel = ({watch,setValue,reset,- formState: { isDirty }+ formState: { isDirty, isSubmitting }} = useForm<AcmeForm>({defaultValues: {skipDnsOwnershipVerification: initial?.skipDnsOwnershipVerification ?? false,@@ -624,11 +680,34 @@ const AcmePanel = ({const skipDns = watch("skipDnsOwnershipVerification");const skipEab = watch("skipEabBinding");+ const isPending =+ setMutation.isPending ||+ clearMutation.isPending ||+ isSubmitting ||+ revealMutation.isPending ||+ rotateMutation.isPending;useEffect(() => {- onDirtyChange(isDirty);+ onDirtyChange("acme", isDirty);}, [isDirty, onDirtyChange]);+ useEffect(() => {+ onPendingChange("acme", isPending);+ }, [isPending, onPendingChange]);+ useEffect(+ () => () => {+ onDirtyChange("acme", false);+ onPendingChange("acme", false);+ },+ [onDirtyChange, onPendingChange]+ );const onSave = handleSubmit(async (values) => {+ if (+ setMutation.isPending ||+ clearMutation.isPending ||+ revealMutation.isPending ||+ rotateMutation.isPending+ )+ return;if (values.skipDnsOwnershipVerification && values.skipEabBinding) {createNotification({type: "error",@@ -636,26 +715,15 @@ const AcmePanel = ({});return;}- try {- await setMutation.mutateAsync({ applicationId, profileId, ...values });- reset(values);- createNotification({ type: "success", text: "ACME enrollment saved" });- } catch (err) {- createNotification({ type: "error", text: errorText(err, "Failed to save ACME enrollment") });- }+ await setMutation.mutateAsync({ applicationId, profileId, ...values });+ reset(values);+ createNotification({ type: "success", text: "ACME enrollment saved" });});const onDisable = async () => {- try {- await clearMutation.mutateAsync({ applicationId, profileId });- setCredentials(null);- createNotification({ type: "success", text: "ACME enrollment disabled" });- } catch (err) {- createNotification({- type: "error",- text: errorText(err, "Failed to disable ACME enrollment")- });- }+ await clearMutation.mutateAsync({ applicationId, profileId });+ setCredentials(null);+ createNotification({ type: "success", text: "ACME enrollment disabled" });};const onReveal = async () => {@@ -663,190 +731,186 @@ const AcmePanel = ({setCredentials(null);return;}- try {- const data = await revealMutation.mutateAsync({ applicationId, profileId });- setCredentials({ eabKid: data.eabKid, eabSecret: data.eabSecret });- } catch (err) {- createNotification({ type: "error", text: errorText(err, "Failed to reveal EAB secret") });- }+ const data = await revealMutation.mutateAsync({ applicationId, profileId });+ setCredentials({ eabKid: data.eabKid, eabSecret: data.eabSecret });};const onRotate = async () => {- try {- await rotateMutation.mutateAsync({ applicationId, profileId });- const data = await revealMutation.mutateAsync({ applicationId, profileId });- setCredentials({ eabKid: data.eabKid, eabSecret: data.eabSecret });- createNotification({ type: "success", text: "ACME EAB secret rotated" });- } catch (err) {- createNotification({ type: "error", text: errorText(err, "Failed to rotate EAB secret") });- }+ await rotateMutation.mutateAsync({ applicationId, profileId });+ const data = await revealMutation.mutateAsync({ applicationId, profileId });+ setCredentials({ eabKid: data.eabKid, eabSecret: data.eabSecret });+ createNotification({ type: "success", text: "ACME EAB secret rotated" });};return (- <div className="space-y-5">- {enabled && initial?.directoryUrl ? (- <SectionCard title="Endpoint">- <CopyableField- label="ACME directory URL"- value={initial.directoryUrl}- helper="Point your ACME client at this URL to register an account."- />- </SectionCard>- ) : null}- {enabled && (- <SectionCard- title="EAB credentials"- actions={- <>- <Button- variant="outline"- size="xs"- onClick={onReveal}- isPending={revealMutation.isPending}- >- {credentials ? <EyeOffIcon /> : <EyeIcon />}- {credentials ? "Hide" : "Reveal"}- </Button>- <Button- variant="outline"- size="xs"- onClick={onRotate}- isPending={rotateMutation.isPending}- >- <RotateCwIcon />- Rotate- </Button>- </>- }- >- {credentials ? (- <>- <CopyableField label="EAB KID" value={credentials.eabKid} />- <CopyableField- label="EAB Secret"- value={credentials.eabSecret}- helper="External Account Binding key + secret used by ACME clients to register against this profile."- />- </>- ) : (- <p className="text-xs text-accent">- EAB credentials are hidden by default. Reveal them to copy into your ACME client.- </p>- )}- </SectionCard>- )}- <SectionCard title="Advanced options">- <Controller- control={control}- name="skipDnsOwnershipVerification"- render={({ field }) => (- <Field orientation="horizontal">- <FieldContent>- <Label>Skip DNS ownership verification</Label>- <FieldDescription>- Skip DNS-01 / HTTP-01 challenge enforcement during enrollment.- </FieldDescription>- </FieldContent>- {skipEab ? (- <Tooltip>- <TooltipTrigger asChild>- {/* span wrapper lets the tooltip listen for hover on a disabled control */}- <span className="inline-flex">- <Toggle- variant="project"- id="acme-skip-dns"- checked={field.value}- onCheckedChange={(v) => {- field.onChange(v);- if (v) setValue("skipEabBinding", false);- }}- disabled- />- </span>- </TooltipTrigger>- <TooltipContent>- You can only enable one of these at a time. Disable “Skip EAB binding” first.- </TooltipContent>- </Tooltip>- ) : (- <Toggle- variant="project"- id="acme-skip-dns"- checked={field.value}- onCheckedChange={(v) => {- field.onChange(v);- if (v) setValue("skipEabBinding", false);- }}- />- )}- </Field>- )}- />- <Controller- control={control}- name="skipEabBinding"- render={({ field }) => (- <Field orientation="horizontal">- <FieldContent>- <Label>Skip EAB binding</Label>- <FieldDescription>- Allow ACME accounts to register without providing an EAB key.- </FieldDescription>- </FieldContent>- {skipDns ? (- <Tooltip>- <TooltipTrigger asChild>- <span className="inline-flex">- <Toggle- variant="project"- id="acme-skip-eab"- checked={field.value}- onCheckedChange={(v) => {- field.onChange(v);- if (v) setValue("skipDnsOwnershipVerification", false);- }}- disabled- />- </span>- </TooltipTrigger>- <TooltipContent>- You can only enable one of these at a time. Disable “Skip DNS ownership- verification” first.- </TooltipContent>- </Tooltip>- ) : (- <Toggle- variant="project"- id="acme-skip-eab"- checked={field.value}- onCheckedChange={(v) => {- field.onChange(v);- if (v) setValue("skipDnsOwnershipVerification", false);- }}+ <form className="contents" onSubmit={(event) => onSave(event).catch(() => undefined)}>+ <fieldset+ disabled={isPending}+ className="min-h-0 thin-scrollbar flex-1 space-y-5 overflow-y-auto p-4"+ >+ {enabled && initial?.directoryUrl ? (+ <SectionCard title="Endpoint">+ <CopyableField+ label="ACME directory URL"+ value={initial.directoryUrl}+ helper="Point your ACME client at this URL to register an account."+ />+ </SectionCard>+ ) : null}+ {enabled && (+ <SectionCard+ title="EAB credentials"+ actions={+ <>+ <Button+ variant="outline"+ size="xs"+ onClick={() => onReveal().catch(() => undefined)}+ isPending={revealMutation.isPending}+ >+ {credentials ? <EyeOffIcon /> : <EyeIcon />}+ {credentials ? "Hide" : "Reveal"}+ </Button>+ <Button+ variant="outline"+ size="xs"+ onClick={() => onRotate().catch(() => undefined)}+ isPending={rotateMutation.isPending}+ >+ <RotateCwIcon />+ Rotate+ </Button>+ </>+ }+ >+ {credentials ? (+ <>+ <CopyableField label="EAB KID" value={credentials.eabKid} />+ <CopyableField+ label="EAB Secret"+ value={credentials.eabSecret}+ helper="External Account Binding key + secret used by ACME clients to register against this profile."/>- )}- </Field>- )}- />- </SectionCard>- <div className="flex justify-end gap-2 pt-2">- {!enabled && (- <Button variant="outline" onClick={onCancelPending}>- Cancel- </Button>+ </>+ ) : (+ <p className="text-xs text-accent">+ EAB credentials are hidden by default. Reveal them to copy into your ACME client.+ </p>+ )}+ </SectionCard>)}- {enabled && (- <DisableEnrollmentButton- method="ACME"- onConfirmed={onDisable}- isPending={clearMutation.isPending}+ <SectionCard title="Advanced options">+ <Controller+ control={control}+ name="skipDnsOwnershipVerification"+ render={({ field }) => (+ <Field orientation="horizontal">+ <FieldContent>+ <Label>Skip DNS ownership verification</Label>+ <FieldDescription>+ Skip DNS-01 / HTTP-01 challenge enforcement during enrollment.+ </FieldDescription>+ </FieldContent>+ {skipEab ? (+ <Tooltip>+ <TooltipTrigger asChild>+ {/* span wrapper lets the tooltip listen for hover on a disabled control */}+ <span className="inline-flex">+ <Toggle+ variant="project"+ id="acme-skip-dns"+ checked={field.value}+ onCheckedChange={(v) => {+ field.onChange(v);+ if (v) setValue("skipEabBinding", false);+ }}+ disabled+ />+ </span>+ </TooltipTrigger>+ <TooltipContent>+ You can only enable one of these at a time. Disable “Skip EAB binding” first.+ </TooltipContent>+ </Tooltip>+ ) : (+ <Toggle+ variant="project"+ id="acme-skip-dns"+ checked={field.value}+ onCheckedChange={(v) => {+ field.onChange(v);+ if (v) setValue("skipEabBinding", false);+ }}+ />+ )}+ </Field>+ )}+ />+ <Controller+ control={control}+ name="skipEabBinding"+ render={({ field }) => (+ <Field orientation="horizontal">+ <FieldContent>+ <Label>Skip EAB binding</Label>+ <FieldDescription>+ Allow ACME accounts to register without providing an EAB key.+ </FieldDescription>+ </FieldContent>+ {skipDns ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="inline-flex">+ <Toggle+ variant="project"+ id="acme-skip-eab"+ checked={field.value}+ onCheckedChange={(v) => {+ field.onChange(v);+ if (v) setValue("skipDnsOwnershipVerification", false);+ }}+ disabled+ />+ </span>+ </TooltipTrigger>+ <TooltipContent>+ You can only enable one of these at a time. Disable “Skip DNS ownership+ verification” first.+ </TooltipContent>+ </Tooltip>+ ) : (+ <Toggle+ variant="project"+ id="acme-skip-eab"+ checked={field.value}+ onCheckedChange={(v) => {+ field.onChange(v);+ if (v) setValue("skipDnsOwnershipVerification", false);+ }}+ />+ )}+ </Field>+ )}/>+ </SectionCard>+ </fieldset>+ <SheetFooter className="justify-end border-t">+ {enabled && (+ <DisableEnrollmentButton method="ACME" onConfirmed={onDisable} isPending={isPending} />)}- <Button variant="project" onClick={onSave} isPending={setMutation.isPending}>+ <Button type="button" variant="ghost" onClick={onCancelPending} isDisabled={isPending}>+ Cancel+ </Button>+ <Button+ type="submit"+ variant="project"+ isPending={setMutation.isPending || isSubmitting}+ isDisabled={isPending}+ >{enabled ? "Save" : "Enable"}</Button>- </div>- </div>+ </SheetFooter>+ </form>);};@@ -858,7 +922,8 @@ const ScepPanel = ({caType,initial,onCancelPending,- onDirtyChange+ onDirtyChange,+ onPendingChange}: {applicationId: string;profileId: string;@@ -866,7 +931,8 @@ const ScepPanel = ({enabled: boolean;caType: CaType;onCancelPending: () => void;- onDirtyChange: (isDirty: boolean) => void;+ onDirtyChange: (method: EnrollmentMethod, isDirty: boolean) => void;+ onPendingChange: (method: EnrollmentMethod, isPending: boolean) => void;initial: {challengeType: ScepChallengeType;includeCaCertInResponse: boolean;@@ -890,7 +956,7 @@ const ScepPanel = ({watch,reset,setValue,- formState: { isDirty }+ formState: { isDirty, isSubmitting }} = useForm<{challengeType: ScepChallengeType;challengePassword?: string;@@ -941,11 +1007,13 @@ const ScepPanel = ({const raCaSigningSupported = isScepRaCaSigningSupported(caType);const { permission } = useProjectPermission();- const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp(["addConnection"] as const);const canCreateConnection = permission.can(ProjectPermissionAppConnectionActions.Create,ProjectPermissionSub.AppConnections);+ const connectionCreation = useConnectionCreation(AppConnection.MicrosoftIntune, (connection) =>+ setValue("validationConnectionId", connection.id, { shouldDirty: true, shouldValidate: true })+ );useEffect(() => {if (isIntune && !isScepConfigured && raCaSigningSupported) setValue("signRaWithCa", true);@@ -956,43 +1024,44 @@ const ScepPanel = ({enabled: isIntune});+ const isPending = setMutation.isPending || clearMutation.isPending || isSubmitting;useEffect(() => {- onDirtyChange(isDirty);+ onDirtyChange("scep", isDirty);}, [isDirty, onDirtyChange]);+ useEffect(() => {+ onPendingChange("scep", isPending);+ }, [isPending, onPendingChange]);+ useEffect(+ () => () => {+ onDirtyChange("scep", false);+ onPendingChange("scep", false);+ },+ [onDirtyChange, onPendingChange]+ );const onSave = handleSubmit(async (values) => {- try {- const signRaWithCa = raCaSigningSupported && values.signRaWithCa;- const payload = isIntune- ? {- applicationId,- profileId,- challengeType: values.challengeType,- includeCaCertInResponse: values.includeCaCertInResponse,- // Cert-based renewal would bypass Intune's per-request validation, so it is always off.- allowCertBasedRenewal: false,- signRaWithCa,- validationConnectionId: values.validationConnectionId- }- : { applicationId, profileId, ...values, signRaWithCa, validationConnectionId: undefined };- await setMutation.mutateAsync(payload);- reset({ ...values, challengePassword: "" });- createNotification({ type: "success", text: "SCEP enrollment saved" });- } catch (err) {- createNotification({ type: "error", text: errorText(err, "Failed to save SCEP enrollment") });- }+ if (setMutation.isPending || clearMutation.isPending) return;+ const signRaWithCa = raCaSigningSupported && values.signRaWithCa;+ const payload = isIntune+ ? {+ applicationId,+ profileId,+ challengeType: values.challengeType,+ includeCaCertInResponse: values.includeCaCertInResponse,+ // Cert-based renewal would bypass Intune's per-request validation, so it is always off.+ allowCertBasedRenewal: false,+ signRaWithCa,+ validationConnectionId: values.validationConnectionId+ }+ : { applicationId, profileId, ...values, signRaWithCa, validationConnectionId: undefined };+ await setMutation.mutateAsync(payload);+ reset({ ...values, challengePassword: "" });+ createNotification({ type: "success", text: "SCEP enrollment saved" });});const onDisable = async () => {- try {- await clearMutation.mutateAsync({ applicationId, profileId });- createNotification({ type: "success", text: "SCEP enrollment disabled" });- } catch (err) {- createNotification({- type: "error",- text: errorText(err, "Failed to disable SCEP enrollment")- });- }+ await clearMutation.mutateAsync({ applicationId, profileId });+ createNotification({ type: "success", text: "SCEP enrollment disabled" });};const raCertExpiresAtLabel = initial?.raCertExpiresAt@@ -1004,338 +1073,338 @@ const ScepPanel = ({: null;return (- <div className="space-y-5">- {enabled && initial ? (- <SectionCard title="Endpoint">- <CopyableField- label="SCEP endpoint URL"- value={initial.scepEndpointUrl}- helper="Configure your MDM or SCEP client to point at this URL. For Windows devices, remove /pkiclient.exe from the end."- />- {initial.challengeType === ScepChallengeType.DYNAMIC && initial.challengeEndpointUrl ? (+ <form className="contents" onSubmit={(event) => onSave(event).catch(() => undefined)}>+ <fieldset+ disabled={isPending}+ className="min-h-0 thin-scrollbar flex-1 space-y-5 overflow-y-auto p-4"+ >+ {enabled && initial ? (+ <SectionCard title="Endpoint"><CopyableField- label="Challenge endpoint URL"- value={initial.challengeEndpointUrl}- helper="Authenticated POST endpoint to mint a one-time challenge (e.g. the JAMF SCEPChallenge webhook)."+ label="SCEP endpoint URL"+ value={initial.scepEndpointUrl}+ helper="Configure your MDM or SCEP client to point at this URL. For Windows devices, remove /pkiclient.exe from the end."/>- ) : null}- </SectionCard>- ) : null}- {enabled && initial?.raCertificatePem ? (- <SectionCard- title="RA certificate"- actions={- <Button- variant="outline"- size="xs"- onClick={() =>- downloadFile(- initial.raCertificatePem,- `${profileSlug}-ra-cert.pem`,- "application/x-pem-file"- )- }- >- <FontAwesomeIcon icon={faDownload} />- Download PEM- </Button>- }- >- <div className="flex items-center gap-3">- <div className="flex size-9 shrink-0 items-center justify-center rounded-md border border-border bg-foreground/[0.04] text-accent">- <FileTextIcon />- </div>- <div className="flex flex-col">- <span className="font-mono text-sm text-foreground">{profileSlug}-ra-cert.pem</span>- <span className="text-xs text-accent">- Expires {raCertExpiresAtLabel ?? "Unknown"}- </span>+ {initial.challengeType === ScepChallengeType.DYNAMIC && initial.challengeEndpointUrl ? (+ <CopyableField+ label="Challenge endpoint URL"+ value={initial.challengeEndpointUrl}+ helper="Authenticated POST endpoint to mint a one-time challenge (e.g. the JAMF SCEPChallenge webhook)."+ />+ ) : null}+ </SectionCard>+ ) : null}+ {enabled && initial?.raCertificatePem ? (+ <SectionCard+ title="RA certificate"+ actions={+ <Button+ variant="outline"+ size="xs"+ onClick={() =>+ downloadFile(+ initial.raCertificatePem,+ `${profileSlug}-ra-cert.pem`,+ "application/x-pem-file"+ )+ }+ >+ <FontAwesomeIcon icon={faDownload} />+ Download PEM+ </Button>+ }+ >+ <div className="flex items-center gap-3">+ <div className="flex size-9 shrink-0 items-center justify-center rounded-md border border-border bg-foreground/[0.04] text-accent">+ <FileTextIcon />+ </div>+ <div className="flex flex-col">+ <span className="font-mono text-sm text-foreground">{profileSlug}-ra-cert.pem</span>+ <span className="text-xs text-accent">+ Expires {raCertExpiresAtLabel ?? "Unknown"}+ </span>+ </div></div>- </div>- </SectionCard>- ) : null}- <SectionCard title="Challenge">- <Controller- control={control}- name="challengeType"- render={({ field }) => (- <Field>- <FieldLabel>Challenge type</FieldLabel>- <FieldContent>- <Select value={field.value} onValueChange={field.onChange}>- <SelectTrigger className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value={ScepChallengeType.STATIC}>Static password</SelectItem>- <SelectItem value={ScepChallengeType.DYNAMIC}>Dynamic (per-client)</SelectItem>- <SelectItem value={ScepChallengeType.MICROSOFT_INTUNE}>- Microsoft Intune- </SelectItem>- </SelectContent>- </Select>- </FieldContent>- <FieldDescription>- {(() => {- if (field.value === ScepChallengeType.STATIC)- return "All clients present the same shared challenge password.";- if (field.value === ScepChallengeType.DYNAMIC)- return "Each client requests a fresh, one-time challenge before enrolling.";- return "Requests are validated with Microsoft Intune, which seals its own challenge into each device request.";- })()}- </FieldDescription>- </Field>- )}- />- {isIntune && (- <Controller- control={control}- name="validationConnectionId"- rules={{ required: true }}- render={({ field: { value, onChange }, fieldState: { error } }) => {- const selected = intuneConnections?.find((c) => c.id === value) ?? null;- return (- <Field>- <FieldLabel>Microsoft Intune connection</FieldLabel>- <FieldContent>- <FilterableSelect- value={selected}- isError={Boolean(error)}- isLoading={isIntuneConnectionsLoading}- onChange={(newValue) => {- if (- (newValue as SingleValue<{ id: string }>)?.id === CREATE_CONNECTION_ID- ) {- handlePopUpOpen("addConnection");- onChange(undefined);- return;- }- onChange((newValue as { id: string } | null)?.id ?? undefined);- }}- options={[- ...(canCreateConnection- ? [{ id: CREATE_CONNECTION_ID, name: "Create Connection" }]- : []),- ...(intuneConnections ?? [])- ]}- placeholder="Select connection..."- getOptionLabel={(option) => option.name}- getOptionValue={(option) => option.id}- components={{ Option: AppConnectionOption }}- />- </FieldContent>- <FieldDescription>- Selecting the connection is all that is required. The transaction and- certificate request arrive in the device request, and the expected subject and- SAN are validated by Intune. See the{" "}- <a- href={PkiDocsUrls.appConnections.microsoftIntune}- target="_blank"- rel="noopener noreferrer"- className="text-project hover:text-project"- >- setup guide- </a>{" "}- for what to configure on the Intune side.- </FieldDescription>- {!isIntuneConnectionsLoading &&- !intuneConnections?.length &&- !canCreateConnection ? (- <FieldDescription className="text-warning">- You do not have access to any Microsoft Intune Connections. Contact an admin- to create one.- </FieldDescription>- ) : null}- {error ? (- <FieldError>A Microsoft Intune connection is required.</FieldError>- ) : null}- </Field>- );- }}- />- )}- {challengeType === ScepChallengeType.STATIC && (+ </SectionCard>+ ) : null}+ <SectionCard title="Challenge"><Controllercontrol={control}- name="challengePassword"- rules={{ required: !enabled }}- render={({ field, fieldState: { error } }) => (+ name="challengeType"+ render={({ field }) => (<Field>- <FieldLabel>{enabled ? "New challenge password" : "Challenge password"}</FieldLabel>+ <FieldLabel>Challenge type</FieldLabel><FieldContent>- <Input- type="password"- {...field}- placeholder="••••••••"- isError={Boolean(error)}- />+ <Select value={field.value} onValueChange={field.onChange}>+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={ScepChallengeType.STATIC}>Static password</SelectItem>+ <SelectItem value={ScepChallengeType.DYNAMIC}>+ Dynamic (per-client)+ </SelectItem>+ <SelectItem value={ScepChallengeType.MICROSOFT_INTUNE}>+ Microsoft Intune+ </SelectItem>+ </SelectContent>+ </Select></FieldContent><FieldDescription>- {enabled- ? "Leave blank to keep the current challenge password."- : "Shared password presented by every SCEP client during enrollment."}+ {(() => {+ if (field.value === ScepChallengeType.STATIC)+ return "All clients present the same shared challenge password.";+ if (field.value === ScepChallengeType.DYNAMIC)+ return "Each client requests a fresh, one-time challenge before enrolling.";+ return "Requests are validated with Microsoft Intune, which seals its own challenge into each device request.";+ })()}</FieldDescription>- {error ? <FieldError>Required</FieldError> : null}</Field>)}/>- )}- {challengeType === ScepChallengeType.DYNAMIC && (- <div className="grid grid-cols-2 gap-4">+ {isIntune && (<Controllercontrol={control}- name="dynamicChallengeExpiryMinutes"- render={({ field }) => (- <Field>- <FieldLabel>Challenge expiry (minutes)</FieldLabel>- <FieldContent>- <Input- type="number"- inputMode="numeric"- value={field.value ?? ""}- onChange={handleOptionalIntChange(field.onChange)}- />- </FieldContent>- </Field>- )}+ name="validationConnectionId"+ rules={{ required: true }}+ render={({+ field: { value, onChange, onBlur, name, ref },+ fieldState: { error }+ }) => {+ const selected = intuneConnections?.find((c) => c.id === value) ?? null;+ return (+ <Field>+ <FieldLabel htmlFor="scep-intune-connection">+ Microsoft Intune connection+ </FieldLabel>+ <FieldContent>+ <Combobox+ ref={ref}+ id="scep-intune-connection"+ name={name}+ onBlur={onBlur}+ isDisabled={isPending}+ value={selected}+ isError={Boolean(error)}+ isLoading={isIntuneConnectionsLoading}+ onValueChange={(newValue) => {+ onChange(newValue?.id ?? undefined);+ }}+ options={intuneConnections ?? []}+ placeholder="Select connection..."+ getOptionLabel={(option) => option.name}+ getOptionValue={(option) => option.id}+ creation={connectionCreation}+ />+ </FieldContent>+ <FieldDescription>+ Selecting the connection is all that is required. The transaction and+ certificate request arrive in the device request, and the expected subject and+ SAN are validated by Intune. See the{" "}+ <a+ href={PkiDocsUrls.appConnections.microsoftIntune}+ target="_blank"+ rel="noopener noreferrer"+ className="text-project hover:text-project"+ >+ setup guide+ </a>{" "}+ for what to configure on the Intune side.+ </FieldDescription>+ {!isIntuneConnectionsLoading &&+ !intuneConnections?.length &&+ !canCreateConnection ? (+ <FieldDescription className="text-warning">+ You do not have access to any Microsoft Intune Connections. Contact an admin+ to create one.+ </FieldDescription>+ ) : null}+ {error ? (+ <FieldError>A Microsoft Intune connection is required.</FieldError>+ ) : null}+ </Field>+ );+ }}/>+ )}+ {challengeType === ScepChallengeType.STATIC && (<Controllercontrol={control}- name="dynamicChallengeMaxPending"- render={({ field }) => (+ name="challengePassword"+ rules={{ required: !enabled }}+ render={({ field, fieldState: { error } }) => (<Field>- <FieldLabel>Max pending challenges</FieldLabel>+ <FieldLabel>+ {enabled ? "New challenge password" : "Challenge password"}+ </FieldLabel><FieldContent><Input- type="number"- inputMode="numeric"- value={field.value ?? ""}- onChange={handleOptionalIntChange(field.onChange)}+ type="password"+ {...field}+ placeholder="••••••••"+ isError={Boolean(error)}/></FieldContent>+ <FieldDescription>+ {enabled+ ? "Leave blank to keep the current challenge password."+ : "Shared password presented by every SCEP client during enrollment."}+ </FieldDescription>+ {error ? <FieldError>Required</FieldError> : null}</Field>)}/>- </div>- )}- </SectionCard>- <SectionCard title="Advanced options">- <Controller- control={control}- name="signRaWithCa"- render={({ field }) => (- <div className="flex items-start justify-between gap-4">- <div>- <FieldLabel>Sign RA certificate with the CA</FieldLabel>- <p className="text-xs text-accent">- Issue the SCEP RA certificate from this profile's CA so clients can build a- chain to a CA they already trust. Required by strict clients such as Apple and- Microsoft Intune, which reject a self-signed RA. Only available for internal- certificate authorities.- </p>- </div>- {raCaSigningSupported && !isScepConfigured ? (- <Toggle- variant="project"- id="scep-sign-ra-with-ca"- checked={field.value}- onCheckedChange={field.onChange}- />- ) : (- <Tooltip>- <TooltipTrigger asChild>- <div>- <Toggle- variant="project"- id="scep-sign-ra-with-ca"- checked={raCaSigningSupported && field.value}- disabled- />- </div>- </TooltipTrigger>- <TooltipContent>- {raCaSigningSupported- ? "Cannot be changed once SCEP enrollment is set up. Disable SCEP enrollment and set it up again to change it."- : `Not supported for ${caType} certificate authorities.`}- </TooltipContent>- </Tooltip>- )}- </div>)}- />- <Controller- control={control}- name="includeCaCertInResponse"- render={({ field }) => (- <Field orientation="horizontal">- <FieldContent>- <Label>Include CA cert in response</Label>- <FieldDescription>- Return the issuing CA certificate inline alongside the issued cert.- </FieldDescription>- </FieldContent>- <Toggle- variant="project"- id="scep-include-ca"- checked={field.value}- onCheckedChange={field.onChange}+ {challengeType === ScepChallengeType.DYNAMIC && (+ <div className="grid grid-cols-2 gap-4">+ <Controller+ control={control}+ name="dynamicChallengeExpiryMinutes"+ render={({ field }) => (+ <Field>+ <FieldLabel>Challenge expiry (minutes)</FieldLabel>+ <FieldContent>+ <Input+ ref={field.ref}+ name={field.name}+ onBlur={field.onBlur}+ type="number"+ inputMode="numeric"+ value={field.value ?? ""}+ onChange={handleOptionalIntChange(field.onChange)}+ />+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="dynamicChallengeMaxPending"+ render={({ field }) => (+ <Field>+ <FieldLabel>Max pending challenges</FieldLabel>+ <FieldContent>+ <Input+ ref={field.ref}+ name={field.name}+ onBlur={field.onBlur}+ type="number"+ inputMode="numeric"+ value={field.value ?? ""}+ onChange={handleOptionalIntChange(field.onChange)}+ />+ </FieldContent>+ </Field>+ )}/>- </Field>+ </div>)}- />- {!isIntune && (+ </SectionCard>+ <SectionCard title="Advanced options">+ <Controller+ control={control}+ name="signRaWithCa"+ render={({ field }) => (+ <div className="flex items-start justify-between gap-4">+ <div>+ <FieldLabel>Sign RA certificate with the CA</FieldLabel>+ <p className="text-xs text-accent">+ Issue the SCEP RA certificate from this profile's CA so clients can build a+ chain to a CA they already trust. Required by strict clients such as Apple and+ Microsoft Intune, which reject a self-signed RA. Only available for internal+ certificate authorities.+ </p>+ </div>+ {raCaSigningSupported && !isScepConfigured ? (+ <Toggle+ variant="project"+ id="scep-sign-ra-with-ca"+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ ) : (+ <Tooltip>+ <TooltipTrigger asChild>+ <div>+ <Toggle+ variant="project"+ id="scep-sign-ra-with-ca"+ checked={raCaSigningSupported && field.value}+ disabled+ />+ </div>+ </TooltipTrigger>+ <TooltipContent>+ {raCaSigningSupported+ ? "Cannot be changed once SCEP enrollment is set up. Disable SCEP enrollment and set it up again to change it."+ : `Not supported for ${caType} certificate authorities.`}+ </TooltipContent>+ </Tooltip>+ )}+ </div>+ )}+ /><Controllercontrol={control}- name="allowCertBasedRenewal"+ name="includeCaCertInResponse"render={({ field }) => (<Field orientation="horizontal"><FieldContent>- <Label>Allow cert-based renewal</Label>+ <Label>Include CA cert in response</Label><FieldDescription>- Let clients renew using their existing certificate as authentication.+ Return the issuing CA certificate inline alongside the issued cert.</FieldDescription></FieldContent><Togglevariant="project"- id="scep-cert-renewal"+ id="scep-include-ca"checked={field.value}onCheckedChange={field.onChange}/></Field>)}/>- )}- </SectionCard>- <div className="flex justify-end gap-2 pt-2">- {!enabled && (- <Button variant="outline" onClick={onCancelPending}>- Cancel- </Button>- )}+ {!isIntune && (+ <Controller+ control={control}+ name="allowCertBasedRenewal"+ render={({ field }) => (+ <Field orientation="horizontal">+ <FieldContent>+ <Label>Allow cert-based renewal</Label>+ <FieldDescription>+ Let clients renew using their existing certificate as authentication.+ </FieldDescription>+ </FieldContent>+ <Toggle+ variant="project"+ id="scep-cert-renewal"+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </Field>+ )}+ />+ )}+ </SectionCard>+ </fieldset>+ <SheetFooter className="justify-end border-t">{enabled && (- <DisableEnrollmentButton- method="SCEP"- onConfirmed={onDisable}- isPending={clearMutation.isPending}- />+ <DisableEnrollmentButton method="SCEP" onConfirmed={onDisable} isPending={isPending} />)}- <Button variant="project" onClick={onSave} isPending={setMutation.isPending}>+ <Button type="button" variant="ghost" onClick={onCancelPending} isDisabled={isPending}>+ Cancel+ </Button>+ <Button+ type="submit"+ variant="project"+ isPending={setMutation.isPending || isSubmitting}+ isDisabled={isPending}+ >{enabled ? "Save" : "Enable"}</Button>- </div>- <AddAppConnectionModal- isOpen={popUp.addConnection.isOpen}- onOpenChange={(isAddConnectionOpen) =>- handlePopUpToggle("addConnection", isAddConnectionOpen)- }- projectType={currentProject.type}- projectId={currentProject.id}- app={AppConnection.MicrosoftIntune}- onComplete={(connection) => {- if (connection) setValue("validationConnectionId", connection.id);- }}- />- </div>+ </SheetFooter>+ </form>);};@@ -1403,8 +1472,12 @@ export const ConfigureEnrollmentModal = ({const [pendingMethods, setPendingMethods] = useState<EnrollmentMethod[]>([]);const [activeTab, setActiveTab] = useState<EnrollmentMethod | "">("");- const [isDiscardOpen, setIsDiscardOpen] = useState(false);const [dirtyMethods, setDirtyMethods] = useState<Partial<Record<EnrollmentMethod, boolean>>>({});+ const [pendingByMethod, setPendingByMethod] = useState<+ Partial<Record<EnrollmentMethod, boolean>>+ >({});+ const discardMethod = useRef<EnrollmentMethod | null>(null);+ const isPending = Object.values(pendingByMethod).some(Boolean);const { subscription } = useSubscription();const { openUpgradeGate, upgradeGate } = useUpgradeGate();@@ -1426,8 +1499,8 @@ export const ConfigureEnrollmentModal = ({if (!isOpen) {setPendingMethods([]);setActiveTab("");- setIsDiscardOpen(false);setDirtyMethods({});+ setPendingByMethod({});}}, [isOpen, profileId]);@@ -1453,6 +1526,7 @@ export const ConfigureEnrollmentModal = ({};const handleAddMethod = (method: EnrollmentMethod) => {+ if (isPending) return;if (!lockedMethods[method]) {handleAdd(method);return;@@ -1464,9 +1538,6 @@ export const ConfigureEnrollmentModal = ({});};- const handleCancelPending = (method: EnrollmentMethod) =>- setPendingMethods((prev) => prev.filter((m) => m !== method));-const handleDirtyChange = useCallback((method: EnrollmentMethod, isDirty: boolean) =>setDirtyMethods((prev) =>@@ -1476,31 +1547,52 @@ export const ConfigureEnrollmentModal = ({);const hasUnsavedWork = pendingMethods.length > 0 || Object.values(dirtyMethods).some(Boolean);+ const handlePendingChange = useCallback(+ (method: EnrollmentMethod, pending: boolean) =>+ setPendingByMethod((prev) =>+ Boolean(prev[method]) === pending ? prev : { ...prev, [method]: pending }+ ),+ []+ );+ const { requestDiscard, isDiscardDialogOpen, setIsDiscardDialogOpen, confirmDiscard } =+ useDiscardChangesGuard({+ isDirty: hasUnsavedWork,+ onDiscard: () => {+ const method = discardMethod.current;+ if (method) {+ setPendingMethods((prev) => prev.filter((m) => m !== method));+ setDirtyMethods((prev) => ({ ...prev, [method]: false }));+ return;+ }+ onOpenChange(false);+ }+ });const isUnsaved = (method: EnrollmentMethod) =>pendingMethods.includes(method) || Boolean(dirtyMethods[method]);- const handleOpenChange = (open: boolean) => {- if (!open && hasUnsavedWork) {- setIsDiscardOpen(true);- return;- }- onOpenChange(open);+ const handleDismiss = () => {+ if (isPending) return;+ discardMethod.current = null;+ requestDiscard();};-- const handleDiscard = () => {- setPendingMethods([]);- setDirtyMethods({});- setIsDiscardOpen(false);- onOpenChange(false);+ const handleCancelPending = (method: EnrollmentMethod) => {+ if (isPending) return;+ discardMethod.current = method;+ requestDiscard();};return (- <Dialog open={isOpen} onOpenChange={handleOpenChange}>- <DialogContent className="max-h-[90vh] thin-scrollbar max-w-3xl overflow-y-auto">- <DialogHeader>- <DialogTitle>Configure enrollment methods for {profile?.profileSlug}</DialogTitle>- <DialogDescription>+ <Sheet+ open={isOpen}+ onOpenChange={(open) => {+ if (!open) handleDismiss();+ }}+ >+ <SheetContent size="form" isPending={isPending}>+ <SheetHeader>+ <SheetTitle>Configure Enrollment Methods for {profile?.profileSlug}</SheetTitle>+ <SheetDescription>Enable an enrollment method to allow clients to request certificates using this profile.{" "}<ahref={PkiDocsUrls.applications.enrollment.overview}@@ -1510,21 +1602,27 @@ export const ConfigureEnrollmentModal = ({>Learn more</a>- </DialogDescription>- </DialogHeader>+ </SheetDescription>+ </SheetHeader>{!profile || isLoading ? (- <div className="flex items-center justify-center py-8">+ <div className="flex flex-1 items-center justify-center p-4"><Spinner size="sm" /></div>) : (- <>- <div className="flex items-center justify-between gap-2 border-b border-border">- {visibleMethods.length > 0 ? (- <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as EnrollmentMethod)}>+ <Tabs+ value={activeTab}+ onValueChange={(v) => {+ if (!isPending) setActiveTab(v as EnrollmentMethod);+ }}+ className="min-h-0 flex-1"+ >+ <div className="flex items-center justify-between gap-2 border-b border-border px-4 pt-4">+ <div className="min-w-0 flex-1">+ {visibleMethods.length > 0 ? (<TabsList variant="project" className="border-b-0">{visibleMethods.map((m) => (- <TabsTrigger key={m} value={m}>+ <TabsTrigger key={m} value={m} disabled={isPending}>{METHOD_LABELS[m]}{isUnsaved(m) && (<span className="ml-1.5 text-xs text-muted">(unsaved)</span>@@ -1532,14 +1630,14 @@ export const ConfigureEnrollmentModal = ({</TabsTrigger>))}</TabsList>- </Tabs>- ) : (- <div />- )}+ ) : (+ <div />+ )}+ </div>{addableMethods.length > 0 ? (<DropdownMenu><DropdownMenuTrigger asChild>- <Button variant="outline" size="sm" className="mb-2">+ <Button variant="outline" size="sm" className="mb-2" isDisabled={isPending}><Plus className="size-4" />Add enrollment method</Button>@@ -1548,7 +1646,11 @@ export const ConfigureEnrollmentModal = ({{addableMethods.map((m) => {const isLocked = lockedMethods[m] ?? false;return (- <DropdownMenuItem key={m} onClick={() => handleAddMethod(m)}>+ <DropdownMenuItem+ key={m}+ onClick={() => handleAddMethod(m)}+ isDisabled={isPending}+ ><div className="flex flex-col"><span className="flex items-center gap-2 font-medium">{METHOD_LABELS[m]}@@ -1567,100 +1669,124 @@ export const ConfigureEnrollmentModal = ({</div>{visibleMethods.length === 0 ? (- <Empty className="border">- <EmptyHeader>- <EmptyTitle>No enrollment methods configured</EmptyTitle>- <EmptyDescription>- <span className="font-medium">Add enrollment method</span> above to let clients- request certificates from this profile.- </EmptyDescription>- </EmptyHeader>- </Empty>+ <div className="min-h-0 thin-scrollbar flex-1 overflow-y-auto p-4">+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>No enrollment methods configured</EmptyTitle>+ <EmptyDescription>+ <span className="font-medium">Add enrollment method</span> above to let+ clients request certificates from this profile.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ </div>) : (<>{activeTab && (- <p className="text-sm text-accent">+ <p className="px-4 pt-4 text-sm text-accent"><MethodDescription method={activeTab as EnrollmentMethod} /></p>)}- <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as EnrollmentMethod)}>- {visibleMethods.includes("api") ? (- <TabsContent value="api" className="data-[state=inactive]:hidden" forceMount>- <ApiPanel- applicationId={applicationId}- profileId={profileId}- enabled={Boolean(data?.api)}- initial={data?.api ?? null}- onCancelPending={() => handleCancelPending("api")}- onDirtyChange={(d) => handleDirtyChange("api", d)}- />- </TabsContent>- ) : null}- {visibleMethods.includes("est") ? (- <TabsContent value="est" className="data-[state=inactive]:hidden" forceMount>- <EstPanel- applicationId={applicationId}- profileId={profileId}- enabled={Boolean(data?.estConfigured)}- initial={data?.est ?? null}- onCancelPending={() => handleCancelPending("est")}- onDirtyChange={(d) => handleDirtyChange("est", d)}- />- </TabsContent>- ) : null}- {visibleMethods.includes("acme") ? (- <TabsContent value="acme" className="data-[state=inactive]:hidden" forceMount>- <AcmePanel- applicationId={applicationId}- profileId={profileId}- enabled={Boolean(data?.acmeConfigured)}- initial={data?.acme ?? null}- onCancelPending={() => handleCancelPending("acme")}- onDirtyChange={(d) => handleDirtyChange("acme", d)}- />- </TabsContent>- ) : null}- {visibleMethods.includes("scep") ? (- <TabsContent value="scep" className="data-[state=inactive]:hidden" forceMount>- <ScepPanel- applicationId={applicationId}- profileId={profileId}- profileSlug={profile?.profileSlug ?? ""}- enabled={Boolean(data?.scepConfigured)}- caType={data?.caType ?? CaType.INTERNAL}- initial={data?.scep ?? null}- onCancelPending={() => handleCancelPending("scep")}- onDirtyChange={(d) => handleDirtyChange("scep", d)}- />- </TabsContent>- ) : null}- </Tabs>+ {visibleMethods.includes("api") ? (+ <TabsContent+ value="api"+ className="flex min-h-0 flex-1 flex-col data-[state=inactive]:hidden"+ forceMount+ >+ <ApiPanel+ applicationId={applicationId}+ profileId={profileId}+ enabled={Boolean(data?.api)}+ initial={data?.api ?? null}+ onCancelPending={data?.api ? handleDismiss : () => handleCancelPending("api")}+ onDirtyChange={handleDirtyChange}+ onPendingChange={handlePendingChange}+ />+ </TabsContent>+ ) : null}+ {visibleMethods.includes("est") ? (+ <TabsContent+ value="est"+ className="flex min-h-0 flex-1 flex-col data-[state=inactive]:hidden"+ forceMount+ >+ <EstPanel+ applicationId={applicationId}+ profileId={profileId}+ enabled={Boolean(data?.estConfigured)}+ initial={data?.est ?? null}+ onCancelPending={+ data?.estConfigured ? handleDismiss : () => handleCancelPending("est")+ }+ onDirtyChange={handleDirtyChange}+ onPendingChange={handlePendingChange}+ />+ </TabsContent>+ ) : null}+ {visibleMethods.includes("acme") ? (+ <TabsContent+ value="acme"+ className="flex min-h-0 flex-1 flex-col data-[state=inactive]:hidden"+ forceMount+ >+ <AcmePanel+ applicationId={applicationId}+ profileId={profileId}+ enabled={Boolean(data?.acmeConfigured)}+ initial={data?.acme ?? null}+ onCancelPending={+ data?.acmeConfigured ? handleDismiss : () => handleCancelPending("acme")+ }+ onDirtyChange={handleDirtyChange}+ onPendingChange={handlePendingChange}+ />+ </TabsContent>+ ) : null}+ {visibleMethods.includes("scep") ? (+ <TabsContent+ value="scep"+ className="flex min-h-0 flex-1 flex-col data-[state=inactive]:hidden"+ forceMount+ >+ <ScepPanel+ applicationId={applicationId}+ profileId={profileId}+ profileSlug={profile?.profileSlug ?? ""}+ enabled={Boolean(data?.scepConfigured)}+ caType={data?.caType ?? CaType.INTERNAL}+ initial={data?.scep ?? null}+ onCancelPending={+ data?.scepConfigured ? handleDismiss : () => handleCancelPending("scep")+ }+ onDirtyChange={handleDirtyChange}+ onPendingChange={handlePendingChange}+ />+ </TabsContent>+ ) : null}</>)}- </>+ </Tabs>)}- </DialogContent>-- <AlertDialog open={isDiscardOpen} onOpenChange={setIsDiscardOpen}>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogMedia>- <AlertTriangleIcon className="text-warning" />- </AlertDialogMedia>- <AlertDialogTitle>Discard unsaved enrollment methods?</AlertDialogTitle>- <AlertDialogDescription>- Enrollment methods you added but have not enabled yet will be discarded.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>Keep editing</AlertDialogCancel>- <AlertDialogAction variant="danger" onClick={handleDiscard}>- Discard- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>+ {(!profile || isLoading || visibleMethods.length === 0) && (+ <SheetFooter className="justify-end border-t">+ <Button type="button" variant="ghost" onClick={handleDismiss} isDisabled={isPending}>+ Cancel+ </Button>+ </SheetFooter>+ )}+ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Enrollment Changes?"+ description={+ discardMethod.current+ ? `Unsaved ${METHOD_LABELS[discardMethod.current]} enrollment settings will be lost.`+ : "All unsaved enrollment settings and newly added methods will be lost."+ }+ />+ </SheetContent>{upgradeGate}- </Dialog>+ </Sheet>);};diff --git a/frontend/src/pages/cert-manager/ApplicationsPage/components/ConfigureProfilesModal.tsx b/frontend/src/pages/cert-manager/ApplicationsPage/components/ConfigureProfilesModal.tsxindex 4dc731aece..5ad94038bf 100644--- a/frontend/src/pages/cert-manager/ApplicationsPage/components/ConfigureProfilesModal.tsx+++ b/frontend/src/pages/cert-manager/ApplicationsPage/components/ConfigureProfilesModal.tsx@@ -1,16 +1,20 @@-import { useEffect, useMemo, useState } from "react";+import { useEffect, useId, useMemo, useState } from "react";import { Link, useParams } from "@tanstack/react-router";import { createNotification } from "@app/components/notifications";import {Button,+ Combobox,Dialog,+ DialogBody,DialogContent,DialogDescription,DialogFooter,DialogHeader,DialogTitle,- FilterableSelect+ DiscardChangesAlertDialog,+ Field,+ FieldLabel} from "@app/components/v3";import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";import {@@ -19,6 +23,8 @@ import {useDetachPkiApplicationProfile,useListPkiApplicationProfiles} from "@app/hooks/api/pkiApplications";+import { useDiscardChangesGuard } from "@app/hooks/useDiscardChangesGuard";+import { useProfileCreation } from "@app/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/useProfileCreation";type Option = { value: string; label: string };@@ -53,6 +59,19 @@ export const ConfigureProfilesModal = ({ application, isOpen, onOpenChange }: Pr);const [selected, setSelected] = useState<Option[]>(initialOptions);+ const inputId = useId();+ const profileCreation = useProfileCreation((profile) =>+ setSelected((previous) => [...previous, { value: profile.id, label: profile.slug }])+ );+ const { requestDiscard, confirmDiscard, isDiscardDialogOpen, setIsDiscardDialogOpen } =+ useDiscardChangesGuard({+ isDirty:+ selected.length !== initialOptions.length ||+ selected.some(+ (option) => !initialOptions.some((initial) => initial.value === option.value)+ ),+ onDiscard: () => onOpenChange(false)+ });useEffect(() => {if (isOpen) setSelected(initialOptions);@@ -90,44 +109,77 @@ export const ConfigureProfilesModal = ({ application, isOpen, onOpenChange }: Prconst isPending = attachProfiles.isPending || detachProfile.isPending;return (- <Dialog open={isOpen} onOpenChange={onOpenChange}>- <DialogContent className="max-w-md">- <DialogHeader>- <DialogTitle>Configure Profiles</DialogTitle>- <DialogDescription>- Select the certificate profiles attached to {application?.name ?? "this Application"}.- </DialogDescription>- </DialogHeader>- <div className="py-2">- <FilterableSelect- isMulti- value={selected}- onChange={(val) => setSelected((val ?? []) as Option[])}- options={profileOptions}- placeholder="Select profiles..."- />- {!profilesLoading && !profileOptions.length && (- <p className="mt-3 text-xs text-warning">- No certificate profiles available.{" "}- <Link- to="/organizations/$orgId/cert-manager/certificate-profiles"- params={{ orgId: orgId ?? "" }}- className="underline hover:text-warning"- >- Create one in Certificate Profiles- </Link>- </p>- )}- </div>- <DialogFooter>- <Button variant="ghost" onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button variant="project" onClick={handleSave} isPending={isPending}>- Save Changes- </Button>- </DialogFooter>- </DialogContent>- </Dialog>+ <>+ <Dialog+ open={isOpen}+ onOpenChange={(open) => {+ if (open) onOpenChange(true);+ else requestDiscard();+ }}+ >+ <DialogContent isPending={isPending}>+ <DialogHeader>+ <DialogTitle>Configure Profiles</DialogTitle>+ <DialogDescription>+ Select the certificate profiles attached to {application?.name ?? "this Application"}.+ </DialogDescription>+ </DialogHeader>+ <form+ className="flex min-h-0 flex-1 flex-col gap-6"+ onSubmit={(event) => {+ event.preventDefault();+ if (!isPending) handleSave();+ }}+ >+ <DialogBody>+ <fieldset disabled={isPending} className="min-w-0">+ <Field>+ <FieldLabel htmlFor={inputId}>Certificate Profiles</FieldLabel>+ <Combobox+ id={inputId}+ multiple+ value={selected}+ onValueChange={setSelected}+ getOptionValue={(option) => option.value}+ getOptionLabel={(option) => option.label}+ isLoading={profilesLoading}+ creation={profileCreation}+ options={profileOptions}+ placeholder="Select profiles..."+ />+ </Field>+ {!profilesLoading && !profileOptions.length && (+ <p className="mt-3 text-xs text-warning">+ No certificate profiles available.{" "}+ <Link+ to="/organizations/$orgId/cert-manager/certificate-profiles"+ params={{ orgId: orgId ?? "" }}+ className="underline hover:text-warning"+ >+ Create one in Certificate Profiles+ </Link>+ </p>+ )}+ </fieldset>+ </DialogBody>+ <DialogFooter>+ <Button variant="ghost" isDisabled={isPending} onClick={requestDiscard}>+ Cancel+ </Button>+ <Button variant="project" type="submit" isPending={isPending}>+ Save Changes+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Profile Changes?"+ description="Your pending profile changes will be lost."+ />+ </>);};diff --git a/frontend/src/pages/cert-manager/ApplicationsPage/components/PkiApplicationModal.tsx b/frontend/src/pages/cert-manager/ApplicationsPage/components/PkiApplicationModal.tsxindex d300e14a0e..26af9c05ca 100644--- a/frontend/src/pages/cert-manager/ApplicationsPage/components/PkiApplicationModal.tsx+++ b/frontend/src/pages/cert-manager/ApplicationsPage/components/PkiApplicationModal.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo } from "react";+import { useEffect, useId, useMemo } from "react";import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { useNavigate, useParams } from "@tanstack/react-router";@@ -7,18 +7,20 @@ import { z } from "zod";import { createNotification } from "@app/components/notifications";import {Button,+ Combobox,Dialog,+ DialogBody,DialogContent,DialogDescription,DialogFooter,DialogHeader,DialogTitle,+ DiscardChangesAlertDialog,Field,FieldContent,FieldDescription,FieldError,FieldLabel,- FilterableSelect,Input,TextArea} from "@app/components/v3";@@ -28,8 +30,10 @@ import {useCreatePkiApplication,useUpdatePkiApplication} from "@app/hooks/api/pkiApplications";+import { useDiscardChangesGuard } from "@app/hooks/useDiscardChangesGuard";import { UsePopUpState } from "@app/hooks/usePopUp";import { ApplicationTab } from "@app/pages/cert-manager/ApplicationDetailsByIDPage/application-tabs";+import { useProfileCreation } from "@app/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/useProfileCreation";const SLUG_REGEX = /^[a-z0-9-]+$/;@@ -57,6 +61,7 @@ export const PkiApplicationModal = ({ popUp, handlePopUpToggle }: Props) => {const editing = (popUp?.application?.data as TPkiApplication | undefined) ?? null;const create = useCreatePkiApplication();const update = useUpdatePkiApplication();+ const inputId = useId();const { data: profilesData } = useListCertificateProfiles({ limit: 100 });@@ -73,13 +78,25 @@ export const PkiApplicationModal = ({ popUp, handlePopUpToggle }: Props) => {control,handleSubmit,reset,- formState: { isSubmitting }+ getValues,+ setValue,+ formState: { isSubmitting, isDirty }} = useForm<FormData>({resolver: zodResolver(schema),defaultValues: { name: "", description: "", profileIds: [] }});+ const profileCreation = useProfileCreation((profile) =>+ setValue(+ "profileIds",+ [...(getValues("profileIds") ?? []), { value: profile.id, label: profile.slug }],+ { shouldDirty: true }+ )+ );+ const { requestDiscard, confirmDiscard, isDiscardDialogOpen, setIsDiscardDialogOpen } =+ useDiscardChangesGuard({ isDirty, onDiscard: () => handlePopUpToggle("application", false) });useEffect(() => {+ if (!popUp.application.isOpen) return;if (editing) {reset({name: editing.name,@@ -89,7 +106,7 @@ export const PkiApplicationModal = ({ popUp, handlePopUpToggle }: Props) => {} else {reset({ name: "", description: "", profileIds: [] });}- }, [editing, reset]);+ }, [editing, reset, popUp.application.isOpen]);const onSubmit = async (data: FormData) => {try {@@ -129,97 +146,124 @@ export const PkiApplicationModal = ({ popUp, handlePopUpToggle }: Props) => {};return (- <Dialog- open={popUp?.application?.isOpen}- onOpenChange={(isOpen) => handlePopUpToggle("application", isOpen)}- >- <DialogContent className="max-w-lg">- <DialogHeader>- <DialogTitle>{editing ? "Edit Application" : "Create Application"}</DialogTitle>- <DialogDescription>- {editing- ? "Update this Application's name and description."- : "A logical grouping for a service or workload that needs certificates."}- </DialogDescription>- </DialogHeader>+ <>+ <Dialog+ open={popUp?.application?.isOpen}+ onOpenChange={(isOpen) => {+ if (isOpen) handlePopUpToggle("application", true);+ else requestDiscard();+ }}+ >+ <DialogContent isPending={isSubmitting}>+ <DialogHeader>+ <DialogTitle>{editing ? "Edit Application" : "Create Application"}</DialogTitle>+ <DialogDescription>+ {editing+ ? "Update this Application's name and description."+ : "A logical grouping for a service or workload that needs certificates."}+ </DialogDescription>+ </DialogHeader>- <form onSubmit={handleSubmit(onSubmit)} className="space-y-3">- <Controller- control={control}- name="name"- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel>Name</FieldLabel>- <FieldContent>- <Input- {...field}- placeholder="my-service"- autoComplete="off"- name="pki-application-name"- />- </FieldContent>- {error ? <FieldError>{error.message}</FieldError> : null}- </Field>- )}- />- <Controller- control={control}- name="description"- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel>Description</FieldLabel>- <FieldContent>- <TextArea- {...field}- placeholder="Issues and rotates certificates for my application stack."+ <form onSubmit={handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col gap-6">+ <DialogBody>+ <fieldset disabled={isSubmitting} className="flex min-w-0 flex-col gap-4">+ <Controller+ control={control}+ name="name"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel htmlFor={`${inputId}-name`}>Name</FieldLabel>+ <FieldContent>+ <Input+ {...field}+ id={`${inputId}-name`}+ isError={Boolean(error)}+ placeholder="my-service"+ autoComplete="off"+ name="pki-application-name"+ />+ </FieldContent>+ {error ? <FieldError>{error.message}</FieldError> : null}+ </Field>+ )}+ />+ <Controller+ control={control}+ name="description"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel htmlFor={`${inputId}-description`}>Description</FieldLabel>+ <FieldContent>+ <TextArea+ {...field}+ id={`${inputId}-description`}+ isError={Boolean(error)}+ placeholder="Issues and rotates certificates for my application stack."+ />+ </FieldContent>+ {error ? <FieldError>{error.message}</FieldError> : null}+ </Field>+ )}+ />+ {!editing ? (+ <Controller+ control={control}+ name="profileIds"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel htmlFor={`${inputId}-profiles`}>+ Certificate Profiles+ </FieldLabel>+ <FieldContent>+ <Combobox+ ref={field.ref}+ id={`${inputId}-profiles`}+ multiple+ onBlur={field.onBlur}+ isError={Boolean(error)}+ value={field.value ?? []}+ onValueChange={field.onChange}+ getOptionValue={(option) => option.value}+ getOptionLabel={(option) => option.label}+ options={profileOptions}+ creation={profileCreation}+ placeholder="Select profiles to attach..."+ />+ </FieldContent>+ <FieldDescription>+ Select the profiles this application can issue certificates from. You can+ also attach them later from the application's settings.+ </FieldDescription>+ {error ? <FieldError>{error.message}</FieldError> : null}+ </Field>+ )}/>- </FieldContent>- {error ? <FieldError>{error.message}</FieldError> : null}- </Field>- )}- />- {!editing && profileOptions.length > 0 ? (- <Controller- control={control}- name="profileIds"- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel>Certificate Profiles</FieldLabel>- <FieldContent>- <FilterableSelect- isMulti- value={field.value ?? []}- onChange={(val) =>- field.onChange((val ?? []) as { value: string; label: string }[])- }- options={profileOptions}- placeholder="Select profiles to attach..."- />- </FieldContent>- <FieldDescription>- Select the profiles this application can issue certificates from. You can also- attach them later from the application's settings.- </FieldDescription>- {error ? <FieldError>{error.message}</FieldError> : null}- </Field>- )}- />- ) : null}-- <DialogFooter className="mt-4">- <Button- type="button"- variant="ghost"- onClick={() => handlePopUpToggle("application", false)}- >- Cancel- </Button>- <Button type="submit" variant="project" isPending={isSubmitting}>- {editing ? "Save Changes" : "Create Application"}- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>+ ) : null}+ </fieldset>+ </DialogBody>+ <DialogFooter>+ <Button+ type="button"+ variant="ghost"+ isDisabled={isSubmitting}+ onClick={requestDiscard}+ >+ Cancel+ </Button>+ <Button type="submit" variant="project" isPending={isSubmitting}>+ {editing ? "Save Changes" : "Create Application"}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Application Changes?"+ description="Your unsaved application settings will be lost."+ />+ </>);};diff --git a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsx b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsxindex f8c05d5d7a..1ab2aaf803 100644--- a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsx+++ b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsx@@ -7,8 +7,21 @@ import { format } from "date-fns";import { twMerge } from "tailwind-merge";import { createNotification } from "@app/components/notifications";-import { ContentLoader, EmptyState } from "@app/components/v2";-import { Badge, Button, ConfirmationAlertDialog } from "@app/components/v3";+import {+ Badge,+ Button,+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ ConfirmationAlertDialog,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+ PageLoader+} from "@app/components/v3";import { useOrganization, useProject, useUser } from "@app/context";import { usePopUp } from "@app/hooks";import { ApprovalPolicyScope, ApprovalPolicyType } from "@app/hooks/api/approvalPolicies";@@ -47,73 +60,85 @@ const CodeSigningDetailsSection = ({}) => {return (<div className="flex flex-col gap-4">- <div className="rounded-lg border border-border-control bg-surface-base p-4">- <h2 className="text-lg font-normal text-foreground">- Signing access for {requestData.signerName}- </h2>- <div className="mt-4 flex items-center gap-3">- <div className="flex h-10 w-10 items-center justify-center rounded-full bg-surface-hover text-sm font-medium text-foreground-secondary">- {(requesterName || "U")- .split(" ")- .map((n) => n[0])- .join("")- .slice(0, 2)- .toUpperCase()}- </div>- <div>- <p className="text-sm font-medium text-foreground">{requesterName || "Unknown"}</p>- {requesterEmail && <p className="text-sm text-muted">{requesterEmail}</p>}- </div>- </div>- </div>- <div className="rounded-lg border border-border-control bg-surface-base p-5">- <h3 className="mb-4 text-lg font-normal text-foreground">Signing Access Details</h3>- <div className="grid grid-cols-2 gap-4">- <div>- <span className="text-xs text-muted">Signer</span>- <p className="text-sm text-foreground">{requestData.signerName}</p>- </div>- {requestData.requestedWindowDuration && (- <div>- <span className="text-xs text-muted">Access Duration</span>- <p className="text-sm text-foreground">- {requestData.requestedWindowDuration} from approval- </p>+ <Card>+ <CardHeader>+ <CardTitle role="heading" aria-level={2}>+ Signing access for {requestData.signerName}+ </CardTitle>+ </CardHeader>+ <CardContent>+ <div className="flex items-center gap-3">+ <div className="flex h-10 w-10 items-center justify-center rounded-full bg-surface-hover text-sm font-medium text-foreground-secondary">+ {(requesterName || "U")+ .split(" ")+ .map((n) => n[0])+ .join("")+ .slice(0, 2)+ .toUpperCase()}</div>- )}- {requestData.requestedSignings && (<div>- <span className="text-xs text-muted">Allowed Sign Operations</span>- <p className="text-sm text-foreground">{requestData.requestedSignings}</p>+ <p className="text-sm font-medium text-foreground">{requesterName || "Unknown"}</p>+ {requesterEmail && <p className="text-sm text-muted">{requesterEmail}</p>}</div>- )}- </div>- {requestData.scope && Object.values(requestData.scope).some(Boolean) && (- <div className="mt-4 border-t border-border-control pt-4">- <h4 className="mb-1 text-sm font-normal text-foreground">Request Scope</h4>- <p className="mb-3 text-xs text-muted">- Signing is only allowed when every parameter below matches exactly.- </p>- <div className="flex flex-col gap-4">- {Object.values(CodeSigningScopeField)- .filter((field) => requestData.scope?.[field])- .map((field) => (- <div key={field}>- <span className="text-xs text-muted">{codeSigningScopeFieldLabels[field]}</span>- <p- className={twMerge(- "text-sm break-all text-foreground",- MONOSPACED_SCOPE_FIELDS.includes(field) && "font-mono text-xs"- )}- >- {requestData.scope?.[field]}- </p>- </div>- ))}+ </div>+ </CardContent>+ </Card>+ <Card>+ <CardHeader>+ <CardTitle role="heading" aria-level={3}>+ Signing Access Details+ </CardTitle>+ </CardHeader>+ <CardContent>+ <div className="grid grid-cols-2 gap-4">+ <div>+ <span className="text-xs text-muted">Signer</span>+ <p className="text-sm text-foreground">{requestData.signerName}</p></div>+ {requestData.requestedWindowDuration && (+ <div>+ <span className="text-xs text-muted">Access Duration</span>+ <p className="text-sm text-foreground">+ {requestData.requestedWindowDuration} from approval+ </p>+ </div>+ )}+ {requestData.requestedSignings && (+ <div>+ <span className="text-xs text-muted">Allowed Sign Operations</span>+ <p className="text-sm text-foreground">{requestData.requestedSignings}</p>+ </div>+ )}</div>- )}- </div>+ {requestData.scope && Object.values(requestData.scope).some(Boolean) && (+ <div className="mt-4 border-t border-border-control pt-4">+ <h4 className="mb-1 text-sm font-normal text-foreground">Request Scope</h4>+ <p className="mb-3 text-xs text-muted">+ Signing is only allowed when every parameter below matches exactly.+ </p>+ <div className="flex flex-col gap-4">+ {Object.values(CodeSigningScopeField)+ .filter((field) => requestData.scope?.[field])+ .map((field) => (+ <div key={field}>+ <span className="text-xs text-muted">+ {codeSigningScopeFieldLabels[field]}+ </span>+ <p+ className={twMerge(+ "text-sm break-all text-foreground",+ MONOSPACED_SCOPE_FIELDS.includes(field) && "font-mono text-xs"+ )}+ >+ {requestData.scope?.[field]}+ </p>+ </div>+ ))}+ </div>+ </div>+ )}+ </CardContent>+ </Card></div>);};@@ -202,7 +227,7 @@ const PageContent = () => {if (isPending) {return (<div className="flex h-full w-full items-center justify-center">- <ContentLoader />+ <PageLoader /></div>);}@@ -210,11 +235,17 @@ const PageContent = () => {if (!request) {return (<div className="flex h-full w-full items-center justify-center px-20">- <EmptyState- className="max-w-2xl rounded-md text-center"- icon={faBan}- title={`Could not find approval request with ID ${approvalRequestId}`}- />+ <Empty>+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <FontAwesomeIcon icon={faBan} />+ </EmptyMedia>+ <EmptyTitle>Approval Request Not Found</EmptyTitle>+ <EmptyDescription>+ Could not find approval request with ID {approvalRequestId}.+ </EmptyDescription>+ </EmptyHeader>+ </Empty></div>);}@@ -419,6 +450,7 @@ const PageContent = () => {title="Do you want to cancel this approval request?"onOpenChange={(isOpen) => handlePopUpToggle("cancelRequest", isOpen)}onConfirm={handleRequestCancel}+ isPending={cancelApprovalRequest.isPending}confirmLabel="Confirm"/></div>diff --git a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/CertificateDetailsSection.tsx b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/CertificateDetailsSection.tsxindex 494adec33e..467d8b2530 100644--- a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/CertificateDetailsSection.tsx+++ b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/CertificateDetailsSection.tsx@@ -10,8 +10,15 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { Link } from "@tanstack/react-router";import { ExternalLinkIcon } from "lucide-react";-import { Skeleton } from "@app/components/v2";-import { Badge, ButtonGroup } from "@app/components/v3";+import {+ Badge,+ ButtonGroup,+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ Skeleton+} from "@app/components/v3";import { useOrganization } from "@app/context";import { CertRequestRequestData, TApprovalRequest } from "@app/hooks/api/approvalRequests";import { useGetCertificateProfileById } from "@app/hooks/api/certificateProfiles";@@ -99,276 +106,299 @@ export const CertificateDetailsSection = ({ request }: Props) => {return (<div className="flex flex-col gap-4">- <div className="rounded-lg border border-border-control bg-surface-base p-4">- <h2 className="text-lg font-normal text-foreground">- Request for {certRequest?.altNames?.[0]?.value || certRequest?.commonName || "-"}- </h2>-- <div className="mt-4 flex items-center gap-3">- <div className="flex h-10 w-10 items-center justify-center rounded-full bg-surface-hover text-sm font-medium text-foreground-secondary">- {(request.requesterName || "U")- .split(" ")- .map((n) => n[0])- .join("")- .slice(0, 2)- .toUpperCase()}- </div>- <div>- <p className="text-sm font-medium text-foreground">- {request.requesterName || "Unknown"}- </p>- <p className="text-sm text-muted">{request.requesterEmail}</p>- </div>- </div>- </div>-- <div className="rounded-lg border border-border-control bg-surface-base p-4">- <h3 className="mb-4 flex items-center gap-2 text-base font-normal text-foreground">- <FontAwesomeIcon icon={faLock} className="text-sm text-muted" />- Certificate Specifications- </h3>-- <div className="grid grid-cols-2 gap-x-8 gap-y-3">- {certRequest?.keyAlgorithm && (- <div>- <p className="text-xs text-muted">Key Algorithm</p>- <p className="mt-0.5 text-sm text-foreground">- {formatKeyAlgorithm(certRequest.keyAlgorithm)}- </p>+ <Card>+ <CardHeader>+ <CardTitle role="heading" aria-level={2}>+ Request for {certRequest?.altNames?.[0]?.value || certRequest?.commonName || "-"}+ </CardTitle>+ </CardHeader>+ <CardContent>+ <div className="flex items-center gap-3">+ <div className="flex h-10 w-10 items-center justify-center rounded-full bg-surface-hover text-sm font-medium text-foreground-secondary">+ {(request.requesterName || "U")+ .split(" ")+ .map((n) => n[0])+ .join("")+ .slice(0, 2)+ .toUpperCase()}</div>- )}- {certRequest?.signatureAlgorithm && (<div>- <p className="text-xs text-muted">Signature Algorithm</p>- <p className="mt-0.5 text-sm text-foreground">{certRequest.signatureAlgorithm}</p>- </div>- )}- {certRequest?.validity?.ttl && (- <div>- <p className="text-xs text-muted">Validity</p>- <p className="mt-0.5 text-sm text-foreground">- {formatValidity(certRequest.validity.ttl)}+ <p className="text-sm font-medium text-foreground">+ {request.requesterName || "Unknown"}</p>+ <p className="text-sm text-muted">{request.requesterEmail}</p></div>- )}- <div>- <p className="text-xs text-muted">Certificate Authority</p>- {isProfileLoading && <Skeleton className="mt-0.5 h-4 w-24" />}- {!isProfileLoading && isInternalCa && caId && (- <Badge variant="outline" asChild className="mt-1">- <Link- to="/organizations/$orgId/cert-manager/ca/$caId"- params={{- orgId: currentOrg.id,- caId- }}- >- {profile?.certificateAuthority?.name || "N/A"}- <ExternalLinkIcon />- </Link>- </Badge>+ </div>+ </CardContent>+ </Card>++ <Card>+ <CardHeader>+ <CardTitle role="heading" aria-level={3}>+ <FontAwesomeIcon icon={faLock} className="text-sm text-muted" />+ Certificate Specifications+ </CardTitle>+ </CardHeader>+ <CardContent>+ <div className="grid grid-cols-2 gap-x-8 gap-y-3">+ {certRequest?.keyAlgorithm && (+ <div>+ <p className="text-xs text-muted">Key Algorithm</p>+ <p className="mt-0.5 text-sm text-foreground">+ {formatKeyAlgorithm(certRequest.keyAlgorithm)}+ </p>+ </div>)}- {!isProfileLoading && !(isInternalCa && caId) && (- <p className="mt-0.5 text-sm text-foreground">- {profile?.certificateAuthority?.name || "N/A"}- </p>+ {certRequest?.signatureAlgorithm && (+ <div>+ <p className="text-xs text-muted">Signature Algorithm</p>+ <p className="mt-0.5 text-sm text-foreground">{certRequest.signatureAlgorithm}</p>+ </div>+ )}+ {certRequest?.validity?.ttl && (+ <div>+ <p className="text-xs text-muted">Validity</p>+ <p className="mt-0.5 text-sm text-foreground">+ {formatValidity(certRequest.validity.ttl)}+ </p>+ </div>)}- </div>- <div>- <p className="text-xs text-muted">Certificate Profile</p>- <p className="mt-0.5 text-sm text-foreground">{requestData.profileName}</p>- </div>- </div>- </div>-- <div className="rounded-lg border border-border-control bg-surface-base p-4">- <h3 className="mb-4 flex items-center gap-2 text-base font-normal text-foreground">- <FontAwesomeIcon icon={faGlobe} className="text-sm text-muted" />- Subject Information- </h3>-- <div className="grid grid-cols-2 gap-x-8 gap-y-3">- {certRequest?.commonName && (- <div>- <p className="text-xs text-muted">Common Name (CN)</p>- <p className="mt-0.5 text-sm text-foreground">{certRequest.commonName}</p>- </div>- )}- {organization && (- <div>- <p className="text-xs text-muted">Organization (O)</p>- <p className="mt-0.5 text-sm text-foreground">{organization}</p>- </div>- )}- {organizationalUnit && (- <div>- <p className="text-xs text-muted">Organizational Unit (OU)</p>- <p className="mt-0.5 text-sm text-foreground">{organizationalUnit}</p>- </div>- )}- {country && (- <div>- <p className="text-xs text-muted">Country (C)</p>- <p className="mt-0.5 text-sm text-foreground">{country}</p>- </div>- )}- {state && (<div>- <p className="text-xs text-muted">State (ST)</p>- <p className="mt-0.5 text-sm text-foreground">{state}</p>+ <p className="text-xs text-muted">Certificate Authority</p>+ {isProfileLoading && <Skeleton className="mt-0.5 h-4 w-24" />}+ {!isProfileLoading && isInternalCa && caId && (+ <Badge variant="outline" asChild className="mt-1">+ <Link+ to="/organizations/$orgId/cert-manager/ca/$caId"+ params={{+ orgId: currentOrg.id,+ caId+ }}+ >+ {profile?.certificateAuthority?.name || "N/A"}+ <ExternalLinkIcon />+ </Link>+ </Badge>+ )}+ {!isProfileLoading && !(isInternalCa && caId) && (+ <p className="mt-0.5 text-sm text-foreground">+ {profile?.certificateAuthority?.name || "N/A"}+ </p>+ )}</div>- )}- {locality && (<div>- <p className="text-xs text-muted">Locality (L)</p>- <p className="mt-0.5 text-sm text-foreground">{locality}</p>- </div>- )}- </div>-- {hasDomainComponents && (- <div className="mt-4 border-t border-border-control pt-4">- <p className="mb-3 text-xs text-muted">Domain Components (DC)</p>- <div className="flex flex-wrap gap-2">- {domainComponents!.map((dc) => (- <span- key={dc}- className="rounded bg-surface-hover px-2.5 py-1 text-sm text-foreground-secondary"- >- {dc}- </span>- ))}- </div>- </div>- )}-- {hasAltNames && (- <div className="mt-4 border-t border-border-control pt-4">- <p className="mb-3 text-xs text-muted">Subject Alternative Names (SANs)</p>- <div className="flex flex-wrap gap-2">- {filteredAltNames.map((san: { type: string; value: string }) => (- <span- key={`${san.type}-${san.value}`}- className="rounded bg-surface-hover px-2.5 py-1 text-sm text-foreground-secondary"- >- {san.value}- </span>- ))}+ <p className="text-xs text-muted">Certificate Profile</p>+ <p className="mt-0.5 text-sm text-foreground">{requestData.profileName}</p></div></div>- )}-- {!certRequest?.commonName &&- !organization &&- !organizationalUnit &&- !country &&- !state &&- !locality &&- !hasDomainComponents &&- !hasAltNames && <p className="text-sm text-muted">No subject information specified</p>}- </div>-- {customExtensions.length > 0 && (- <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">- <h3 className="mb-4 flex items-center gap-2 text-base font-normal text-mineshaft-100">- <FontAwesomeIcon icon={faPuzzlePiece} className="text-sm text-mineshaft-400" />- Custom Extensions- </h3>- <CustomExtensionList extensions={customExtensions} />- </div>- )}-- {basicConstraints?.isCA && (- <div className="rounded-lg border border-border-control bg-surface-base p-4">- <h3 className="mb-4 flex items-center gap-2 text-base font-normal text-foreground">- <FontAwesomeIcon icon={faShieldHalved} className="text-sm text-muted" />- Basic Constraints- </h3>-+ </CardContent>+ </Card>++ <Card>+ <CardHeader>+ <CardTitle role="heading" aria-level={3}>+ <FontAwesomeIcon icon={faGlobe} className="text-sm text-muted" />+ Subject Information+ </CardTitle>+ </CardHeader>+ <CardContent><div className="grid grid-cols-2 gap-x-8 gap-y-3">- <div>- <p className="text-xs text-muted">Certificate Authority</p>- <p className="mt-0.5 text-sm text-foreground">Yes (CA Certificate)</p>- </div>- {basicConstraints.pathLength !== undefined && (+ {certRequest?.commonName && (+ <div>+ <p className="text-xs text-muted">Common Name (CN)</p>+ <p className="mt-0.5 text-sm text-foreground">{certRequest.commonName}</p>+ </div>+ )}+ {organization && (<div>- <p className="text-xs text-muted">Path Length</p>- <p className="mt-0.5 text-sm text-foreground">{basicConstraints.pathLength}</p>+ <p className="text-xs text-muted">Organization (O)</p>+ <p className="mt-0.5 text-sm text-foreground">{organization}</p>+ </div>+ )}+ {organizationalUnit && (+ <div>+ <p className="text-xs text-muted">Organizational Unit (OU)</p>+ <p className="mt-0.5 text-sm text-foreground">{organizationalUnit}</p>+ </div>+ )}+ {country && (+ <div>+ <p className="text-xs text-muted">Country (C)</p>+ <p className="mt-0.5 text-sm text-foreground">{country}</p>+ </div>+ )}+ {state && (+ <div>+ <p className="text-xs text-muted">State (ST)</p>+ <p className="mt-0.5 text-sm text-foreground">{state}</p>+ </div>+ )}+ {locality && (+ <div>+ <p className="text-xs text-muted">Locality (L)</p>+ <p className="mt-0.5 text-sm text-foreground">{locality}</p></div>)}</div>- </div>- )}- {(hasKeyUsages || hasExtendedKeyUsages) && (- <div className="rounded-lg border border-border-control bg-surface-base p-4">- <h3 className="mb-4 flex items-center gap-2 text-base font-normal text-foreground">- <FontAwesomeIcon icon={faKey} className="text-sm text-muted" />- Key Usages- </h3>-- {hasKeyUsages && certRequest?.keyUsages && (- <div className="mb-4">- <p className="mb-3 text-xs text-muted">Key Usages</p>+ {hasDomainComponents && (+ <div className="mt-4 border-t border-border-control pt-4">+ <p className="mb-3 text-xs text-muted">Domain Components (DC)</p><div className="flex flex-wrap gap-2">- {certRequest.keyUsages.map((usage: string) => (+ {domainComponents!.map((dc) => (<span- key={usage}+ key={dc}className="rounded bg-surface-hover px-2.5 py-1 text-sm text-foreground-secondary">- {formatKeyUsageDisplay(usage)}+ {dc}</span>))}</div></div>)}- {hasExtendedKeyUsages && certRequest?.extendedKeyUsages && (- <div className={hasKeyUsages ? "border-t border-border-control pt-4" : ""}>- <p className="mb-3 text-xs text-muted">Extended Key Usages</p>+ {hasAltNames && (+ <div className="mt-4 border-t border-border-control pt-4">+ <p className="mb-3 text-xs text-muted">Subject Alternative Names (SANs)</p><div className="flex flex-wrap gap-2">- {certRequest.extendedKeyUsages.map((usage: string) => (+ {filteredAltNames.map((san: { type: string; value: string }) => (<span- key={usage}+ key={`${san.type}-${san.value}`}className="rounded bg-surface-hover px-2.5 py-1 text-sm text-foreground-secondary">- {formatExtendedKeyUsageDisplay(usage)}+ {san.value}</span>))}</div></div>)}- </div>++ {!certRequest?.commonName &&+ !organization &&+ !organizationalUnit &&+ !country &&+ !state &&+ !locality &&+ !hasDomainComponents &&+ !hasAltNames && <p className="text-sm text-muted">No subject information specified</p>}+ </CardContent>+ </Card>++ {customExtensions.length > 0 && (+ <Card>+ <CardHeader>+ <CardTitle role="heading" aria-level={3}>+ <FontAwesomeIcon icon={faPuzzlePiece} className="text-sm text-muted" />+ Custom Extensions+ </CardTitle>+ </CardHeader>+ <CardContent>+ <CustomExtensionList extensions={customExtensions} />+ </CardContent>+ </Card>+ )}++ {basicConstraints?.isCA && (+ <Card>+ <CardHeader>+ <CardTitle role="heading" aria-level={3}>+ <FontAwesomeIcon icon={faShieldHalved} className="text-sm text-muted" />+ Basic Constraints+ </CardTitle>+ </CardHeader>+ <CardContent>+ <div className="grid grid-cols-2 gap-x-8 gap-y-3">+ <div>+ <p className="text-xs text-muted">Certificate Authority</p>+ <p className="mt-0.5 text-sm text-foreground">Yes (CA Certificate)</p>+ </div>+ {basicConstraints.pathLength !== undefined && (+ <div>+ <p className="text-xs text-muted">Path Length</p>+ <p className="mt-0.5 text-sm text-foreground">{basicConstraints.pathLength}</p>+ </div>+ )}+ </div>+ </CardContent>+ </Card>+ )}++ {(hasKeyUsages || hasExtendedKeyUsages) && (+ <Card>+ <CardHeader>+ <CardTitle role="heading" aria-level={3}>+ <FontAwesomeIcon icon={faKey} className="text-sm text-muted" />+ Key Usages+ </CardTitle>+ </CardHeader>+ <CardContent>+ {hasKeyUsages && certRequest?.keyUsages && (+ <div className="mb-4">+ <p className="mb-3 text-xs text-muted">Key Usages</p>+ <div className="flex flex-wrap gap-2">+ {certRequest.keyUsages.map((usage: string) => (+ <span+ key={usage}+ className="rounded bg-surface-hover px-2.5 py-1 text-sm text-foreground-secondary"+ >+ {formatKeyUsageDisplay(usage)}+ </span>+ ))}+ </div>+ </div>+ )}++ {hasExtendedKeyUsages && certRequest?.extendedKeyUsages && (+ <div className={hasKeyUsages ? "border-t border-border-control pt-4" : ""}>+ <p className="mb-3 text-xs text-muted">Extended Key Usages</p>+ <div className="flex flex-wrap gap-2">+ {certRequest.extendedKeyUsages.map((usage: string) => (+ <span+ key={usage}+ className="rounded bg-surface-hover px-2.5 py-1 text-sm text-foreground-secondary"+ >+ {formatExtendedKeyUsageDisplay(usage)}+ </span>+ ))}+ </div>+ </div>+ )}+ </CardContent>+ </Card>)}- <div className="rounded-lg border border-border-control bg-surface-base p-4">- <h3 className="mb-4 flex items-center gap-2 text-base font-normal text-foreground">- <FontAwesomeIcon icon={faTags} className="text-sm text-muted" />- Metadata- </h3>- {metadata.length > 0 ? (- <div className="flex flex-wrap gap-2">- {metadata.map((item: { key: string; value?: string }) =>- item.value ? (- <ButtonGroup className="max-w-full min-w-0" key={`${item.key}=${item.value}`}>- <Badge isTruncatable className="max-w-[12rem] shrink-0">+ <Card>+ <CardHeader>+ <CardTitle role="heading" aria-level={3}>+ <FontAwesomeIcon icon={faTags} className="text-sm text-muted" />+ Metadata+ </CardTitle>+ </CardHeader>+ <CardContent>+ {metadata.length > 0 ? (+ <div className="flex flex-wrap gap-2">+ {metadata.map((item: { key: string; value?: string }) =>+ item.value ? (+ <ButtonGroup className="max-w-full min-w-0" key={`${item.key}=${item.value}`}>+ <Badge isTruncatable className="max-w-[12rem] shrink-0">+ <span>{item.key}</span>+ </Badge>+ <Badge variant="outline" isTruncatable>+ <span>{item.value}</span>+ </Badge>+ </ButtonGroup>+ ) : (+ <Badge key={item.key} isTruncatable><span>{item.key}</span></Badge>- <Badge variant="outline" isTruncatable>- <span>{item.value}</span>- </Badge>- </ButtonGroup>- ) : (- <Badge key={item.key} isTruncatable>- <span>{item.key}</span>- </Badge>- )- )}- </div>- ) : (- <p className="text-sm text-muted">No metadata attached to this request.</p>- )}- </div>+ )+ )}+ </div>+ ) : (+ <p className="text-sm text-muted">No metadata attached to this request.</p>+ )}+ </CardContent>+ </Card></div>);};diff --git a/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicyModal.tsx b/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicyModal.tsxindex db431dc666..4ccb49c00b 100644--- a/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicyModal.tsx+++ b/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicyModal.tsx@@ -1,11 +1,23 @@import { useEffect, useState } from "react";import { FormProvider, useForm } from "react-hook-form";-import { Tab } from "@headlessui/react";import { zodResolver } from "@hookform/resolvers/zod";import { PolicyApprovalSteps } from "@app/components/approvals";import { createNotification } from "@app/components/notifications";-import { Button, Modal, ModalContent } from "@app/components/v2";+import {+ Button,+ DiscardChangesAlertDialog,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger+} from "@app/components/v3";import { useProject } from "@app/context";import {ApprovalPolicyScope,@@ -15,6 +27,7 @@ import {useCreateApprovalPolicy,useUpdateApprovalPolicy} from "@app/hooks/api/approvalPolicies";+import { useDiscardChangesGuard } from "@app/hooks/useDiscardChangesGuard";import { UsePopUpState } from "@app/hooks/usePopUp";import { PolicyDetailsStep } from "./PolicySteps/PolicyDetailsStep";@@ -65,10 +78,21 @@ export const PolicyModal = ({ popUp, handlePopUpToggle, applicationId }: Props)}});- const { handleSubmit, trigger, reset } = formMethods;+ const {+ handleSubmit,+ trigger,+ reset,+ formState: { isDirty, isSubmitting, isValidating }+ } = formMethods;const { mutateAsync: createPolicy, isPending: isCreating } = useCreateApprovalPolicy();const { mutateAsync: updatePolicy, isPending: isUpdating } = useUpdateApprovalPolicy();+ const isPending = isCreating || isUpdating || isSubmitting;+ const { requestDiscard, isDiscardDialogOpen, setIsDiscardDialogOpen, confirmDiscard } =+ useDiscardChangesGuard({+ isDirty,+ onDiscard: () => handlePopUpToggle("policy", false)+ });useEffect(() => {if (policyData?.policy) {@@ -149,6 +173,7 @@ export const PolicyModal = ({ popUp, handlePopUpToggle, applicationId }: Props)const isFinalStep = selectedStepIndex === FORM_STEPS.length - 1;const handleNext = async () => {+ if (isPending || isValidating) return;if (isFinalStep) {await handleSubmit(onSubmit)();return;@@ -162,11 +187,7 @@ export const PolicyModal = ({ popUp, handlePopUpToggle, applicationId }: Props)};const handlePrev = () => {- if (selectedStepIndex === 0) {- handlePopUpToggle("policy", false);- return;- }-+ if (isPending || isValidating) return;setSelectedStepIndex((prev) => prev - 1);};@@ -181,70 +202,101 @@ export const PolicyModal = ({ popUp, handlePopUpToggle, applicationId }: Props)};return (- <Modal isOpen={isOpen} onOpenChange={(open) => handlePopUpToggle("policy", open)}>- <ModalContent- title={- policyData?.policyId- ? "Edit Certificate Approval Policy"- : "Create Certificate Approval Policy"- }- subTitle="Configure a certificate approval policy requiring approval for certificate issuance"- className="max-w-3xl"- >+ <Sheet+ open={isOpen}+ onOpenChange={(open) => {+ if (!open && !isPending) requestDiscard();+ }}+ >+ <SheetContent size="form" isPending={isPending}>+ <SheetHeader>+ <SheetTitle>+ {policyData?.policyId+ ? "Edit Certificate Approval Policy"+ : "Create Certificate Approval Policy"}+ </SheetTitle>+ <SheetDescription>+ Configure a certificate approval policy requiring approval for certificate issuance.+ </SheetDescription>+ </SheetHeader><FormProvider {...formMethods}>- <form>- <Tab.Group selectedIndex={selectedStepIndex} onChange={setSelectedStepIndex}>- <Tab.List className="-pb-1 mb-6 w-full border-b-2 border-border-control">- {FORM_STEPS.map((step, index) => (- <Tab- onClick={async (e) => {- e.preventDefault();- const isEnabled = await isTabEnabled(index);- setSelectedStepIndex((prev) => (isEnabled ? index : prev));- }}- className={({ selected }) =>- `-mb-[0.14rem] whitespace-nowrap ${index > selectedStepIndex ? "opacity-30" : ""} px-4 py-2 text-sm font-medium outline-hidden disabled:opacity-60 ${- selected- ? "border-b-2 border-border-bright text-foreground-secondary"- : "text-label-secondary"- }`- }- key={step.key}- >- {index + 1}. {step.name}- </Tab>- ))}- </Tab.List>- <Tab.Panels>- <Tab.Panel>+ <form+ className="contents"+ onSubmit={async (event) => {+ event.preventDefault();+ await handleNext();+ }}+ >+ <fieldset+ disabled={isPending}+ className="min-h-0 thin-scrollbar flex-1 overflow-y-auto p-4"+ >+ <Tabs+ value={FORM_STEPS[selectedStepIndex].key}+ onValueChange={async (value) => {+ if (isPending || isValidating) return;+ const index = FORM_STEPS.findIndex((step) => step.key === value);+ if (await isTabEnabled(index)) setSelectedStepIndex(index);+ }}+ >+ <TabsList variant="project" aria-label="Policy configuration steps">+ {FORM_STEPS.map((step, index) => (+ <TabsTrigger+ value={step.key}+ disabled={isPending || isValidating}+ key={step.key}+ >+ {index + 1}. {step.name}+ </TabsTrigger>+ ))}+ </TabsList>+ <TabsContent value="configuration"><PolicyDetailsStep applicationId={applicationId} />- </Tab.Panel>- <Tab.Panel>+ </TabsContent>+ <TabsContent value="approvals"><PolicyApprovalSteps applicationId={applicationId} />- </Tab.Panel>- <Tab.Panel>+ </TabsContent>+ <TabsContent value="review"><PolicyReviewStep />- </Tab.Panel>- </Tab.Panels>- </Tab.Group>+ </TabsContent>+ </Tabs>+ </fieldset>- <div className="mt-6 flex justify-between border-t border-border-control pt-4">- <Button type="button" variant="outline_bg" onClick={handlePrev}>- {selectedStepIndex === 0 ? "Cancel" : "Back"}+ <SheetFooter className="justify-end border-t">+ {selectedStepIndex > 0 && (+ <Button+ type="button"+ variant="outline"+ className="mr-auto"+ onClick={handlePrev}+ isDisabled={isPending || isValidating}+ >+ Back+ </Button>+ )}+ <Button type="button" variant="ghost" onClick={requestDiscard} isDisabled={isPending}>+ Cancel</Button><Button- type="button"- onClick={handleNext}- isLoading={isCreating || isUpdating}- isDisabled={isCreating || isUpdating}+ type="submit"+ variant="project"+ isPending={isPending}+ isDisabled={isPending || isValidating}>{isFinalStep && (policyData?.policyId ? "Update" : "Create")}{!isFinalStep && "Next"}</Button>- </div>+ </SheetFooter></form></FormProvider>- </ModalContent>- </Modal>+ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Changes?"+ description="Your unsaved policy changes will be lost."+ />+ </SheetContent>+ </Sheet>);};diff --git a/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicySteps/PolicyDetailsStep.tsx b/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicySteps/PolicyDetailsStep.tsxindex 56917554a9..3d3cb87bfb 100644--- a/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicySteps/PolicyDetailsStep.tsx+++ b/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicySteps/PolicyDetailsStep.tsx@@ -1,10 +1,11 @@-import { useMemo } from "react";+import { useMemo, useState } from "react";import { Controller, useFormContext } from "react-hook-form";+import axios from "axios";import { TtlFormLabel } from "@app/components/features";-import { FilterableSelect } from "@app/components/v2";import {Checkbox,+ Combobox,Field,FieldContent,FieldDescription,@@ -13,7 +14,14 @@ import {Input} from "@app/components/v3";import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";-import { useListPkiApplicationProfiles } from "@app/hooks/api/pkiApplications";+import {+ PkiApplicationResourceActions,+ PkiApplicationResourceSub,+ useAttachPkiApplicationProfiles,+ useGetPkiApplicationPermissions,+ useListPkiApplicationProfiles+} from "@app/hooks/api/pkiApplications";+import { useProfileCreation } from "@app/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/useProfileCreation";import { TPolicyForm } from "../PolicySchema";@@ -27,11 +35,73 @@ type Props = {};export const PolicyDetailsStep = ({ applicationId }: Props) => {- const { control } = useFormContext<TPolicyForm>();+ const { control, getValues, setValue } = useFormContext<TPolicyForm>();- const { data: profilesData, isPending: isProfilesLoading } = useListCertificateProfiles({});- const { data: appProfiles = [], isPending: isAppProfilesLoading } = useListPkiApplicationProfiles(- applicationId ?? ""+ const { data: profilesData, isPending: isProfilesLoading } = useListCertificateProfiles({+ enabled: !applicationId+ });+ const {+ data: appProfiles = [],+ isPending: isAppProfilesLoading,+ refetch: refetchAppProfiles+ } = useListPkiApplicationProfiles(applicationId ?? "");+ const { data: appPermission } = useGetPkiApplicationPermissions(applicationId ?? "");+ const canManageAppProfiles = appPermission?.permission.can(+ PkiApplicationResourceActions.ManageProfiles,+ PkiApplicationResourceSub.Application+ );+ const attach = useAttachPkiApplicationProfiles();+ const [attachedProfileId, setAttachedProfileId] = useState<string>();+ const creationLabel = applicationId ? "Create and Attach Profile" : "Create New Profile";+ const profileCreation = useProfileCreation<ProfileOption>(+ async (profile) => {+ let { slug } = profile;+ if (applicationId) {+ if (!canManageAppProfiles) {+ throw new Error(+ "The profile was created, but you no longer have permission to attach it to this application."+ );+ }+ if (attachedProfileId !== profile.id) {+ try {+ await attach.mutateAsync({ applicationId, profileIds: [profile.id] });+ } catch (error) {+ let message =+ "The profile was created, but attachment failed. Retry to attach it to this application.";+ if (axios.isAxiosError<{ message?: unknown }>(error)) {+ if (!error.response) {+ message =+ "The profile was created, but no response was received for the attachment request. Check your connection to Infisical, then retry.";+ } else if (typeof error.response.data?.message === "string") {+ const apiMessage = error.response.data.message.trim();+ if (apiMessage) {+ message = `The profile was created, but attachment failed: ${apiMessage}`;+ }+ }+ }+ throw new Error(message);+ }+ setAttachedProfileId(profile.id);+ }+ const result = await refetchAppProfiles();+ const listedProfile = result.data?.find((option) => option.profileId === profile.id);+ if (result.isError || !listedProfile) {+ throw new Error(+ "The profile was attached, but the available profiles could not be refreshed. Retry to load and select it."+ );+ }+ slug = listedProfile.profileSlug;+ }+ setValue(+ "conditions.0.profileNames",+ [...new Set([...getValues("conditions.0.profileNames"), slug])],+ {+ shouldDirty: true,+ shouldValidate: true+ }+ );+ },+ { mode: applicationId ? "create-and-attach" : "create-only" });const profileOptions: ProfileOption[] = useMemo(() => {@@ -111,19 +181,31 @@ export const PolicyDetailsStep = ({ applicationId }: Props) => {Certificate Profiles <span className="text-danger">*</span></FieldLabel><FieldContent>- <FilterableSelect- inputId="policy-profile-names"- isMulti+ <Combobox+ ref={profileField.ref}+ id="policy-profile-names"+ onBlur={profileField.onBlur}+ multiple+ isError={Boolean(error)}isLoading={applicationId ? isAppProfilesLoading : isProfilesLoading}options={profileOptions}+ getOptionValue={(option) => option.value}+ getOptionLabel={(option) => option.label}value={profileField.value.map((slug) => ({ label: slug, value: slug }))}- onChange={(selected) => {- const selectedOptions = selected as ProfileOption[];- profileField.onChange(selectedOptions.map((opt) => opt.value));+ onValueChange={(selected) => {+ profileField.onChange(selected.map((opt) => opt.value));}}placeholder="Select certificate profiles..."- noOptionsMessage={() => "No profiles found"}- maxMenuHeight={150}+ emptyMessage="No profiles found"+ creation={+ (!applicationId || canManageAppProfiles) && profileCreation+ ? {+ ...profileCreation,+ emptyLabel: creationLabel,+ formatLabel: () => creationLabel+ }+ : undefined+ }/><FieldDescription isOpen={!error}>Policy applies to certificates issued from these selected profilesdiff --git a/frontend/src/pages/cert-manager/ApprovalsPage/components/RequestsTab/RequestDetailModal.tsx b/frontend/src/pages/cert-manager/ApprovalsPage/components/RequestsTab/RequestDetailModal.tsxindex 970f611aa6..7fdce27257 100644--- a/frontend/src/pages/cert-manager/ApprovalsPage/components/RequestsTab/RequestDetailModal.tsx+++ b/frontend/src/pages/cert-manager/ApprovalsPage/components/RequestsTab/RequestDetailModal.tsx@@ -1,4 +1,4 @@-import { useState } from "react";+import { useEffect, useRef, useState } from "react";import { useForm } from "react-hook-form";import { faCheck, faTimes, faUsers } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -7,8 +7,21 @@ import { formatDistance } from "date-fns";import { z } from "zod";import { createNotification } from "@app/components/notifications";-import { Button, FormControl, Modal, ModalContent, TextArea } from "@app/components/v2";-import { Badge } from "@app/components/v3";+import {+ Badge,+ Button,+ DiscardChangesAlertDialog,+ Field,+ FieldError,+ FieldLabel,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,+ TextArea+} from "@app/components/v3";import { useProject, useProjectPermission, useUser } from "@app/context";import { getMemberLabel } from "@app/helpers/members";import { useGetWorkspaceUsers, useListWorkspaceGroups } from "@app/hooks/api";@@ -22,6 +35,7 @@ import {useCancelApprovalRequest,useRejectApprovalRequest} from "@app/hooks/api/approvalRequests";+import { useDiscardChangesGuard } from "@app/hooks/useDiscardChangesGuard";import { UsePopUpState } from "@app/hooks/usePopUp";// Helper function to format validity TTL (e.g., "365d" -> "365 days")@@ -112,10 +126,39 @@ export const RequestDetailModal = ({ popUp, handlePopUpToggle }: Props) => {register,handleSubmit,reset,- formState: { errors }+ formState: { errors, isDirty, isSubmitting }} = useForm<TCommentForm>({- resolver: zodResolver(commentSchema)+ resolver: zodResolver(commentSchema),+ defaultValues: { comment: "" }});+ const isPending = isApproving || isRejecting || isCancelling || isSubmitting;+ const discardAction = useRef<() => void>(() => undefined);+ const { requestDiscard, isDiscardDialogOpen, setIsDiscardDialogOpen, confirmDiscard } =+ useDiscardChangesGuard({+ isDirty,+ onDiscard: () => discardAction.current()+ });+ const clearComment = () => {+ setShowCommentForm(null);+ reset();+ };+ const handleDismiss = () => {+ if (isPending) return;+ discardAction.current = () => {+ clearComment();+ handlePopUpToggle("requestDetail", false);+ };+ requestDiscard();+ };+ const handleCommentCancel = () => {+ if (isPending) return;+ discardAction.current = clearComment;+ requestDiscard();+ };+ useEffect(() => {+ setShowCommentForm(null);+ reset();+ }, [request?.id, isOpen, reset]);const getApproverLabel = (approverId: string, approverType: ApproverType) => {if (approverType === ApproverType.User) {@@ -162,7 +205,7 @@ export const RequestDetailModal = ({ popUp, handlePopUpToggle }: Props) => {};const handleApprove = async (data: TCommentForm) => {- if (!request) return;+ if (!request || isApproving || isRejecting || isCancelling) return;try {await approveRequest({@@ -187,7 +230,7 @@ export const RequestDetailModal = ({ popUp, handlePopUpToggle }: Props) => {};const handleReject = async (data: TCommentForm) => {- if (!request) return;+ if (!request || isApproving || isRejecting || isCancelling) return;try {await rejectRequest({@@ -212,7 +255,7 @@ export const RequestDetailModal = ({ popUp, handlePopUpToggle }: Props) => {};const handleCancel = async () => {- if (!request) return;+ if (!request || isPending) return;try {await cancelRequest({@@ -240,217 +283,263 @@ export const RequestDetailModal = ({ popUp, handlePopUpToggle }: Props) => {const showCancelButton = canUserCancel();return (- <Modal isOpen={isOpen} onOpenChange={(open) => handlePopUpToggle("requestDetail", open)}>- <ModalContent- title="Certificate Issuance Request"- subTitle="Review the details of this certificate request"- className="max-w-2xl"- >- <div className="space-y-6">- <div className="flex items-center justify-between">- <Badge variant={getStatusBadgeColor(request.status)} className="capitalize">- {request.status.split("-").join(" ")}- </Badge>- <span className="text-sm text-muted">- Requested{" "}- {formatDistance(new Date(request.createdAt), new Date(), { addSuffix: true })}- </span>- </div>+ <Sheet+ open={isOpen}+ onOpenChange={(open) => {+ if (!open) handleDismiss();+ }}+ >+ <SheetContent size="form" isPending={isPending}>+ <SheetHeader>+ <SheetTitle>Certificate Issuance Request</SheetTitle>+ <SheetDescription>Review the details of this certificate request.</SheetDescription>+ </SheetHeader>+ <form+ className="contents"+ onSubmit={async (event) => {+ event.preventDefault();+ if (!showCommentForm || isPending) return;+ await handleSubmit(showCommentForm === "approve" ? handleApprove : handleReject)(event);+ }}+ >+ <div className="min-h-0 thin-scrollbar flex-1 space-y-6 overflow-y-auto p-4">+ <div className="flex items-center justify-between">+ <Badge variant={getStatusBadgeColor(request.status)} className="capitalize">+ {request.status.split("-").join(" ")}+ </Badge>+ <span className="text-sm text-muted">+ Requested{" "}+ {formatDistance(new Date(request.createdAt), new Date(), { addSuffix: true })}+ </span>+ </div>- <div>- <h4 className="mb-2 text-sm font-normal text-foreground-secondary">Requester</h4>- <div className="rounded border border-border-control bg-surface-hover p-3">- <div className="text-sm font-medium text-foreground">- {request.requesterName || "Unknown"}+ <div>+ <h4 className="mb-2 text-sm font-normal text-foreground-secondary">Requester</h4>+ <div className="rounded border border-border-control bg-surface-hover p-3">+ <div className="text-sm font-medium text-foreground">+ {request.requesterName || "Unknown"}+ </div>+ <div className="text-xs text-muted">{request.requesterEmail}</div></div>- <div className="text-xs text-muted">{request.requesterEmail}</div></div>- </div>- <div>- <h4 className="mb-2 text-sm font-normal text-foreground-secondary">- Certificate Details- </h4>- <div className="space-y-2 rounded border border-border-control bg-surface-hover p-3">- <div className="flex justify-between">- <span className="text-sm text-muted">Profile</span>- <span className="text-sm text-foreground-secondary">{requestData.profileName}</span>- </div>- {requestData.certificateRequest?.commonName && (+ <div>+ <h4 className="mb-2 text-sm font-normal text-foreground-secondary">+ Certificate Details+ </h4>+ <div className="space-y-2 rounded border border-border-control bg-surface-hover p-3"><div className="flex justify-between">- <span className="text-sm text-muted">Common Name</span>+ <span className="text-sm text-muted">Profile</span><span className="text-sm text-foreground-secondary">- {requestData.certificateRequest.commonName}+ {requestData.profileName}</span></div>- )}- <div className="flex justify-between">- <span className="text-sm text-muted">Validity</span>- <span className="text-sm text-foreground-secondary">- {requestData.certificateRequest?.validity?.ttl- ? formatValidity(requestData.certificateRequest.validity.ttl)- : "Not specified"}- </span>- </div>- {requestData.certificateRequest?.domainComponents &&- requestData.certificateRequest.domainComponents.length > 0 && (- <div>- <span className="text-sm text-muted">Domain Components</span>- <div className="mt-1 flex flex-wrap gap-1">- {requestData.certificateRequest.domainComponents.map((dc) => (- <span- key={dc}- className="rounded bg-surface-active px-2 py-0.5 text-xs text-foreground-secondary"- >- {dc}- </span>- ))}- </div>+ {requestData.certificateRequest?.commonName && (+ <div className="flex justify-between">+ <span className="text-sm text-muted">Common Name</span>+ <span className="text-sm text-foreground-secondary">+ {requestData.certificateRequest.commonName}+ </span></div>)}- {requestData.certificateRequest?.altNames &&- requestData.certificateRequest.altNames.length > 0 && (- <div>- <span className="text-sm text-muted">Alt Names</span>- <div className="mt-1 flex flex-wrap gap-1">- {requestData.certificateRequest.altNames.map(- (san: { type: string; value: string }) => (+ <div className="flex justify-between">+ <span className="text-sm text-muted">Validity</span>+ <span className="text-sm text-foreground-secondary">+ {requestData.certificateRequest?.validity?.ttl+ ? formatValidity(requestData.certificateRequest.validity.ttl)+ : "Not specified"}+ </span>+ </div>+ {requestData.certificateRequest?.domainComponents &&+ requestData.certificateRequest.domainComponents.length > 0 && (+ <div>+ <span className="text-sm text-muted">Domain Components</span>+ <div className="mt-1 flex flex-wrap gap-1">+ {requestData.certificateRequest.domainComponents.map((dc) => (<span- key={`${san.type}-${san.value}`}+ key={dc}className="rounded bg-surface-active px-2 py-0.5 text-xs text-foreground-secondary">- {san.type}: {san.value}+ {dc}</span>- )- )}+ ))}+ </div></div>- </div>- )}+ )}+ {requestData.certificateRequest?.altNames &&+ requestData.certificateRequest.altNames.length > 0 && (+ <div>+ <span className="text-sm text-muted">Alt Names</span>+ <div className="mt-1 flex flex-wrap gap-1">+ {requestData.certificateRequest.altNames.map(+ (san: { type: string; value: string }) => (+ <span+ key={`${san.type}-${san.value}`}+ className="rounded bg-surface-active px-2 py-0.5 text-xs text-foreground-secondary"+ >+ {san.type}: {san.value}+ </span>+ )+ )}+ </div>+ </div>+ )}+ </div></div>- </div>- {request.justification && (- <div>- <h4 className="mb-2 text-sm font-normal text-foreground-secondary">Justification</h4>- <div className="rounded border border-border-control bg-surface-hover p-3 text-sm text-label">- {request.justification}+ {request.justification && (+ <div>+ <h4 className="mb-2 text-sm font-normal text-foreground-secondary">+ Justification+ </h4>+ <div className="rounded border border-border-control bg-surface-hover p-3 text-sm text-label">+ {request.justification}+ </div></div>- </div>- )}-- <div>- <h4 className="mb-2 text-sm font-normal text-foreground-secondary">- Approval Progress- </h4>- <div className="space-y-2">- {request.steps.map((step, index) => (- <div- key={step.id}- className="rounded border border-border-control bg-surface-hover p-3"- >- <div className="mb-2 flex items-center justify-between">- <div className="flex items-center gap-2">- <span- className={`flex h-6 w-6 items-center justify-center rounded-full text-xs font-semibold ${getStepNumberClass(step.status)}`}- >- {index + 1}- </span>- <span className="text-sm font-medium text-foreground-secondary">- {step.name || `Step ${index + 1}`}- </span>- </div>- <Badge variant={getStepBadgeVariant(step.status)} className="capitalize">- {step.status.split("-").join(" ")}- </Badge>- </div>- <div className="text-xs text-muted">- {step.approvals.length} of {step.requiredApprovals} approvals- </div>- {step.approvals.length > 0 && (- <div className="mt-2 flex flex-wrap gap-1">- {step.approvals.map((approval) => (- <div- key={approval.id}- className="flex items-center gap-1 rounded bg-success/10 px-2 py-0.5 text-xs text-success"+ )}++ <div>+ <h4 className="mb-2 text-sm font-normal text-foreground-secondary">+ Approval Progress+ </h4>+ <div className="space-y-2">+ {request.steps.map((step, index) => (+ <div+ key={step.id}+ className="rounded border border-border-control bg-surface-hover p-3"+ >+ <div className="mb-2 flex items-center justify-between">+ <div className="flex items-center gap-2">+ <span+ className={`flex h-6 w-6 items-center justify-center rounded-full text-xs font-semibold ${getStepNumberClass(step.status)}`}>- <FontAwesomeIcon icon={faUsers} />- {getApproverLabel(approval.approverUserId, ApproverType.User)}- </div>- ))}+ {index + 1}+ </span>+ <span className="text-sm font-medium text-foreground-secondary">+ {step.name || `Step ${index + 1}`}+ </span>+ </div>+ <Badge variant={getStepBadgeVariant(step.status)} className="capitalize">+ {step.status.split("-").join(" ")}+ </Badge></div>- )}- </div>- ))}+ <div className="text-xs text-muted">+ {step.approvals.length} of {step.requiredApprovals} approvals+ </div>+ {step.approvals.length > 0 && (+ <div className="mt-2 flex flex-wrap gap-1">+ {step.approvals.map((approval) => (+ <div+ key={approval.id}+ className="flex items-center gap-1 rounded bg-success/10 px-2 py-0.5 text-xs text-success"+ >+ <FontAwesomeIcon icon={faUsers} />+ {getApproverLabel(approval.approverUserId, ApproverType.User)}+ </div>+ ))}+ </div>+ )}+ </div>+ ))}+ </div></div>- </div>- {showCommentForm && (- <form- onSubmit={handleSubmit(showCommentForm === "approve" ? handleApprove : handleReject)}- >- <FormControl- label="Comment (Optional)"- isError={Boolean(errors.comment)}- errorText={errors.comment?.message}- >- <TextArea {...register("comment")} placeholder="Add a comment..." rows={3} />- </FormControl>- <div className="mt-4 flex gap-2">+ {showCommentForm && (+ <Field data-invalid={Boolean(errors.comment)}>+ <FieldLabel htmlFor="approval-request-comment">Comment (Optional)</FieldLabel>+ <TextArea+ id="approval-request-comment"+ {...register("comment")}+ placeholder="Add a comment..."+ rows={3}+ maxLength={500}+ disabled={isPending}+ isError={Boolean(errors.comment)}+ aria-describedby={errors.comment ? "approval-request-comment-error" : undefined}+ />+ {errors.comment && (+ <FieldError id="approval-request-comment-error">+ {errors.comment.message}+ </FieldError>+ )}+ </Field>+ )}+ </div>+ <SheetFooter className="justify-end border-t">+ {showCommentForm ? (+ <>+ <Button+ type="button"+ variant="ghost"+ onClick={handleCommentCancel}+ isDisabled={isPending}+ >+ Cancel+ </Button><Buttontype="submit"- colorSchema={showCommentForm === "approve" ? "primary" : "danger"}- isLoading={isApproving || isRejecting}- isDisabled={isApproving || isRejecting}+ variant={showCommentForm === "approve" ? "project" : "danger"}+ isPending={isPending}+ isDisabled={isPending}>{showCommentForm === "approve" ? "Confirm Approve" : "Confirm Reject"}</Button>+ </>+ ) : (+ <><Buttontype="button"- variant="outline_bg"- onClick={() => {- setShowCommentForm(null);- reset();- }}+ variant="ghost"+ onClick={handleDismiss}+ isDisabled={isPending}>- Cancel+ Close</Button>- </div>- </form>- )}-- {!showCommentForm && (showApprovalButtons || showCancelButton) && (- <div className="flex gap-2 border-t border-border-control pt-4">- {showApprovalButtons && (- <>- <Button- leftIcon={<FontAwesomeIcon icon={faCheck} />}- onClick={() => setShowCommentForm("approve")}- >- Approve- </Button>+ {showCancelButton && (<Button- colorSchema="danger"- leftIcon={<FontAwesomeIcon icon={faTimes} />}- onClick={() => setShowCommentForm("reject")}+ type="button"+ variant="outline"+ onClick={handleCancel}+ isPending={isCancelling}+ isDisabled={isPending}>- Reject+ Cancel Request</Button>- </>- )}- {showCancelButton && (- <Button- variant="outline_bg"- onClick={handleCancel}- isLoading={isCancelling}- isDisabled={isCancelling}- >- Cancel Request- </Button>- )}- </div>- )}- </div>- </ModalContent>- </Modal>+ )}+ {showApprovalButtons && (+ <>+ <Button+ type="button"+ variant="danger"+ isDisabled={isPending}+ onClick={() => setShowCommentForm("reject")}+ >+ <FontAwesomeIcon icon={faTimes} />+ Reject+ </Button>+ <Button+ type="button"+ variant="project"+ isDisabled={isPending}+ onClick={() => setShowCommentForm("approve")}+ >+ <FontAwesomeIcon icon={faCheck} />+ Approve+ </Button>+ </>+ )}+ </>+ )}+ </SheetFooter>+ </form>+ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Changes?"+ description="Your unsaved request comment will be lost."+ />+ </SheetContent>+ </Sheet>);};diff --git a/frontend/src/pages/cert-manager/ApprovalsPage/components/RequestsTab/RequestsTab.tsx b/frontend/src/pages/cert-manager/ApprovalsPage/components/RequestsTab/RequestsTab.tsxindex fea38ab0a3..b5c5bd770b 100644--- a/frontend/src/pages/cert-manager/ApprovalsPage/components/RequestsTab/RequestsTab.tsx+++ b/frontend/src/pages/cert-manager/ApprovalsPage/components/RequestsTab/RequestsTab.tsx@@ -1,42 +1,49 @@import { useMemo, useState } from "react";import {- faCheckCircle,- faChevronRight,faExclamationCircle,faFileCircleQuestion,faFilter,- faMagnifyingGlass,faSearch} from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { useQuery } from "@tanstack/react-query";import { useNavigate } from "@tanstack/react-router";import { formatDistance } from "date-fns";-import { twMerge } from "tailwind-merge";import {+ Badge,+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,DropdownMenu,DropdownMenuContent,- DropdownMenuItem,DropdownMenuLabel,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,DropdownMenuTrigger,- DropdownSubMenu,- DropdownSubMenuContent,- DropdownSubMenuTrigger,- EmptyState,+ Empty,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,IconButton,- Input,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,Pagination,Table,- TableContainer,- TableSkeleton,- TBody,- Td,- Th,- THead,- Tr-} from "@app/components/v2";-import { Badge } from "@app/components/v3";+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+ TableSkeletonRows+} from "@app/components/v3";import { useOrganization, useProject, useProjectPermission, useUser } from "@app/context";import { getUserTablePreference, PreferenceKey } from "@app/helpers/userTablePreferences";import { usePagination } from "@app/hooks";@@ -148,147 +155,93 @@ export const RequestsTab = () => {const isTableFiltered = filter !== ApprovalRequestStatus.Pending;return (- <div className="mb-6 rounded-lg border border-border-control bg-surface-base p-4">- <div className="mb-4">- <div className="flex items-center gap-x-2">- <p className="text-xl font-medium text-foreground">Certificate Approval Requests</p>- </div>- <p className="text-sm text-label-secondary">- Review and manage certificate requests that require approval- </p>- </div>- <div>- <div className="flex gap-2">+ <Card className="mb-6">+ <CardHeader>+ <CardTitle>Certificate Approval Requests</CardTitle>+ <CardDescription>+ Review and manage certificate requests that require approval.+ </CardDescription>+ <div className="col-span-full flex gap-2"><DropdownMenu><DropdownMenuTrigger asChild><IconButton- ariaLabel="Filter Requests"- variant="plain"- size="sm"- className={twMerge(- "flex h-9.5 w-[2.6rem] items-center justify-center overflow-hidden border border-border-control bg-surface-raised p-0 transition-all hover:border-project/60 hover:bg-project/10",- isTableFiltered && "border-project/50 text-project"- )}+ aria-label="Filter Requests"+ variant={isTableFiltered ? "project" : "outline"}><FontAwesomeIcon icon={faFilter} /></IconButton></DropdownMenuTrigger>- <DropdownMenuContent align="start" className="p-0">+ <DropdownMenuContent align="start"><DropdownMenuLabel>Filter By</DropdownMenuLabel>- <DropdownMenuItem- onClick={(evt) => {- evt.preventDefault();- setFilter(ApprovalRequestStatus.Pending);+ <DropdownMenuRadioGroup+ value={filter}+ onValueChange={(value) => {+ setFilter(value as ApprovalRequestStatus);+ setPage(1);}}- icon={- filter === ApprovalRequestStatus.Pending && (- <FontAwesomeIcon icon={faCheckCircle} />- )- }- iconPos="right">- Open Requests- </DropdownMenuItem>- <DropdownSubMenu>- <DropdownSubMenuTrigger- iconPos="right"- icon={<FontAwesomeIcon icon={faChevronRight} size="sm" />}- >- Closed Requests- </DropdownSubMenuTrigger>- <DropdownSubMenuContent className="max-h-80 thin-scrollbar overflow-y-auto rounded-l-none">- <DropdownMenuLabel className="sticky top-0 bg-surface-base">- Filter by Status- </DropdownMenuLabel>- <DropdownMenuItem- onClick={(evt) => {- evt.preventDefault();- setFilter(ApprovalRequestStatus.Approved);- }}- icon={- filter === ApprovalRequestStatus.Approved && (- <FontAwesomeIcon icon={faCheckCircle} />- )- }- iconPos="right"- >- Approved- </DropdownMenuItem>- <DropdownMenuItem- onClick={(evt) => {- evt.preventDefault();- setFilter(ApprovalRequestStatus.Cancelled);- }}- icon={- filter === ApprovalRequestStatus.Cancelled && (- <FontAwesomeIcon icon={faCheckCircle} />- )- }- iconPos="right"- >- Cancelled- </DropdownMenuItem>- <DropdownMenuItem- onClick={(evt) => {- evt.preventDefault();- setFilter(ApprovalRequestStatus.Rejected);- }}- icon={- filter === ApprovalRequestStatus.Rejected && (- <FontAwesomeIcon icon={faCheckCircle} />- )- }- iconPos="right"- >- Rejected- </DropdownMenuItem>- <DropdownMenuItem- onClick={(evt) => {- evt.preventDefault();- setFilter(ApprovalRequestStatus.Expired);- }}- icon={- filter === ApprovalRequestStatus.Expired && (- <FontAwesomeIcon icon={faCheckCircle} />- )- }- iconPos="right"- >- Expired- </DropdownMenuItem>- </DropdownSubMenuContent>- </DropdownSubMenu>+ <DropdownMenuRadioItem value={ApprovalRequestStatus.Pending}>+ Open Requests+ </DropdownMenuRadioItem>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>Closed Requests</DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ <DropdownMenuLabel>Filter by Status</DropdownMenuLabel>+ <DropdownMenuRadioItem value={ApprovalRequestStatus.Approved}>+ Approved+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value={ApprovalRequestStatus.Cancelled}>+ Cancelled+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value={ApprovalRequestStatus.Rejected}>+ Rejected+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value={ApprovalRequestStatus.Expired}>+ Expired+ </DropdownMenuRadioItem>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ </DropdownMenuRadioGroup></DropdownMenuContent></DropdownMenu>- <Input- value={search}- onChange={(e) => setSearch(e.target.value)}- leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}- placeholder="Search certificate requests..."- />+ <InputGroup>+ <InputGroupAddon>+ <FontAwesomeIcon icon={faSearch} />+ </InputGroupAddon>+ <InputGroupInput+ value={search}+ onChange={(e) => {+ setSearch(e.target.value);+ setPage(1);+ }}+ placeholder="Search certificate requests..."+ />+ </InputGroup></div>- <TableContainer className="mt-4">+ </CardHeader>+ <CardContent>+ {isRequestsLoading || filteredRequests.length > 0 ? (<Table>- <THead>- <Tr>- <Th>Requester</Th>- <Th>Profile</Th>- <Th>Common Name</Th>- <Th>Status</Th>- <Th>Requested</Th>- </Tr>- </THead>- <TBody>- {isRequestsLoading && <TableSkeleton columns={5} innerKey="cert-approval-requests" />}+ <TableHeader>+ <TableRow>+ <TableHead>Requester</TableHead>+ <TableHead>Profile</TableHead>+ <TableHead>Common Name</TableHead>+ <TableHead>Status</TableHead>+ <TableHead>Requested</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {isRequestsLoading && <TableSkeletonRows columns={5} />}{!isRequestsLoading &&paginatedRequests.map((request) => {const needsApproval = checkIfUserNeedsToApprove(request, userId, userGroups);const requestData = request.requestData.requestData as CertRequestRequestData;return (- <Tr+ <TableRowkey={request.id}- className="h-14 cursor-pointer transition-colors hover:bg-surface-hover"+ className="cursor-pointer"onClick={() =>navigate({to: "/organizations/$orgId/cert-manager/approvals/$approvalRequestId",@@ -302,70 +255,66 @@ export const RequestsTab = () => {})}>- <Td>+ <TableCell><div><div className="text-sm font-medium text-foreground">{request.requesterName || "Unknown"}</div><div className="text-xs text-muted">{request.requesterEmail}</div></div>- </Td>- <Td>- <span className="text-sm text-foreground-secondary">- {requestData.profileName}- </span>- </Td>- <Td>- <span className="text-sm text-foreground-secondary">- {requestData.certificateRequest?.commonName || "-"}- </span>- </Td>- <Td>- <div className="flex items-center gap-2">- {needsApproval ? (- <div className="flex items-center gap-1 rounded bg-project/20 px-2 py-0.5 text-xs text-project">- <FontAwesomeIcon icon={faExclamationCircle} className="h-3 w-3" />- <span>Approval Required</span>- </div>- ) : (- <Badge- className="capitalize"- variant={getStatusBadgeColor(request.status)}- >- {request.status.split("-").join(" ")}- </Badge>- )}- </div>- </Td>- <Td>- <span className="text-sm text-muted">- {formatDistance(new Date(request.createdAt), new Date(), {- addSuffix: true- })}- </span>- </Td>- </Tr>+ </TableCell>+ <TableCell>{requestData.profileName}</TableCell>+ <TableCell>{requestData.certificateRequest?.commonName || "-"}</TableCell>+ <TableCell>+ {needsApproval ? (+ <Badge variant="warning">+ <FontAwesomeIcon icon={faExclamationCircle} />+ Approval Required+ </Badge>+ ) : (+ <Badge+ className="capitalize"+ variant={getStatusBadgeColor(request.status)}+ >+ {request.status.split("-").join(" ")}+ </Badge>+ )}+ </TableCell>+ <TableCell className="text-muted">+ {formatDistance(new Date(request.createdAt), new Date(), {+ addSuffix: true+ })}+ </TableCell>+ </TableRow>);})}- </TBody>+ </TableBody></Table>- {Boolean(filteredRequests.length) && (- <Pagination- count={filteredRequests.length}- page={page}- perPage={perPage}- onChangePage={setPage}- onChangePerPage={setPerPage}- />- )}- {!isRequestsLoading && !filteredRequests?.length && (- <EmptyState- title="No certificate approval requests found"- icon={requests.length ? faSearch : faFileCircleQuestion}- />- )}- </TableContainer>- </div>- </div>+ ) : (+ <Empty className="border">+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <FontAwesomeIcon icon={requests.length ? faSearch : faFileCircleQuestion} />+ </EmptyMedia>+ <EmptyTitle>No Certificate Approval Requests Found</EmptyTitle>+ </EmptyHeader>+ </Empty>+ )}+ </CardContent>+ {Boolean(filteredRequests.length) && (+ <CardFooter>+ <Pagination+ count={filteredRequests.length}+ page={page}+ perPage={perPage}+ onChangePage={setPage}+ onChangePerPage={(value) => {+ setPerPage(value);+ setPage(1);+ }}+ />+ </CardFooter>+ )}+ </Card>);};diff --git a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicyCustomExtensionsSection.tsx b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicyCustomExtensionsSection.tsxindex 3e4c9fca3e..4c27138a91 100644--- a/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicyCustomExtensionsSection.tsx+++ b/frontend/src/pages/cert-manager/CertificatePolicyDetailsByIDPage/components/PolicyCustomExtensionsSection.tsx@@ -48,7 +48,7 @@ export const PolicyCustomExtensionsSection = ({ policy }: Props) => {{policy.customExtensions.map((rule) => (<divkey={rule.oid}- className="flex flex-col gap-y-3 border-b border-mineshaft-700 pb-3 last:border-b-0 last:pb-0"+ className="flex flex-col gap-y-3 border-b border-border pb-3 last:border-b-0 last:pb-0"><div className="flex flex-wrap items-center gap-2"><span className="text-sm font-medium text-foreground">@@ -58,7 +58,7 @@ export const PolicyCustomExtensionsSection = ({ policy }: Props) => {<Badge variant="neutral">{CRITICALITY_LABEL[rule.critical]}</Badge>)}</div>- <p className="font-mono text-xs text-mineshaft-400">{rule.oid}</p>+ <p className="font-mono text-xs text-muted">{rule.oid}</p>{Boolean(rule.required?.length) && (<RuleList label="Required" values={rule.required ?? []} />)}diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificate-import-fields.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/certificate-import-fields.tsxindex dcd6ed989a..9cf31714ef 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/certificate-import-fields.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificate-import-fields.tsx@@ -1,5 +1,6 @@import { useState } from "react";import { useQueryClient } from "@tanstack/react-query";+import axios from "axios";import { Combobox, Input } from "@app/components/v3";import { useDigiCertConnectionListOrders } from "@app/hooks/api/appConnections/digicert";@@ -99,10 +100,21 @@ export const CertificateProfileSelect = ({if (attachedProfileId !== profile.id) {try {await attach.mutateAsync({ applicationId, profileIds: [profile.id] });- } catch {- throw new Error(- "The profile was created, but attachment failed. Retry to attach it to this application."- );+ } catch (error) {+ let message =+ "The profile was created, but attachment failed. Retry to attach it to this application.";+ if (axios.isAxiosError<{ message?: unknown }>(error)) {+ if (!error.response) {+ message =+ "The profile was created, but no response was received for the attachment request. Check your connection to Infisical, then retry.";+ } else if (typeof error.response.data?.message === "string") {+ const apiMessage = error.response.data.message.trim();+ if (apiMessage) {+ message = `The profile was created, but attachment failed: ${apiMessage}`;+ }+ }+ }+ throw new Error(message);}setAttachedProfileId(profile.id);}diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CertificatePolicyOption.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CertificatePolicyOption.tsxdeleted file mode 100644index df1d4c8494..0000000000--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CertificatePolicyOption.tsx+++ /dev/null@@ -1,30 +0,0 @@-import { components, OptionProps } from "react-select";-import { CheckIcon, PlusIcon } from "lucide-react";--import { TCertificatePolicy } from "@app/hooks/api/certificatePolicies";--type PolicyOptionData = TCertificatePolicy | { id: "_create"; name: string };--export const CertificatePolicyOption = ({- isSelected,- children,- ...props-}: OptionProps<PolicyOptionData>) => {- const isCreateOption = props.data.id === "_create";-- return (- <components.Option isSelected={isSelected} {...props}>- {isCreateOption ? (- <div className="flex cursor-pointer flex-row items-center gap-x-1.5 text-muted">- <PlusIcon className="size-4 shrink-0" />- <span>Add Certificate Policy</span>- </div>- ) : (- <div className="flex cursor-pointer flex-row items-center justify-between">- <p className="truncate">{children}</p>- {isSelected && <CheckIcon className="ml-2 size-4 shrink-0" />}- </div>- )}- </components.Option>- );-};diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/RevealAcmeEabSecretModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/RevealAcmeEabSecretModal.tsxdeleted file mode 100644index 970918cc03..0000000000--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/RevealAcmeEabSecretModal.tsx+++ /dev/null@@ -1,135 +0,0 @@-import { faCheck, faCopy } from "@fortawesome/free-solid-svg-icons";-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";--import {- Alert,- AlertDescription,- FormLabel,- IconButton,- Input,- Modal,- ModalContent,- Spinner-} from "@app/components/v2";-import { useToggle } from "@app/hooks";-import { TCertificateProfileWithDetails } from "@app/hooks/api/certificateProfiles";-import { useRevealAcmeEabSecret } from "@app/hooks/api/certificateProfiles/queries";--const RESET_COPIED_DELAY = 1 * 1000;--type Props = {- isOpen: boolean;- onClose: () => void;- profile: TCertificateProfileWithDetails;-};--export const RevealAcmeEabSecretModal = ({ isOpen, onClose, profile }: Props) => {- const [isAcmeDirectoryUrlCopied, setIsAcmeDirectoryUrlCopied] = useToggle(false);- const [isEabKidCopied, setIsEabKidCopied] = useToggle(false);- const [isEabSecretCopied, setIsEabSecretCopied] = useToggle(false);- const revealAcmeEabSecret = useRevealAcmeEabSecret({ profileId: profile.id });- const { data, isLoading, isError, error } = revealAcmeEabSecret;- const { directoryUrl } = profile.acmeConfig!;- const { eabKid, eabSecret } = data ?? { eabKid: "", eabSecret: "" };-- return (- <Modal- isOpen={isOpen}- onOpenChange={(open) => {- if (!open) {- onClose();- }- }}- >- <ModalContent- title="Reveal ACME EAB"- subTitle="To issue certificates automatically, your ACME client needs the following details."- >- {isLoading && (- <div className="flex items-center justify-center py-4">- <Spinner size="sm" />- </div>- )}- {isError && (- <Alert variant="danger">- <AlertDescription>Failed to reveal EAB secret: {error.message}</AlertDescription>- </Alert>- )}- {data && (- <>- <FormLabel- label="ACME Directory URL"- tooltipText="The ACME directory URL for your ACME client to issue certificates."- />- <div className="flex gap-2">- <Input value={directoryUrl} disabled />- <IconButton- ariaLabel="copy"- variant="outline_bg"- colorSchema="secondary"- onClick={() => {- navigator.clipboard.writeText(directoryUrl);- setIsAcmeDirectoryUrlCopied.on();- setTimeout(() => {- setIsAcmeDirectoryUrlCopied.off();- }, RESET_COPIED_DELAY);- }}- className="w-10"- >- <FontAwesomeIcon icon={isAcmeDirectoryUrlCopied ? faCheck : faCopy} />- </IconButton>- </div>-- <FormLabel- label="EAB KID"- className="mt-4"- tooltipText="The EAB Key Identifier (KID) for your ACME client to authenticate when registering a new account."- />- <div className="flex gap-2">- <Input value={eabKid} disabled />- <IconButton- ariaLabel="copy"- variant="outline_bg"- colorSchema="secondary"- onClick={() => {- navigator.clipboard.writeText(eabKid);- setIsEabKidCopied.on();- setTimeout(() => {- setIsEabKidCopied.off();- }, RESET_COPIED_DELAY);- }}- className="w-10"- >- <FontAwesomeIcon icon={isEabKidCopied ? faCheck : faCopy} />- </IconButton>- </div>-- <FormLabel- label="EAB Secret"- className="mt-4"- tooltipText="The EAB Secret for your ACME client to authenticate when registering a new account."- />- <div className="flex gap-2">- <Input value={eabSecret} isDisabled />- <IconButton- ariaLabel="copy"- variant="outline_bg"- colorSchema="secondary"- onClick={() => {- navigator.clipboard.writeText(eabSecret);- setIsEabSecretCopied.on();- setTimeout(() => {- setIsEabSecretCopied.off();- }, RESET_COPIED_DELAY);- }}- className="w-10"- >- <FontAwesomeIcon icon={isEabSecretCopied ? faCheck : faCopy} />- </IconButton>- </div>- </>- )}- </ModalContent>- </Modal>- );-};diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ScepDetailsModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ScepDetailsModal.tsxdeleted file mode 100644index 3f264be850..0000000000--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ScepDetailsModal.tsx+++ /dev/null@@ -1,136 +0,0 @@-import { faCheck, faCopy, faDownload } from "@fortawesome/free-solid-svg-icons";-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";--import { FormLabel, IconButton, Input, Modal, ModalContent } from "@app/components/v2";-import { downloadFile } from "@app/helpers/download";-import { useToggle } from "@app/hooks";-import {- ScepChallengeType,- TCertificateProfileWithDetails-} from "@app/hooks/api/certificateProfiles";--const RESET_COPIED_DELAY = 1 * 1000;--type Props = {- isOpen: boolean;- onClose: () => void;- profile: TCertificateProfileWithDetails;-};--export const ScepDetailsModal = ({ isOpen, onClose, profile }: Props) => {- const [isUrlCopied, setIsUrlCopied] = useToggle(false);- const [isChallengeUrlCopied, setIsChallengeUrlCopied] = useToggle(false);-- const { scepConfig } = profile;- const scepEndpointUrl = scepConfig?.scepEndpointUrl ?? "";-- if (!scepConfig) {- return (- <Modal isOpen={isOpen} onOpenChange={(open) => !open && onClose()}>- <ModalContent title="SCEP Enrollment Details">- <p className="text-sm text-muted">- SCEP configuration is not available for this profile.- </p>- </ModalContent>- </Modal>- );- }-- const raCertPem = scepConfig.raCertificatePem;- const raCertExpiresAt = scepConfig.raCertExpiresAt- ? new Date(scepConfig.raCertExpiresAt).toLocaleDateString("en-US", {- year: "numeric",- month: "long",- day: "numeric"- })- : "Unknown";-- return (- <Modal- isOpen={isOpen}- onOpenChange={(open) => {- if (!open) {- onClose();- }- }}- >- <ModalContent- title="SCEP Enrollment Details"- subTitle="To enroll devices via SCEP, configure your MDM or device with the following details."- >- <FormLabel- label="SCEP Endpoint URL"- tooltipText="The URL your SCEP client or MDM should point to for certificate enrollment."- />- <div className="flex gap-2">- <Input value={scepEndpointUrl} isDisabled />- <IconButton- ariaLabel="copy"- variant="outline_bg"- colorSchema="secondary"- onClick={() => {- navigator.clipboard.writeText(scepEndpointUrl);- setIsUrlCopied.on();- setTimeout(() => {- setIsUrlCopied.off();- }, RESET_COPIED_DELAY);- }}- className="w-10"- >- <FontAwesomeIcon icon={isUrlCopied ? faCheck : faCopy} />- </IconButton>- </div>-- {scepConfig.challengeType === ScepChallengeType.DYNAMIC &&- scepConfig.challengeEndpointUrl && (- <>- <FormLabel- label="Challenge Endpoint URL"- className="mt-4"- tooltipText="The authenticated API endpoint to generate dynamic SCEP challenges. Use this URL in your MDM webhook configuration (e.g., JAMF SCEPChallenge)."- />- <div className="flex gap-2">- <Input value={scepConfig.challengeEndpointUrl} isDisabled />- <IconButton- ariaLabel="copy"- variant="outline_bg"- colorSchema="secondary"- onClick={() => {- navigator.clipboard.writeText(scepConfig.challengeEndpointUrl!);- setIsChallengeUrlCopied.on();- setTimeout(() => {- setIsChallengeUrlCopied.off();- }, RESET_COPIED_DELAY);- }}- className="w-10"- >- <FontAwesomeIcon icon={isChallengeUrlCopied ? faCheck : faCopy} />- </IconButton>- </div>- </>- )}-- <FormLabel- label="RA Certificate"- className="mt-4"- tooltipText="The Registration Authority certificate used by SCEP clients."- />- <div className="flex items-center justify-between rounded-md border border-border-control bg-surface-base px-4 py-3">- <p className="text-xs text-muted">Expires: {raCertExpiresAt}</p>- <IconButton- ariaLabel="download RA certificate"- variant="outline_bg"- colorSchema="secondary"- onClick={() =>- downloadFile(raCertPem, `${profile.slug}-ra-cert.pem`, "application/x-pem-file")- }- className="flex items-center gap-2"- >- <FontAwesomeIcon icon={faDownload} />- <span className="text-sm">Download PEM</span>- </IconButton>- </div>- </ModalContent>- </Modal>- );-};diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/useProfileCreation.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/useProfileCreation.tsxindex b1b4826c1e..9646f24c03 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/useProfileCreation.tsx+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/useProfileCreation.tsx@@ -15,9 +15,11 @@ import { CreateProfileForm } from "./CreateProfileModal";type ProfileOption = { value: string; label: string };export const useProfileCreation = <TOption = ProfileOption,>(- onCreated: (profile: TCertificateProfile) => void | Promise<void>+ onCreated: (profile: TCertificateProfile) => void | Promise<void>,+ { mode = "create-and-attach" }: { mode?: "create-only" | "create-and-attach" } = {}): ComboboxSheetCreationConfig<TOption> | undefined => {const { permission } = useProjectPermission();+ const requiresAttachment = mode === "create-and-attach";const [isDirty, setIsDirty] = useState(false);const [isPending, setIsPending] = useState(false);const cancelRef = useRef(() => {});@@ -44,10 +46,11 @@ export const useProfileCreation = <TOption = ProfileOption,>(ProjectPermissionCertificateProfileActions.Create,ProjectPermissionSub.CertificateProfiles) ||- !permission.can(- ProjectPermissionCertificateProfileActions.ManageApplicationAttachments,- ProjectPermissionSub.CertificateProfiles- )+ (requiresAttachment &&+ !permission.can(+ ProjectPermissionCertificateProfileActions.ManageApplicationAttachments,+ ProjectPermissionSub.CertificateProfiles+ )))return undefined;@@ -65,7 +68,7 @@ export const useProfileCreation = <TOption = ProfileOption,>(onClose={complete}onCancel={() => requestCancel(cancel)}onComplete={(profile) => {- if (!canAttachProfile(profile.slug)) {+ if (requiresAttachment && !canAttachProfile(profile.slug)) {throw new Error("The profile was created, but you no longer have permission to attach it to an application.");@@ -77,9 +80,10 @@ export const useProfileCreation = <TOption = ProfileOption,>(permission.can(ProjectPermissionCertificateProfileActions.Create,subject(ProjectPermissionSub.CertificateProfiles, { slug })- ) && canAttachProfile(slug)+ ) &&+ (!requiresAttachment || canAttachProfile(slug))? undefined- : "You don't have permission to create and attach a profile with this name. Choose an allowed name."+ : `You don't have permission to ${requiresAttachment ? "create and attach" : "create"} a profile with this name. Choose an allowed name.`}onDirtyChange={setIsDirty}onPendingChange={setIsPending}