form validation improvements

This commit is contained in:
miloschwartz
2026-06-05 14:55:27 -07:00
parent ea8eaf9736
commit 8ee520dbb5
13 changed files with 1312 additions and 972 deletions
+7 -2
View File
@@ -2032,13 +2032,13 @@
"healthCheckUnknown": "Unknown", "healthCheckUnknown": "Unknown",
"healthCheck": "Health Check", "healthCheck": "Health Check",
"configureHealthCheck": "Configure Health Check", "configureHealthCheck": "Configure Health Check",
"configureHealthCheckDescription": "Set up health monitoring for {target}", "configureHealthCheckDescription": "Set up monitoring for your resource to ensure it is always available",
"enableHealthChecks": "Enable Health Checks", "enableHealthChecks": "Enable Health Checks",
"healthCheckDisabledStateDescription": "When disabled, the site will not perform health checks and the state will be considered unknown.", "healthCheckDisabledStateDescription": "When disabled, the site will not perform health checks and the state will be considered unknown.",
"enableHealthChecksDescription": "Monitor the health of this target. You can monitor a different endpoint than the target if required.", "enableHealthChecksDescription": "Monitor the health of this target. You can monitor a different endpoint than the target if required.",
"healthScheme": "Method", "healthScheme": "Method",
"healthSelectScheme": "Select Method", "healthSelectScheme": "Select Method",
"healthCheckPortInvalid": "Health check port must be between 1 and 65535", "healthCheckPortInvalid": "Port must be between 1 and 65535",
"healthCheckPath": "Path", "healthCheckPath": "Path",
"healthHostname": "IP / Host", "healthHostname": "IP / Host",
"healthPort": "Port", "healthPort": "Port",
@@ -2080,6 +2080,11 @@
"sshServerDestination": "Server Destination", "sshServerDestination": "Server Destination",
"sshServerDestinationDescription": "Configure the destination of the SSH server", "sshServerDestinationDescription": "Configure the destination of the SSH server",
"destination": "Destination", "destination": "Destination",
"destinationRequired": "Destination is required.",
"domainRequired": "Domain is required.",
"proxyPortRequired": "Port is required.",
"invalidPathConfiguration": "Invalid path configuration.",
"invalidRewritePathConfiguration": "Invalid rewrite path configuration.",
"bgTargetMultiSiteDisclaimer": "Selecting multiple sites enables resilient routing and failover for high availability.", "bgTargetMultiSiteDisclaimer": "Selecting multiple sites enables resilient routing and failover for high availability.",
"roleAllowSsh": "Allow SSH", "roleAllowSsh": "Allow SSH",
"roleAllowSshAllow": "Allow", "roleAllowSshAllow": "Allow",
@@ -11,22 +11,23 @@ import {
} from "@app/components/Settings"; } from "@app/components/Settings";
import { BrowserGatewayTargetForm } from "@app/components/BrowserGatewayTargetForm"; import { BrowserGatewayTargetForm } from "@app/components/BrowserGatewayTargetForm";
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert"; import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
import { type Selectedsite } from "@app/components/site-selector";
import { Button } from "@app/components/ui/button"; import { Button } from "@app/components/ui/button";
import { Form } from "@app/components/ui/form";
import { toast } from "@app/hooks/useToast"; import { toast } from "@app/hooks/useToast";
import { useResourceContext } from "@app/hooks/useResourceContext"; import { useResourceContext } from "@app/hooks/useResourceContext";
import { useEnvContext } from "@app/hooks/useEnvContext"; import { useEnvContext } from "@app/hooks/useEnvContext";
import { usePaidStatus } from "@app/hooks/usePaidStatus"; import { usePaidStatus } from "@app/hooks/usePaidStatus";
import { createBrowserGatewayTargetFormSchema } from "@app/lib/browserGatewayTargetFormSchema";
import type { BrowserGatewayTargetFormValues } from "@app/lib/browserGatewayTargetFormSchema";
import { tierMatrix, TierFeature } from "@server/lib/billing/tierMatrix"; import { tierMatrix, TierFeature } from "@server/lib/billing/tierMatrix";
import { createApiClient } from "@app/lib/api"; import { createApiClient } from "@app/lib/api";
import { formatAxiosError } from "@app/lib/api/formatAxiosError"; import { formatAxiosError } from "@app/lib/api/formatAxiosError";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { use, useActionState, useEffect, useState } from "react"; import { use, useActionState, useMemo, useState } from "react";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { GetResourceResponse } from "@server/routers/resource"; import { GetResourceResponse } from "@server/routers/resource";
import type { ResourceContextType } from "@app/contexts/resourceContext"; import type { ResourceContextType } from "@app/contexts/resourceContext";
@@ -35,79 +36,7 @@ type ExistingTarget = {
siteId: number; siteId: number;
}; };
const sshFormSchema = z.object({ type BgTarget = {
authDaemonPort: z.string().refine(
(val) => {
if (!val) return true;
const n = Number(val);
return Number.isInteger(n) && n >= 1 && n <= 65535;
},
{ message: "Port must be between 1 and 65535" }
)
});
export default function SshSettingsPage(props: {
params: Promise<{ orgId: string }>;
}) {
const params = use(props.params);
const { resource, updateResource } = useResourceContext();
const { isPaidUser } = usePaidStatus();
const disabled = !isPaidUser(
tierMatrix[TierFeature.AdvancedPublicResources]
);
return (
<SettingsContainer>
<PaidFeaturesAlert
tiers={tierMatrix[TierFeature.AdvancedPublicResources]}
/>
<SshServerForm
orgId={params.orgId}
resource={resource}
updateResource={updateResource}
disabled={disabled}
/>
</SettingsContainer>
);
}
function SshServerForm({
orgId,
resource,
updateResource,
disabled
}: {
orgId: string;
resource: GetResourceResponse;
updateResource: ResourceContextType["updateResource"];
disabled: boolean;
}) {
const t = useTranslations();
const api = createApiClient(useEnvContext());
const router = useRouter();
// Standard mode: multi-site
const [selectedSites, setSelectedSites] = useState<Selectedsite[]>([]);
const [bgDestination, setBgDestination] = useState("");
const [bgDestinationPort, setBgDestinationPort] = useState("22");
const [existingTargets, setExistingTargets] = useState<ExistingTarget[]>(
[]
);
// Native mode: single site
const [selectedNativeSite, setSelectedNativeSite] =
useState<Selectedsite | null>(null);
const [nativeExistingTarget, setNativeExistingTarget] =
useState<ExistingTarget | null>(null);
const { data: bgTargetsResponse } = useQuery({
queryKey: ["browserGatewayTargets", resource.resourceId, orgId],
queryFn: async () => {
const res = await api.get(
`/org/${orgId}/resource/${resource.resourceId}/browser-gateway-targets`
);
return res.data.data as {
targets: Array<{
browserGatewayTargetId: number; browserGatewayTargetId: number;
resourceId: number; resourceId: number;
siteId: number; siteId: number;
@@ -115,41 +44,110 @@ function SshServerForm({
type: string; type: string;
destination: string; destination: string;
destinationPort: number; destinationPort: number;
}>;
}; };
type BgTargetsResponse = {
targets: BgTarget[];
};
export default function RdpSettingsPage(props: {
params: Promise<{ orgId: string }>;
}) {
const params = use(props.params);
const { resource, updateResource } = useResourceContext();
const { isPaidUser } = usePaidStatus();
const api = createApiClient(useEnvContext());
const disabled = !isPaidUser(
tierMatrix[TierFeature.AdvancedPublicResources]
);
const { data: bgTargetsResponse, isLoading: isLoadingTargets } = useQuery({
queryKey: ["browserGatewayTargets", resource.resourceId, params.orgId],
queryFn: async () => {
const res = await api.get(
`/org/${params.orgId}/resource/${resource.resourceId}/browser-gateway-targets`
);
return res.data.data as BgTargetsResponse;
} }
}); });
useEffect(() => { if (isLoadingTargets) {
if (!bgTargetsResponse?.targets?.length) return; return null;
const targets = bgTargetsResponse.targets; }
const first = targets[0];
setBgDestination(first.destination); return (
setBgDestinationPort(String(first.destinationPort)); <SettingsContainer>
setExistingTargets( <PaidFeaturesAlert
targets.map((t) => ({ tiers={tierMatrix[TierFeature.AdvancedPublicResources]}
browserGatewayTargetId: t.browserGatewayTargetId, />
siteId: t.siteId <RdpServerForm
})) orgId={params.orgId}
resource={resource}
updateResource={updateResource}
disabled={disabled}
bgTargetsResponse={bgTargetsResponse ?? { targets: [] }}
/>
</SettingsContainer>
); );
setSelectedSites( }
targets.map((t) => ({
siteId: t.siteId, function RdpServerForm({
name: t.siteName ?? String(t.siteId), orgId,
resource,
disabled,
bgTargetsResponse
}: {
orgId: string;
resource: GetResourceResponse;
updateResource: ResourceContextType["updateResource"];
disabled: boolean;
bgTargetsResponse: BgTargetsResponse;
}) {
const t = useTranslations();
const api = createApiClient(useEnvContext());
const router = useRouter();
const targets = bgTargetsResponse.targets;
const firstTarget = targets[0];
const formSchema = useMemo(
() => createBrowserGatewayTargetFormSchema(t),
[t]
);
const form = useForm<BrowserGatewayTargetFormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
selectedSites: targets.map((target) => ({
siteId: target.siteId,
name: target.siteName ?? String(target.siteId),
type: "newt" as const type: "newt" as const
})),
destination: firstTarget?.destination ?? "",
destinationPort: firstTarget
? String(firstTarget.destinationPort)
: "3389"
}
});
const [existingTargets, setExistingTargets] = useState<ExistingTarget[]>(
() =>
targets.map((target) => ({
browserGatewayTargetId: target.browserGatewayTargetId,
siteId: target.siteId
})) }))
); );
}, [bgTargetsResponse]);
const [, formAction, isSubmitting] = useActionState(save, null); const [, formAction, isSubmitting] = useActionState(save, null);
async function save() { async function save() {
const isValid = await form.trigger();
if (!isValid) return;
const { selectedSites, destination, destinationPort } =
form.getValues();
try { try {
if (bgDestination && bgDestinationPort) { const selectedSiteIds = new Set(selectedSites.map((s) => s.siteId));
const selectedSiteIds = new Set(
selectedSites.map((s) => s.siteId)
);
const existingSiteIds = new Set( const existingSiteIds = new Set(
existingTargets.map((t) => t.siteId) existingTargets.map((t) => t.siteId)
); );
@@ -174,8 +172,8 @@ function SshServerForm({
`/org/${orgId}/browser-gateway-target/${t.browserGatewayTargetId}`, `/org/${orgId}/browser-gateway-target/${t.browserGatewayTargetId}`,
{ {
type: "rdp", type: "rdp",
destination: bgDestination, destination,
destinationPort: Number(bgDestinationPort), destinationPort: Number(destinationPort),
siteId: t.siteId siteId: t.siteId
} }
) )
@@ -192,20 +190,18 @@ function SshServerForm({
{ {
siteId: s.siteId, siteId: s.siteId,
type: "rdp", type: "rdp",
destination: bgDestination, destination,
destinationPort: Number(bgDestinationPort) destinationPort: Number(destinationPort)
} }
) )
) )
); );
const newTargets: ExistingTarget[] = created.map((res, i) => ({ const newTargets: ExistingTarget[] = created.map((res, i) => ({
browserGatewayTargetId: browserGatewayTargetId: res.data.data.browserGatewayTargetId,
res.data.data.browserGatewayTargetId,
siteId: toCreate[i].siteId siteId: toCreate[i].siteId
})); }));
setExistingTargets([...toUpdate, ...newTargets]); setExistingTargets([...toUpdate, ...newTargets]);
}
toast({ toast({
title: t("settingsUpdated"), title: t("settingsUpdated"),
@@ -237,17 +233,16 @@ function SshServerForm({
disabled={disabled} disabled={disabled}
className={disabled ? "opacity-50 pointer-events-none" : ""} className={disabled ? "opacity-50 pointer-events-none" : ""}
> >
<Form {...form}>
<SettingsSectionBody> <SettingsSectionBody>
<SettingsSectionForm variant="half"> <SettingsSectionForm variant="half">
<BrowserGatewayTargetForm <BrowserGatewayTargetForm
control={form.control}
orgId={orgId} orgId={orgId}
multiSite={true} multiSite={true}
selectedSites={selectedSites} sitesField="selectedSites"
onSitesChange={setSelectedSites} destinationField="destination"
destination={bgDestination} destinationPortField="destinationPort"
destinationPort={bgDestinationPort}
onDestinationChange={setBgDestination}
onDestinationPortChange={setBgDestinationPort}
learnMoreHref="https://docs.pangolin.net/manage/resources/public/rdp" learnMoreHref="https://docs.pangolin.net/manage/resources/public/rdp"
defaultPort={3389} defaultPort={3389}
/> />
@@ -262,6 +257,7 @@ function SshServerForm({
{t("saveSettings")} {t("saveSettings")}
</Button> </Button>
</form> </form>
</Form>
</fieldset> </fieldset>
</SettingsSection> </SettingsSection>
); );
@@ -16,8 +16,7 @@ import { StrategySelect, StrategyOption } from "@app/components/StrategySelect";
import { BrowserGatewayTargetForm } from "@app/components/BrowserGatewayTargetForm"; import { BrowserGatewayTargetForm } from "@app/components/BrowserGatewayTargetForm";
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert"; import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
import { import {
SitesSelector, SitesSelector
type Selectedsite
} from "@app/components/site-selector"; } from "@app/components/site-selector";
import { usePaidStatus } from "@app/hooks/usePaidStatus"; import { usePaidStatus } from "@app/hooks/usePaidStatus";
import { tierMatrix, TierFeature } from "@server/lib/billing/tierMatrix"; import { tierMatrix, TierFeature } from "@server/lib/billing/tierMatrix";
@@ -41,15 +40,16 @@ import { Badge } from "@app/components/ui/badge";
import { toast } from "@app/hooks/useToast"; import { toast } from "@app/hooks/useToast";
import { useResourceContext } from "@app/hooks/useResourceContext"; import { useResourceContext } from "@app/hooks/useResourceContext";
import { useEnvContext } from "@app/hooks/useEnvContext"; import { useEnvContext } from "@app/hooks/useEnvContext";
import { createSshSettingsFormSchema } from "@app/lib/browserGatewayTargetFormSchema";
import type { SshSettingsFormValues } from "@app/lib/browserGatewayTargetFormSchema";
import { createApiClient } from "@app/lib/api"; import { createApiClient } from "@app/lib/api";
import { formatAxiosError } from "@app/lib/api/formatAxiosError"; import { formatAxiosError } from "@app/lib/api/formatAxiosError";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { use, useActionState, useEffect, useState } from "react"; import { use, useActionState, useMemo, useState } from "react";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { GetResourceResponse } from "@server/routers/resource"; import { GetResourceResponse } from "@server/routers/resource";
import type { ResourceContextType } from "@app/contexts/resourceContext"; import type { ResourceContextType } from "@app/contexts/resourceContext";
@@ -58,16 +58,19 @@ type ExistingTarget = {
siteId: number; siteId: number;
}; };
const sshFormSchema = z.object({ type BgTarget = {
authDaemonPort: z.string().refine( browserGatewayTargetId: number;
(val) => { resourceId: number;
if (!val) return true; siteId: number;
const n = Number(val); siteName?: string;
return Number.isInteger(n) && n >= 1 && n <= 65535; type: string;
}, destination: string;
{ message: "Port must be between 1 and 65535" } destinationPort: number;
) };
});
type BgTargetsResponse = {
targets: BgTarget[];
};
export default function SshSettingsPage(props: { export default function SshSettingsPage(props: {
params: Promise<{ orgId: string }>; params: Promise<{ orgId: string }>;
@@ -75,10 +78,25 @@ export default function SshSettingsPage(props: {
const params = use(props.params); const params = use(props.params);
const { resource, updateResource } = useResourceContext(); const { resource, updateResource } = useResourceContext();
const { isPaidUser } = usePaidStatus(); const { isPaidUser } = usePaidStatus();
const api = createApiClient(useEnvContext());
const disabled = !isPaidUser( const disabled = !isPaidUser(
tierMatrix[TierFeature.AdvancedPublicResources] tierMatrix[TierFeature.AdvancedPublicResources]
); );
const { data: bgTargetsResponse, isLoading: isLoadingTargets } = useQuery({
queryKey: ["browserGatewayTargets", resource.resourceId, params.orgId],
queryFn: async () => {
const res = await api.get(
`/org/${params.orgId}/resource/${resource.resourceId}/browser-gateway-targets`
);
return res.data.data as BgTargetsResponse;
}
});
if (isLoadingTargets) {
return null;
}
return ( return (
<SettingsContainer> <SettingsContainer>
<PaidFeaturesAlert <PaidFeaturesAlert
@@ -89,6 +107,7 @@ export default function SshSettingsPage(props: {
resource={resource} resource={resource}
updateResource={updateResource} updateResource={updateResource}
disabled={disabled} disabled={disabled}
bgTargetsResponse={bgTargetsResponse ?? { targets: [] }}
/> />
</SettingsContainer> </SettingsContainer>
); );
@@ -98,142 +117,146 @@ function SshServerForm({
orgId, orgId,
resource, resource,
updateResource, updateResource,
disabled disabled,
bgTargetsResponse
}: { }: {
orgId: string; orgId: string;
resource: GetResourceResponse; resource: GetResourceResponse;
updateResource: ResourceContextType["updateResource"]; updateResource: ResourceContextType["updateResource"];
disabled: boolean; disabled: boolean;
bgTargetsResponse: BgTargetsResponse;
}) { }) {
const t = useTranslations(); const t = useTranslations();
const api = createApiClient(useEnvContext()); const api = createApiClient(useEnvContext());
const router = useRouter(); const router = useRouter();
const isNativeInitially = resource.authDaemonMode === "native"; const isNativeInitially = resource.authDaemonMode === "native";
const targets = bgTargetsResponse.targets;
const firstTarget = targets[0];
const initialPamMode =
(resource.pamMode as "passthrough" | "push") || "passthrough";
const initialStandardDaemonLocation = isNativeInitially
? "site"
: ((resource.authDaemonMode as "site" | "remote") || "site");
const useSingleSiteOnLoad =
!isNativeInitially &&
initialPamMode === "push" &&
initialStandardDaemonLocation === "site";
const [sshServerMode, setSshServerMode] = useState<"standard" | "native">( const [sshServerMode] = useState<"standard" | "native">(
isNativeInitially ? "native" : "standard" isNativeInitially ? "native" : "standard"
); );
const isNative = sshServerMode === "native"; const isNative = sshServerMode === "native";
const [pamMode, setPamMode] = useState<"passthrough" | "push">( const formSchema = useMemo(
(resource.pamMode as "passthrough" | "push") || "passthrough" () => createSshSettingsFormSchema(t, { isNative }),
[t, isNative]
); );
const [standardDaemonLocation, setStandardDaemonLocation] = useState< const form = useForm<SshSettingsFormValues>({
"site" | "remote" resolver: zodResolver(formSchema),
>(
isNativeInitially
? "site"
: (resource.authDaemonMode as "site" | "remote") || "site"
);
const form = useForm({
resolver: zodResolver(sshFormSchema),
defaultValues: { defaultValues: {
authDaemonPort: (resource as any).authDaemonPort pamMode: initialPamMode,
? String((resource as any).authDaemonPort) standardDaemonLocation: initialStandardDaemonLocation,
: "22123" authDaemonPort: (resource as { authDaemonPort?: number })
.authDaemonPort
? String((resource as { authDaemonPort?: number }).authDaemonPort)
: "22123",
selectedSites:
isNativeInitially || useSingleSiteOnLoad
? []
: targets.map((target) => ({
siteId: target.siteId,
name: target.siteName ?? String(target.siteId),
type: "newt" as const
})),
selectedSite:
useSingleSiteOnLoad && firstTarget
? {
siteId: firstTarget.siteId,
name:
firstTarget.siteName ??
String(firstTarget.siteId),
type: "newt" as const
}
: null,
selectedNativeSite:
isNativeInitially && firstTarget
? {
siteId: firstTarget.siteId,
name:
firstTarget.siteName ??
String(firstTarget.siteId),
type: "newt" as const
}
: null,
destination: isNativeInitially
? ""
: (firstTarget?.destination ?? ""),
destinationPort: isNativeInitially
? "22"
: firstTarget
? String(firstTarget.destinationPort)
: "22"
} }
}); });
// Standard mode: multi-site
const [selectedSites, setSelectedSites] = useState<Selectedsite[]>([]);
const [selectedSite, setSelectedSite] = useState<Selectedsite | null>(null);
const [bgDestination, setBgDestination] = useState("");
const [bgDestinationPort, setBgDestinationPort] = useState("22");
const [existingTargets, setExistingTargets] = useState<ExistingTarget[]>( const [existingTargets, setExistingTargets] = useState<ExistingTarget[]>(
[] () =>
isNativeInitially
? []
: targets.map((target) => ({
browserGatewayTargetId: target.browserGatewayTargetId,
siteId: target.siteId
}))
); );
// Native mode: single site
const [selectedNativeSite, setSelectedNativeSite] =
useState<Selectedsite | null>(null);
const [nativeExistingTarget, setNativeExistingTarget] = const [nativeExistingTarget, setNativeExistingTarget] =
useState<ExistingTarget | null>(null); useState<ExistingTarget | null>(() =>
isNativeInitially && firstTarget
? {
browserGatewayTargetId:
firstTarget.browserGatewayTargetId,
siteId: firstTarget.siteId
}
: null
);
const [nativeSiteOpen, setNativeSiteOpen] = useState(false); const [nativeSiteOpen, setNativeSiteOpen] = useState(false);
const { data: bgTargetsResponse } = useQuery({
queryKey: ["browserGatewayTargets", resource.resourceId, orgId],
queryFn: async () => {
const res = await api.get(
`/org/${orgId}/resource/${resource.resourceId}/browser-gateway-targets`
);
return res.data.data as {
targets: Array<{
browserGatewayTargetId: number;
resourceId: number;
siteId: number;
siteName?: string;
type: string;
destination: string;
destinationPort: number;
}>;
};
}
});
useEffect(() => {
if (!bgTargetsResponse?.targets?.length) return;
const targets = bgTargetsResponse.targets;
const first = targets[0];
if (isNativeInitially) {
setSelectedNativeSite({
siteId: first.siteId,
name: first.siteName ?? String(first.siteId),
type: "newt" as const
});
setNativeExistingTarget({
browserGatewayTargetId: first.browserGatewayTargetId,
siteId: first.siteId
});
} else {
setBgDestination(first.destination);
setBgDestinationPort(String(first.destinationPort));
setExistingTargets(
targets.map((t) => ({
browserGatewayTargetId: t.browserGatewayTargetId,
siteId: t.siteId
}))
);
setSelectedSites(
targets.map((t) => ({
siteId: t.siteId,
name: t.siteName ?? String(t.siteId),
type: "newt" as const
}))
);
}
}, [bgTargetsResponse]);
const [, formAction, isSubmitting] = useActionState(save, null); const [, formAction, isSubmitting] = useActionState(save, null);
const pamMode = form.watch("pamMode");
const standardDaemonLocation = form.watch("standardDaemonLocation");
const selectedNativeSite = form.watch("selectedNativeSite");
async function save() { async function save() {
const isValid = await form.trigger(); const isValid = await form.trigger();
if (!isValid) return; if (!isValid) return;
const effectiveMode = isNative ? "native" : standardDaemonLocation; const values = form.getValues();
const portVal = form.getValues().authDaemonPort; const effectiveMode = isNative ? "native" : values.standardDaemonLocation;
const effectivePort = const effectivePort =
!isNative && standardDaemonLocation === "remote" && portVal !isNative &&
? Number(portVal) values.standardDaemonLocation === "remote" &&
values.authDaemonPort
? Number(values.authDaemonPort)
: null; : null;
try { try {
await api.post(`/resource/${resource.resourceId}`, { await api.post(`/resource/${resource.resourceId}`, {
pamMode, pamMode: values.pamMode,
authDaemonMode: effectiveMode, authDaemonMode: effectiveMode,
authDaemonPort: effectivePort authDaemonPort: effectivePort
}); });
updateResource({ updateResource({
...resource, ...resource,
pamMode, pamMode: values.pamMode,
authDaemonMode: effectiveMode authDaemonMode: effectiveMode
}); });
if (isNative) { if (isNative) {
if (selectedNativeSite) { if (values.selectedNativeSite) {
if (nativeExistingTarget) { if (nativeExistingTarget) {
await api.post( await api.post(
`/org/${orgId}/browser-gateway-target/${nativeExistingTarget.browserGatewayTargetId}`, `/org/${orgId}/browser-gateway-target/${nativeExistingTarget.browserGatewayTargetId}`,
@@ -241,14 +264,14 @@ function SshServerForm({
type: "ssh", type: "ssh",
destination: "localhost", destination: "localhost",
destinationPort: 22, destinationPort: 22,
siteId: selectedNativeSite.siteId siteId: values.selectedNativeSite.siteId
} }
); );
} else { } else {
const res = await api.put( const res = await api.put(
`/org/${orgId}/resource/${resource.resourceId}/browser-gateway-target`, `/org/${orgId}/resource/${resource.resourceId}/browser-gateway-target`,
{ {
siteId: selectedNativeSite.siteId, siteId: values.selectedNativeSite.siteId,
type: "ssh", type: "ssh",
destination: "localhost", destination: "localhost",
destinationPort: 22 destinationPort: 22
@@ -257,14 +280,22 @@ function SshServerForm({
setNativeExistingTarget({ setNativeExistingTarget({
browserGatewayTargetId: browserGatewayTargetId:
res.data.data.browserGatewayTargetId, res.data.data.browserGatewayTargetId,
siteId: selectedNativeSite.siteId siteId: values.selectedNativeSite.siteId
}); });
} }
} }
} else { } else {
if (bgDestination && bgDestinationPort) { const useMultiSite =
values.standardDaemonLocation !== "site" ||
values.pamMode === "passthrough";
const activeSites = useMultiSite
? values.selectedSites
: values.selectedSite
? [values.selectedSite]
: [];
const selectedSiteIds = new Set( const selectedSiteIds = new Set(
selectedSites.map((s) => s.siteId) activeSites.map((s) => s.siteId)
); );
const existingSiteIds = new Set( const existingSiteIds = new Set(
existingTargets.map((t) => t.siteId) existingTargets.map((t) => t.siteId)
@@ -290,15 +321,17 @@ function SshServerForm({
`/org/${orgId}/browser-gateway-target/${t.browserGatewayTargetId}`, `/org/${orgId}/browser-gateway-target/${t.browserGatewayTargetId}`,
{ {
type: "ssh", type: "ssh",
destination: bgDestination, destination: values.destination,
destinationPort: Number(bgDestinationPort), destinationPort: Number(
values.destinationPort
),
siteId: t.siteId siteId: t.siteId
} }
) )
) )
); );
const toCreate = selectedSites.filter( const toCreate = activeSites.filter(
(s) => !existingSiteIds.has(s.siteId) (s) => !existingSiteIds.has(s.siteId)
); );
const created = await Promise.all( const created = await Promise.all(
@@ -308,23 +341,22 @@ function SshServerForm({
{ {
siteId: s.siteId, siteId: s.siteId,
type: "ssh", type: "ssh",
destination: bgDestination, destination: values.destination,
destinationPort: Number(bgDestinationPort) destinationPort: Number(
values.destinationPort
)
} }
) )
) )
); );
const newTargets: ExistingTarget[] = created.map( const newTargets: ExistingTarget[] = created.map((res, i) => ({
(res, i) => ({
browserGatewayTargetId: browserGatewayTargetId:
res.data.data.browserGatewayTargetId, res.data.data.browserGatewayTargetId,
siteId: toCreate[i].siteId siteId: toCreate[i].siteId
}) }));
);
setExistingTargets([...toUpdate, ...newTargets]); setExistingTargets([...toUpdate, ...newTargets]);
} }
}
toast({ toast({
title: t("settingsUpdated"), title: t("settingsUpdated"),
@@ -373,6 +405,9 @@ function SshServerForm({
const showDaemonLocation = !isNative && pamMode === "push"; const showDaemonLocation = !isNative && pamMode === "push";
const showDaemonPort = const showDaemonPort =
!isNative && pamMode === "push" && standardDaemonLocation === "remote"; !isNative && pamMode === "push" && standardDaemonLocation === "remote";
const useMultiSiteTargetForm =
!isNative &&
(standardDaemonLocation !== "site" || pamMode === "passthrough");
return ( return (
<SettingsSection> <SettingsSection>
@@ -386,12 +421,11 @@ function SshServerForm({
disabled={disabled} disabled={disabled}
className={disabled ? "opacity-50 pointer-events-none" : ""} className={disabled ? "opacity-50 pointer-events-none" : ""}
> >
<Form {...form}>
<SettingsSectionBody> <SettingsSectionBody>
<SettingsSectionForm variant="half"> <SettingsSectionForm variant="half">
<div className="space-y-3"> <div className="space-y-2">
<SettingsSubsectionTitle> <p className="font-semibold text-sm">{t("sshServerMode")}</p>
{t("sshServerMode")}
</SettingsSubsectionTitle>
<Badge variant="secondary"> <Badge variant="secondary">
{sshServerMode == "standard" {sshServerMode == "standard"
? t("sshServerModeStandard") ? t("sshServerModeStandard")
@@ -399,27 +433,33 @@ function SshServerForm({
</Badge> </Badge>
</div> </div>
<div className="space-y-3"> <div className="space-y-2">
<SettingsSubsectionTitle> <p className="font-semibold text-sm">{t("sshAuthenticationMethod")}</p>
{t("sshAuthenticationMethod")}
</SettingsSubsectionTitle>
<StrategySelect<"passthrough" | "push"> <StrategySelect<"passthrough" | "push">
value={pamMode} value={pamMode}
options={authMethodOptions} options={authMethodOptions}
onChange={setPamMode} onChange={(value) =>
form.setValue("pamMode", value, {
shouldValidate: true
})
}
cols={2} cols={2}
/> />
</div> </div>
{showDaemonLocation && ( {showDaemonLocation && (
<div className="space-y-3"> <div className="space-y-2">
<SettingsSubsectionTitle> <p className="font-semibold text-sm">{t("sshAuthDaemonLocation")}</p>
{t("sshAuthDaemonLocation")}
</SettingsSubsectionTitle>
<StrategySelect<"site" | "remote"> <StrategySelect<"site" | "remote">
value={standardDaemonLocation} value={standardDaemonLocation}
options={daemonLocationOptions} options={daemonLocationOptions}
onChange={setStandardDaemonLocation} onChange={(value) =>
form.setValue(
"standardDaemonLocation",
value,
{ shouldValidate: true }
)
}
cols={2} cols={2}
/> />
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
@@ -438,7 +478,7 @@ function SshServerForm({
)} )}
{showDaemonPort && ( {showDaemonPort && (
<Form {...form}> <div className="w-full md:w-1/2">
<FormField <FormField
control={form.control} control={form.control}
name="authDaemonPort" name="authDaemonPort"
@@ -459,7 +499,7 @@ function SshServerForm({
</FormItem> </FormItem>
)} )}
/> />
</Form> </div>
)} )}
<div className="space-y-3"> <div className="space-y-3">
@@ -472,11 +512,19 @@ function SshServerForm({
</SettingsSubsectionDescription> </SettingsSubsectionDescription>
</SettingsSubsectionHeader> </SettingsSubsectionHeader>
{isNative ? ( {isNative ? (
<FormField
control={form.control}
name="selectedNativeSite"
render={() => (
<FormItem>
<Popover <Popover
open={nativeSiteOpen} open={nativeSiteOpen}
onOpenChange={setNativeSiteOpen} onOpenChange={
setNativeSiteOpen
}
> >
<PopoverTrigger asChild> <PopoverTrigger asChild>
<FormControl>
<Button <Button
variant="outline" variant="outline"
role="combobox" role="combobox"
@@ -484,46 +532,61 @@ function SshServerForm({
> >
<span className="truncate"> <span className="truncate">
{selectedNativeSite?.name ?? {selectedNativeSite?.name ??
t("siteSelect")} t(
"siteSelect"
)}
</span> </span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" /> <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button> </Button>
</FormControl>
</PopoverTrigger> </PopoverTrigger>
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0"> <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
<SitesSelector <SitesSelector
orgId={orgId} orgId={orgId}
selectedSite={selectedNativeSite} selectedSite={
onSelectSite={(site) => { selectedNativeSite
setSelectedNativeSite(site); }
setNativeSiteOpen(false); onSelectSite={(
site
) => {
form.setValue(
"selectedNativeSite",
site,
{
shouldValidate:
true
}
);
setNativeSiteOpen(
false
);
}} }}
/> />
</PopoverContent> </PopoverContent>
</Popover> </Popover>
) : standardDaemonLocation !== "site" || <FormMessage />
pamMode === "passthrough" ? ( </FormItem>
)}
/>
) : useMultiSiteTargetForm ? (
<BrowserGatewayTargetForm <BrowserGatewayTargetForm
control={form.control}
orgId={orgId} orgId={orgId}
multiSite={true} multiSite={true}
selectedSites={selectedSites} sitesField="selectedSites"
onSitesChange={setSelectedSites} destinationField="destination"
destination={bgDestination} destinationPortField="destinationPort"
destinationPort={bgDestinationPort}
onDestinationChange={setBgDestination}
onDestinationPortChange={setBgDestinationPort}
learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh" learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh"
defaultPort={22} defaultPort={22}
/> />
) : ( ) : (
<BrowserGatewayTargetForm <BrowserGatewayTargetForm
control={form.control}
orgId={orgId} orgId={orgId}
multiSite={false} multiSite={false}
selectedSite={selectedSite} siteField="selectedSite"
onSiteChange={setSelectedSite} destinationField="destination"
destination={bgDestination} destinationPortField="destinationPort"
destinationPort={bgDestinationPort}
onDestinationChange={setBgDestination}
onDestinationPortChange={setBgDestinationPort}
learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh" learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh"
defaultPort={22} defaultPort={22}
/> />
@@ -540,6 +603,7 @@ function SshServerForm({
{t("saveSettings")} {t("saveSettings")}
</Button> </Button>
</form> </form>
</Form>
</fieldset> </fieldset>
</SettingsSection> </SettingsSection>
); );
@@ -11,20 +11,23 @@ import {
} from "@app/components/Settings"; } from "@app/components/Settings";
import { BrowserGatewayTargetForm } from "@app/components/BrowserGatewayTargetForm"; import { BrowserGatewayTargetForm } from "@app/components/BrowserGatewayTargetForm";
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert"; import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
import { type Selectedsite } from "@app/components/site-selector";
import { Button } from "@app/components/ui/button"; import { Button } from "@app/components/ui/button";
import { Form } from "@app/components/ui/form";
import { toast } from "@app/hooks/useToast"; import { toast } from "@app/hooks/useToast";
import { useResourceContext } from "@app/hooks/useResourceContext"; import { useResourceContext } from "@app/hooks/useResourceContext";
import { useEnvContext } from "@app/hooks/useEnvContext"; import { useEnvContext } from "@app/hooks/useEnvContext";
import { usePaidStatus } from "@app/hooks/usePaidStatus"; import { usePaidStatus } from "@app/hooks/usePaidStatus";
import { createBrowserGatewayTargetFormSchema } from "@app/lib/browserGatewayTargetFormSchema";
import type { BrowserGatewayTargetFormValues } from "@app/lib/browserGatewayTargetFormSchema";
import { tierMatrix, TierFeature } from "@server/lib/billing/tierMatrix"; import { tierMatrix, TierFeature } from "@server/lib/billing/tierMatrix";
import { createApiClient } from "@app/lib/api"; import { createApiClient } from "@app/lib/api";
import { formatAxiosError } from "@app/lib/api/formatAxiosError"; import { formatAxiosError } from "@app/lib/api/formatAxiosError";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { use, useActionState, useEffect, useState } from "react"; import { use, useActionState, useMemo, useState } from "react";
import { z } from "zod"; import { useForm } from "react-hook-form";
import { GetResourceResponse } from "@server/routers/resource"; import { GetResourceResponse } from "@server/routers/resource";
import type { ResourceContextType } from "@app/contexts/resourceContext"; import type { ResourceContextType } from "@app/contexts/resourceContext";
@@ -33,79 +36,7 @@ type ExistingTarget = {
siteId: number; siteId: number;
}; };
const sshFormSchema = z.object({ type BgTarget = {
authDaemonPort: z.string().refine(
(val) => {
if (!val) return true;
const n = Number(val);
return Number.isInteger(n) && n >= 1 && n <= 65535;
},
{ message: "Port must be between 1 and 65535" }
)
});
export default function SshSettingsPage(props: {
params: Promise<{ orgId: string }>;
}) {
const params = use(props.params);
const { resource, updateResource } = useResourceContext();
const { isPaidUser } = usePaidStatus();
const disabled = !isPaidUser(
tierMatrix[TierFeature.AdvancedPublicResources]
);
return (
<SettingsContainer>
<PaidFeaturesAlert
tiers={tierMatrix[TierFeature.AdvancedPublicResources]}
/>
<SshServerForm
orgId={params.orgId}
resource={resource}
updateResource={updateResource}
disabled={disabled}
/>
</SettingsContainer>
);
}
function SshServerForm({
orgId,
resource,
updateResource,
disabled
}: {
orgId: string;
resource: GetResourceResponse;
updateResource: ResourceContextType["updateResource"];
disabled: boolean;
}) {
const t = useTranslations();
const api = createApiClient(useEnvContext());
const router = useRouter();
// Standard mode: multi-site
const [selectedSites, setSelectedSites] = useState<Selectedsite[]>([]);
const [bgDestination, setBgDestination] = useState("");
const [bgDestinationPort, setBgDestinationPort] = useState("22");
const [existingTargets, setExistingTargets] = useState<ExistingTarget[]>(
[]
);
// Native mode: single site
const [selectedNativeSite, setSelectedNativeSite] =
useState<Selectedsite | null>(null);
const [nativeExistingTarget, setNativeExistingTarget] =
useState<ExistingTarget | null>(null);
const { data: bgTargetsResponse } = useQuery({
queryKey: ["browserGatewayTargets", resource.resourceId, orgId],
queryFn: async () => {
const res = await api.get(
`/org/${orgId}/resource/${resource.resourceId}/browser-gateway-targets`
);
return res.data.data as {
targets: Array<{
browserGatewayTargetId: number; browserGatewayTargetId: number;
resourceId: number; resourceId: number;
siteId: number; siteId: number;
@@ -113,41 +44,110 @@ function SshServerForm({
type: string; type: string;
destination: string; destination: string;
destinationPort: number; destinationPort: number;
}>;
}; };
type BgTargetsResponse = {
targets: BgTarget[];
};
export default function VncSettingsPage(props: {
params: Promise<{ orgId: string }>;
}) {
const params = use(props.params);
const { resource, updateResource } = useResourceContext();
const { isPaidUser } = usePaidStatus();
const api = createApiClient(useEnvContext());
const disabled = !isPaidUser(
tierMatrix[TierFeature.AdvancedPublicResources]
);
const { data: bgTargetsResponse, isLoading: isLoadingTargets } = useQuery({
queryKey: ["browserGatewayTargets", resource.resourceId, params.orgId],
queryFn: async () => {
const res = await api.get(
`/org/${params.orgId}/resource/${resource.resourceId}/browser-gateway-targets`
);
return res.data.data as BgTargetsResponse;
} }
}); });
useEffect(() => { if (isLoadingTargets) {
if (!bgTargetsResponse?.targets?.length) return; return null;
const targets = bgTargetsResponse.targets; }
const first = targets[0];
setBgDestination(first.destination); return (
setBgDestinationPort(String(first.destinationPort)); <SettingsContainer>
setExistingTargets( <PaidFeaturesAlert
targets.map((t) => ({ tiers={tierMatrix[TierFeature.AdvancedPublicResources]}
browserGatewayTargetId: t.browserGatewayTargetId, />
siteId: t.siteId <VncServerForm
})) orgId={params.orgId}
resource={resource}
updateResource={updateResource}
disabled={disabled}
bgTargetsResponse={bgTargetsResponse ?? { targets: [] }}
/>
</SettingsContainer>
); );
setSelectedSites( }
targets.map((t) => ({
siteId: t.siteId, function VncServerForm({
name: t.siteName ?? String(t.siteId), orgId,
resource,
disabled,
bgTargetsResponse
}: {
orgId: string;
resource: GetResourceResponse;
updateResource: ResourceContextType["updateResource"];
disabled: boolean;
bgTargetsResponse: BgTargetsResponse;
}) {
const t = useTranslations();
const api = createApiClient(useEnvContext());
const router = useRouter();
const targets = bgTargetsResponse.targets;
const firstTarget = targets[0];
const formSchema = useMemo(
() => createBrowserGatewayTargetFormSchema(t),
[t]
);
const form = useForm<BrowserGatewayTargetFormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
selectedSites: targets.map((target) => ({
siteId: target.siteId,
name: target.siteName ?? String(target.siteId),
type: "newt" as const type: "newt" as const
})),
destination: firstTarget?.destination ?? "",
destinationPort: firstTarget
? String(firstTarget.destinationPort)
: "5900"
}
});
const [existingTargets, setExistingTargets] = useState<ExistingTarget[]>(
() =>
targets.map((target) => ({
browserGatewayTargetId: target.browserGatewayTargetId,
siteId: target.siteId
})) }))
); );
}, [bgTargetsResponse]);
const [, formAction, isSubmitting] = useActionState(save, null); const [, formAction, isSubmitting] = useActionState(save, null);
async function save() { async function save() {
const isValid = await form.trigger();
if (!isValid) return;
const { selectedSites, destination, destinationPort } =
form.getValues();
try { try {
if (bgDestination && bgDestinationPort) { const selectedSiteIds = new Set(selectedSites.map((s) => s.siteId));
const selectedSiteIds = new Set(
selectedSites.map((s) => s.siteId)
);
const existingSiteIds = new Set( const existingSiteIds = new Set(
existingTargets.map((t) => t.siteId) existingTargets.map((t) => t.siteId)
); );
@@ -172,8 +172,8 @@ function SshServerForm({
`/org/${orgId}/browser-gateway-target/${t.browserGatewayTargetId}`, `/org/${orgId}/browser-gateway-target/${t.browserGatewayTargetId}`,
{ {
type: "vnc", type: "vnc",
destination: bgDestination, destination,
destinationPort: Number(bgDestinationPort), destinationPort: Number(destinationPort),
siteId: t.siteId siteId: t.siteId
} }
) )
@@ -190,20 +190,18 @@ function SshServerForm({
{ {
siteId: s.siteId, siteId: s.siteId,
type: "vnc", type: "vnc",
destination: bgDestination, destination,
destinationPort: Number(bgDestinationPort) destinationPort: Number(destinationPort)
} }
) )
) )
); );
const newTargets: ExistingTarget[] = created.map((res, i) => ({ const newTargets: ExistingTarget[] = created.map((res, i) => ({
browserGatewayTargetId: browserGatewayTargetId: res.data.data.browserGatewayTargetId,
res.data.data.browserGatewayTargetId,
siteId: toCreate[i].siteId siteId: toCreate[i].siteId
})); }));
setExistingTargets([...toUpdate, ...newTargets]); setExistingTargets([...toUpdate, ...newTargets]);
}
toast({ toast({
title: t("settingsUpdated"), title: t("settingsUpdated"),
@@ -235,17 +233,16 @@ function SshServerForm({
disabled={disabled} disabled={disabled}
className={disabled ? "opacity-50 pointer-events-none" : ""} className={disabled ? "opacity-50 pointer-events-none" : ""}
> >
<Form {...form}>
<SettingsSectionBody> <SettingsSectionBody>
<SettingsSectionForm variant="half"> <SettingsSectionForm variant="half">
<BrowserGatewayTargetForm <BrowserGatewayTargetForm
control={form.control}
orgId={orgId} orgId={orgId}
multiSite={true} multiSite={true}
selectedSites={selectedSites} sitesField="selectedSites"
onSitesChange={setSelectedSites} destinationField="destination"
destination={bgDestination} destinationPortField="destinationPort"
destinationPort={bgDestinationPort}
onDestinationChange={setBgDestination}
onDestinationPortChange={setBgDestinationPort}
learnMoreHref="https://docs.pangolin.net/manage/resources/public/vnc" learnMoreHref="https://docs.pangolin.net/manage/resources/public/vnc"
defaultPort={5900} defaultPort={5900}
/> />
@@ -260,6 +257,7 @@ function SshServerForm({
{t("saveSettings")} {t("saveSettings")}
</Button> </Button>
</form> </form>
</Form>
</fieldset> </fieldset>
</SettingsSection> </SettingsSection>
); );
@@ -50,6 +50,12 @@ import { toast } from "@app/hooks/useToast";
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert"; import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
import { tierMatrix, TierFeature } from "@server/lib/billing/tierMatrix"; import { tierMatrix, TierFeature } from "@server/lib/billing/tierMatrix";
import { createApiClient, formatAxiosError } from "@app/lib/api"; import { createApiClient, formatAxiosError } from "@app/lib/api";
import {
createBrowserGatewayTargetFormSchema,
createSshSettingsFormSchema,
selectedSiteSchema,
type SshSettingsFormValues
} from "@app/lib/browserGatewayTargetFormSchema";
import { DockerManager, DockerState } from "@app/lib/docker"; import { DockerManager, DockerState } from "@app/lib/docker";
import { orgQueries } from "@app/lib/queries"; import { orgQueries } from "@app/lib/queries";
import { finalizeSubdomainSanitize } from "@app/lib/subdomain-utils"; import { finalizeSubdomainSanitize } from "@app/lib/subdomain-utils";
@@ -79,41 +85,68 @@ import {
useTransition, useTransition,
useEffect useEffect
} from "react"; } from "react";
import { useForm } from "react-hook-form"; import { useForm, type Resolver } from "react-hook-form";
import { z } from "zod"; import { z } from "zod";
const baseResourceFormSchema = z.object({ type TranslateFn = (key: string) => string;
name: z.string().min(1).max(255),
function createBaseResourceFormSchema(t: TranslateFn) {
return z.object({
name: z
.string()
.min(1, { message: t("nameRequired") })
.max(255, {
message: t("createInternalResourceDialogNameMaxLength")
}),
http: z.boolean() http: z.boolean()
}); });
}
const httpResourceFormSchema = z.object({ function createHttpResourceFormSchema(t: TranslateFn) {
domainId: z.string().nonempty(), return z.object({
domainId: z.string().min(1, { message: t("domainRequired") }),
subdomain: z.string().optional() subdomain: z.string().optional()
}); });
}
const tcpUdpResourceFormSchema = z.object({ function createTcpUdpResourceFormSchema(t: TranslateFn) {
return z.object({
protocol: z.string(), protocol: z.string(),
proxyPort: z.int().min(1).max(65535) proxyPort: z
.number({ error: t("proxyPortRequired") })
.int({ error: t("healthCheckPortInvalid") })
.min(1, { message: t("healthCheckPortInvalid") })
.max(65535, { message: t("healthCheckPortInvalid") })
}); });
}
const sshDaemonPortSchema = z.object({ function createSshDaemonPortSchema(t: TranslateFn) {
return z.object({
authDaemonPort: z.string().refine( authDaemonPort: z.string().refine(
(val) => { (val) => {
if (!val) return true; if (!val) return true;
const n = Number(val); const n = Number(val);
return Number.isInteger(n) && n >= 1 && n <= 65535; return Number.isInteger(n) && n >= 1 && n <= 65535;
}, },
{ message: "Port must be between 1 and 65535" } { message: t("healthCheckPortInvalid") }
) )
}); });
}
const addTargetSchema = z function createAddTargetSchema(t: TranslateFn) {
return z
.object({ .object({
ip: z.string().refine(isTargetValid), ip: z.string().refine(isTargetValid, {
message: t("targetErrorInvalidIpDescription")
}),
method: z.string().nullable(), method: z.string().nullable(),
port: z.coerce.number<number>().int().positive(), port: z.coerce
siteId: z.int().positive(), .number<number>({ error: t("targetErrorInvalidPortDescription") })
.int({ error: t("targetErrorInvalidPortDescription") })
.positive({ error: t("targetErrorInvalidPortDescription") }),
siteId: z
.int({ error: t("siteRequired") })
.positive({ error: t("siteRequired") }),
path: z.string().optional().nullable(), path: z.string().optional().nullable(),
pathMatchType: z pathMatchType: z
.enum(["exact", "prefix", "regex"]) .enum(["exact", "prefix", "regex"])
@@ -124,7 +157,11 @@ const addTargetSchema = z
.enum(["exact", "prefix", "regex", "stripPrefix"]) .enum(["exact", "prefix", "regex", "stripPrefix"])
.optional() .optional()
.nullable(), .nullable(),
priority: z.int().min(1).max(1000).optional() priority: z
.int()
.min(1, { message: t("healthCheckPortInvalid") })
.max(1000, { message: t("healthCheckPortInvalid") })
.optional()
}) })
.refine( .refine(
(data) => { (data) => {
@@ -151,7 +188,7 @@ const addTargetSchema = z
return true; return true;
}, },
{ {
error: "Invalid path configuration" message: t("invalidPathConfiguration")
} }
) )
.refine( .refine(
@@ -167,12 +204,15 @@ const addTargetSchema = z
return true; return true;
}, },
{ {
error: "Invalid rewrite path configuration" message: t("invalidRewritePathConfiguration")
} }
); );
}
type NewResourceType = "http" | "ssh" | "rdp" | "vnc" | "tcp" | "udp"; type NewResourceType = "http" | "ssh" | "rdp" | "vnc" | "tcp" | "udp";
type CreateBgTargetFormValues = SshSettingsFormValues;
export default function Page() { export default function Page() {
const { env } = useEnvContext(); const { env } = useEnvContext();
const api = createApiClient({ env }); const api = createApiClient({ env });
@@ -223,29 +263,6 @@ export default function Page() {
useState<Selectedsite | null>(null); useState<Selectedsite | null>(null);
const [nativeSiteOpen, setNativeSiteOpen] = useState(false); const [nativeSiteOpen, setNativeSiteOpen] = useState(false);
// Browser-gateway targets state (SSH standard, RDP, VNC)
const [bgSelectedSites, setBgSelectedSites] = useState<Selectedsite[]>([]);
const [bgSelectedSite, setBgSelectedSite] = useState<Selectedsite | null>(
null
);
const [bgDestination, setBgDestination] = useState("");
const [bgDestinationPort, setBgDestinationPort] = useState("22");
// Reset BG state when resource type changes
useEffect(() => {
if (resourceType === "rdp") {
setBgDestinationPort("3389");
} else if (resourceType === "vnc") {
setBgDestinationPort("5900");
} else if (resourceType === "ssh") {
setBgDestinationPort("22");
}
setBgDestination("");
setBgSelectedSites([]);
setBgSelectedSite(null);
setNativeSelectedSite(null);
}, [resourceType]);
useEffect(() => { useEffect(() => {
if (build !== "saas") return; if (build !== "saas") return;
@@ -278,6 +295,39 @@ export default function Page() {
pamMode === "push" && pamMode === "push" &&
standardDaemonLocation === "remote"; standardDaemonLocation === "remote";
const bgTargetFormSchema = useMemo(() => {
if (resourceType === "ssh" && !isNative) {
return createSshSettingsFormSchema(t, { isNative: false });
}
if (resourceType === "rdp" || resourceType === "vnc") {
return createBrowserGatewayTargetFormSchema(t);
}
return z.object({
selectedSites: z.array(selectedSiteSchema),
selectedSite: selectedSiteSchema.nullable(),
destination: z.string(),
destinationPort: z.string(),
pamMode: z.enum(["passthrough", "push"]),
standardDaemonLocation: z.enum(["site", "remote"])
});
}, [resourceType, isNative, t]);
const bgTargetForm = useForm<CreateBgTargetFormValues>({
resolver: zodResolver(
bgTargetFormSchema
) as unknown as Resolver<CreateBgTargetFormValues>,
defaultValues: {
selectedSites: [],
selectedSite: null,
selectedNativeSite: null,
destination: "",
destinationPort: "22",
pamMode: "passthrough",
standardDaemonLocation: "site",
authDaemonPort: "22123"
}
});
// Whether raw (TCP/UDP) resources are available // Whether raw (TCP/UDP) resources are available
const rawResourcesAllowed = const rawResourcesAllowed =
env.flags.allowRawResources && env.flags.allowRawResources &&
@@ -302,6 +352,24 @@ export default function Page() {
} }
}, [availableTypes, resourceType]); }, [availableTypes, resourceType]);
const baseResourceFormSchema = useMemo(
() => createBaseResourceFormSchema(t),
[t]
);
const httpResourceFormSchema = useMemo(
() => createHttpResourceFormSchema(t),
[t]
);
const tcpUdpResourceFormSchema = useMemo(
() => createTcpUdpResourceFormSchema(t),
[t]
);
const sshDaemonPortSchema = useMemo(
() => createSshDaemonPortSchema(t),
[t]
);
const addTargetSchema = useMemo(() => createAddTargetSchema(t), [t]);
const baseForm = useForm({ const baseForm = useForm({
resolver: zodResolver(baseResourceFormSchema), resolver: zodResolver(baseResourceFormSchema),
defaultValues: { defaultValues: {
@@ -330,6 +398,31 @@ export default function Page() {
} }
}); });
useEffect(() => {
const defaultPort =
resourceType === "rdp"
? "3389"
: resourceType === "vnc"
? "5900"
: "22";
bgTargetForm.reset({
selectedSites: [],
selectedSite: null,
selectedNativeSite: null,
destination: "",
destinationPort: defaultPort,
pamMode,
standardDaemonLocation,
authDaemonPort: sshDaemonPortForm.getValues().authDaemonPort
});
setNativeSelectedSite(null);
}, [resourceType]);
useEffect(() => {
bgTargetForm.setValue("pamMode", pamMode);
bgTargetForm.setValue("standardDaemonLocation", standardDaemonLocation);
}, [pamMode, standardDaemonLocation]);
// Sync form http field with resourceType // Sync form http field with resourceType
useEffect(() => { useEffect(() => {
baseForm.setValue("http", isHttpResource); baseForm.setValue("http", isHttpResource);
@@ -508,11 +601,14 @@ export default function Page() {
); );
} }
} else { } else {
const sitesToCreate = const bgValues = bgTargetForm.getValues();
standardDaemonLocation !== "site" const useMultiSite =
? bgSelectedSites standardDaemonLocation !== "site" ||
: bgSelectedSite pamMode === "passthrough";
? [bgSelectedSite] const sitesToCreate = useMultiSite
? bgValues.selectedSites
: bgValues.selectedSite
? [bgValues.selectedSite]
: []; : [];
for (const site of sitesToCreate) { for (const site of sitesToCreate) {
await api.put( await api.put(
@@ -520,8 +616,10 @@ export default function Page() {
{ {
siteId: site.siteId, siteId: site.siteId,
type: "ssh", type: "ssh",
destination: bgDestination, destination: bgValues.destination,
destinationPort: Number(bgDestinationPort) destinationPort: Number(
bgValues.destinationPort
)
} }
); );
} }
@@ -531,14 +629,17 @@ export default function Page() {
`/${orgId}/settings/resources/public/${newNiceId}` `/${orgId}/settings/resources/public/${newNiceId}`
); );
} else if (resourceType === "rdp" || resourceType === "vnc") { } else if (resourceType === "rdp" || resourceType === "vnc") {
for (const site of bgSelectedSites) { const bgValues = bgTargetForm.getValues();
for (const site of bgValues.selectedSites) {
await api.put( await api.put(
`/org/${orgId}/resource/${id}/browser-gateway-target`, `/org/${orgId}/resource/${id}/browser-gateway-target`,
{ {
siteId: site.siteId, siteId: site.siteId,
type: resourceType, type: resourceType,
destination: bgDestination, destination: bgValues.destination,
destinationPort: Number(bgDestinationPort) destinationPort: Number(
bgValues.destinationPort
)
} }
); );
} }
@@ -760,32 +861,56 @@ export default function Page() {
{/* Domain/Subdomain (HTTP-based types) */} {/* Domain/Subdomain (HTTP-based types) */}
{isHttpResource && ( {isHttpResource && (
<div className="space-y-2"> <Form {...httpForm}>
<FormField
control={httpForm.control}
name="domainId"
render={() => (
<FormItem>
<DomainPicker <DomainPicker
allowWildcard={true} allowWildcard={
orgId={orgId as string} true
}
orgId={
orgId as string
}
warnOnProvidedDomain={ warnOnProvidedDomain={
remoteExitNodes.length >= remoteExitNodes.length >=
1 1
} }
onDomainChange={(res) => { onDomainChange={(
if (!res) return; res
) => {
if (!res)
return;
httpForm.setValue( httpForm.setValue(
"subdomain", "subdomain",
res.subdomain res.subdomain,
{
shouldValidate:
true
}
); );
httpForm.setValue( httpForm.setValue(
"domainId", "domainId",
res.domainId res.domainId,
{
shouldValidate:
true
}
); );
}} }}
/> />
<p className="text-sm text-muted-foreground"> <FormMessage />
<FormDescription>
{t( {t(
"resourceDomainDescription" "resourceDomainDescription"
)} )}
</p> </FormDescription>
</div> </FormItem>
)}
/>
</Form>
)} )}
{/* Proxy Port (TCP/UDP types) */} {/* Proxy Port (TCP/UDP types) */}
@@ -883,9 +1008,7 @@ export default function Page() {
<SettingsSectionForm variant="half"> <SettingsSectionForm variant="half">
{/* Mode */} {/* Mode */}
<div className="space-y-2"> <div className="space-y-2">
<SettingsSubsectionTitle> <p className="font-semibold text-sm">{t("sshServerMode")}</p>
{t("sshServerMode")}
</SettingsSubsectionTitle>
<StrategySelect< <StrategySelect<
"standard" | "native" "standard" | "native"
> >
@@ -897,11 +1020,7 @@ export default function Page() {
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<SettingsSubsectionTitle> <p className="font-semibold text-sm">{t("sshAuthenticationMethod")}</p>
{t(
"sshAuthenticationMethod"
)}
</SettingsSubsectionTitle>
<StrategySelect< <StrategySelect<
"passthrough" | "push" "passthrough" | "push"
> >
@@ -917,11 +1036,7 @@ export default function Page() {
{/* Daemon Location (standard + push) */} {/* Daemon Location (standard + push) */}
{showDaemonLocation && ( {showDaemonLocation && (
<div className="space-y-2"> <div className="space-y-2">
<SettingsSubsectionTitle> <p className="font-semibold text-sm">{t("sshAuthDaemonLocation")}</p>
{t(
"sshAuthDaemonLocation"
)}
</SettingsSubsectionTitle>
<StrategySelect< <StrategySelect<
"site" | "remote" "site" | "remote"
> >
@@ -1052,55 +1167,39 @@ export default function Page() {
"site" || "site" ||
pamMode === pamMode ===
"passthrough" ? ( "passthrough" ? (
<Form {...bgTargetForm}>
<BrowserGatewayTargetForm <BrowserGatewayTargetForm
orgId={orgId as string} control={
bgTargetForm.control
}
orgId={
orgId as string
}
multiSite={true} multiSite={true}
selectedSites={ sitesField="selectedSites"
bgSelectedSites destinationField="destination"
} destinationPortField="destinationPort"
onSitesChange={
setBgSelectedSites
}
destination={
bgDestination
}
destinationPort={
bgDestinationPort
}
onDestinationChange={
setBgDestination
}
onDestinationPortChange={
setBgDestinationPort
}
learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh" learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh"
defaultPort={22} defaultPort={22}
/> />
</Form>
) : ( ) : (
<Form {...bgTargetForm}>
<BrowserGatewayTargetForm <BrowserGatewayTargetForm
orgId={orgId as string} control={
bgTargetForm.control
}
orgId={
orgId as string
}
multiSite={false} multiSite={false}
selectedSite={ siteField="selectedSite"
bgSelectedSite destinationField="destination"
} destinationPortField="destinationPort"
onSiteChange={
setBgSelectedSite
}
destination={
bgDestination
}
destinationPort={
bgDestinationPort
}
onDestinationChange={
setBgDestination
}
onDestinationPortChange={
setBgDestinationPort
}
learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh" learnMoreHref="https://docs.pangolin.net/manage/resources/public/ssh"
defaultPort={22} defaultPort={22}
/> />
</Form>
)} )}
</div> </div>
</SettingsSectionForm> </SettingsSectionForm>
@@ -1138,26 +1237,18 @@ export default function Page() {
> >
<SettingsSectionBody> <SettingsSectionBody>
<SettingsSectionForm variant="half"> <SettingsSectionForm variant="half">
<Form {...bgTargetForm}>
<BrowserGatewayTargetForm <BrowserGatewayTargetForm
control={bgTargetForm.control}
orgId={orgId as string} orgId={orgId as string}
multiSite={true} multiSite={true}
selectedSites={bgSelectedSites} sitesField="selectedSites"
onSitesChange={ destinationField="destination"
setBgSelectedSites destinationPortField="destinationPort"
}
destination={bgDestination}
destinationPort={
bgDestinationPort
}
onDestinationChange={
setBgDestination
}
onDestinationPortChange={
setBgDestinationPort
}
learnMoreHref="https://docs.pangolin.net/manage/resources/public/rdp" learnMoreHref="https://docs.pangolin.net/manage/resources/public/rdp"
defaultPort={3389} defaultPort={3389}
/> />
</Form>
</SettingsSectionForm> </SettingsSectionForm>
</SettingsSectionBody> </SettingsSectionBody>
</fieldset> </fieldset>
@@ -1193,26 +1284,18 @@ export default function Page() {
> >
<SettingsSectionBody> <SettingsSectionBody>
<SettingsSectionForm variant="half"> <SettingsSectionForm variant="half">
<Form {...bgTargetForm}>
<BrowserGatewayTargetForm <BrowserGatewayTargetForm
control={bgTargetForm.control}
orgId={orgId as string} orgId={orgId as string}
multiSite={true} multiSite={true}
selectedSites={bgSelectedSites} sitesField="selectedSites"
onSitesChange={ destinationField="destination"
setBgSelectedSites destinationPortField="destinationPort"
}
destination={bgDestination}
destinationPort={
bgDestinationPort
}
onDestinationChange={
setBgDestination
}
onDestinationPortChange={
setBgDestinationPort
}
learnMoreHref="https://docs.pangolin.net/manage/resources/public/vnc" learnMoreHref="https://docs.pangolin.net/manage/resources/public/vnc"
defaultPort={5900} defaultPort={5900}
/> />
</Form>
</SettingsSectionForm> </SettingsSectionForm>
</SettingsSectionBody> </SettingsSectionBody>
</fieldset> </fieldset>
@@ -1253,15 +1336,31 @@ export default function Page() {
const tcpValid = !isHttpResource const tcpValid = !isHttpResource
? await tcpUdpForm.trigger() ? await tcpUdpForm.trigger()
: true; : true;
const sshPortValid = showDaemonPort
? await sshDaemonPortForm.trigger() if (
resourceType === "ssh" &&
!isNative
) {
bgTargetForm.setValue(
"authDaemonPort",
sshDaemonPortForm.getValues()
.authDaemonPort
);
}
const bgValid =
resourceType === "rdp" ||
resourceType === "vnc" ||
(resourceType === "ssh" &&
!isNative)
? await bgTargetForm.trigger()
: true; : true;
if ( if (
baseValid && baseValid &&
domainValid && domainValid &&
tcpValid && tcpValid &&
sshPortValid bgValid
) { ) {
onSubmit(); onSubmit();
} }
+141 -96
View File
@@ -1,128 +1,173 @@
"use client"; "use client";
import { cn } from "@app/lib/cn";
import { ChevronsUpDown, ExternalLink } from "lucide-react"; import { ChevronsUpDown, ExternalLink } from "lucide-react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { useState } from "react"; import { useState } from "react";
import type { Control, FieldValues, Path } from "react-hook-form";
import { useWatch } from "react-hook-form";
import { import {
MultiSitesSelector, MultiSitesSelector,
formatMultiSitesSelectorLabel formatMultiSitesSelectorLabel
} from "./multi-site-selector"; } from "./multi-site-selector";
import { SitesSelector, type Selectedsite } from "./site-selector"; import { SitesSelector, type Selectedsite } from "./site-selector";
import { Button } from "./ui/button"; import { Button } from "./ui/button";
import {
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage
} from "./ui/form";
import { Input } from "./ui/input"; import { Input } from "./ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover"; import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
type SingleSiteProps = { type BaseProps<T extends FieldValues> = {
multiSite?: false; control: Control<T>;
selectedSite: Selectedsite | null;
onSiteChange: (site: Selectedsite | null) => void;
};
type MultiSiteProps = {
multiSite: true;
selectedSites: Selectedsite[];
onSitesChange: (sites: Selectedsite[]) => void;
};
export type BrowserGatewayTargetFormProps = {
orgId: string; orgId: string;
destination: string; destinationField: Path<T>;
defaultPort: number; destinationPortField: Path<T>;
destinationPort: string;
onDestinationChange: (v: string) => void;
onDestinationPortChange: (v: string) => void;
learnMoreHref?: string; learnMoreHref?: string;
} & (SingleSiteProps | MultiSiteProps); defaultPort: number;
};
export function BrowserGatewayTargetForm(props: BrowserGatewayTargetFormProps) { type MultiSiteFormProps<T extends FieldValues> = BaseProps<T> & {
multiSite: true;
sitesField: Path<T>;
};
type SingleSiteFormProps<T extends FieldValues> = BaseProps<T> & {
multiSite?: false;
siteField: Path<T>;
};
export type BrowserGatewayTargetFormProps<T extends FieldValues = FieldValues> =
| MultiSiteFormProps<T>
| SingleSiteFormProps<T>;
export function BrowserGatewayTargetForm<T extends FieldValues>(
props: BrowserGatewayTargetFormProps<T>
) {
const t = useTranslations(); const t = useTranslations();
const [siteOpen, setSiteOpen] = useState(false); const [siteOpen, setSiteOpen] = useState(false);
const siteSelector = const sitesFieldName =
props.multiSite === true ? ( props.multiSite === true ? props.sitesField : props.siteField;
<Popover open={siteOpen} onOpenChange={setSiteOpen}>
<PopoverTrigger asChild> const watchedSites = useWatch({
<Button control: props.control,
variant="outline" name: sitesFieldName
role="combobox" });
className="w-full justify-between font-normal"
> const showMultiSiteDisclaimer =
<span className="truncate"> props.multiSite === true &&
{formatMultiSitesSelectorLabel( ((watchedSites as Selectedsite[] | undefined)?.length ?? 0) > 1;
props.selectedSites,
t
)}
</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
<MultiSitesSelector
orgId={props.orgId}
selectedSites={props.selectedSites}
onSelectionChange={props.onSitesChange}
/>
</PopoverContent>
</Popover>
) : (
<Popover open={siteOpen} onOpenChange={setSiteOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
className="w-full justify-between font-normal"
>
<span className="truncate">
{props.selectedSite?.name ?? t("siteSelect")}
</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
<SitesSelector
orgId={props.orgId}
selectedSite={props.selectedSite}
onSelectSite={(site) => {
props.onSiteChange(site);
setSiteOpen(false);
}}
/>
</PopoverContent>
</Popover>
);
return ( return (
<div className="space-y-2"> <div className="space-y-2">
<div className="grid grid-cols-3 gap-4"> <div className="grid grid-cols-3 gap-4 items-start">
<div className="space-y-2"> <FormField
<label className="text-sm font-semibold"> control={props.control}
{t("sites")} name={sitesFieldName}
</label> render={({ field }) => (
{siteSelector} <FormItem>
</div> <FormLabel>{t("sites")}</FormLabel>
<div className="space-y-2"> <Popover open={siteOpen} onOpenChange={setSiteOpen}>
<label className="text-sm font-semibold"> <PopoverTrigger asChild>
{t("destination")} <FormControl>
</label> <Button
<Input variant="outline"
value={props.destination} role="combobox"
onChange={(e) => className={cn(
props.onDestinationChange(e.target.value) "w-full justify-between font-normal",
"aria-invalid:border-destructive aria-invalid:ring-destructive/20",
props.multiSite === true
? (
field.value as Selectedsite[]
)?.length === 0 &&
"text-muted-foreground"
: !field.value &&
"text-muted-foreground"
)}
>
<span className="truncate">
{props.multiSite === true
? formatMultiSitesSelectorLabel(
(field.value as Selectedsite[]) ??
[],
t
)
: ((
field.value as Selectedsite | null
)?.name ??
t("siteSelect"))}
</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
{props.multiSite === true ? (
<MultiSitesSelector
orgId={props.orgId}
selectedSites={
(field.value as Selectedsite[]) ??
[]
} }
onSelectionChange={field.onChange}
/> />
</div> ) : (
<div className="space-y-2"> <SitesSelector
<label className="text-sm font-semibold">{t("port")}</label> orgId={props.orgId}
selectedSite={
field.value as Selectedsite | null
}
onSelectSite={(site) => {
field.onChange(site);
setSiteOpen(false);
}}
/>
)}
</PopoverContent>
</Popover>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={props.control}
name={props.destinationField}
render={({ field }) => (
<FormItem>
<FormLabel>{t("destination")}</FormLabel>
<FormControl>
<Input {...field} value={field.value ?? ""} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={props.control}
name={props.destinationPortField}
render={({ field }) => (
<FormItem>
<FormLabel>{t("port")}</FormLabel>
<FormControl>
<Input <Input
type="number" type="number"
value={props.destinationPort} min={1}
onChange={(e) => max={65535}
props.onDestinationPortChange(e.target.value) {...field}
} value={field.value ?? ""}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/> />
</div> </div>
</div> {showMultiSiteDisclaimer && (
{props.multiSite === true && props.selectedSites.length > 1 && (
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
{t("bgTargetMultiSiteDisclaimer")}{" "} {t("bgTargetMultiSiteDisclaimer")}{" "}
<a <a
+1 -6
View File
@@ -408,12 +408,7 @@ export function HealthCheckCredenza(props: HealthCheckCredenzaProps) {
? t("standaloneHcEditTitle") ? t("standaloneHcEditTitle")
: t("standaloneHcCreateTitle"); : t("standaloneHcCreateTitle");
const description = const description = t("configureHealthCheckDescription");
mode === "autoSave"
? t("configureHealthCheckDescription", {
target: (props as any).targetAddress
})
: t("standaloneHcDescription");
const disableTabInputs = mode === "autoSave" && !watchedEnabled; const disableTabInputs = mode === "autoSave" && !watchedEnabled;
const isSnmpOrIcmp = watchedMode === "snmp" || watchedMode === "icmp"; const isSnmpOrIcmp = watchedMode === "snmp" || watchedMode === "icmp";
+6 -6
View File
@@ -1813,9 +1813,9 @@ export function PrivateResourceForm({
{/* Mode */} {/* Mode */}
<div className="space-y-2"> <div className="space-y-2">
<SettingsSubsectionTitle> <p className="font-semibold text-sm">
{t("sshServerMode")} {t("sshServerMode")}
</SettingsSubsectionTitle> </p>
<StrategySelect<"standard" | "native"> <StrategySelect<"standard" | "native">
value={sshServerMode} value={sshServerMode}
options={[ options={[
@@ -1870,9 +1870,9 @@ export function PrivateResourceForm({
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<SettingsSubsectionTitle> <p className="font-semibold text-sm">
{t("sshAuthenticationMethod")} {t("sshAuthenticationMethod")}
</SettingsSubsectionTitle> </p>
<FormField <FormField
control={form.control} control={form.control}
name="pamMode" name="pamMode"
@@ -1965,9 +1965,9 @@ export function PrivateResourceForm({
{/* Daemon Location (standard + push) */} {/* Daemon Location (standard + push) */}
{showDaemonLocation && ( {showDaemonLocation && (
<div className="space-y-2"> <div className="space-y-2">
<SettingsSubsectionTitle> <p className="font-semibold text-sm">
{t("sshAuthDaemonLocation")} {t("sshAuthDaemonLocation")}
</SettingsSubsectionTitle> </p>
<FormField <FormField
control={form.control} control={form.control}
name="authDaemonMode" name="authDaemonMode"
+1 -1
View File
@@ -90,7 +90,7 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) {
</InfoSectionTitle> </InfoSectionTitle>
<InfoSectionContent> <InfoSectionContent>
<span className="inline-flex items-center"> <span className="inline-flex items-center">
{resource.mode!.toUpperCase()} {resource.ssl ? "HTTPS" : "HTTP"}
</span> </span>
</InfoSectionContent> </InfoSectionContent>
</InfoSection> </InfoSection>
+2 -4
View File
@@ -70,7 +70,7 @@ export function SettingsSubsectionHeader({
children: React.ReactNode; children: React.ReactNode;
className?: string; className?: string;
}) { }) {
return <div className={cn("space-y-0.5", className)}>{children}</div>; return <div className={cn("py-3 space-y-0.5", className)}>{children}</div>;
} }
export function SettingsSubsectionTitle({ export function SettingsSubsectionTitle({
@@ -80,9 +80,7 @@ export function SettingsSubsectionTitle({
children: React.ReactNode; children: React.ReactNode;
className?: string; className?: string;
}) { }) {
return ( return <h3 className={cn("font-semibold", className)}>{children}</h3>;
<h3 className={cn("text-sm font-semibold", className)}>{children}</h3>
);
} }
export function SettingsSubsectionDescription({ export function SettingsSubsectionDescription({
+1 -1
View File
@@ -157,7 +157,7 @@ export function LabelsSelector({
/> />
<Select defaultValue={randomColor} name="color"> <Select defaultValue={randomColor} name="color">
<SelectTrigger className="w-18 [&_[data-name]]:hidden [&_[svg]]:hidden!"> <SelectTrigger className="w-auto min-w-24">
<SelectValue <SelectValue
placeholder={t("selectColor")} placeholder={t("selectColor")}
/> />
@@ -153,7 +153,7 @@ export function ResourceTargetAddressItem({
}) })
} }
> >
<SelectTrigger className="h-9 pl-2 w-17.5 border-none bg-transparent shadow-none data-[state=open]:bg-transparent rounded-none mr-0 pr-0"> <SelectTrigger className="h-9 w-17.5 border-none bg-transparent shadow-none data-[state=open]:bg-transparent rounded-none mr-0 pr-0">
{proxyTarget.method || "http"} {proxyTarget.method || "http"}
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
@@ -173,7 +173,7 @@ export function ResourceTargetAddressItem({
<Input <Input
defaultValue={proxyTarget.ip} defaultValue={proxyTarget.ip}
placeholder="Host" placeholder="Host"
className="flex-1 min-w-30 px-2 border-none placeholder-gray-400 rounded-xs" className="flex-1 min-w-30 border-none placeholder-gray-400 rounded-xs"
onBlur={(e) => { onBlur={(e) => {
const input = e.target.value.trim(); const input = e.target.value.trim();
const hasProtocol = /^(https?|h2c):\/\//.test(input); const hasProtocol = /^(https?|h2c):\/\//.test(input);
+140
View File
@@ -0,0 +1,140 @@
import { z } from "zod";
type TranslateFn = (key: string) => string;
export const selectedSiteSchema = z.object({
siteId: z.number().int().positive(),
name: z.string(),
type: z.string()
});
export type SelectedSiteFormValue = z.infer<typeof selectedSiteSchema>;
export function createPortStringSchema(t: TranslateFn) {
return z.string().refine(
(val) => {
if (!val) return false;
const n = Number(val);
return Number.isInteger(n) && n >= 1 && n <= 65535;
},
{ message: t("healthCheckPortInvalid") }
);
}
function createOptionalAuthDaemonPortSchema(t: TranslateFn) {
return z.string().refine(
(val) => {
if (!val) return true;
const n = Number(val);
return Number.isInteger(n) && n >= 1 && n <= 65535;
},
{ message: t("healthCheckPortInvalid") }
);
}
export function createBrowserGatewayTargetFormSchema(t: TranslateFn) {
return z.object({
selectedSites: z.array(selectedSiteSchema).min(1, {
message: t("siteRequired")
}),
destination: z.string().min(1, {
message: t("destinationRequired")
}),
destinationPort: createPortStringSchema(t)
});
}
export type BrowserGatewayTargetFormValues = z.infer<
ReturnType<typeof createBrowserGatewayTargetFormSchema>
>;
export function createSshSettingsFormSchema(
t: TranslateFn,
options: { isNative: boolean }
) {
const { isNative } = options;
const portSchema = createPortStringSchema(t);
const optionalAuthDaemonPortSchema = createOptionalAuthDaemonPortSchema(t);
return z
.object({
pamMode: z.enum(["passthrough", "push"]),
standardDaemonLocation: z.enum(["site", "remote"]),
authDaemonPort: z.string(),
selectedSites: z.array(selectedSiteSchema),
selectedSite: selectedSiteSchema.nullable(),
selectedNativeSite: selectedSiteSchema.nullable(),
destination: z.string(),
destinationPort: z.string()
})
.superRefine((data, ctx) => {
if (isNative) {
if (!data.selectedNativeSite) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["selectedNativeSite"],
message: t("siteRequired")
});
}
return;
}
const useMultiSite =
data.standardDaemonLocation !== "site" ||
data.pamMode === "passthrough";
if (useMultiSite) {
if (data.selectedSites.length === 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["selectedSites"],
message: t("siteRequired")
});
}
} else if (!data.selectedSite) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["selectedSite"],
message: t("siteRequired")
});
}
if (!data.destination.trim()) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["destination"],
message: t("destinationRequired")
});
}
const portResult = portSchema.safeParse(data.destinationPort);
if (!portResult.success) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["destinationPort"],
message: t("healthCheckPortInvalid")
});
}
const showDaemonPort =
data.pamMode === "push" &&
data.standardDaemonLocation === "remote";
if (showDaemonPort) {
const authPortResult = optionalAuthDaemonPortSchema.safeParse(
data.authDaemonPort
);
if (!data.authDaemonPort.trim() || !authPortResult.success) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["authDaemonPort"],
message: t("healthCheckPortInvalid")
});
}
}
});
}
export type SshSettingsFormValues = z.infer<
ReturnType<typeof createSshSettingsFormSchema>
>;