Compare commits

...

8 Commits

Author SHA1 Message Date
Maycon Santos
42cd088c5d rebuild self-hosted page as Clusters with type features (#641)
Some checks failed
build and push / build_n_push (push) Has been cancelled
* feat(reverse-proxy): rebuild self-hosted page as Clusters with type + features

The Self-Hosted Proxies page was account-only by design but the
underlying API already returned every cluster the account could see.
Lifting that filter and renaming the page surfaces shared clusters
too — operators can see what NetBird-deployed clusters are reachable
alongside their own self-hosted ones, with online status and feature
support visible per row.

ReverseProxyCluster matches the new backend shape: `type`
(account/shared), `online`, and the three capability flags. The
`isSelfHostedCluster` provider hook now compares against `type ===
account` instead of a deprecated boolean.

Page folder renamed self-hosted-proxies → clusters (history-preserving
git mv). Table columns: Cluster (with an EphemeralPeerIndicator-style
icon next to the name marking account vs shared and a colored dot for
online status), Connected Proxies (plain numeric), Features (one
tooltip-backed badge per supported capability), Actions (Delete only
on account-owned rows; shared clusters render an empty action cell).

Empty state shows when the list is fully empty with a doc link in the
page header. Sidebar entry restored under Reverse Proxy.

* Update record in modal, update doc link, update modal title

* update reverse proxy documentation links to latest anchors

* update cluster modal description to "proxy cluster" instead of "self-hosted cluster"

---------

Co-authored-by: Eduard Gert <kontakt@eduardgert.de>
2026-05-20 11:48:38 +02:00
Maycon Santos
7400ac806e remove self-hosted proxies menu item (#640)
Some checks failed
build and push / build_n_push (push) Has been cancelled
2026-05-14 17:50:07 +02:00
Viktor Liu
240ff5af9a Fix IPv6 input across reverse proxy, routes and resources (#638) 2026-05-14 16:43:02 +02:00
Eduard Gert
dc86c30463 Add self-hosted proxies (#636)
* Add self-hosted proxies

* fix selfhosted badge for domain
2026-05-12 15:22:12 +02:00
Nicolas Frati
e58f75ae3c Enable MFA for local users toggle (#615)
* implement enable mfa for local users toggle

* fix visibility check

* Added beta badge to MFA auth toggle
2026-05-08 16:51:17 +02:00
Viktor Liu
dc1adebd27 Add IPv6 overlay settings and peer display (#594) 2026-05-07 15:20:12 +02:00
Bethuel Mmbaga
d76cbd1122 Add Microsoft AD FS support for embedded Dex identity providers (#625) 2026-04-28 12:42:48 +03:00
Eduard Gert
01330e0f58 Fix missing peer context in group network routes tab (#620)
Some checks failed
build and push / build_n_push (push) Has been cancelled
2026-04-23 17:05:05 +02:00
51 changed files with 1650 additions and 192 deletions

View File

@@ -2,7 +2,6 @@
import Breadcrumbs from "@components/Breadcrumbs";
import Button from "@components/Button";
import { Callout } from "@components/Callout";
import Card from "@components/Card";
import HelpText from "@components/HelpText";
import { Input } from "@components/Input";
@@ -72,6 +71,7 @@ import ReverseProxiesProvider, {
useReverseProxies,
} from "@/contexts/ReverseProxiesProvider";
import { ReverseProxyFlatTargetsTabContent } from "@/modules/reverse-proxy/targets/flat/ReverseProxyFlatTargetsTabContent";
import { PeerEditIPModal } from "@/modules/peer/PeerEditIPModal";
import { PeerSSHToggle } from "@/modules/peer/PeerSSHToggle";
import { RDPButton } from "@/modules/remote-access/rdp/RDPButton";
import { SSHButton } from "@/modules/remote-access/ssh/SSHButton";
@@ -469,31 +469,55 @@ function PeerInformationCard({ peer }: Readonly<{ peer: Peer }>) {
const { update } = usePeer();
const { mutate } = useSWRConfig();
const [showEditIPModal, setShowEditIPModal] = useState(false);
const [showEditIPv6Modal, setShowEditIPv6Modal] = useState(false);
const { permission } = usePermissions();
const countryText = useMemo(() => {
return getRegionByPeer(peer);
}, [getRegionByPeer, peer]);
const handleSaveIP = (newIP: string) => {
notify({
title: peer.name,
description: "NetBird Peer IP was successfully updated",
promise: update({ ip: newIP }).then(() => {
mutate("/peers/" + peer.id);
setShowEditIPModal(false);
}),
loadingMessage: "Updating peer IP...",
});
};
const handleSaveIPv6 = (newIPv6: string) => {
notify({
title: peer.name,
description: "NetBird Peer IPv6 was successfully updated",
promise: update({ ipv6: newIPv6 }).then(() => {
mutate("/peers/" + peer.id);
setShowEditIPv6Modal(false);
}),
loadingMessage: "Updating peer IPv6...",
});
};
return (
<>
<Modal open={showEditIPModal} onOpenChange={setShowEditIPModal}>
<EditIPModal
onSuccess={(newIP) => {
notify({
title: peer.name,
description: "Peer IP was successfully updated",
promise: update({ ip: newIP }).then(() => {
mutate("/peers/" + peer.id);
setShowEditIPModal(false);
}),
loadingMessage: "Updating peer IP...",
});
}}
peer={peer}
key={showEditIPModal ? 1 : 0}
/>
</Modal>
<PeerEditIPModal
version="v4"
currentIP={peer.ip}
open={showEditIPModal}
onOpenChange={setShowEditIPModal}
onSave={handleSaveIP}
key={showEditIPModal ? "v4-open" : "v4-closed"}
/>
<PeerEditIPModal
version="v6"
currentIP={peer.ipv6 || ""}
open={showEditIPv6Modal}
onOpenChange={setShowEditIPv6Modal}
onSave={handleSaveIPv6}
key={showEditIPv6Modal ? "v6-open" : "v6-closed"}
/>
<Card className={"w-full xl:w-1/2"}>
<Card.List>
<Card.ListItem
@@ -502,35 +526,48 @@ function PeerInformationCard({ peer }: Readonly<{ peer: Peer }>) {
copyText={"NetBird IP Address"}
label={
<>
<MapPin size={16} />
<MapPin size={16} className={"shrink-0"} />
NetBird IP Address
</>
}
valueToCopy={peer.ip}
value={
<div className="flex items-center gap-2 justify-between w-full">
<span>{peer.ip}</span>
{permission.peers.update && (
<button
className="flex w-7 h-7 items-center justify-center gap-2 text-nb-gray-400 hover:text-neutral-100 transition-all hover:bg-nb-gray-800/60 rounded-md cursor-pointer"
onClick={(e) => {
e.stopPropagation();
setShowEditIPModal(true);
}}
>
<PencilIcon size={14} />
</button>
)}
</div>
<EditableValue
value={peer.ip}
canEdit={permission.peers.update}
onEdit={() => setShowEditIPModal(true)}
/>
}
/>
{peer.ipv6 && (
<Card.ListItem
copy
tooltip={false}
copyText={"NetBird IPv6 Address"}
label={
<>
<MapPin size={16} className={"shrink-0"} />
NetBird IPv6 Address
</>
}
valueToCopy={peer.ipv6}
value={
<EditableValue
value={peer.ipv6}
canEdit={permission.peers.update}
onEdit={() => setShowEditIPv6Modal(true)}
/>
}
/>
)}
<Card.ListItem
copy
copyText={"Public IP Address"}
label={
<>
<NetworkIcon size={16} />
<NetworkIcon size={16} className={"shrink-0"} />
Public IP Address
</>
}
@@ -542,7 +579,7 @@ function PeerInformationCard({ peer }: Readonly<{ peer: Peer }>) {
copyText={"DNS label"}
label={
<>
<Globe size={16} />
<Globe size={16} className={"shrink-0"} />
Domain Name
</>
}
@@ -560,7 +597,7 @@ function PeerInformationCard({ peer }: Readonly<{ peer: Peer }>) {
copyText={"Hostname"}
label={
<>
<MonitorSmartphoneIcon size={16} />
<MonitorSmartphoneIcon size={16} className={"shrink-0"} />
Hostname
</>
}
@@ -570,7 +607,7 @@ function PeerInformationCard({ peer }: Readonly<{ peer: Peer }>) {
<Card.ListItem
label={
<>
<FlagIcon size={16} />
<FlagIcon size={16} className={"shrink-0"} />
Region
</>
}
@@ -600,7 +637,7 @@ function PeerInformationCard({ peer }: Readonly<{ peer: Peer }>) {
<Card.ListItem
label={
<>
<Cpu size={16} />
<Cpu size={16} className={"shrink-0"} />
Operating System
</>
}
@@ -611,7 +648,7 @@ function PeerInformationCard({ peer }: Readonly<{ peer: Peer }>) {
<Card.ListItem
label={
<>
<Barcode size={16} />
<Barcode size={16} className={"shrink-0"} />
Serial Number
</>
}
@@ -623,7 +660,7 @@ function PeerInformationCard({ peer }: Readonly<{ peer: Peer }>) {
<Card.ListItem
label={
<>
<CalendarDays size={16} />
<CalendarDays size={16} className={"shrink-0"} />
Registered on
</>
}
@@ -639,7 +676,7 @@ function PeerInformationCard({ peer }: Readonly<{ peer: Peer }>) {
<Card.ListItem
label={
<>
<History size={16} />
<History size={16} className={"shrink-0"} />
Last seen
</>
}
@@ -656,7 +693,7 @@ function PeerInformationCard({ peer }: Readonly<{ peer: Peer }>) {
<Card.ListItem
label={
<>
<NetBirdIcon size={16} />
<NetBirdIcon size={16} className={"shrink-0"} />
Agent Version
</>
}
@@ -667,7 +704,7 @@ function PeerInformationCard({ peer }: Readonly<{ peer: Peer }>) {
<Card.ListItem
label={
<>
<NetBirdIcon size={16} />
<NetBirdIcon size={16} className={"shrink-0"} />
UI Version
</>
}
@@ -765,82 +802,29 @@ function EditNameModal({ onSuccess, peer, initialName }: Readonly<ModalProps>) {
);
}
interface EditIPModalProps {
onSuccess: (ip: string) => void;
peer: Peer;
}
function EditIPModal({ onSuccess, peer }: Readonly<EditIPModalProps>) {
const [ip, setIP] = useState(peer.ip);
const [error, setError] = useState("");
const validateIP = (ipAddress: string) => {
const ipRegex =
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
return ipRegex.test(ipAddress);
};
const isDisabled = useMemo(() => {
if (ip === peer.ip) return true;
const trimmedIP = trim(ip);
return trimmedIP.length === 0 || !validateIP(ip);
}, [ip, peer.ip]);
React.useEffect(() => {
switch (true) {
case ip === peer.ip:
setError("");
break;
case !validateIP(ip):
setError("Please enter a valid IP, e.g., 100.64.0.15");
break;
default:
setError("");
break;
}
}, [ip, peer.ip]);
function EditableValue({
value,
canEdit,
onEdit,
}: {
value: string;
canEdit: boolean;
onEdit: () => void;
}) {
return (
<ModalContent maxWidthClass={"max-w-md"}>
<form>
<ModalHeader
title={"Edit Peer IP Address"}
description={"Update the NetBird IP address for this peer."}
color={"blue"}
/>
<div className={"p-default flex flex-col gap-4"}>
<div>
<Input
placeholder={"e.g., 100.64.0.15"}
value={ip}
onChange={(e) => setIP(e.target.value)}
error={error}
/>
</div>
<Callout>Changes take effect when the peer reconnects.</Callout>
</div>
<ModalFooter className={"items-center"} separator={false}>
<div className={"flex gap-3 w-full justify-end"}>
<ModalClose asChild={true}>
<Button variant={"secondary"} className={"w-full"}>
Cancel
</Button>
</ModalClose>
<Button
variant={"primary"}
className={"w-full"}
onClick={() => onSuccess(ip)}
disabled={isDisabled}
>
Save
</Button>
</div>
</ModalFooter>
</form>
</ModalContent>
<div className="flex items-center gap-2 justify-between w-full">
<span>{value}</span>
{canEdit && (
<button
className="flex w-7 h-7 items-center justify-center gap-2 text-nb-gray-400 hover:text-neutral-100 transition-all hover:bg-nb-gray-800/60 rounded-md cursor-pointer"
onClick={(e) => {
e.stopPropagation();
onEdit();
}}
>
<PencilIcon size={14} />
</button>
)}
</div>
);
}

View File

@@ -0,0 +1,8 @@
import { globalMetaTitle } from "@utils/meta";
import type { Metadata } from "next";
import BlankLayout from "@/layouts/BlankLayout";
export const metadata: Metadata = {
title: `Clusters - Reverse Proxy - ${globalMetaTitle}`,
};
export default BlankLayout;

View File

@@ -0,0 +1,66 @@
"use client";
import Breadcrumbs from "@components/Breadcrumbs";
import InlineLink from "@components/InlineLink";
import Paragraph from "@components/Paragraph";
import SkeletonTable from "@components/skeletons/SkeletonTable";
import { RestrictedAccess } from "@components/ui/RestrictedAccess";
import { usePortalElement } from "@hooks/usePortalElement";
import { ExternalLinkIcon } from "lucide-react";
import React, { lazy, Suspense } from "react";
import ReverseProxyIcon from "@/assets/icons/ReverseProxyIcon";
import { usePermissions } from "@/contexts/PermissionsProvider";
import { REVERSE_PROXY_CLUSTERS_DOCS_LINK } from "@/interfaces/ReverseProxy";
import PageContainer from "@/layouts/PageContainer";
const ClustersTable = lazy(
() => import("@/modules/reverse-proxy/clusters/ClustersTable"),
);
export default function ReverseProxyClustersPage() {
const { permission } = usePermissions();
const { ref: headingRef, portalTarget } =
usePortalElement<HTMLHeadingElement>();
return (
<PageContainer>
<div className={"p-default py-6"}>
<Breadcrumbs>
<Breadcrumbs.Item
href={"/reverse-proxy/services"}
label={"Reverse Proxy"}
icon={<ReverseProxyIcon size={16} />}
/>
<Breadcrumbs.Item
href={"/reverse-proxy/clusters"}
label={"Clusters"}
active={true}
/>
</Breadcrumbs>
<h1 ref={headingRef}>Clusters</h1>
<Paragraph>
Proxy clusters that route inbound traffic to your services. Shared
clusters are deployed at the server level; account clusters are
self-hosted on your own infrastructure.
</Paragraph>
<Paragraph>
Learn more about
<InlineLink href={REVERSE_PROXY_CLUSTERS_DOCS_LINK} target={"_blank"}>
Clusters
<ExternalLinkIcon size={12} />
</InlineLink>
in our documentation.
</Paragraph>
</div>
<RestrictedAccess
page={"Clusters"}
hasAccess={permission?.services?.read}
>
<Suspense fallback={<SkeletonTable />}>
<ClustersTable headingTarget={portalTarget} />
</Suspense>
</RestrictedAccess>
</PageContainer>
);
}

View File

@@ -18,7 +18,7 @@ import {
} from "@utils/version";
export default function SSHPage() {
const { peerId, username, port } = useSSHQueryParams();
const { peerId, username, port, ipVersion } = useSSHQueryParams();
const {
data: peer,
@@ -48,6 +48,7 @@ export default function SSHPage() {
peer={peer}
username={username}
port={port}
ipVersion={ipVersion}
/>
) : (
<LoadingMessage message={"Starting ssh session..."} />
@@ -60,9 +61,10 @@ type Props = {
username: string;
port: string;
peer: Peer;
ipVersion: string | null;
};
function SSHTerminal({ username, port, peer }: Props) {
function SSHTerminal({ username, port, peer, ipVersion }: Props) {
const client = useNetBirdClient();
const connected = useRef(false);
const sshConnectedOnce = useRef(false);
@@ -81,9 +83,12 @@ function SSHTerminal({ username, port, peer }: Props) {
const isClientDisconnected = client.status === NetBirdStatus.DISCONNECTED;
const isClientConnecting = client.status === NetBirdStatus.CONNECTING;
// Use the FQDN when an IP version is specified so the dialer resolves to the correct address family.
const sshHost = ipVersion ? peer.dns_label || peer.ip : peer.ip;
useEffect(() => {
document.title = `${username}@${peer.ip} - ${peer.hostname}`;
}, [username, peer, client]);
document.title = `${username}@${sshHost} - ${peer.hostname}`;
}, [username, peer, client, sshHost]);
const handleReconnect = async () => {
if (!peer?.id) return;
@@ -97,9 +102,10 @@ function SSHTerminal({ username, port, peer }: Props) {
const rules = [`${protocol}/${aclPort}`];
await client?.connectTemporary(peer.id, rules);
await ssh({
hostname: peer.ip,
hostname: sshHost,
port: Number(port),
username,
ipVersion: ipVersion || undefined,
});
} catch (error) {
console.error("Reconnection failed:", error);
@@ -123,9 +129,10 @@ function SSHTerminal({ username, port, peer }: Props) {
const rules = [`${protocol}/${aclPort}`];
await client?.connectTemporary(peer.id, rules);
const res = await ssh({
hostname: peer.ip,
hostname: sshHost,
port: Number(port),
username,
ipVersion: ipVersion || undefined,
});
if (res === SSHStatus.CONNECTED) {
sshConnectedOnce.current = true;

View File

@@ -23,6 +23,7 @@ export const idpIcon = (
zitadel: <ZitadelIcon size={size} />,
authentik: <AuthentikIcon size={size} />,
keycloak: <KeycloakIcon size={size} />,
adfs: <MicrosoftIcon size={size} />,
oidc: <KeyRound size={size} className="text-nb-gray-400" />,
};

View File

@@ -50,11 +50,11 @@ function CardListItem({
return (
<li
className={cn(
"flex justify-between px-4 border-b border-nb-gray-900 py-4 last:border-b-0 items-center h-full",
"flex justify-between px-4 border-b border-nb-gray-900 py-3.5 last:border-b-0 items-center h-full",
className,
)}
>
<div className={"flex gap-2.5 items-center text-sm"}>{label}</div>
<div className={"flex gap-2.5 items-center text-[0.84rem]"}>{label}</div>
<div className={"flex flex-col gap-2"}>
<CardTextItem
label={label}
@@ -100,7 +100,7 @@ const CardTextItem = ({
return (
<div
className={cn(
"text-right text-nb-gray-400 text-sm flex items-center gap-2",
"text-right text-nb-gray-400 text-[0.84rem] flex items-center gap-2",
copy && "cursor-pointer hover:text-nb-gray-300 transition-all",
)}
onClick={() =>

View File

@@ -0,0 +1,129 @@
import useCopyToClipboard from "@hooks/useCopyToClipboard";
import { cn } from "@utils/helpers";
import { Copy } from "lucide-react";
import React from "react";
type CardTableProps = {
children: React.ReactNode;
className?: string;
};
function CardTable({ children, className }: CardTableProps) {
return (
<div
className={cn(
"bg-nb-gray-940 rounded-md border border-nb-gray-900 w-full overflow-hidden",
className,
)}
>
<table className={"w-full border-collapse text-sm"}>{children}</table>
</div>
);
}
function CardTableHeader({ children, className }: CardTableProps) {
return (
<thead>
<tr
className={cn(
"border-b border-nb-gray-900",
className,
)}
>
{children}
</tr>
</thead>
);
}
type CardTableHeaderCellProps = {
children: React.ReactNode;
width?: number;
className?: string;
};
function CardTableHeaderCell({
children,
width,
className,
}: CardTableHeaderCellProps) {
return (
<th
className={cn(
"px-4 py-2.5 text-left text-sm font-normal",
className,
)}
style={width ? { width } : undefined}
>
{children}
</th>
);
}
function CardTableBody({ children, className }: CardTableProps) {
return <tbody className={className}>{children}</tbody>;
}
type CardTableRowProps = {
children: React.ReactNode;
className?: string;
};
function CardTableRow({ children, className }: CardTableRowProps) {
return (
<tr
className={cn(
"border-b border-nb-gray-900 last:border-b-0",
className,
)}
>
{children}
</tr>
);
}
type CardTableCellProps = {
children: React.ReactNode;
copy?: boolean;
copyText?: string;
width?: number;
className?: string;
};
function CardTableCell({
children,
copy = false,
copyText,
width,
className,
}: CardTableCellProps) {
const [, copyToClipBoard] = useCopyToClipboard(copyText ?? "");
return (
<td
className={cn("px-4 py-3", className)}
style={width ? { width } : undefined}
>
<div
className={cn(
"text-nb-gray-400 text-sm flex items-center gap-2",
copy && "cursor-pointer hover:text-nb-gray-300 transition-all",
)}
onClick={() =>
copy &&
copyToClipBoard(`${copyText} has been copied to clipboard.`)
}
>
{children}
{copy && <Copy size={13} className={"shrink-0"} />}
</div>
</td>
);
}
CardTable.Header = CardTableHeader;
CardTable.HeaderCell = CardTableHeaderCell;
CardTable.Body = CardTableBody;
CardTable.Row = CardTableRow;
CardTable.Cell = CardTableCell;
export default CardTable;

View File

@@ -290,7 +290,7 @@ export function PeerGroupSelector({
const searchPlaceholder = useMemo(() => {
if (tab === "groups") return placeholderForSearch;
if (tab === "resources") return "Search resource...";
if (tab === "peers") return "Search peer...";
if (tab === "peers") return "Search peer by name or ip...";
return "Search...";
}, [tab, placeholderForSearch]);
@@ -537,9 +537,6 @@ export function PeerGroupSelector({
const isSelected =
values.find((group) => group.name == option.name) !=
undefined;
const peerCount =
option.peers?.length ?? option?.peers_count ?? 0;
const isDisabled = disabledGroups
? disabledGroups?.findIndex(
(g) => g.id === option.id,
@@ -968,7 +965,8 @@ const ResourcesList = ({
const peersSearchPredicate = (item: Peer, query: string) => {
const lowerCaseQuery = query.toLowerCase();
if (item.name.toLowerCase().includes(lowerCaseQuery)) return true;
return item.ip.toLowerCase().includes(lowerCaseQuery);
if (item.ip.toLowerCase().includes(lowerCaseQuery)) return true;
return item.ipv6?.toLowerCase().includes(lowerCaseQuery) ?? false;
};
const PeersList = ({

View File

@@ -30,7 +30,8 @@ const searchPredicate = (item: Peer, query: string) => {
const lowerCaseQuery = query.toLowerCase();
if (item.name.toLowerCase().includes(lowerCaseQuery)) return true;
if (item.hostname.toLowerCase().includes(lowerCaseQuery)) return true;
return item.ip.toLowerCase().startsWith(lowerCaseQuery);
if (item.ip.toLowerCase().startsWith(lowerCaseQuery)) return true;
return !!item.ipv6?.toLowerCase().startsWith(lowerCaseQuery);
};
export function PeerSelector({
@@ -124,7 +125,6 @@ export function PeerSelector({
"text-neutral-500 dark:text-nb-gray-300 font-medium flex items-center gap-1 font-mono text-[10px]"
}
>
<MapPinIcon />
{value.ip}
</div>
</div>
@@ -238,7 +238,6 @@ export function PeerSelector({
!isSupported && "opacity-50",
)}
>
<MapPinIcon />
{option.ip}
</div>
</FullTooltip>

View File

@@ -30,6 +30,7 @@ const PeerContext = React.createContext(
inactivityExpiration?: boolean;
approval_required?: boolean;
ip?: string;
ipv6?: string;
}) => Promise<Peer>;
toggleSSH: (newState: boolean) => Promise<void>;
setSSHInstructionsModal: (open: boolean) => void;
@@ -80,6 +81,7 @@ export default function PeerProvider({
inactivityExpiration?: boolean;
approval_required?: boolean;
ip?: string;
ipv6?: string;
}) => {
return peerRequest.put(
{
@@ -99,6 +101,7 @@ export default function PeerProvider({
? undefined
: props.approval_required,
ip: props.ip != undefined ? props.ip : undefined,
ipv6: props.ipv6 != undefined ? props.ipv6 : undefined,
},
`/${peer.id}`,
);

View File

@@ -2,6 +2,7 @@
import { notify } from "@components/Notification";
import useFetchApi, { useApiCall } from "@utils/api";
import { wrapIPv6 } from "@utils/ip";
import React, {
createContext,
useCallback,
@@ -15,6 +16,8 @@ import { Network, NetworkResource } from "@/interfaces/Network";
import { Peer } from "@/interfaces/Peer";
import {
ReverseProxy,
ReverseProxyCluster,
ReverseProxyClusterType,
ReverseProxyDomain,
ReverseProxyFlatTarget,
ReverseProxyTarget,
@@ -23,6 +26,7 @@ import {
} from "@/interfaces/ReverseProxy";
import ReverseProxyModal from "@/modules/reverse-proxy/ReverseProxyModal";
import ReverseProxyTargetModal from "@/modules/reverse-proxy/targets/ReverseProxyTargetModal";
import { usePermissions } from "@/contexts/PermissionsProvider";
type ReverseProxiesContextValue = {
reverseProxies: ReverseProxy[] | undefined;
@@ -51,6 +55,9 @@ type ReverseProxiesContextValue = {
domain: string,
targetCluster: string,
) => Promise<ReverseProxyDomain>;
clusters: ReverseProxyCluster[] | undefined;
isClustersLoading: boolean;
isSelfHostedCluster: (clusterAddress?: string) => boolean;
};
type OpenModalOptions = {
@@ -90,10 +97,14 @@ export default function ReverseProxiesProvider({
}: Readonly<Props>) {
const { mutate } = useSWRConfig();
const { confirm } = useDialog();
const { permission } = usePermissions();
// Reverse Proxies
const { data: rawReverseProxies, isLoading } = useFetchApi<ReverseProxy[]>(
"/reverse-proxies/services",
false,
true,
permission?.services.read,
);
const request = useApiCall<ReverseProxy>("/reverse-proxies/services", true);
@@ -101,6 +112,9 @@ export default function ReverseProxiesProvider({
const { data: peers } = useFetchApi<Peer[]>("/peers");
const { data: resources } = useFetchApi<NetworkResource[]>(
"/networks/resources",
false,
true,
permission?.services.read,
);
const resolveDestination = useCallback(
@@ -125,12 +139,28 @@ export default function ReverseProxiesProvider({
// Domains
const { data: domains, isLoading: isLoadingDomains } = useFetchApi<
ReverseProxyDomain[]
>("/reverse-proxies/domains");
>("/reverse-proxies/domains", false, true, permission.services?.read);
const domainRequest = useApiCall<ReverseProxyDomain>(
"/reverse-proxies/domains",
true,
);
// Clusters
const { data: clusters, isLoading: isClustersLoading } = useFetchApi<
ReverseProxyCluster[]
>("/reverse-proxies/clusters", false, true, permission.services?.read);
const isSelfHostedCluster = useCallback(
(clusterAddress?: string) => {
if (!clusterAddress) return false;
return (
clusters?.find((c) => c.address === clusterAddress)?.type ===
ReverseProxyClusterType.ACCOUNT
);
},
[clusters],
);
const [modalOpen, setModalOpen] = useState(false);
const [currentProxy, setCurrentProxy] = useState<ReverseProxy | undefined>();
const [initialTab, setInitialTab] = useState<string | undefined>();
@@ -483,6 +513,9 @@ export default function ReverseProxiesProvider({
createDomain,
validateDomain,
deleteDomain,
clusters,
isClustersLoading,
isSelfHostedCluster,
}}
>
{children}
@@ -604,7 +637,7 @@ function formatTargetDestination(
target: ReverseProxyTarget,
resolvedHost?: string,
): string {
const host = target.host || resolvedHost || "localhost";
const host = wrapIPv6(target.host || resolvedHost || "localhost");
const isDefault =
(target.protocol === "http" && target.port === 80) ||
(target.protocol === "https" && target.port === 443) ||

View File

@@ -28,6 +28,9 @@ export interface Account {
auto_update_version: string;
auto_update_always: boolean;
local_auth_disabled?: boolean;
local_mfa_enabled?: boolean;
ipv6_enabled_groups?: string[];
network_range_v6?: string;
};
onboarding?: AccountOnboarding;
}

View File

@@ -44,7 +44,8 @@ export type SSOIdentityProviderType =
| "pocketid"
| "microsoft"
| "authentik"
| "keycloak";
| "keycloak"
| "adfs";
export const SSOIdentityProviderOptions: {
value: SSOIdentityProviderType;
@@ -59,6 +60,7 @@ export const SSOIdentityProviderOptions: {
{ value: "pocketid", label: "PocketID" },
{ value: "authentik", label: "Authentik" },
{ value: "keycloak", label: "Keycloak" },
{ value: "adfs", label: "Microsoft AD FS" },
];
export const getSSOIdentityProviderLabelByType = (

View File

@@ -5,6 +5,7 @@ export interface Peer {
id?: string;
name: string;
ip: string;
ipv6?: string;
connected: boolean;
created_at?: Date;
last_seen: Date;

View File

@@ -15,6 +15,7 @@ export interface ReverseProxy {
proxy_cluster?: string;
targets: ReverseProxyTarget[];
enabled: boolean;
terminated?: boolean;
pass_host_header?: boolean;
rewrite_redirects?: boolean;
auth?: ReverseProxyAuth;
@@ -162,6 +163,33 @@ export interface ReverseProxyEvent {
metadata?: Record<string, string>;
}
export enum ReverseProxyClusterType {
ACCOUNT = "account",
SHARED = "shared",
}
export interface ReverseProxyCluster {
id?: string;
address: string;
type: ReverseProxyClusterType;
online: boolean;
connected_proxies: number;
supports_custom_ports?: boolean;
require_subdomain?: boolean;
supports_crowdsec?: boolean;
}
export interface ReverseProxyClusterToken {
id?: string;
name: string;
plain_token?: string;
expires_at?: string;
expires_in?: number;
created_at?: string;
last_used?: string;
revoked?: boolean;
}
export function isL4Event(event: ReverseProxyEvent): boolean {
return (
event.protocol === EventProtocol.TCP ||
@@ -198,19 +226,19 @@ export const REVERSE_PROXY_SETTINGS_DOCS_LINK =
"https://docs.netbird.io/manage/reverse-proxy#step-4-configure-advanced-settings";
export const REVERSE_PROXY_CLUSTERS_DOCS_LINK =
"https://docs.netbird.io/manage/reverse-proxy#self-hosted-proxy-setup";
"https://docs.netbird.io/manage/reverse-proxy/bring-your-own-proxy#shared-and-account-clusters";
export const REVERSE_PROXY_CUSTOM_DOMAINS_DOCS_LINK =
"https://docs.netbird.io/manage/reverse-proxy/custom-domains";
export const REVERSE_PROXY_DOMAIN_VERIFICATION_LINK =
"https://docs.netbird.io/manage/reverse-proxy/custom-domains#validating-a-custom-domain";
"https://docs.netbird.io/manage/reverse-proxy/custom-domains#verifying-a-custom-domain";
export const REVERSE_PROXY_EVENTS_DOCS_LINK =
"https://docs.netbird.io/manage/reverse-proxy/access-logs";
export const REVERSE_PROXY_ACCESS_CONTROL_DOCS_LINK =
"https://docs.netbird.io/manage/reverse-proxy";
"https://docs.netbird.io/manage/reverse-proxy#step-3b-configure-access-control";
export const REVERSE_PROXY_TROUBLESHOOTING_DOCS_LINK =
"https://docs.netbird.io/manage/reverse-proxy#troubleshooting";
"https://docs.netbird.io/manage/reverse-proxy/troubleshooting";

View File

@@ -37,6 +37,7 @@ export default function Navigation({
return (
<div
data-navigation
className={cn(
"whitespace-nowrap md:border-r dark:border-zinc-700/40 bg-gray-50 dark:bg-nb-gray relative group/navigation transition-all",
hideOnMobile ? "hidden md:block" : "",
@@ -165,6 +166,13 @@ export default function Navigation({
exactPathMatch={true}
visible={permission?.services?.read}
/>
<SidebarItem
label="Clusters"
isChild
href={"/reverse-proxy/clusters"}
exactPathMatch={true}
visible={permission?.services?.read}
/>
</SidebarItem>
<SidebarItem

View File

@@ -1,5 +1,6 @@
import React from "react";
import { useGroupContext } from "@/contexts/GroupProvider";
import PeersProvider from "@/contexts/PeersProvider";
import { Route } from "@/interfaces/Route";
import { GroupDetailsTableContainer } from "@/modules/groups/details/GroupDetailsTableContainer";
import NetworkRoutesTable from "@/modules/route-group/NetworkRoutesTable";
@@ -18,14 +19,16 @@ export const GroupNetworkRoutesSection = ({
const { group } = useGroupContext();
return (
<GroupDetailsTableContainer>
<NetworkRoutesTable
isGroupPage={true}
isLoading={isLoading}
groupedRoutes={groupedRoutes}
routes={routes}
distributionGroups={[group]}
/>
</GroupDetailsTableContainer>
<PeersProvider>
<GroupDetailsTableContainer>
<NetworkRoutesTable
isGroupPage={true}
isLoading={isLoading}
groupedRoutes={groupedRoutes}
routes={routes}
distributionGroups={[group]}
/>
</GroupDetailsTableContainer>
</PeersProvider>
);
};

View File

@@ -19,6 +19,7 @@ import { HelpTooltip } from "@components/HelpTooltip";
import { PeerGroupSelector } from "@components/PeerGroupSelector";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@components/Tabs";
import { useApiCall } from "@utils/api";
import { normalizeHostCIDR } from "@utils/ip";
import { useDialog } from "@/contexts/DialogProvider";
import { usePolicies } from "@/contexts/PoliciesProvider";
import { useNetworksContext } from "@/modules/networks/NetworkProvider";
@@ -172,7 +173,7 @@ export function ResourceModalContent({
const promise = create({
name,
description,
address,
address: normalizeHostCIDR(address),
groups: savedGroups ? savedGroups.map((g) => g.id) : undefined,
enabled,
}).then(async (r) => {
@@ -196,7 +197,7 @@ export function ResourceModalContent({
const promise = update({
name,
description,
address,
address: normalizeHostCIDR(address),
groups: savedGroups ? savedGroups.map((g) => g.id) : undefined,
enabled,
}).then(async (r) => {

View File

@@ -58,7 +58,7 @@ export const ResourceSingleAddressInput = ({
// Case 2: If it's not a valid domain, check if it's a valid CIDR
if (!cidr.isValidAddress(value)) {
return "Please enter a valid IP or CIDR, e.g., 10.0.0.21, 192.168.1.0/24";
return "Please enter a valid IP or CIDR, e.g., 10.0.0.21, 192.168.1.0/24, 2001:db8::1 or 2001:db8::/64";
}
return ""; // Valid CIDR

View File

@@ -34,7 +34,7 @@ export const NetworkRoutingPeersTabContent = ({
return {
...router,
search: `${peer?.name ?? ""} ${peer?.ip ?? ""} ${user?.name ?? ""} ${user?.id ?? ""} ${group?.name ?? ""}`,
search: `${peer?.name ?? ""} ${peer?.ip ?? ""} ${peer?.ipv6 ?? ""} ${user?.name ?? ""} ${user?.id ?? ""} ${group?.name ?? ""}`,
};
});
}, [users, peers, routers, groups]);

View File

@@ -2,6 +2,7 @@ import Button from "@components/Button";
import { notify } from "@components/Notification";
import { RadioCard, RadioCardGroup } from "@components/RadioCard";
import { useApiCall } from "@utils/api";
import { normalizeHostCIDR } from "@utils/ip";
import { GlobeIcon, NetworkIcon, WorkflowIcon } from "lucide-react";
import * as React from "react";
import { useMemo, useState } from "react";
@@ -67,7 +68,7 @@ export const OnboardingAddResource = ({
{
name: resourceType === "subnet" ? "My Subnet" : "My Resource",
description: "Created during onboarding",
address: resourceAddress,
address: normalizeHostCIDR(resourceAddress),
enabled: true,
groups: [],
},
@@ -178,15 +179,15 @@ export const OnboardingAddResource = ({
const description = useMemo(() => {
if (resourceType === "ip")
return "Enter a single IPv4 address of your resource";
return "Enter a single IPv4 or IPv6 address of your resource";
if (resourceType === "subnet") return "Enter a CIDR range of your network";
if (resourceType === "domain")
return "Enter a domain name of your resource";
}, [resourceType]);
const placeholder = useMemo(() => {
if (resourceType === "ip") return "e.g., 192.168.31.45";
if (resourceType === "subnet") return "e.g., 192.168.1.0/24";
if (resourceType === "ip") return "e.g., 192.168.31.45 or 2001:db8::1";
if (resourceType === "subnet") return "e.g., 192.168.1.0/24 or 2001:db8::/64";
if (resourceType === "domain")
return "e.g., service.internal or *.services.internal";
}, [resourceType]);
@@ -211,13 +212,13 @@ export const OnboardingAddResource = ({
value={"ip"}
title={"Single IP Address"}
icon={<WorkflowIcon size={12} />}
description={"IPv4 address like 192.168.31.45"}
description={"IPv4 or IPv6 address like 192.168.31.45"}
/>
<RadioCard
value={"subnet"}
title={"Entire Subnet"}
icon={<NetworkIcon size={12} />}
description={"CIDR range like 192.168.0.0/24"}
description={"CIDR range like 192.168.0.0/24 or 2001:db8::/64"}
/>
<RadioCard
value={"domain"}

View File

@@ -32,8 +32,9 @@ export const OnboardingTestResource = ({
const pingAddress = useMemo(() => {
let a = resource?.address || "";
if (isHost && a.endsWith("/32")) {
a = a.slice(0, -3);
if (isHost) {
if (a.endsWith("/32")) a = a.slice(0, -3);
else if (a.endsWith("/128")) a = a.slice(0, -4);
}
if (isWildCard) return `(any subdomain of ${a})`;
return isSubnet ? `(resource ip in your subnet)` : a;

View File

@@ -0,0 +1,118 @@
import Button from "@components/Button";
import { Callout } from "@components/Callout";
import { Input } from "@components/Input";
import {
Modal,
ModalClose,
ModalContent,
ModalFooter,
} from "@components/modal/Modal";
import ModalHeader from "@components/modal/ModalHeader";
import cidr from "ip-cidr";
import { trim } from "lodash";
import React, { useMemo, useState } from "react";
type IPVersion = "v4" | "v6";
interface PeerEditIPModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onSave: (ip: string) => void;
currentIP: string;
version: IPVersion;
}
const config: Record<
IPVersion,
{
title: string;
description: string;
placeholder: string;
errorMessage: string;
validate: (ip: string) => boolean;
}
> = {
v4: {
title: "Edit Peer IP Address",
description: "Update the NetBird IP address for this peer.",
placeholder: "e.g., 100.64.0.15",
errorMessage: "Please enter a valid IP, e.g., 100.64.0.15",
validate: (ip: string) =>
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(
ip,
),
},
v6: {
title: "Edit Peer IPv6 Address",
description: "Update the NetBird IPv6 address for this peer.",
placeholder: "e.g., fd00:1234::1",
errorMessage: "Please enter a valid IPv6 address, e.g., fd00:1234::1",
validate: (ip: string) => cidr.isValidAddress(ip) && ip.includes(":"),
},
};
export function PeerEditIPModal({
open,
onOpenChange,
onSave,
currentIP,
version,
}: Readonly<PeerEditIPModalProps>) {
const { title, description, placeholder, errorMessage, validate } =
config[version];
const [ip, setIP] = useState(currentIP);
const isDisabled = useMemo(() => {
if (ip === currentIP) return true;
const trimmed = trim(ip);
return trimmed.length === 0 || !validate(trimmed);
}, [ip, currentIP, validate]);
const error = useMemo(() => {
if (ip === currentIP) return "";
if (!validate(trim(ip))) return errorMessage;
return "";
}, [ip, currentIP, validate, errorMessage]);
return (
<Modal open={open} onOpenChange={onOpenChange}>
<ModalContent maxWidthClass={"max-w-md"}>
<form>
<ModalHeader title={title} description={description} color={"blue"} />
<div className={"p-default flex flex-col gap-4"}>
<div>
<Input
placeholder={placeholder}
value={ip}
onChange={(e) => setIP(e.target.value)}
error={error}
/>
</div>
<Callout>Changes take effect when the peer reconnects.</Callout>
</div>
<ModalFooter className={"items-center"} separator={false}>
<div className={"flex gap-3 w-full justify-end"}>
<ModalClose asChild={true}>
<Button variant={"secondary"} className={"w-full"}>
Cancel
</Button>
</ModalClose>
<Button
variant={"primary"}
className={"w-full"}
onClick={() => onSave(trim(ip))}
disabled={isDisabled}
>
Save
</Button>
</div>
</ModalFooter>
</form>
</ModalContent>
</Modal>
);
}

View File

@@ -11,6 +11,7 @@ import { PeerAddressTooltipContent } from "@/modules/peers/PeerAddressTooltipCon
type Props = {
peer: Peer;
};
export default function PeerAddressCell({ peer }: Props) {
return (
<FullTooltip

View File

@@ -38,6 +38,21 @@ export const PeerAddressTooltipContent = ({ peer }: Props) => {
</CopyToClipboardText>
}
/>
{peer.ipv6 && (
<ListItem
icon={<MapPin size={14} />}
label={"NetBird IPv6"}
value={
<CopyToClipboardText
iconAlignment={"right"}
message={"NetBird IPv6 has been copied to your clipboard"}
alwaysShowIcon={true}
>
{peer.ipv6}
</CopyToClipboardText>
}
/>
)}
<ListItem
icon={<NetworkIcon size={14} />}
label={"Public IP"}

View File

@@ -214,6 +214,10 @@ const PeersTableColumns: ColumnDef<Peer>[] = [
</PeerProvider>
),
},
{
id: "ipv6",
accessorFn: (row) => row.ipv6,
},
];
type Props = {
@@ -327,6 +331,7 @@ export default function PeersTable({
connect: permission.peers.update,
groups: permission.groups.read,
os: false,
ipv6: false,
}}
isLoading={isLoading}
getStartedCard={<NoPeersGettingStarted showBackground={true} />}

View File

@@ -5,6 +5,7 @@ interface SSHConfig {
hostname: string;
port: number;
username: string;
ipVersion?: string;
}
interface SSHConnection {
@@ -71,6 +72,7 @@ export const useSSH = (client: any) => {
config.port,
config.username,
requiresJwt ? accessToken : undefined,
config.ipVersion,
);
ssh.onclose = () => {

View File

@@ -6,6 +6,7 @@ interface SSHQueryParams {
peerId: string | null;
username: string | null;
port: string | null;
ipVersion: string | null;
}
export function useSSHQueryParams() {
@@ -15,6 +16,7 @@ export function useSSHQueryParams() {
peerId: null,
username: null,
port: null,
ipVersion: null,
});
const [, setLocalQueryParams] = useLocalStorage("netbird-query-params", "");
@@ -22,10 +24,11 @@ export function useSSHQueryParams() {
const peerId = searchParams.get("id");
const username = searchParams.get("user");
const port = searchParams.get("port");
const ipVersion = searchParams.get("ip_version");
// If all params are present in URL, use them
if (peerId && username && port) {
setParams({ peerId, username, port });
setParams({ peerId, username, port, ipVersion });
return;
}
@@ -47,18 +50,23 @@ export function useSSHQueryParams() {
const storedPeerId = urlParams.get("id");
const storedUsername = urlParams.get("user");
const storedPort = urlParams.get("port");
const storedIpVersion = urlParams.get("ip_version");
if (storedPeerId && storedUsername && storedPort) {
const newSearchParams = new URLSearchParams();
newSearchParams.set("id", storedPeerId);
newSearchParams.set("user", storedUsername);
newSearchParams.set("port", storedPort);
if (storedIpVersion) {
newSearchParams.set("ip_version", storedIpVersion);
}
router.replace(`/peer/ssh?${newSearchParams.toString()}`);
setParams({
peerId: storedPeerId,
username: storedUsername,
port: storedPort,
ipVersion: storedIpVersion,
});
// Clear stored params after restoring

View File

@@ -224,6 +224,7 @@ export const useNetBirdClient = () => {
port: number,
username: string,
jwtToken?: string,
ipVersion?: string,
): Promise<any> => {
if (!netBirdClient.current?.createSSHConnection) {
throw new Error("Go client not ready");
@@ -233,6 +234,7 @@ export const useNetBirdClient = () => {
port,
username,
jwtToken,
ipVersion,
);
},
[],

View File

@@ -4,6 +4,7 @@ import HelpText from "@components/HelpText";
import Button from "@components/Button";
import { Input } from "@components/Input";
import cidr from "ip-cidr";
import { isIPv6 } from "@utils/ip";
import {
FlagIcon,
MinusCircleIcon,
@@ -180,13 +181,17 @@ type Props = {
function validateRule(rule: AccessRule): string {
if (rule.type === "country" || !rule.value) return "";
if (rule.type === "ip") {
const val = rule.value.includes("/") ? rule.value : `${rule.value}/32`;
let val = rule.value;
if (!val.includes("/")) {
const suffix = isIPv6(val) ? 128 : 32;
val = `${val}/${suffix}`;
}
if (!cidr.isValidAddress(val)) {
return "Please enter a valid IP address, e.g., 85.203.15.42";
return "Please enter a valid IP address, e.g., 85.203.15.42 or 2001:db8::1";
}
} else {
if (!rule.value.includes("/") || !cidr.isValidAddress(rule.value)) {
return "Please enter a valid CIDR block, e.g., 74.125.0.0/16";
return "Please enter a valid CIDR block, e.g., 74.125.0.0/16 or 2001:db8::/64";
}
}
return "";
@@ -312,8 +317,8 @@ export const ReverseProxyAccessControlRules = ({
<Input
placeholder={
rule.type === "ip"
? "e.g., 85.203.15.42"
: "e.g., 74.125.0.0/16"
? "e.g., 85.203.15.42 or 2001:db8::1"
: "e.g., 74.125.0.0/16 or 2001:db8::/64"
}
value={rule.value}
onChange={(e) =>

View File

@@ -0,0 +1,45 @@
import FullTooltip from "@components/FullTooltip";
import { ServerIcon, UserCog } from "lucide-react";
import * as React from "react";
import {
ReverseProxyCluster,
ReverseProxyClusterType,
} from "@/interfaces/ReverseProxy";
type Props = {
cluster: ReverseProxyCluster;
};
// ClusterTypeIndicator renders a small icon next to the cluster name —
// same pattern as EphemeralPeerIndicator — so the source of the
// cluster is visible at a glance without a dedicated column.
export const ClusterTypeIndicator = ({ cluster }: Props) => {
if (cluster.type === ReverseProxyClusterType.ACCOUNT) {
return (
<FullTooltip
content={
<div className={"text-xs max-w-xs"}>
<span className={"font-medium text-white"}>Account cluster.</span>{" "}
Self-hosted on your own infrastructure you operate the proxy
nodes and control where traffic terminates.
</div>
}
>
<UserCog size={12} className={"shrink-0 text-netbird"} />
</FullTooltip>
);
}
return (
<FullTooltip
content={
<div className={"text-xs max-w-xs"}>
<span className={"font-medium text-white"}>Shared cluster.</span>{" "}
Deployed at the server level and available to every account on this
instance.
</div>
}
>
<ServerIcon size={12} className={"shrink-0 text-nb-gray-300"} />
</FullTooltip>
);
};

View File

@@ -0,0 +1,68 @@
import Button from "@components/Button";
import { notify } from "@components/Notification";
import { useApiCall } from "@utils/api";
import { Trash2 } from "lucide-react";
import * as React from "react";
import { useSWRConfig } from "swr";
import { useDialog } from "@/contexts/DialogProvider";
import { usePermissions } from "@/contexts/PermissionsProvider";
import {
ReverseProxyCluster,
ReverseProxyClusterType,
} from "@/interfaces/ReverseProxy";
type Props = {
cluster: ReverseProxyCluster;
};
export default function ClustersActionCell({ cluster }: Readonly<Props>) {
const { confirm } = useDialog();
const request = useApiCall<ReverseProxyCluster>("/reverse-proxies/clusters");
const { mutate } = useSWRConfig();
const { permission } = usePermissions();
// Shared clusters are operated by NetBird; only account-owned (BYOP)
// clusters can be deleted from this page. Rendering nothing for
// shared rows keeps the cell column-aligned without an inert button.
if (cluster.type !== ReverseProxyClusterType.ACCOUNT) {
return <div className={"pr-4"} />;
}
const handleDelete = async () => {
const choice = await confirm({
title: `Delete '${cluster.address}'?`,
description:
"Are you sure you want to delete this proxy cluster? This action cannot be undone.",
confirmText: "Delete",
cancelText: "Cancel",
type: "danger",
maxWidthClass: "max-w-md",
});
if (!choice) return;
notify({
title: cluster.address,
description: "Proxy cluster was successfully deleted",
promise: request
.del({}, `/${encodeURIComponent(cluster.address)}`)
.then(() => {
mutate("/reverse-proxies/clusters");
}),
loadingMessage: "Deleting the proxy cluster...",
});
};
return (
<div className={"flex justify-end pr-4"}>
<Button
variant={"danger-outline"}
size={"sm"}
onClick={handleDelete}
disabled={!permission?.services?.delete}
>
<Trash2 size={16} />
Delete
</Button>
</div>
);
}

View File

@@ -0,0 +1,21 @@
import Badge from "@components/Badge";
import { Server } from "lucide-react";
import { ReverseProxyCluster } from "@/interfaces/ReverseProxy";
type Props = {
cluster: ReverseProxyCluster;
};
export default function ClustersConnectedCell({ cluster }: Readonly<Props>) {
const count = cluster.connected_proxies;
return (
<div className={"flex"}>
<Badge variant={"gray"}>
<Server size={11} />
<div>
<span className={"font-medium text-xs"}>{count}</span>
</div>
</Badge>
</div>
);
}

View File

@@ -0,0 +1,75 @@
import Badge from "@components/Badge";
import FullTooltip from "@components/FullTooltip";
import { ShieldAlert, SlidersHorizontal, Globe } from "lucide-react";
import { ReverseProxyCluster } from "@/interfaces/ReverseProxy";
import EmptyRow from "@/modules/common-table-rows/EmptyRow";
type Props = {
cluster: ReverseProxyCluster;
};
type Feature = {
key: string;
label: string;
description: string;
icon: React.ReactNode;
};
// ClustersFeaturesCell renders one badge per supported capability.
// Only "true" flags get a badge; nil and false are omitted (the
// backend distinguishes "unsupported" from "not yet reported" via
// nullable booleans, but visually both mean "not available here").
export default function ClustersFeaturesCell({ cluster }: Readonly<Props>) {
const features: Feature[] = [];
if (cluster.supports_custom_ports) {
features.push({
key: "custom-ports",
label: "Custom Ports",
description: "Cluster can bind arbitrary TCP/UDP ports for services.",
icon: <SlidersHorizontal size={14} className={"text-netbird"} />,
});
}
if (cluster.require_subdomain) {
features.push({
key: "subdomain",
label: "Subdomain Required",
description:
"Services on this cluster must use a subdomain — the bare cluster domain is not addressable.",
icon: <Globe size={14} className={"text-nb-gray-300"} />,
});
}
if (cluster.supports_crowdsec) {
features.push({
key: "crowdsec",
label: "CrowdSec",
description:
"Cluster has CrowdSec IP reputation configured across all active proxies.",
icon: <ShieldAlert size={14} className={"text-green-500"} />,
});
}
if (features.length === 0) {
return <EmptyRow />;
}
return (
<div className="flex items-center gap-1.5 flex-wrap">
{features.map((f) => (
<FullTooltip
key={f.key}
content={
<div className={"text-xs max-w-xs"}>
<div className={"font-medium text-white"}>{f.label}</div>
<div className={"text-nb-gray-300 mt-1"}>{f.description}</div>
</div>
}
>
<Badge variant={"gray"} className={"h-[34px] cursor-help"}>
{f.icon}
<span className="font-medium text-xs">{f.label}</span>
</Badge>
</FullTooltip>
))}
</div>
);
}

View File

@@ -0,0 +1,339 @@
import Button from "@components/Button";
import { Callout } from "@components/Callout";
import { notify } from "@components/Notification";
import CardTable from "@components/CardTable";
import Code from "@components/Code";
import HelpText from "@components/HelpText";
import { Input } from "@components/Input";
import { Label } from "@components/Label";
import InlineLink from "@components/InlineLink";
import {
Modal,
ModalClose,
ModalContent,
ModalFooter,
} from "@components/modal/Modal";
import Paragraph from "@components/Paragraph";
import ModalHeader from "@components/modal/ModalHeader";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@components/Tabs";
import {
ExternalLinkIcon,
GlobeIcon,
ListIcon,
Loader2,
ServerIcon,
SquareTerminalIcon,
} from "lucide-react";
import React, { useCallback, useMemo, useState } from "react";
import { useSWRConfig } from "swr";
import { useApiCall } from "@/utils/api";
import { cn, validator } from "@utils/helpers";
import { GRPC_API_ORIGIN, isNetBirdHosted } from "@/utils/netbird";
import {
REVERSE_PROXY_CLUSTERS_DOCS_LINK,
ReverseProxyClusterToken,
} from "@/interfaces/ReverseProxy";
type Props = {
open: boolean;
onOpenChange: (open: boolean) => void;
};
export const ClustersModal = ({ open, onOpenChange }: Props) => {
const { mutate } = useSWRConfig();
const [tab, setTab] = useState("domain");
const [domain, setDomain] = useState("");
const [token, setToken] = useState("");
const [isGeneratingToken, setIsGeneratingToken] = useState(true);
const tokenRequest = useApiCall<ReverseProxyClusterToken>(
"/reverse-proxies/proxy-tokens",
);
const domainError = useMemo(() => {
if (!domain) return "";
const isValid = validator.isValidDomain(domain, {
allowWildcard: false,
allowOnlyTld: false,
preventLeadingAndTrailingDots: true,
});
if (!isValid) {
return "Please enter a valid TLD domain, e.g., company.com";
}
return "";
}, [domain]);
const managementUrl = isNetBirdHosted()
? "https://api.netbird.io"
: GRPC_API_ORIGIN || "";
const dockerCommand = `docker run -d \\
-v /var/lib/certs:/certs \\
-e NB_PROXY_CERTIFICATE_DIRECTORY=/certs \\
-e NB_PROXY_ALLOW_INSECURE=true \\
-e NB_PROXY_MANAGEMENT_ADDRESS=${managementUrl} \\
-e NB_PROXY_ACME_CERTIFICATES=true \\
-e NB_PROXY_DOMAIN=${domain} \\
-e NB_PROXY_LOG_LEVEL=info \\
-e NB_PROXY_TOKEN=${token || "<TOKEN>"} \\
-p 80:80 -p 443:443 \\
netbirdio/reverse-proxy:latest`;
const generateToken = useCallback(async () => {
setIsGeneratingToken(true);
const promise = tokenRequest
.post({
name: domain,
expires_in: 0,
})
.then((res) => {
setToken(res?.plain_token ?? "");
})
.finally(() => {
setIsGeneratingToken(false);
});
notify({
title: "Proxy Token",
description: "Failed to generate proxy token",
promise,
loadingMessage: "Generating proxy token...",
showOnlyError: true,
preventSuccessToast: true,
});
return promise;
}, [domain, tokenRequest]);
const goToInstall = useCallback(() => {
setTab("install");
if (!token) generateToken();
}, [token, generateToken]);
const finishSetup = () => {
onOpenChange(false);
mutate("/reverse-proxies/clusters");
};
return (
<Modal open={open} onOpenChange={onOpenChange}>
<ModalContent maxWidthClass={"relative max-w-[600px]"} showClose={true}>
<ModalHeader
icon={<ServerIcon size={16} />}
title={"Setup Cluster"}
description={"Setup a proxy cluster"}
color={"netbird"}
/>
<Tabs
value={tab}
onValueChange={(v) => (v === "install" ? goToInstall() : setTab(v))}
>
<TabsList justify={"start"} className={"px-8"}>
<TabsTrigger value={"domain"}>
<GlobeIcon size={14} />
Domain
</TabsTrigger>
<TabsTrigger
value={"dns"}
disabled={!domain.trim() || !!domainError}
>
<ListIcon size={14} />
DNS Records
</TabsTrigger>
<TabsTrigger
value={"install"}
disabled={!domain.trim() || !!domainError}
>
<SquareTerminalIcon size={14} />
Run the Proxy
</TabsTrigger>
</TabsList>
<TabsContent value={"domain"} className={"pb-8"}>
<div className={"px-8 flex flex-col gap-6"}>
<div>
<Label>Domain</Label>
<HelpText>
Enter a domain name that will be used for your cluster.
</HelpText>
<Input
autoFocus={true}
placeholder={"e.g., proxy.company.com"}
value={domain}
error={domainError}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setDomain(e.target.value)
}
/>
</div>
<Callout variant={"info"}>
In order to run the proxy, please make sure your machine meets
the following requirements:
<ul className={"list-disc pl-4 mt-2 flex flex-col gap-1"}>
<li>
<span className={"text-white font-medium"}>
Publicly accessible IP address
</span>
</li>
<li>
<span className={"text-white font-medium"}>Docker</span>{" "}
installed and running
</li>
<li>
<span className={"text-white font-medium"}>
Port 80 and 443
</span>{" "}
open and not in use
</li>
</ul>
</Callout>
</div>
</TabsContent>
<TabsContent value={"dns"} className={"pb-8"}>
<div className={"px-8 flex flex-col"}>
<div>
<Label>Configure DNS</Label>
<HelpText>
Add the following DNS records pointing to your machine&apos;s
public IP address.
</HelpText>
</div>
<CardTable>
<CardTable.Header>
<CardTable.HeaderCell width={100}>Type</CardTable.HeaderCell>
<CardTable.HeaderCell>Name</CardTable.HeaderCell>
<CardTable.HeaderCell>Content</CardTable.HeaderCell>
</CardTable.Header>
<CardTable.Body>
<CardTable.Row>
<CardTable.Cell>A</CardTable.Cell>
<CardTable.Cell copy copyText={domain}>
{domain}
</CardTable.Cell>
<CardTable.Cell className={"italic"}>
Your machine&apos;s IP
</CardTable.Cell>
</CardTable.Row>
<CardTable.Row>
<CardTable.Cell>CNAME</CardTable.Cell>
<CardTable.Cell copy copyText={`*.${domain}`}>
{`*.${domain}`}
</CardTable.Cell>
<CardTable.Cell copy copyText={domain}>
{domain}
</CardTable.Cell>
</CardTable.Row>
</CardTable.Body>
</CardTable>
</div>
</TabsContent>
<TabsContent value={"install"} className={"pb-8"}>
<div className={"px-8 flex flex-col"}>
<div>
<Label>Run the Proxy with Docker</Label>
<HelpText>
Run the following command on your machine to start the proxy.
</HelpText>
</div>
<Code
codeToCopy={dockerCommand}
className={cn(
"overflow-hidden",
isGeneratingToken && "!border-nb-gray-930",
)}
showCopyIcon={!isGeneratingToken}
>
{isGeneratingToken && (
<div className="absolute inset-0 z-10 flex items-center justify-center gap-2 text-nb-gray-100 bg-nb-gray-950/90">
<Loader2 size={16} className="animate-spin" />
Generating proxy token...
</div>
)}
<Code.Line>docker run -d \</Code.Line>
<Code.Line> -v /var/lib/certs:/certs \</Code.Line>
<Code.Line>
{" "}
-e NB_PROXY_CERTIFICATE_DIRECTORY=/certs \
</Code.Line>
<Code.Line> -e NB_PROXY_ALLOW_INSECURE=true \</Code.Line>
<Code.Line>
{" "}
-e NB_PROXY_MANAGEMENT_ADDRESS=
<span className={"text-netbird"}>{managementUrl}</span> \
</Code.Line>
<Code.Line> -e NB_PROXY_ACME_CERTIFICATES=true \</Code.Line>
<Code.Line>
{" "}
-e NB_PROXY_DOMAIN=
<span className={"text-netbird"}>{domain}</span> \
</Code.Line>
<Code.Line> -e NB_PROXY_LOG_LEVEL=info \</Code.Line>
<Code.Line>
{" "}
-e NB_PROXY_TOKEN=
<span className={"text-netbird"}>{token || "<TOKEN>"}</span> \
</Code.Line>
<Code.Line> -p 80:80 -p 443:443 \</Code.Line>
<Code.Line> netbirdio/reverse-proxy:latest</Code.Line>
</Code>
</div>
</TabsContent>
</Tabs>
<ModalFooter className={"items-center"}>
<div className={"w-full"}>
<Paragraph className={"text-sm mt-auto"}>
Learn more about
<InlineLink
href={REVERSE_PROXY_CLUSTERS_DOCS_LINK}
target={"_blank"}
>
Proxy Cluster
<ExternalLinkIcon size={12} />
</InlineLink>
</Paragraph>
</div>
<div className={"flex gap-3 w-full justify-end"}>
{tab === "domain" && (
<>
<ModalClose asChild={true}>
<Button variant={"secondary"}>Cancel</Button>
</ModalClose>
<Button
variant={"primary"}
onClick={() => setTab("dns")}
disabled={!domain.trim() || !!domainError}
>
Continue
</Button>
</>
)}
{tab === "dns" && (
<>
<Button variant={"secondary"} onClick={() => setTab("domain")}>
Back
</Button>
<Button variant={"primary"} onClick={goToInstall}>
Continue
</Button>
</>
)}
{tab === "install" && (
<>
<Button variant={"secondary"} onClick={() => setTab("dns")}>
Back
</Button>
<Button variant={"primary"} onClick={finishSetup}>
Finish Setup
</Button>
</>
)}
</div>
</ModalFooter>
</ModalContent>
</Modal>
);
};

View File

@@ -0,0 +1,22 @@
import CopyToClipboardText from "@components/CopyToClipboardText";
import CircleIcon from "@/assets/icons/CircleIcon";
import { ReverseProxyCluster } from "@/interfaces/ReverseProxy";
import { ClusterTypeIndicator } from "@/modules/reverse-proxy/clusters/ClusterTypeIndicator";
type Props = {
cluster: ReverseProxyCluster;
};
export default function ClustersNameCell({ cluster }: Readonly<Props>) {
return (
<div className="flex items-center gap-2.5 ml-2">
<CircleIcon active={cluster.online} size={8} inactiveDot={"gray"} />
<CopyToClipboardText
message={`${cluster.address} has been copied to clipboard`}
>
<span className="font-medium">{cluster.address}</span>
</CopyToClipboardText>
<ClusterTypeIndicator cluster={cluster} />
</div>
);
}

View File

@@ -0,0 +1,167 @@
import Button from "@components/Button";
import SquareIcon from "@components/SquareIcon";
import { DataTable } from "@components/table/DataTable";
import DataTableHeader from "@components/table/DataTableHeader";
import DataTableRefreshButton from "@components/table/DataTableRefreshButton";
import { DataTableRowsPerPage } from "@components/table/DataTableRowsPerPage";
import GetStartedTest from "@components/ui/GetStartedTest";
import { ColumnDef, SortingState } from "@tanstack/react-table";
import { PlusCircle, ServerIcon } from "lucide-react";
import { usePathname } from "next/navigation";
import React, { useState } from "react";
import { useSWRConfig } from "swr";
import { usePermissions } from "@/contexts/PermissionsProvider";
import { useLocalStorage } from "@/hooks/useLocalStorage";
import { ReverseProxyCluster } from "@/interfaces/ReverseProxy";
import useFetchApi from "@/utils/api";
import ClustersActionCell from "@/modules/reverse-proxy/clusters/ClustersActionCell";
import ClustersConnectedCell from "@/modules/reverse-proxy/clusters/ClustersConnectedCell";
import ClustersFeaturesCell from "@/modules/reverse-proxy/clusters/ClustersFeaturesCell";
import { ClustersModal } from "@/modules/reverse-proxy/clusters/ClustersModal";
import ClustersNameCell from "@/modules/reverse-proxy/clusters/ClustersNameCell";
const ClustersColumns: ColumnDef<ReverseProxyCluster>[] = [
{
accessorKey: "address",
header: ({ column }) => {
return <DataTableHeader column={column}>Cluster</DataTableHeader>;
},
sortingFn: "text",
cell: ({ row }) => <ClustersNameCell cluster={row.original} />,
},
{
accessorKey: "connected_proxies",
header: ({ column }) => {
return (
<DataTableHeader column={column}>Connected Proxies</DataTableHeader>
);
},
sortingFn: "basic",
cell: ({ row }) => <ClustersConnectedCell cluster={row.original} />,
},
{
id: "features",
header: () => <span className={"font-medium text-xs"}>Features</span>,
enableSorting: false,
cell: ({ row }) => <ClustersFeaturesCell cluster={row.original} />,
},
{
id: "searchString",
accessorFn: (row) => row.address,
},
{
id: "actions",
accessorKey: "address",
header: "",
cell: ({ row }) => <ClustersActionCell cluster={row.original} />,
},
];
type Props = {
headingTarget?: HTMLHeadingElement | null;
};
export default function ClustersTable({ headingTarget }: Readonly<Props>) {
const { mutate } = useSWRConfig();
const path = usePathname();
const { permission } = usePermissions();
const { data: clusters, isLoading } = useFetchApi<ReverseProxyCluster[]>(
"/reverse-proxies/clusters",
);
const rows = clusters ?? [];
const [addModalOpen, setAddModalOpen] = useState(false);
const [sorting, setSorting] = useLocalStorage<SortingState>(
"netbird-table-sort" + path,
[
{
id: "address",
desc: false,
},
],
);
return (
<>
<ClustersModal
open={addModalOpen}
onOpenChange={setAddModalOpen}
key={addModalOpen ? 1 : 0}
/>
<DataTable
headingTarget={headingTarget}
isLoading={isLoading}
inset={false}
keepStateInLocalStorage={false}
text={"Clusters"}
sorting={sorting}
setSorting={setSorting}
columns={ClustersColumns}
data={rows}
useRowId={true}
searchPlaceholder={"Search by cluster domain..."}
columnVisibility={{ searchString: false }}
getStartedCard={
<GetStartedTest
icon={
<SquareIcon
icon={<ServerIcon className={"text-nb-gray-200"} size={20} />}
color={"gray"}
size={"large"}
/>
}
title={"No clusters available"}
description={
"There are no shared clusters connected to your account and no self-hosted clusters configured. Set up a self-hosted cluster to route traffic through your own infrastructure — see the documentation linked above for setup steps."
}
button={
<Button
variant={"primary"}
onClick={() => setAddModalOpen(true)}
disabled={!permission?.services?.create}
>
<PlusCircle size={16} />
Setup Self-Hosted Cluster
</Button>
}
/>
}
rightSide={() => (
<>
{rows.length > 0 && (
<Button
variant={"primary"}
className={"ml-auto"}
onClick={() => setAddModalOpen(true)}
disabled={!permission?.services?.create}
>
<PlusCircle size={16} />
Setup Self-Hosted Cluster
</Button>
)}
</>
)}
>
{(table) => (
<>
<DataTableRowsPerPage
table={table}
disabled={rows.length === 0}
/>
<DataTableRefreshButton
isDisabled={rows.length === 0}
onClick={() => {
mutate("/reverse-proxies/clusters").then();
}}
/>
</>
)}
</DataTable>
</>
);
}

View File

@@ -10,6 +10,7 @@ import { useMemo } from "react";
import { useReverseProxies } from "@/contexts/ReverseProxiesProvider";
import { ReverseProxyDomainType } from "@/interfaces/ReverseProxy";
import { isNetBirdHosted } from "@utils/netbird";
import TruncatedText from "@components/ui/TruncatedText";
interface DomainSelectorProps {
value: string;
@@ -25,7 +26,7 @@ export function CustomDomainSelector({
className,
}: DomainSelectorProps) {
const router = useRouter();
const { domains } = useReverseProxies();
const { domains, isSelfHostedCluster } = useReverseProxies();
const options: SelectOption[] = useMemo(() => {
const opts: SelectOption[] = [];
@@ -34,15 +35,20 @@ export function CustomDomainSelector({
domains
?.filter((d) => d.type === ReverseProxyDomainType.FREE)
.forEach((domain) => {
const isSelfHosted = isSelfHostedCluster(
domain?.target_cluster ?? domain?.domain,
);
opts.push({
value: domain.domain,
label: `.${domain.domain}`,
renderItem: () => (
<div className="flex items-center gap-2 w-full text-sm justify-between">
<div className="flex items-center gap-2">
<span>.{domain.domain}</span>
<TruncatedText text={`.${domain.domain}`} maxWidth={"260px"} />
</div>
{isNetBirdHosted() ? (
{isSelfHosted ? (
<SmallBadge text="Self-hosted" variant="sky" size="md" />
) : isNetBirdHosted() ? (
<SmallBadge text="Free" variant="green" size="md" />
) : (
<SmallBadge text="Cluster" variant="green" size="md" />
@@ -83,7 +89,7 @@ export function CustomDomainSelector({
});
return opts;
}, [domains]);
}, [domains, isSelfHostedCluster]);
const handleChange = (selectedValue: string) => {
if (selectedValue === "add_custom") {
@@ -98,7 +104,7 @@ export function CustomDomainSelector({
value={value}
onChange={handleChange}
options={options}
popoverWidth={335}
popoverWidth={380}
showSearch={true}
searchPlaceholder="Search domains..."
disabled={disabled}

View File

@@ -146,7 +146,7 @@ export default function CustomDomainsTable({ headingTarget }: Readonly<Props>) {
<GetStartedTest
icon={
<SquareIcon
icon={<GlobeIcon className={"fill-nb-gray-200"} size={20} />}
icon={<GlobeIcon className={"text-nb-gray-200"} size={20} />}
color={"gray"}
size={"large"}
/>

View File

@@ -1,5 +1,6 @@
import CopyToClipboardText from "@components/CopyToClipboardText";
import TruncatedText from "@components/ui/TruncatedText";
import { wrapIPv6 } from "@utils/ip";
import * as React from "react";
import {
isL4Event,
@@ -32,9 +33,10 @@ export const ReverseProxyEventsUrlCell = ({ event, service }: Props) => {
const isL4 = isL4Event(event);
const listenPort = service?.listen_port;
const wrappedHost = wrapIPv6(event.host || "");
const hostWithPort =
isL4 && listenPort ? `${event.host}:${listenPort}` : event.host || "-";
const fullUrl = isL4 ? hostWithPort : `${event.host}${event.path}`;
isL4 && listenPort ? `${wrappedHost}:${listenPort}` : wrappedHost || "-";
const fullUrl = isL4 ? hostWithPort : `${wrappedHost}${event.path}`;
return (
<TruncatedText
@@ -51,7 +53,7 @@ export const ReverseProxyEventsUrlCell = ({ event, service }: Props) => {
>
<CopyToClipboardText message={"URL has been copied to your clipboard"}>
<span className="font-mono text-[0.82rem] whitespace-nowrap">
<span className="text-nb-gray-200">{event.host}</span>
<span className="text-nb-gray-200">{wrappedHost}</span>
{isL4 && listenPort && (
<span className="text-nb-gray-300">:{listenPort}</span>
)}

View File

@@ -1,5 +1,6 @@
import Badge from "@components/Badge";
import Button from "@components/Button";
import { wrapIPv6 } from "@utils/ip";
import { PlusCircle, Server } from "lucide-react";
import * as React from "react";
import { usePermissions } from "@/contexts/PermissionsProvider";
@@ -20,7 +21,7 @@ export default function ReverseProxyTargetsCell({
if (isL4Mode(reverseProxy.mode)) {
const target = reverseProxy?.targets?.[0];
const address = target.host
? `${target.host}:${target.port}`
? `${wrapIPv6(target.host)}:${target.port}`
: `:${target.port}`;
return (

View File

@@ -20,8 +20,10 @@ export function useReverseProxyAddress(target: Target | undefined) {
if (!resourceAddress) return false;
if (!cidr.isValidCIDR(resourceAddress)) return false;
const parts = resourceAddress.split("/");
const mask = parts.length === 2 ? parseInt(parts[1], 10) : 32;
return mask < 32;
if (parts.length !== 2) return false;
const mask = parseInt(parts[1], 10);
const hostMask = resourceAddress.includes(":") ? 128 : 32;
return mask < hostMask;
}, [target?.type, resourceAddress]);
const cidrInfo = useMemo(() => {
@@ -84,13 +86,13 @@ export default function ReverseProxyAddressInput({
value={target?.host ?? ""}
onChange={(e) => {
const host = isHostEditable
? e.target.value.replace(/[^0-9.]/g, "")
? e.target.value.replace(/[^0-9a-fA-F.:]/g, "")
: e.target.value;
onChange((prev) => prev && { ...prev, host });
}}
maxWidthClass={"w-full"}
customSuffix={":"}
placeholder="e.g., 192.168.0.10"
placeholder="e.g., 192.168.0.10 or 2001:db8::1"
disabled={!target}
readOnly={target && !isHostEditable ? true : undefined}
className={cn("rounded-r-none border-r-0", className)}

View File

@@ -174,7 +174,7 @@ export default function NetworkRoutesTable({
wrapperComponent={isGroupPage ? Card : undefined}
wrapperProps={isGroupPage ? { className: "mt-6 w-full" } : undefined}
paginationPaddingClassName={isGroupPage ? "px-0 pt-8" : undefined}
tableClassName={isGroupPage ? "mt-0 mb-2" : undefined}
tableClassName={isGroupPage ? "mt-0" : undefined}
inset={false}
minimal={isGroupPage}
keepStateInLocalStorage={!isGroupPage}

View File

@@ -26,6 +26,7 @@ import InputDomain, { domainReducer } from "@components/ui/InputDomain";
import { getOperatingSystem } from "@hooks/useOperatingSystem";
import { IconDirectionSign } from "@tabler/icons-react";
import { cn } from "@utils/helpers";
import { normalizeHostCIDR } from "@utils/ip";
import cidr from "ip-cidr";
import { uniqBy } from "lodash";
import {
@@ -308,7 +309,7 @@ export function RouteModalContent({
enabled: enabled,
peer: useSinglePeer ? routingPeer?.id : undefined,
peer_groups: useSinglePeer ? undefined : peerGroups || undefined,
network: routeType === "ip-range" ? networkRange : undefined,
network: routeType === "ip-range" ? normalizeHostCIDR(networkRange) : undefined,
domains: domainRouteNames,
keep_route: useKeepRoute,
metric: Number(metric) || 9999,
@@ -334,7 +335,7 @@ export function RouteModalContent({
const cidrError = useMemo(() => {
if (networkRange == "") return "";
const validCIDR = cidr.isValidAddress(networkRange);
if (!validCIDR) return "Please enter a valid CIDR, e.g., 192.168.1.0/24";
if (!validCIDR) return "Please enter a valid IP or CIDR, e.g., 192.168.1.1, 192.168.1.0/24 or 2001:db8::/64";
}, [networkRange]);
const isGroupsEntered = useMemo(() => {
@@ -500,11 +501,11 @@ export function RouteModalContent({
)}
>
<Label>Network Range</Label>
<HelpText>Add a private IPv4 address range</HelpText>
<HelpText>Add a private IPv4 or IPv6 address or range</HelpText>
<Input
ref={networkRangeRef}
customPrefix={<NetworkIcon size={16} />}
placeholder={"e.g., 172.16.0.0/16"}
placeholder={"e.g., 172.16.0.1, 172.16.0.0/16, 2001:db8::1 or 2001:db8::/64"}
value={networkRange}
data-cy={"network-range"}
className={"font-mono !text-[13px]"}

View File

@@ -7,6 +7,7 @@ import { Input } from "@components/Input";
import { Label } from "@components/Label";
import { notify } from "@components/Notification";
import Paragraph from "@components/Paragraph";
import { SmallBadge } from "@components/ui/SmallBadge";
import {
Select,
SelectContent,
@@ -22,6 +23,7 @@ import { cn } from "@utils/helpers";
import {
CalendarClock,
ExternalLinkIcon,
KeyRound,
ShieldIcon,
ShieldUserIcon,
TimerResetIcon,
@@ -66,6 +68,15 @@ export default function AuthenticationTab({ account }: Readonly<Props>) {
},
);
// Local MFA (UI only, not wired to the backend yet)
const [isLocalMFAEnabled, setIsLocalMFAEnabled] = useState<boolean>(() => {
try {
return account?.settings?.local_mfa_enabled || false;
} catch (error) {
return false;
}
});
// Peer Expiration
const [
loginExpiration,
@@ -105,6 +116,7 @@ export default function AuthenticationTab({ account }: Readonly<Props>) {
peerInactivityExpirationEnabled,
peerInactivityExpiresIn,
peerInactivityExpireInterval,
isLocalMFAEnabled,
]);
const saveChanges = async () => {
@@ -129,6 +141,7 @@ export default function AuthenticationTab({ account }: Readonly<Props>) {
peer_approval_enabled: peerApproval,
user_approval_required: userApprovalRequired,
},
local_mfa_enabled: isLocalMFAEnabled
},
} as Account)
.then(() => {
@@ -213,6 +226,39 @@ export default function AuthenticationTab({ account }: Readonly<Props>) {
/>
</div>
{!account.settings.local_auth_disabled && account.settings.embedded_idp_enabled ?
(
<div className={"flex flex-col"}>
<FancyToggleSwitch
value={isLocalMFAEnabled}
onChange={setIsLocalMFAEnabled}
dataCy={"local-mfa-enabled"}
label={
<>
<KeyRound size={15} />
Enable Local MFA
<SmallBadge
text={"Beta"}
variant={"sky"}
className={"text-[9px] leading-none py-[3px] px-[5px]"}
textClassName={"top-0"}
/>
</>
}
helpText={
<>
Require multi-factor authentication for users
<br />
authenticating with local credentials.
</>
}
disabled={!permission.settings.update}
/>
</div>
) : null
}
<div className={"flex flex-col"}>
<FancyToggleSwitch
value={loginExpiration}

View File

@@ -49,6 +49,7 @@ const issuerHints: Partial<Record<SSOIdentityProviderType, string>> = {
okta: "https://{ORG}.okta.com",
entra: "https://login.microsoftonline.com/{TENANT_ID}/v2.0",
pocketid: "https://pocketid.example.com",
adfs: "https://adfs.example.com/adfs",
};
const defaultNames: Record<SSOIdentityProviderType, string> = {
@@ -61,6 +62,7 @@ const defaultNames: Record<SSOIdentityProviderType, string> = {
pocketid: "PocketID",
authentik: "Authentik",
keycloak: "Keycloak",
adfs: "Microsoft AD FS",
};
type Props = {

View File

@@ -49,6 +49,7 @@ export const idpTypeLabels: Record<SSOIdentityProviderType, string> = {
microsoft: "Microsoft",
authentik: "Authentik",
keycloak: "Keycloak",
adfs: "Microsoft AD FS",
};
type ActionCellProps = {

View File

@@ -6,6 +6,7 @@ import InlineLink from "@components/InlineLink";
import { Input } from "@components/Input";
import { Label } from "@components/Label";
import { notify } from "@components/Notification";
import { PeerGroupSelector } from "@components/PeerGroupSelector";
import { useHasChanges } from "@hooks/useHasChanges";
import * as Tabs from "@radix-ui/react-tabs";
import { useApiCall } from "@utils/api";
@@ -18,12 +19,25 @@ import { useSWRConfig } from "swr";
import SettingsIcon from "@/assets/icons/SettingsIcon";
import { usePermissions } from "@/contexts/PermissionsProvider";
import { Account } from "@/interfaces/Account";
import useGroupHelper from "@/modules/groups/useGroupHelper";
import { useGroups } from "@/contexts/GroupsProvider";
import { SkeletonSettings } from "@components/skeletons/SkeletonSettings";
type Props = {
account: Account;
};
export default function NetworkSettingsTab({ account }: Readonly<Props>) {
const { isLoading: isGroupsLoading } = useGroups();
return isGroupsLoading ? (
<SkeletonSettings />
) : (
<NetworkSettingsTabContent account={account} />
);
}
function NetworkSettingsTabContent({ account }: Readonly<Props>) {
const { permission } = usePermissions();
const { mutate } = useSWRConfig();
@@ -38,6 +52,17 @@ export default function NetworkSettingsTab({ account }: Readonly<Props>) {
const [networkRange, setNetworkRange] = useState(
account.settings.network_range || "",
);
const [networkRangeV6, setNetworkRangeV6] = useState(
account.settings.network_range_v6 || "",
);
const [ipv6EnabledGroups, setIpv6EnabledGroups, { save: saveGroups }] =
useGroupHelper({
initial: account.settings?.ipv6_enabled_groups,
});
const ipv6GroupNames = useMemo(
() => ipv6EnabledGroups.map((g) => g.name).sort(),
[ipv6EnabledGroups],
);
const toggleNetworkDNSSetting = async (toggle: boolean) => {
notify({
@@ -64,19 +89,37 @@ export default function NetworkSettingsTab({ account }: Readonly<Props>) {
const { hasChanges, updateRef } = useHasChanges([
customDNSDomain,
networkRange,
networkRangeV6,
ipv6GroupNames,
]);
const saveChanges = async () => {
const groups = await saveGroups();
const ipv6EnabledGroupIds = groups
.map((group) => group.id)
.filter(Boolean) as string[];
const updatedSettings = {
...account.settings,
ipv6_enabled_groups: ipv6EnabledGroupIds,
};
if (customDNSDomain !== "" || account.settings.dns_domain) {
updatedSettings.dns_domain = customDNSDomain;
}
if (networkRange !== "") {
// Only send network ranges when the user actually changed them, to avoid
// triggering a reallocation when the server hasn't stored an explicit override.
if (networkRange !== (account.settings.network_range || "")) {
updatedSettings.network_range = networkRange;
} else {
delete updatedSettings.network_range;
}
if (networkRangeV6 !== (account.settings.network_range_v6 || "")) {
updatedSettings.network_range_v6 = networkRangeV6;
} else {
delete updatedSettings.network_range_v6;
}
notify({
@@ -89,7 +132,12 @@ export default function NetworkSettingsTab({ account }: Readonly<Props>) {
})
.then(() => {
mutate("/accounts");
updateRef([customDNSDomain, networkRange]);
updateRef([
customDNSDomain,
networkRange,
networkRangeV6,
ipv6GroupNames,
]);
}),
loadingMessage: "Updating network settings...",
});
@@ -124,6 +172,17 @@ export default function NetworkSettingsTab({ account }: Readonly<Props>) {
}
}, [networkRange, account.settings.network_range]);
const networkRangeV6Error = useMemo(() => {
if (networkRangeV6 == "") return "";
if (!networkRangeV6.includes(":") || !cidr.isValidCIDR(networkRangeV6)) {
return "Please enter a valid IPv6 CIDR range, e.g. fd00:1234::/64";
}
const prefixLen = parseInt(networkRangeV6.split("/")[1], 10);
if (prefixLen < 48 || prefixLen > 112) {
return "Prefix length must be between /48 and /112";
}
}, [networkRangeV6]);
return (
<Tabs.Content value={"networks"}>
<div className={"p-default py-6 max-w-2xl"}>
@@ -150,7 +209,8 @@ export default function NetworkSettingsTab({ account }: Readonly<Props>) {
!hasChanges ||
!permission.settings.update ||
!!domainError ||
!!networkRangeError
!!networkRangeError ||
!!networkRangeV6Error
}
onClick={saveChanges}
>
@@ -216,6 +276,51 @@ export default function NetworkSettingsTab({ account }: Readonly<Props>) {
</div>
</div>
<div>
<div
className={
"flex flex-col gap-1 sm:flex-row w-full sm:gap-4 items-center"
}
>
<div className={"min-w-[330px]"}>
<Label>IPv6 Network Range</Label>
<HelpText>
Specify a custom IPv6 range for your network in CIDR format.
All peer IPv6 addresses will be re-allocated when changed.
</HelpText>
</div>
<div className={"w-full"}>
<Input
placeholder={"e.g. fd00:1234:5678::/64"}
errorTooltip={true}
errorTooltipPosition={"top"}
error={networkRangeV6Error}
value={networkRangeV6}
disabled={!permission.settings.update}
onChange={(e) => setNetworkRangeV6(e.target.value)}
/>
</div>
</div>
</div>
<div>
<Label>IPv6 Enabled Groups</Label>
<HelpText>
Peers in the selected groups will receive IPv6 overlay addresses
(dual-stack). Remove all groups to disable IPv6. Changes apply on
save and will restart affected clients.
</HelpText>
<PeerGroupSelector
values={ipv6EnabledGroups}
onChange={setIpv6EnabledGroups}
placeholder="Select groups to enable IPv6..."
showResourceCounter={false}
disabled={!permission.settings.update}
/>
</div>
<div className={"mt-4"} />
<FancyToggleSwitch
value={routingPeerDNSSetting}
onChange={toggleNetworkDNSSetting}

87
src/utils/ip.test.ts Normal file
View File

@@ -0,0 +1,87 @@
import {
hostSuffixFor,
isIPv4,
isIPv6,
normalizeHostCIDR,
wrapIPv6,
} from "./ip.js";
type Case<T> = { input: string; expected: T; desc?: string };
function run<T>(name: string, cases: Case<T>[], fn: (s: string) => T): number {
console.log(`\n=== ${name} ===`);
let failures = 0;
for (const { input, expected, desc } of cases) {
const actual = fn(input);
const ok = actual === expected;
if (!ok) failures++;
const label = desc ? `${JSON.stringify(input)} (${desc})` : JSON.stringify(input);
console.log(
`${ok ? "✓" : "✗"} ${label.padEnd(40)}${JSON.stringify(actual)}` +
(ok ? "" : ` (expected: ${JSON.stringify(expected)})`),
);
}
return failures;
}
let failures = 0;
failures += run<boolean>("isIPv4", [
{ input: "10.0.0.1", expected: true },
{ input: "192.168.1.0", expected: true },
{ input: "10.0.0.1/32", expected: true, desc: "v4 with prefix" },
{ input: "10.0.0.0/24", expected: true, desc: "v4 subnet" },
{ input: "2001:db8::1", expected: false, desc: "v6" },
{ input: "::1", expected: false, desc: "v6 loopback" },
{ input: "service.internal", expected: false, desc: "domain" },
{ input: "*.example.com", expected: false, desc: "wildcard" },
{ input: "", expected: false },
{ input: "not-an-ip", expected: false },
], isIPv4);
failures += run<boolean>("isIPv6", [
{ input: "2001:db8::1", expected: true },
{ input: "::1", expected: true, desc: "loopback" },
{ input: "::", expected: true, desc: "unspecified" },
{ input: "2620:fe::fe", expected: true, desc: "anycast" },
{ input: "2001:db8::1/128", expected: true, desc: "v6 host CIDR" },
{ input: "2001:db8::/64", expected: true, desc: "v6 subnet" },
{ input: "10.0.0.1", expected: false, desc: "v4" },
{ input: "service.internal", expected: false, desc: "domain" },
{ input: "", expected: false },
], isIPv6);
failures += run<string>("normalizeHostCIDR", [
{ input: "10.0.0.1", expected: "10.0.0.1/32", desc: "bare v4 → /32" },
{ input: "2001:db8::1", expected: "2001:db8::1/128", desc: "bare v6 → /128" },
{ input: "2620:fe::fe", expected: "2620:fe::fe/128" },
{ input: "10.0.0.0/24", expected: "10.0.0.0/24", desc: "v4 CIDR unchanged" },
{ input: "2001:db8::/64", expected: "2001:db8::/64", desc: "v6 CIDR unchanged" },
{ input: "10.0.0.1/32", expected: "10.0.0.1/32", desc: "v4 /32 unchanged" },
{ input: "2001:db8::1/128", expected: "2001:db8::1/128", desc: "v6 /128 unchanged" },
{ input: "service.internal", expected: "service.internal", desc: "domain passthrough" },
{ input: "*.example.com", expected: "*.example.com", desc: "wildcard passthrough" },
{ input: "", expected: "" },
{ input: " 10.0.0.1 ", expected: "10.0.0.1/32", desc: "trims whitespace" },
{ input: "not-an-ip", expected: "not-an-ip", desc: "invalid passthrough" },
], normalizeHostCIDR);
failures += run<number | null>("hostSuffixFor", [
{ input: "10.0.0.1", expected: 32 },
{ input: "2001:db8::1", expected: 128 },
{ input: "service.internal", expected: null, desc: "domain" },
{ input: "", expected: null },
], hostSuffixFor);
failures += run<string>("wrapIPv6", [
{ input: "2001:db8::1", expected: "[2001:db8::1]" },
{ input: "2620:fe::fe", expected: "[2620:fe::fe]" },
{ input: "::1", expected: "[::1]" },
{ input: "[2001:db8::1]", expected: "[2001:db8::1]", desc: "already wrapped" },
{ input: "10.0.0.1", expected: "10.0.0.1", desc: "v4 unchanged" },
{ input: "example.com", expected: "example.com", desc: "domain unchanged" },
{ input: "", expected: "", desc: "empty" },
], wrapIPv6);
console.log(`\n${failures} test(s) failed`);
process.exit(failures > 0 ? 1 : 0);

35
src/utils/ip.ts Normal file
View File

@@ -0,0 +1,35 @@
import { Address4, Address6 } from "ip-address";
export function isIPv6(value: string): boolean {
const bare = value.split("/")[0];
return bare.includes(":") && Address6.isValid(bare);
}
export function isIPv4(value: string): boolean {
const bare = value.split("/")[0];
return !bare.includes(":") && Address4.isValid(bare);
}
// normalizeHostCIDR adds a host-suffix (/32 for IPv4, /128 for IPv6) to bare IP
// addresses. Existing CIDR strings and non-IP values are returned unchanged.
export function normalizeHostCIDR(value: string): string {
const trimmed = value.trim();
if (!trimmed || trimmed.includes("/")) return trimmed;
if (isIPv4(trimmed)) return `${trimmed}/32`;
if (isIPv6(trimmed)) return `${trimmed}/128`;
return trimmed;
}
// hostSuffixFor returns the host suffix (32 or 128) for a given address family.
export function hostSuffixFor(value: string): number | null {
if (isIPv6(value)) return 128;
if (isIPv4(value)) return 32;
return null;
}
// wrapIPv6 wraps a bare IPv6 host in square brackets for use in URL/host:port
// contexts. Bracketed IPv6 ("[...]"), IPv4, and hostnames are returned as-is.
export function wrapIPv6(host: string): string {
if (!host || host.startsWith("[")) return host;
return isIPv6(host) ? `[${host}]` : host;
}

View File

@@ -94,3 +94,4 @@ export const isNetbirdSSHProtocolSupported = (version: string) => {
if (version == "development") return true;
return compareVersions(version, "0.61.0");
};