From 1b3eb32bf4eedeb2bd8aceec0d4b34601eb1ce4b Mon Sep 17 00:00:00 2001 From: Pallavi Date: Sun, 24 Aug 2025 20:57:27 +0530 Subject: [PATCH 01/12] Show targets and status icons in the dashboard --- messages/en-US.json | 16 +- server/auth/actions.ts | 2 + server/routers/external.ts | 14 + server/routers/resource/index.ts | 1 + server/routers/resource/listResources.ts | 107 +++++++- server/routers/resource/tcpCheck.ts | 290 ++++++++++++++++++++ src/app/[orgId]/settings/resources/page.tsx | 220 +++++++-------- src/components/ResourcesTable.tsx | 216 ++++++++++++++- src/hooks/useResourceHealth.ts | 104 +++++++ 9 files changed, 847 insertions(+), 123 deletions(-) create mode 100644 server/routers/resource/tcpCheck.ts create mode 100644 src/hooks/useResourceHealth.ts diff --git a/messages/en-US.json b/messages/en-US.json index 97272c6f..063d9efc 100644 --- a/messages/en-US.json +++ b/messages/en-US.json @@ -2081,5 +2081,19 @@ "supportSend": "Send", "supportMessageSent": "Message Sent!", "supportWillContact": "We'll be in touch shortly!", - "selectLogRetention": "Select log retention" + "selectLogRetention": "Select log retention", + "showColumns": "Show Columns", + "hideColumns": "Hide Columns", + "columnVisibility": "Column Visibility", + "toggleColumn": "Toggle {columnName} column", + "allColumns": "All Columns", + "defaultColumns": "Default Columns", + "customizeView": "Customize View", + "viewOptions": "View Options", + "selectAll": "Select All", + "selectNone": "Select None", + "selectedResources": "Selected Resources", + "enableSelected": "Enable Selected", + "disableSelected": "Disable Selected", + "checkSelectedStatus": "Check Status of Selected" } diff --git a/server/auth/actions.ts b/server/auth/actions.ts index d08457e5..4e271de9 100644 --- a/server/auth/actions.ts +++ b/server/auth/actions.ts @@ -23,6 +23,8 @@ export enum ActionsEnum { deleteResource = "deleteResource", getResource = "getResource", listResources = "listResources", + tcpCheck = "tcpCheck", + batchTcpCheck = "batchTcpCheck", updateResource = "updateResource", createTarget = "createTarget", deleteTarget = "deleteTarget", diff --git a/server/routers/external.ts b/server/routers/external.ts index 5c235902..26254802 100644 --- a/server/routers/external.ts +++ b/server/routers/external.ts @@ -306,6 +306,20 @@ authenticated.get( resource.listResources ); +authenticated.post( + "/org/:orgId/resources/tcp-check", + verifyOrgAccess, + verifyUserHasAction(ActionsEnum.tcpCheck), + resource.tcpCheck +); + +authenticated.post( + "/org/:orgId/resources/tcp-check-batch", + verifyOrgAccess, + verifyUserHasAction(ActionsEnum.batchTcpCheck), + resource.batchTcpCheck +); + authenticated.get( "/org/:orgId/user-resources", verifyOrgAccess, diff --git a/server/routers/resource/index.ts b/server/routers/resource/index.ts index d1c7011d..a757cae3 100644 --- a/server/routers/resource/index.ts +++ b/server/routers/resource/index.ts @@ -25,3 +25,4 @@ export * from "./getUserResources"; export * from "./setResourceHeaderAuth"; export * from "./addEmailToResourceWhitelist"; export * from "./removeEmailFromResourceWhitelist"; +export * from "./tcpCheck"; diff --git a/server/routers/resource/listResources.ts b/server/routers/resource/listResources.ts index 22a10605..8272ac3a 100644 --- a/server/routers/resource/listResources.ts +++ b/server/routers/resource/listResources.ts @@ -6,7 +6,8 @@ import { userResources, roleResources, resourcePassword, - resourcePincode + resourcePincode, + targets, } from "@server/db"; import response from "@server/lib/response"; import HttpCode from "@server/types/HttpCode"; @@ -40,6 +41,53 @@ const listResourcesSchema = z.object({ .pipe(z.number().int().nonnegative()) }); +// (resource fields + a single joined target) +type JoinedRow = { + resourceId: number; + niceId: string; + name: string; + ssl: boolean; + fullDomain: string | null; + passwordId: number | null; + sso: boolean; + pincodeId: number | null; + whitelist: boolean; + http: boolean; + protocol: string; + proxyPort: number | null; + enabled: boolean; + domainId: string | null; + + targetId: number | null; + targetIp: string | null; + targetPort: number | null; + targetEnabled: boolean | null; +}; + +// grouped by resource with targets[]) +export type ResourceWithTargets = { + resourceId: number; + name: string; + ssl: boolean; + fullDomain: string | null; + passwordId: number | null; + sso: boolean; + pincodeId: number | null; + whitelist: boolean; + http: boolean; + protocol: string; + proxyPort: number | null; + enabled: boolean; + domainId: string | null; + niceId: string | null; + targets: Array<{ + targetId: number; + ip: string; + port: number; + enabled: boolean; + }>; +}; + function queryResources(accessibleResourceIds: number[], orgId: string) { return db .select({ @@ -57,7 +105,13 @@ function queryResources(accessibleResourceIds: number[], orgId: string) { enabled: resources.enabled, domainId: resources.domainId, niceId: resources.niceId, - headerAuthId: resourceHeaderAuth.headerAuthId + headerAuthId: resourceHeaderAuth.headerAuthId, + + targetId: targets.targetId, + targetIp: targets.ip, + targetPort: targets.port, + targetEnabled: targets.enabled, + }) .from(resources) .leftJoin( @@ -72,6 +126,7 @@ function queryResources(accessibleResourceIds: number[], orgId: string) { resourceHeaderAuth, eq(resourceHeaderAuth.resourceId, resources.resourceId) ) + .leftJoin(targets, eq(targets.resourceId, resources.resourceId)) .where( and( inArray(resources.resourceId, accessibleResourceIds), @@ -81,7 +136,7 @@ function queryResources(accessibleResourceIds: number[], orgId: string) { } export type ListResourcesResponse = { - resources: NonNullable>>; + resources: ResourceWithTargets[]; pagination: { total: number; limit: number; offset: number }; }; @@ -146,7 +201,7 @@ export async function listResources( ); } - let accessibleResources; + let accessibleResources: Array<{ resourceId: number }>; if (req.user) { accessibleResources = await db .select({ @@ -183,9 +238,49 @@ export async function listResources( const baseQuery = queryResources(accessibleResourceIds, orgId); - const resourcesList = await baseQuery!.limit(limit).offset(offset); + const rows: JoinedRow[] = await baseQuery.limit(limit).offset(offset); + + // avoids TS issues with reduce/never[] + const map = new Map(); + + for (const row of rows) { + let entry = map.get(row.resourceId); + if (!entry) { + entry = { + resourceId: row.resourceId, + niceId: row.niceId, + name: row.name, + ssl: row.ssl, + fullDomain: row.fullDomain, + passwordId: row.passwordId, + sso: row.sso, + pincodeId: row.pincodeId, + whitelist: row.whitelist, + http: row.http, + protocol: row.protocol, + proxyPort: row.proxyPort, + enabled: row.enabled, + domainId: row.domainId, + targets: [], + }; + map.set(row.resourceId, entry); + } + + // Push target if present (left join can be null) + if (row.targetId != null && row.targetIp && row.targetPort != null && row.targetEnabled != null) { + entry.targets.push({ + targetId: row.targetId, + ip: row.targetIp, + port: row.targetPort, + enabled: row.targetEnabled, + }); + } + } + + const resourcesList: ResourceWithTargets[] = Array.from(map.values()); + const totalCountResult = await countQuery; - const totalCount = totalCountResult[0].count; + const totalCount = totalCountResult[0]?.count ?? 0; return response(res, { data: { diff --git a/server/routers/resource/tcpCheck.ts b/server/routers/resource/tcpCheck.ts new file mode 100644 index 00000000..1779cc10 --- /dev/null +++ b/server/routers/resource/tcpCheck.ts @@ -0,0 +1,290 @@ +import { Request, Response, NextFunction } from "express"; +import { z } from "zod"; +import * as net from "net"; +import response from "@server/lib/response"; +import HttpCode from "@server/types/HttpCode"; +import createHttpError from "http-errors"; +import { fromError } from "zod-validation-error"; +import logger from "@server/logger"; +import { OpenAPITags, registry } from "@server/openApi"; + +const tcpCheckSchema = z + .object({ + host: z.string().min(1, "Host is required"), + port: z.number().int().min(1).max(65535), + timeout: z.number().int().min(1000).max(30000).optional().default(5000) + }) + .strict(); + +export type TcpCheckResponse = { + connected: boolean; + host: string; + port: number; + responseTime?: number; + error?: string; +}; + +registry.registerPath({ + method: "post", + path: "/org/{orgId}/resources/tcp-check", + description: "Check TCP connectivity to a host and port", + tags: [OpenAPITags.Resource], + request: { + body: { + content: { + "application/json": { + schema: tcpCheckSchema + } + } + } + }, + responses: { + 200: { + description: "TCP check result", + content: { + "application/json": { + schema: z.object({ + success: z.boolean(), + data: z.object({ + connected: z.boolean(), + host: z.string(), + port: z.number(), + responseTime: z.number().optional(), + error: z.string().optional() + }), + message: z.string() + }) + } + } + } + } +}); + +function checkTcpConnection(host: string, port: number, timeout: number): Promise { + return new Promise((resolve) => { + const startTime = Date.now(); + const socket = new net.Socket(); + + const cleanup = () => { + socket.removeAllListeners(); + if (!socket.destroyed) { + socket.destroy(); + } + }; + + const timer = setTimeout(() => { + cleanup(); + resolve({ + connected: false, + host, + port, + error: 'Connection timeout' + }); + }, timeout); + + socket.setTimeout(timeout); + + socket.on('connect', () => { + const responseTime = Date.now() - startTime; + clearTimeout(timer); + cleanup(); + resolve({ + connected: true, + host, + port, + responseTime + }); + }); + + socket.on('error', (error) => { + clearTimeout(timer); + cleanup(); + resolve({ + connected: false, + host, + port, + error: error.message + }); + }); + + socket.on('timeout', () => { + clearTimeout(timer); + cleanup(); + resolve({ + connected: false, + host, + port, + error: 'Socket timeout' + }); + }); + + try { + socket.connect(port, host); + } catch (error) { + clearTimeout(timer); + cleanup(); + resolve({ + connected: false, + host, + port, + error: error instanceof Error ? error.message : 'Unknown connection error' + }); + } + }); +} + +export async function tcpCheck( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedBody = tcpCheckSchema.safeParse(req.body); + + if (!parsedBody.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedBody.error).toString() + ) + ); + } + + const { host, port, timeout } = parsedBody.data; + + + const result = await checkTcpConnection(host, port, timeout); + + logger.info(`TCP check for ${host}:${port} - Connected: ${result.connected}`, { + host, + port, + connected: result.connected, + responseTime: result.responseTime, + error: result.error + }); + + return response(res, { + data: result, + success: true, + error: false, + message: `TCP check completed for ${host}:${port}`, + status: HttpCode.OK + }); + } catch (error) { + logger.error("TCP check error:", error); + return next( + createHttpError( + HttpCode.INTERNAL_SERVER_ERROR, + "An error occurred during TCP check" + ) + ); + } +} + +// Batch TCP check endpoint for checking multiple resources at once +const batchTcpCheckSchema = z + .object({ + checks: z.array(z.object({ + id: z.number().int().positive(), + host: z.string().min(1), + port: z.number().int().min(1).max(65535) + })).max(50), // Limit to 50 concurrent checks + timeout: z.number().int().min(1000).max(30000).optional().default(5000) + }) + .strict(); + +export type BatchTcpCheckResponse = { + results: Array; +}; + +registry.registerPath({ + method: "post", + path: "/org/{orgId}/resources/tcp-check-batch", + description: "Check TCP connectivity to multiple hosts and ports", + tags: [OpenAPITags.Resource], + request: { + body: { + content: { + "application/json": { + schema: batchTcpCheckSchema + } + } + } + }, + responses: { + 200: { + description: "Batch TCP check results", + content: { + "application/json": { + schema: z.object({ + success: z.boolean(), + data: z.object({ + results: z.array(z.object({ + id: z.number(), + connected: z.boolean(), + host: z.string(), + port: z.number(), + responseTime: z.number().optional(), + error: z.string().optional() + })) + }), + message: z.string() + }) + } + } + } + } +}); + +export async function batchTcpCheck( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsedBody = batchTcpCheckSchema.safeParse(req.body); + if (!parsedBody.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedBody.error).toString() + ) + ); + } + + const { checks, timeout } = parsedBody.data; + + // all TCP checks concurrently + const checkPromises = checks.map(async (check) => { + const result = await checkTcpConnection(check.host, check.port, timeout); + return { + id: check.id, + ...result + }; + }); + + const results = await Promise.all(checkPromises); + + logger.info(`Batch TCP check completed for ${checks.length} resources`, { + totalChecks: checks.length, + successfulConnections: results.filter(r => r.connected).length, + failedConnections: results.filter(r => !r.connected).length + }); + + return response(res, { + data: { results }, + success: true, + error: false, + message: `Batch TCP check completed for ${checks.length} resources`, + status: HttpCode.OK + }); + } catch (error) { + logger.error("Batch TCP check error:", error); + return next( + createHttpError( + HttpCode.INTERNAL_SERVER_ERROR, + "An error occurred during batch TCP check" + ) + ); + } +} \ No newline at end of file diff --git a/src/app/[orgId]/settings/resources/page.tsx b/src/app/[orgId]/settings/resources/page.tsx index eadb19d4..0f8ee262 100644 --- a/src/app/[orgId]/settings/resources/page.tsx +++ b/src/app/[orgId]/settings/resources/page.tsx @@ -1,8 +1,8 @@ import { internal } from "@app/lib/api"; import { authCookieHeader } from "@app/lib/api/cookies"; import ResourcesTable, { - ResourceRow, - InternalResourceRow + ResourceRow, + InternalResourceRow } from "../../../../components/ResourcesTable"; import { AxiosResponse } from "axios"; import { ListResourcesResponse } from "@server/routers/resource"; @@ -17,123 +17,123 @@ import { pullEnv } from "@app/lib/pullEnv"; import { toUnicode } from "punycode"; type ResourcesPageProps = { - params: Promise<{ orgId: string }>; - searchParams: Promise<{ view?: string }>; + params: Promise<{ orgId: string }>; + searchParams: Promise<{ view?: string }>; }; export const dynamic = "force-dynamic"; export default async function ResourcesPage(props: ResourcesPageProps) { - const params = await props.params; - const searchParams = await props.searchParams; - const t = await getTranslations(); + const params = await props.params; + const searchParams = await props.searchParams; + const t = await getTranslations(); - const env = pullEnv(); + const env = pullEnv(); - // Default to 'proxy' view, or use the query param if provided - let defaultView: "proxy" | "internal" = "proxy"; - if (env.flags.enableClients) { - defaultView = searchParams.view === "internal" ? "internal" : "proxy"; - } + // Default to 'proxy' view, or use the query param if provided + let defaultView: "proxy" | "internal" = "proxy"; + if (env.flags.enableClients) { + defaultView = searchParams.view === "internal" ? "internal" : "proxy"; + } - let resources: ListResourcesResponse["resources"] = []; - try { - const res = await internal.get>( - `/org/${params.orgId}/resources`, - await authCookieHeader() - ); - resources = res.data.data.resources; - } catch (e) { } - - let siteResources: ListAllSiteResourcesByOrgResponse["siteResources"] = []; - try { - const res = await internal.get< - AxiosResponse - >(`/org/${params.orgId}/site-resources`, await authCookieHeader()); - siteResources = res.data.data.siteResources; - } catch (e) { } - - let org = null; - try { - const getOrg = cache(async () => - internal.get>( - `/org/${params.orgId}`, - await authCookieHeader() - ) - ); - const res = await getOrg(); - org = res.data.data; - } catch { - redirect(`/${params.orgId}/settings/resources`); - } - - if (!org) { - redirect(`/${params.orgId}/settings/resources`); - } - - const resourceRows: ResourceRow[] = resources.map((resource) => { - return { - id: resource.resourceId, - name: resource.name, - orgId: params.orgId, - nice: resource.niceId, - domain: `${resource.ssl ? "https://" : "http://"}${toUnicode(resource.fullDomain || "")}`, - protocol: resource.protocol, - proxyPort: resource.proxyPort, - http: resource.http, - authState: !resource.http - ? "none" - : resource.sso || - resource.pincodeId !== null || - resource.passwordId !== null || - resource.whitelist || - resource.headerAuthId - ? "protected" - : "not_protected", - enabled: resource.enabled, - domainId: resource.domainId || undefined, - ssl: resource.ssl - }; - }); - - const internalResourceRows: InternalResourceRow[] = siteResources.map( - (siteResource) => { - return { - id: siteResource.siteResourceId, - name: siteResource.name, - orgId: params.orgId, - siteName: siteResource.siteName, - protocol: siteResource.protocol, - proxyPort: siteResource.proxyPort, - siteId: siteResource.siteId, - destinationIp: siteResource.destinationIp, - destinationPort: siteResource.destinationPort, - siteNiceId: siteResource.siteNiceId - }; - } + let resources: ListResourcesResponse["resources"] = []; + try { + const res = await internal.get>( + `/org/${params.orgId}/resources`, + await authCookieHeader() ); + resources = res.data.data.resources; + } catch (e) { } - return ( - <> - + let siteResources: ListAllSiteResourcesByOrgResponse["siteResources"] = []; + try { + const res = await internal.get< + AxiosResponse + >(`/org/${params.orgId}/site-resources`, await authCookieHeader()); + siteResources = res.data.data.siteResources; + } catch (e) { } - - - - + let org = null; + try { + const getOrg = cache(async () => + internal.get>( + `/org/${params.orgId}`, + await authCookieHeader() + ) ); -} + const res = await getOrg(); + org = res.data.data; + } catch { + redirect(`/${params.orgId}/settings/resources`); + } + + if (!org) { + redirect(`/${params.orgId}/settings/resources`); + } + + const resourceRows: ResourceRow[] = resources.map((resource) => { + return { + id: resource.resourceId, + name: resource.name, + orgId: params.orgId, + nice: resource.niceId, + domain: `${resource.ssl ? "https://" : "http://"}${toUnicode(resource.fullDomain || "")}`, + protocol: resource.protocol, + proxyPort: resource.proxyPort, + http: resource.http, + authState: !resource.http + ? "none" + : resource.sso || + resource.pincodeId !== null || + resource.passwordId !== null || + resource.whitelist || + resource.headerAuthId + ? "protected" + : "not_protected", + enabled: resource.enabled, + domainId: resource.domainId || undefined, + ssl: resource.ssl + }; + }); + + const internalResourceRows: InternalResourceRow[] = siteResources.map( + (siteResource) => { + return { + id: siteResource.siteResourceId, + name: siteResource.name, + orgId: params.orgId, + siteName: siteResource.siteName, + protocol: siteResource.protocol, + proxyPort: siteResource.proxyPort, + siteId: siteResource.siteId, + destinationIp: siteResource.destinationIp, + destinationPort: siteResource.destinationPort, + siteNiceId: siteResource.siteNiceId + }; + } + ); + + return ( + <> + + + + + + + ); +} \ No newline at end of file diff --git a/src/components/ResourcesTable.tsx b/src/components/ResourcesTable.tsx index 200b3142..d2cf4384 100644 --- a/src/components/ResourcesTable.tsx +++ b/src/components/ResourcesTable.tsx @@ -9,13 +9,16 @@ import { SortingState, getSortedRowModel, ColumnFiltersState, - getFilteredRowModel + getFilteredRowModel, + VisibilityState } from "@tanstack/react-table"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, - DropdownMenuTrigger + DropdownMenuTrigger, + DropdownMenuCheckboxItem, + DropdownMenuSeparator } from "@app/components/ui/dropdown-menu"; import { Button } from "@app/components/ui/button"; import { @@ -25,7 +28,14 @@ import { ArrowUpRight, ShieldOff, ShieldCheck, - RefreshCw + RefreshCw, + Settings2, + Wifi, + WifiOff, + Clock, + Plus, + Search, + ChevronDown, } from "lucide-react"; import Link from "next/link"; import { useRouter } from "next/navigation"; @@ -44,7 +54,6 @@ import { useTranslations } from "next-intl"; import { InfoPopup } from "@app/components/ui/info-popup"; import { Input } from "@app/components/ui/input"; import { DataTablePagination } from "@app/components/DataTablePagination"; -import { Plus, Search } from "lucide-react"; import { Card, CardContent, CardHeader } from "@app/components/ui/card"; import { Table, @@ -64,6 +73,14 @@ import { useSearchParams } from "next/navigation"; import EditInternalResourceDialog from "@app/components/EditInternalResourceDialog"; import CreateInternalResourceDialog from "@app/components/CreateInternalResourceDialog"; import { Alert, AlertDescription } from "@app/components/ui/alert"; +import { Badge } from "@app/components/ui/badge"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger +} from "@app/components/ui/tooltip"; +import { useResourceHealth } from "@app/hooks/useResourceHealth"; export type ResourceRow = { id: number; @@ -78,6 +95,8 @@ export type ResourceRow = { enabled: boolean; domainId?: string; ssl: boolean; + targetHost?: string; + targetPort?: number; }; export type InternalResourceRow = { @@ -143,6 +162,25 @@ const setStoredPageSize = (pageSize: number, tableId?: string): void => { }; +function StatusIcon({ status, className = "" }: { + status: 'checking' | 'online' | 'offline' | undefined; + className?: string; +}) { + const iconClass = `h-4 w-4 ${className}`; + + switch (status) { + case 'checking': + return ; + case 'online': + return ; + case 'offline': + return ; + default: + return null; + } +} + + export default function ResourcesTable({ resources, internalResources, @@ -158,6 +196,7 @@ export default function ResourcesTable({ const api = createApiClient({ env }); + const [proxyPageSize, setProxyPageSize] = useState(() => getStoredPageSize('proxy-resources', 20) ); @@ -165,6 +204,9 @@ export default function ResourcesTable({ getStoredPageSize('internal-resources', 20) ); + const { resourceStatus, targetStatus } = useResourceHealth(orgId, resources); + + const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false); const [selectedResource, setSelectedResource] = useState(); @@ -179,6 +221,10 @@ export default function ResourcesTable({ const [proxySorting, setProxySorting] = useState( defaultSort ? [defaultSort] : [] ); + + const [proxyColumnVisibility, setProxyColumnVisibility] = useState({}); + const [internalColumnVisibility, setInternalColumnVisibility] = useState({}); + const [proxyColumnFilters, setProxyColumnFilters] = useState([]); const [proxyGlobalFilter, setProxyGlobalFilter] = useState([]); @@ -272,6 +318,39 @@ export default function ResourcesTable({ ); }; + const getColumnToggle = () => { + const table = currentView === "internal" ? internalTable : proxyTable; + + return ( + + + + + + {table.getAllColumns() + .filter(column => column.getCanHide()) + .map(column => ( + column.toggleVisibility(!!value)} + > + {column.id === "target" ? t("target") : + column.id === "authState" ? t("authentication") : + column.id === "enabled" ? t("enabled") : + column.id === "status" ? t("status") : + column.id} + + ))} + + + ); + }; + const getActionButton = () => { if (currentView === "internal") { return ( @@ -390,6 +469,126 @@ export default function ResourcesTable({ return {resourceRow.http ? (resourceRow.ssl ? "HTTPS" : "HTTP") : resourceRow.protocol.toUpperCase()}; } }, + { + id: "target", + accessorKey: "target", + header: ({ column }) => { + return ( + + ); + }, + cell: ({ row }) => { + const resourceRow = row.original as ResourceRow & { + targets?: { host: string; port: number }[]; + }; + + const targets = resourceRow.targets ?? []; + + if (targets.length === 0) { + return -; + } + + const count = targets.length; + + return ( + + + + + + + {targets.map((target, idx) => { + const key = `${resourceRow.id}:${target.host}:${target.port}`; + const status = targetStatus[key]; + + const color = + status === "online" + ? "bg-green-500" + : status === "offline" + ? "bg-red-500 " + : "bg-gray-400"; + + return ( + +
+ + + ); + })} + + + ); + }, + }, + { + id: "status", + accessorKey: "status", + header: t("status"), + cell: ({ row }) => { + const resourceRow = row.original; + const status = resourceStatus[resourceRow.id]; + + if (!resourceRow.enabled) { + return ( + + + + + {t("disabled")} + + + +

{t("resourceDisabled")}

+
+
+
+ ); + } + + return ( + + + +
+ + + {status === 'checking' ? t("checking") : + status === 'online' ? t("online") : + status === 'offline' ? t("offline") : '-'} + +
+
+ +

+ {status === 'checking' ? t("checkingConnection") : + status === 'online' ? t("connectionSuccessful") : + status === 'offline' ? t("connectionFailed") : + t("statusUnknown")} +

+
+
+
+ ); + } + }, { accessorKey: "domain", header: t("access"), @@ -647,6 +846,7 @@ export default function ResourcesTable({ onColumnFiltersChange: setProxyColumnFilters, getFilteredRowModel: getFilteredRowModel(), onGlobalFilterChange: setProxyGlobalFilter, + onColumnVisibilityChange: setProxyColumnVisibility, initialState: { pagination: { pageSize: proxyPageSize, @@ -656,7 +856,8 @@ export default function ResourcesTable({ state: { sorting: proxySorting, columnFilters: proxyColumnFilters, - globalFilter: proxyGlobalFilter + globalFilter: proxyGlobalFilter, + columnVisibility: proxyColumnVisibility } }); @@ -670,6 +871,7 @@ export default function ResourcesTable({ onColumnFiltersChange: setInternalColumnFilters, getFilteredRowModel: getFilteredRowModel(), onGlobalFilterChange: setInternalGlobalFilter, + onColumnVisibilityChange: setInternalColumnVisibility, initialState: { pagination: { pageSize: internalPageSize, @@ -679,7 +881,8 @@ export default function ResourcesTable({ state: { sorting: internalSorting, columnFilters: internalColumnFilters, - globalFilter: internalGlobalFilter + globalFilter: internalGlobalFilter, + columnVisibility: internalColumnVisibility } }); @@ -784,6 +987,7 @@ export default function ResourcesTable({
+ {getColumnToggle()} {getActionButton()}
diff --git a/src/hooks/useResourceHealth.ts b/src/hooks/useResourceHealth.ts new file mode 100644 index 00000000..315f0a00 --- /dev/null +++ b/src/hooks/useResourceHealth.ts @@ -0,0 +1,104 @@ +import { useState, useEffect } from "react"; +import { createApiClient } from "@app/lib/api"; +import { useEnvContext } from "@app/hooks/useEnvContext"; + +type Target = { + host: string; + port: number; +}; + +type ResourceRow = { + id: number; + enabled: boolean; + targets?: Target[]; +}; + +type Status = "checking" | "online" | "offline"; + +export function useResourceHealth(orgId: string, resources: ResourceRow[]) { + const { env } = useEnvContext(); + const api = createApiClient({ env }); + + const [resourceStatus, setResourceStatus] = useState>({}); + const [targetStatus, setTargetStatus] = useState>({}); + + useEffect(() => { + if (!orgId || resources.length === 0) return; + + // init all as "checking" + const initialRes: Record = {}; + const initialTargets: Record = {}; + resources.forEach((r) => { + initialRes[r.id] = "checking"; + r.targets?.forEach((t) => { + const key = `${r.id}:${t.host}:${t.port}`; + initialTargets[key] = "checking"; + }); + }); + setResourceStatus(initialRes); + setTargetStatus(initialTargets); + + // build batch checks + const checks = resources.flatMap((r) => + r.enabled && r.targets?.length + ? r.targets.map((t) => ({ + id: r.id, + host: t.host, + port: t.port, + })) + : [] + ); + + if (checks.length === 0) return; + + api.post(`/org/${orgId}/resources/tcp-check-batch`, { + checks, + timeout: 5000, + }) + .then((res) => { + const results = res.data.data.results as Array<{ + id: number; + host: string; + port: number; + connected: boolean; + }>; + + // build maps + const newTargetStatus: Record = {}; + const grouped: Record = {}; + + results.forEach((r) => { + const key = `${r.id}:${r.host}:${r.port}`; + newTargetStatus[key] = r.connected ? "online" : "offline"; + + if (!grouped[r.id]) grouped[r.id] = []; + grouped[r.id].push(r.connected); + }); + + const newResourceStatus: Record = {}; + Object.entries(grouped).forEach(([id, arr]) => { + newResourceStatus[+id] = arr.some(Boolean) ? "online" : "offline"; + }); + + setTargetStatus((prev) => ({ ...prev, ...newTargetStatus })); + setResourceStatus((prev) => ({ ...prev, ...newResourceStatus })); + }) + .catch(() => { + // fallback all offline + const fallbackRes: Record = {}; + const fallbackTargets: Record = {}; + resources.forEach((r) => { + if (r.enabled) { + fallbackRes[r.id] = "offline"; + r.targets?.forEach((t) => { + fallbackTargets[`${r.id}:${t.host}:${t.port}`] = "offline"; + }); + } + }); + setResourceStatus((prev) => ({ ...prev, ...fallbackRes })); + setTargetStatus((prev) => ({ ...prev, ...fallbackTargets })); + }); + }, [orgId, resources]); + + return { resourceStatus, targetStatus }; +} From f21188000e4164f979adc055078634075dccf8ef Mon Sep 17 00:00:00 2001 From: Pallavi Date: Wed, 3 Sep 2025 00:15:02 +0530 Subject: [PATCH 02/12] remove status check and add column filtering on all of the tables --- server/auth/actions.ts | 2 - server/routers/external.ts | 14 -- server/routers/resource/index.ts | 1 - server/routers/resource/tcpCheck.ts | 290 ------------------------- src/components/DataTablePagination.tsx | 9 +- src/components/ResourcesTable.tsx | 184 +++++----------- src/components/ui/data-table.tsx | 59 ++++- src/hooks/useResourceHealth.ts | 104 --------- 8 files changed, 119 insertions(+), 544 deletions(-) delete mode 100644 server/routers/resource/tcpCheck.ts delete mode 100644 src/hooks/useResourceHealth.ts diff --git a/server/auth/actions.ts b/server/auth/actions.ts index 4e271de9..d08457e5 100644 --- a/server/auth/actions.ts +++ b/server/auth/actions.ts @@ -23,8 +23,6 @@ export enum ActionsEnum { deleteResource = "deleteResource", getResource = "getResource", listResources = "listResources", - tcpCheck = "tcpCheck", - batchTcpCheck = "batchTcpCheck", updateResource = "updateResource", createTarget = "createTarget", deleteTarget = "deleteTarget", diff --git a/server/routers/external.ts b/server/routers/external.ts index 26254802..5c235902 100644 --- a/server/routers/external.ts +++ b/server/routers/external.ts @@ -306,20 +306,6 @@ authenticated.get( resource.listResources ); -authenticated.post( - "/org/:orgId/resources/tcp-check", - verifyOrgAccess, - verifyUserHasAction(ActionsEnum.tcpCheck), - resource.tcpCheck -); - -authenticated.post( - "/org/:orgId/resources/tcp-check-batch", - verifyOrgAccess, - verifyUserHasAction(ActionsEnum.batchTcpCheck), - resource.batchTcpCheck -); - authenticated.get( "/org/:orgId/user-resources", verifyOrgAccess, diff --git a/server/routers/resource/index.ts b/server/routers/resource/index.ts index a757cae3..d1c7011d 100644 --- a/server/routers/resource/index.ts +++ b/server/routers/resource/index.ts @@ -25,4 +25,3 @@ export * from "./getUserResources"; export * from "./setResourceHeaderAuth"; export * from "./addEmailToResourceWhitelist"; export * from "./removeEmailFromResourceWhitelist"; -export * from "./tcpCheck"; diff --git a/server/routers/resource/tcpCheck.ts b/server/routers/resource/tcpCheck.ts deleted file mode 100644 index 1779cc10..00000000 --- a/server/routers/resource/tcpCheck.ts +++ /dev/null @@ -1,290 +0,0 @@ -import { Request, Response, NextFunction } from "express"; -import { z } from "zod"; -import * as net from "net"; -import response from "@server/lib/response"; -import HttpCode from "@server/types/HttpCode"; -import createHttpError from "http-errors"; -import { fromError } from "zod-validation-error"; -import logger from "@server/logger"; -import { OpenAPITags, registry } from "@server/openApi"; - -const tcpCheckSchema = z - .object({ - host: z.string().min(1, "Host is required"), - port: z.number().int().min(1).max(65535), - timeout: z.number().int().min(1000).max(30000).optional().default(5000) - }) - .strict(); - -export type TcpCheckResponse = { - connected: boolean; - host: string; - port: number; - responseTime?: number; - error?: string; -}; - -registry.registerPath({ - method: "post", - path: "/org/{orgId}/resources/tcp-check", - description: "Check TCP connectivity to a host and port", - tags: [OpenAPITags.Resource], - request: { - body: { - content: { - "application/json": { - schema: tcpCheckSchema - } - } - } - }, - responses: { - 200: { - description: "TCP check result", - content: { - "application/json": { - schema: z.object({ - success: z.boolean(), - data: z.object({ - connected: z.boolean(), - host: z.string(), - port: z.number(), - responseTime: z.number().optional(), - error: z.string().optional() - }), - message: z.string() - }) - } - } - } - } -}); - -function checkTcpConnection(host: string, port: number, timeout: number): Promise { - return new Promise((resolve) => { - const startTime = Date.now(); - const socket = new net.Socket(); - - const cleanup = () => { - socket.removeAllListeners(); - if (!socket.destroyed) { - socket.destroy(); - } - }; - - const timer = setTimeout(() => { - cleanup(); - resolve({ - connected: false, - host, - port, - error: 'Connection timeout' - }); - }, timeout); - - socket.setTimeout(timeout); - - socket.on('connect', () => { - const responseTime = Date.now() - startTime; - clearTimeout(timer); - cleanup(); - resolve({ - connected: true, - host, - port, - responseTime - }); - }); - - socket.on('error', (error) => { - clearTimeout(timer); - cleanup(); - resolve({ - connected: false, - host, - port, - error: error.message - }); - }); - - socket.on('timeout', () => { - clearTimeout(timer); - cleanup(); - resolve({ - connected: false, - host, - port, - error: 'Socket timeout' - }); - }); - - try { - socket.connect(port, host); - } catch (error) { - clearTimeout(timer); - cleanup(); - resolve({ - connected: false, - host, - port, - error: error instanceof Error ? error.message : 'Unknown connection error' - }); - } - }); -} - -export async function tcpCheck( - req: Request, - res: Response, - next: NextFunction -): Promise { - try { - const parsedBody = tcpCheckSchema.safeParse(req.body); - - if (!parsedBody.success) { - return next( - createHttpError( - HttpCode.BAD_REQUEST, - fromError(parsedBody.error).toString() - ) - ); - } - - const { host, port, timeout } = parsedBody.data; - - - const result = await checkTcpConnection(host, port, timeout); - - logger.info(`TCP check for ${host}:${port} - Connected: ${result.connected}`, { - host, - port, - connected: result.connected, - responseTime: result.responseTime, - error: result.error - }); - - return response(res, { - data: result, - success: true, - error: false, - message: `TCP check completed for ${host}:${port}`, - status: HttpCode.OK - }); - } catch (error) { - logger.error("TCP check error:", error); - return next( - createHttpError( - HttpCode.INTERNAL_SERVER_ERROR, - "An error occurred during TCP check" - ) - ); - } -} - -// Batch TCP check endpoint for checking multiple resources at once -const batchTcpCheckSchema = z - .object({ - checks: z.array(z.object({ - id: z.number().int().positive(), - host: z.string().min(1), - port: z.number().int().min(1).max(65535) - })).max(50), // Limit to 50 concurrent checks - timeout: z.number().int().min(1000).max(30000).optional().default(5000) - }) - .strict(); - -export type BatchTcpCheckResponse = { - results: Array; -}; - -registry.registerPath({ - method: "post", - path: "/org/{orgId}/resources/tcp-check-batch", - description: "Check TCP connectivity to multiple hosts and ports", - tags: [OpenAPITags.Resource], - request: { - body: { - content: { - "application/json": { - schema: batchTcpCheckSchema - } - } - } - }, - responses: { - 200: { - description: "Batch TCP check results", - content: { - "application/json": { - schema: z.object({ - success: z.boolean(), - data: z.object({ - results: z.array(z.object({ - id: z.number(), - connected: z.boolean(), - host: z.string(), - port: z.number(), - responseTime: z.number().optional(), - error: z.string().optional() - })) - }), - message: z.string() - }) - } - } - } - } -}); - -export async function batchTcpCheck( - req: Request, - res: Response, - next: NextFunction -): Promise { - try { - const parsedBody = batchTcpCheckSchema.safeParse(req.body); - if (!parsedBody.success) { - return next( - createHttpError( - HttpCode.BAD_REQUEST, - fromError(parsedBody.error).toString() - ) - ); - } - - const { checks, timeout } = parsedBody.data; - - // all TCP checks concurrently - const checkPromises = checks.map(async (check) => { - const result = await checkTcpConnection(check.host, check.port, timeout); - return { - id: check.id, - ...result - }; - }); - - const results = await Promise.all(checkPromises); - - logger.info(`Batch TCP check completed for ${checks.length} resources`, { - totalChecks: checks.length, - successfulConnections: results.filter(r => r.connected).length, - failedConnections: results.filter(r => !r.connected).length - }); - - return response(res, { - data: { results }, - success: true, - error: false, - message: `Batch TCP check completed for ${checks.length} resources`, - status: HttpCode.OK - }); - } catch (error) { - logger.error("Batch TCP check error:", error); - return next( - createHttpError( - HttpCode.INTERNAL_SERVER_ERROR, - "An error occurred during batch TCP check" - ) - ); - } -} \ No newline at end of file diff --git a/src/components/DataTablePagination.tsx b/src/components/DataTablePagination.tsx index 70d64f0c..79b09f20 100644 --- a/src/components/DataTablePagination.tsx +++ b/src/components/DataTablePagination.tsx @@ -24,6 +24,7 @@ interface DataTablePaginationProps { isServerPagination?: boolean; isLoading?: boolean; disabled?: boolean; + renderAdditionalControls?: () => React.ReactNode; } export function DataTablePagination({ @@ -33,7 +34,8 @@ export function DataTablePagination({ totalCount, isServerPagination = false, isLoading = false, - disabled = false + disabled = false, + renderAdditionalControls }: DataTablePaginationProps) { const t = useTranslations(); @@ -113,6 +115,11 @@ export function DataTablePagination({ ))} + {renderAdditionalControls && ( +
+ {renderAdditionalControls()} +
+ )}
diff --git a/src/components/ResourcesTable.tsx b/src/components/ResourcesTable.tsx index d2cf4384..3238d1e4 100644 --- a/src/components/ResourcesTable.tsx +++ b/src/components/ResourcesTable.tsx @@ -18,7 +18,6 @@ import { DropdownMenuItem, DropdownMenuTrigger, DropdownMenuCheckboxItem, - DropdownMenuSeparator } from "@app/components/ui/dropdown-menu"; import { Button } from "@app/components/ui/button"; import { @@ -30,9 +29,6 @@ import { ShieldCheck, RefreshCw, Settings2, - Wifi, - WifiOff, - Clock, Plus, Search, ChevronDown, @@ -73,14 +69,6 @@ import { useSearchParams } from "next/navigation"; import EditInternalResourceDialog from "@app/components/EditInternalResourceDialog"; import CreateInternalResourceDialog from "@app/components/CreateInternalResourceDialog"; import { Alert, AlertDescription } from "@app/components/ui/alert"; -import { Badge } from "@app/components/ui/badge"; -import { - Tooltip, - TooltipContent, - TooltipProvider, - TooltipTrigger -} from "@app/components/ui/tooltip"; -import { useResourceHealth } from "@app/hooks/useResourceHealth"; export type ResourceRow = { id: number; @@ -162,25 +150,6 @@ const setStoredPageSize = (pageSize: number, tableId?: string): void => { }; -function StatusIcon({ status, className = "" }: { - status: 'checking' | 'online' | 'offline' | undefined; - className?: string; -}) { - const iconClass = `h-4 w-4 ${className}`; - - switch (status) { - case 'checking': - return ; - case 'online': - return ; - case 'offline': - return ; - default: - return null; - } -} - - export default function ResourcesTable({ resources, internalResources, @@ -204,9 +173,6 @@ export default function ResourcesTable({ getStoredPageSize('internal-resources', 20) ); - const { resourceStatus, targetStatus } = useResourceHealth(orgId, resources); - - const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false); const [selectedResource, setSelectedResource] = useState(); @@ -318,39 +284,6 @@ export default function ResourcesTable({ ); }; - const getColumnToggle = () => { - const table = currentView === "internal" ? internalTable : proxyTable; - - return ( - - - - - - {table.getAllColumns() - .filter(column => column.getCanHide()) - .map(column => ( - column.toggleVisibility(!!value)} - > - {column.id === "target" ? t("target") : - column.id === "authState" ? t("authentication") : - column.id === "enabled" ? t("enabled") : - column.id === "status" ? t("status") : - column.id} - - ))} - - - ); - }; - const getActionButton = () => { if (currentView === "internal") { return ( @@ -514,18 +447,9 @@ export default function ResourcesTable({ {targets.map((target, idx) => { const key = `${resourceRow.id}:${target.host}:${target.port}`; - const status = targetStatus[key]; - - const color = - status === "online" - ? "bg-green-500" - : status === "offline" - ? "bg-red-500 " - : "bg-gray-400"; return ( -
{ - const resourceRow = row.original; - const status = resourceStatus[resourceRow.id]; - - if (!resourceRow.enabled) { - return ( - - - - - {t("disabled")} - - - -

{t("resourceDisabled")}

-
-
-
- ); - } - - return ( - - - -
- - - {status === 'checking' ? t("checking") : - status === 'online' ? t("online") : - status === 'offline' ? t("offline") : '-'} - -
-
- -

- {status === 'checking' ? t("checkingConnection") : - status === 'online' ? t("connectionSuccessful") : - status === 'offline' ? t("connectionFailed") : - t("statusUnknown")} -

-
-
-
- ); - } - }, { accessorKey: "domain", header: t("access"), @@ -987,7 +860,6 @@ export default function ResourcesTable({
- {getColumnToggle()} {getActionButton()}
@@ -1072,6 +944,34 @@ export default function ResourcesTable({ ( + + + + + + {proxyTable.getAllColumns() + .filter(column => column.getCanHide()) + .map(column => ( + column.toggleVisibility(!!value)} + > + {column.id === "target" ? t("target") : + column.id === "authState" ? t("authentication") : + column.id === "enabled" ? t("enabled") : + column.id === "status" ? t("status") : + column.id} + + ))} + + + )} /> @@ -1173,6 +1073,34 @@ export default function ResourcesTable({ ( + + + + + + {internalTable.getAllColumns() + .filter(column => column.getCanHide()) + .map(column => ( + column.toggleVisibility(!!value)} + > + {column.id === "target" ? t("target") : + column.id === "authState" ? t("authentication") : + column.id === "enabled" ? t("enabled") : + column.id === "status" ? t("status") : + column.id} + + ))} + + + )} /> diff --git a/src/components/ui/data-table.tsx b/src/components/ui/data-table.tsx index ae94b12e..9c2cab88 100644 --- a/src/components/ui/data-table.tsx +++ b/src/components/ui/data-table.tsx @@ -9,7 +9,9 @@ import { SortingState, getSortedRowModel, ColumnFiltersState, - getFilteredRowModel + getFilteredRowModel, + VisibilityState, + Column } from "@tanstack/react-table"; import { Table, @@ -23,7 +25,7 @@ import { Button } from "@app/components/ui/button"; import { useEffect, useMemo, useState } from "react"; import { Input } from "@app/components/ui/input"; import { DataTablePagination } from "@app/components/DataTablePagination"; -import { Plus, Search, RefreshCw } from "lucide-react"; +import { Plus, Search, RefreshCw, Settings2 } from "lucide-react"; import { Card, CardContent, @@ -32,6 +34,12 @@ import { } from "@app/components/ui/card"; import { Tabs, TabsList, TabsTrigger } from "@app/components/ui/tabs"; import { useTranslations } from "next-intl"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuCheckboxItem, + DropdownMenuTrigger +} from "@app/components/ui/dropdown-menu"; const STORAGE_KEYS = { PAGE_SIZE: 'datatable-page-size', @@ -93,6 +101,7 @@ type DataTableProps = { defaultTab?: string; persistPageSize?: boolean | string; defaultPageSize?: number; + enableColumnToggle?: boolean; }; export function DataTable({ @@ -109,7 +118,8 @@ export function DataTable({ tabs, defaultTab, persistPageSize = false, - defaultPageSize = 20 + defaultPageSize = 20, + enableColumnToggle = true }: DataTableProps) { const t = useTranslations(); @@ -129,6 +139,7 @@ export function DataTable({ ); const [columnFilters, setColumnFilters] = useState([]); const [globalFilter, setGlobalFilter] = useState([]); + const [columnVisibility, setColumnVisibility] = useState({}); const [activeTab, setActiveTab] = useState( defaultTab || tabs?.[0]?.id || "" ); @@ -157,6 +168,7 @@ export function DataTable({ onColumnFiltersChange: setColumnFilters, getFilteredRowModel: getFilteredRowModel(), onGlobalFilterChange: setGlobalFilter, + onColumnVisibilityChange: setColumnVisibility, initialState: { pagination: { pageSize: pageSize, @@ -166,7 +178,8 @@ export function DataTable({ state: { sorting, columnFilters, - globalFilter + globalFilter, + columnVisibility } }); @@ -199,6 +212,43 @@ export function DataTable({ } }; + const getColumnLabel = (column: Column) => { + return typeof column.columnDef.header === "string" ? + column.columnDef.header : + column.id; // fallback to id if header is JSX + }; + + + const renderColumnToggle = () => { + if (!enableColumnToggle) return null; + + return ( + + + + + + {table.getAllColumns() + .filter((column) => column.getCanHide()) + .map((column) => ( + column.toggleVisibility(!!value)} + > + {getColumnLabel(column)} + + ))} + + + ); + }; + + return (
@@ -312,6 +362,7 @@ export function DataTable({
diff --git a/src/hooks/useResourceHealth.ts b/src/hooks/useResourceHealth.ts deleted file mode 100644 index 315f0a00..00000000 --- a/src/hooks/useResourceHealth.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { useState, useEffect } from "react"; -import { createApiClient } from "@app/lib/api"; -import { useEnvContext } from "@app/hooks/useEnvContext"; - -type Target = { - host: string; - port: number; -}; - -type ResourceRow = { - id: number; - enabled: boolean; - targets?: Target[]; -}; - -type Status = "checking" | "online" | "offline"; - -export function useResourceHealth(orgId: string, resources: ResourceRow[]) { - const { env } = useEnvContext(); - const api = createApiClient({ env }); - - const [resourceStatus, setResourceStatus] = useState>({}); - const [targetStatus, setTargetStatus] = useState>({}); - - useEffect(() => { - if (!orgId || resources.length === 0) return; - - // init all as "checking" - const initialRes: Record = {}; - const initialTargets: Record = {}; - resources.forEach((r) => { - initialRes[r.id] = "checking"; - r.targets?.forEach((t) => { - const key = `${r.id}:${t.host}:${t.port}`; - initialTargets[key] = "checking"; - }); - }); - setResourceStatus(initialRes); - setTargetStatus(initialTargets); - - // build batch checks - const checks = resources.flatMap((r) => - r.enabled && r.targets?.length - ? r.targets.map((t) => ({ - id: r.id, - host: t.host, - port: t.port, - })) - : [] - ); - - if (checks.length === 0) return; - - api.post(`/org/${orgId}/resources/tcp-check-batch`, { - checks, - timeout: 5000, - }) - .then((res) => { - const results = res.data.data.results as Array<{ - id: number; - host: string; - port: number; - connected: boolean; - }>; - - // build maps - const newTargetStatus: Record = {}; - const grouped: Record = {}; - - results.forEach((r) => { - const key = `${r.id}:${r.host}:${r.port}`; - newTargetStatus[key] = r.connected ? "online" : "offline"; - - if (!grouped[r.id]) grouped[r.id] = []; - grouped[r.id].push(r.connected); - }); - - const newResourceStatus: Record = {}; - Object.entries(grouped).forEach(([id, arr]) => { - newResourceStatus[+id] = arr.some(Boolean) ? "online" : "offline"; - }); - - setTargetStatus((prev) => ({ ...prev, ...newTargetStatus })); - setResourceStatus((prev) => ({ ...prev, ...newResourceStatus })); - }) - .catch(() => { - // fallback all offline - const fallbackRes: Record = {}; - const fallbackTargets: Record = {}; - resources.forEach((r) => { - if (r.enabled) { - fallbackRes[r.id] = "offline"; - r.targets?.forEach((t) => { - fallbackTargets[`${r.id}:${t.host}:${t.port}`] = "offline"; - }); - } - }); - setResourceStatus((prev) => ({ ...prev, ...fallbackRes })); - setTargetStatus((prev) => ({ ...prev, ...fallbackTargets })); - }); - }, [orgId, resources]); - - return { resourceStatus, targetStatus }; -} From 8e5dde887c6d1c19fcbc27d4d59da5815c4965eb Mon Sep 17 00:00:00 2001 From: Pallavi Date: Wed, 3 Sep 2025 00:57:46 +0530 Subject: [PATCH 03/12] list targes in frontend --- src/components/ResourcesTable.tsx | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/components/ResourcesTable.tsx b/src/components/ResourcesTable.tsx index 3238d1e4..a717ae1b 100644 --- a/src/components/ResourcesTable.tsx +++ b/src/components/ResourcesTable.tsx @@ -420,7 +420,7 @@ export default function ResourcesTable({ }, cell: ({ row }) => { const resourceRow = row.original as ResourceRow & { - targets?: { host: string; port: number }[]; + targets?: { ip: string; port: number }[]; }; const targets = resourceRow.targets ?? []; @@ -446,12 +446,10 @@ export default function ResourcesTable({ {targets.map((target, idx) => { - const key = `${resourceRow.id}:${target.host}:${target.port}`; - return ( From cdf77087cdd6e035ad743b03d966ff893657d482 Mon Sep 17 00:00:00 2001 From: Pallavi Date: Fri, 12 Sep 2025 22:10:00 +0530 Subject: [PATCH 04/12] get niceid --- server/routers/resource/listResources.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/server/routers/resource/listResources.ts b/server/routers/resource/listResources.ts index 8272ac3a..b6eecace 100644 --- a/server/routers/resource/listResources.ts +++ b/server/routers/resource/listResources.ts @@ -47,6 +47,7 @@ type JoinedRow = { niceId: string; name: string; ssl: boolean; + niceId: string; fullDomain: string | null; passwordId: number | null; sso: boolean; @@ -79,7 +80,7 @@ export type ResourceWithTargets = { proxyPort: number | null; enabled: boolean; domainId: string | null; - niceId: string | null; + niceId: string; targets: Array<{ targetId: number; ip: string; @@ -261,6 +262,7 @@ export async function listResources( proxyPort: row.proxyPort, enabled: row.enabled, domainId: row.domainId, + niceId: row.niceId, targets: [], }; map.set(row.resourceId, entry); From 49bc2dc5dae5288c392e6061e94bba946d51fee8 Mon Sep 17 00:00:00 2001 From: Pallavi Kumari Date: Mon, 20 Oct 2025 22:04:10 +0530 Subject: [PATCH 05/12] fix duplicate --- server/routers/resource/listResources.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/routers/resource/listResources.ts b/server/routers/resource/listResources.ts index b6eecace..87c3bbdd 100644 --- a/server/routers/resource/listResources.ts +++ b/server/routers/resource/listResources.ts @@ -47,7 +47,6 @@ type JoinedRow = { niceId: string; name: string; ssl: boolean; - niceId: string; fullDomain: string | null; passwordId: number | null; sso: boolean; @@ -81,6 +80,7 @@ export type ResourceWithTargets = { enabled: boolean; domainId: string | null; niceId: string; + headerAuthId: number | null; targets: Array<{ targetId: number; ip: string; From ad6bb3da9fc8db4e018ebb1b36ff12e422761758 Mon Sep 17 00:00:00 2001 From: Pallavi Kumari Date: Mon, 20 Oct 2025 22:31:26 +0530 Subject: [PATCH 06/12] fix type error --- server/routers/resource/listResources.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/server/routers/resource/listResources.ts b/server/routers/resource/listResources.ts index 87c3bbdd..de2158c6 100644 --- a/server/routers/resource/listResources.ts +++ b/server/routers/resource/listResources.ts @@ -57,6 +57,7 @@ type JoinedRow = { proxyPort: number | null; enabled: boolean; domainId: string | null; + headerAuthId: number | null; targetId: number | null; targetIp: string | null; @@ -262,14 +263,19 @@ export async function listResources( proxyPort: row.proxyPort, enabled: row.enabled, domainId: row.domainId, - niceId: row.niceId, + headerAuthId: row.headerAuthId, targets: [], }; map.set(row.resourceId, entry); } - // Push target if present (left join can be null) - if (row.targetId != null && row.targetIp && row.targetPort != null && row.targetEnabled != null) { + // Push target if present + if ( + row.targetId != null && + row.targetIp && + row.targetPort != null && + row.targetEnabled != null + ) { entry.targets.push({ targetId: row.targetId, ip: row.targetIp, From 54f7525f1bf55ee2f288821301a860225e4fe43f Mon Sep 17 00:00:00 2001 From: Pallavi Kumari Date: Tue, 21 Oct 2025 11:55:14 +0530 Subject: [PATCH 07/12] add status column in resource table --- server/routers/resource/listResources.ts | 26 ++- src/app/[orgId]/settings/resources/page.tsx | 9 +- src/components/ResourcesTable.tsx | 180 +++++++++++++++----- 3 files changed, 165 insertions(+), 50 deletions(-) diff --git a/server/routers/resource/listResources.ts b/server/routers/resource/listResources.ts index de2158c6..e612d5ec 100644 --- a/server/routers/resource/listResources.ts +++ b/server/routers/resource/listResources.ts @@ -8,6 +8,7 @@ import { resourcePassword, resourcePincode, targets, + targetHealthCheck, } from "@server/db"; import response from "@server/lib/response"; import HttpCode from "@server/types/HttpCode"; @@ -63,6 +64,9 @@ type JoinedRow = { targetIp: string | null; targetPort: number | null; targetEnabled: boolean | null; + + hcHealth: string | null; + hcEnabled: boolean | null; }; // grouped by resource with targets[]) @@ -87,6 +91,7 @@ export type ResourceWithTargets = { ip: string; port: number; enabled: boolean; + healthStatus?: 'healthy' | 'unhealthy' | 'unknown'; }>; }; @@ -114,6 +119,8 @@ function queryResources(accessibleResourceIds: number[], orgId: string) { targetPort: targets.port, targetEnabled: targets.enabled, + hcHealth: targetHealthCheck.hcHealth, + hcEnabled: targetHealthCheck.hcEnabled, }) .from(resources) .leftJoin( @@ -129,6 +136,10 @@ function queryResources(accessibleResourceIds: number[], orgId: string) { eq(resourceHeaderAuth.resourceId, resources.resourceId) ) .leftJoin(targets, eq(targets.resourceId, resources.resourceId)) + .leftJoin( + targetHealthCheck, + eq(targetHealthCheck.targetId, targets.targetId) + ) .where( and( inArray(resources.resourceId, accessibleResourceIds), @@ -269,18 +280,19 @@ export async function listResources( map.set(row.resourceId, entry); } - // Push target if present - if ( - row.targetId != null && - row.targetIp && - row.targetPort != null && - row.targetEnabled != null - ) { + if (row.targetId != null && row.targetIp && row.targetPort != null && row.targetEnabled != null) { + let healthStatus: 'healthy' | 'unhealthy' | 'unknown' = 'unknown'; + + if (row.hcEnabled && row.hcHealth) { + healthStatus = row.hcHealth as 'healthy' | 'unhealthy' | 'unknown'; + } + entry.targets.push({ targetId: row.targetId, ip: row.targetIp, port: row.targetPort, enabled: row.targetEnabled, + healthStatus: healthStatus, }); } } diff --git a/src/app/[orgId]/settings/resources/page.tsx b/src/app/[orgId]/settings/resources/page.tsx index 0f8ee262..5b18c3c5 100644 --- a/src/app/[orgId]/settings/resources/page.tsx +++ b/src/app/[orgId]/settings/resources/page.tsx @@ -92,7 +92,14 @@ export default async function ResourcesPage(props: ResourcesPageProps) { : "not_protected", enabled: resource.enabled, domainId: resource.domainId || undefined, - ssl: resource.ssl + ssl: resource.ssl, + targets: resource.targets?.map(target => ({ + targetId: target.targetId, + ip: target.ip, + port: target.port, + enabled: target.enabled, + healthStatus: target.healthStatus + })) }; }); diff --git a/src/components/ResourcesTable.tsx b/src/components/ResourcesTable.tsx index a717ae1b..9faee629 100644 --- a/src/components/ResourcesTable.tsx +++ b/src/components/ResourcesTable.tsx @@ -32,6 +32,9 @@ import { Plus, Search, ChevronDown, + Clock, + Wifi, + WifiOff, } from "lucide-react"; import Link from "next/link"; import { useRouter } from "next/navigation"; @@ -70,6 +73,15 @@ import EditInternalResourceDialog from "@app/components/EditInternalResourceDial import CreateInternalResourceDialog from "@app/components/CreateInternalResourceDialog"; import { Alert, AlertDescription } from "@app/components/ui/alert"; + +export type TargetHealth = { + targetId: number; + ip: string; + port: number; + enabled: boolean; + healthStatus?: 'healthy' | 'unhealthy' | 'unknown'; +}; + export type ResourceRow = { id: number; nice: string | null; @@ -85,8 +97,52 @@ export type ResourceRow = { ssl: boolean; targetHost?: string; targetPort?: number; + targets?: TargetHealth[]; }; + +function getOverallHealthStatus(targets?: TargetHealth[]): 'online' | 'degraded' | 'offline' | 'unknown' { + if (!targets || targets.length === 0) { + return 'unknown'; + } + + const monitoredTargets = targets.filter(t => t.enabled && t.healthStatus && t.healthStatus !== 'unknown'); + + if (monitoredTargets.length === 0) { + return 'unknown'; + } + + const healthyCount = monitoredTargets.filter(t => t.healthStatus === 'healthy').length; + const unhealthyCount = monitoredTargets.filter(t => t.healthStatus === 'unhealthy').length; + + if (healthyCount === monitoredTargets.length) { + return 'online'; + } else if (unhealthyCount === monitoredTargets.length) { + return 'offline'; + } else { + return 'degraded'; + } +} + +function StatusIcon({ status, className = "" }: { + status: 'online' | 'degraded' | 'offline' | 'unknown'; + className?: string; +}) { + const iconClass = `h-4 w-4 ${className}`; + + switch (status) { + case 'online': + return ; + case 'degraded': + return ; + case 'offline': + return ; + case 'unknown': + return ; + default: + return null; + } +} export type InternalResourceRow = { id: number; name: string; @@ -150,6 +206,7 @@ const setStoredPageSize = (pageSize: number, tableId?: string): void => { }; + export default function ResourcesTable({ resources, internalResources, @@ -361,6 +418,76 @@ export default function ResourcesTable({ }); } + function TargetStatusCell({ targets }: { targets?: TargetHealth[] }) { + const overallStatus = getOverallHealthStatus(targets); + + if (!targets || targets.length === 0) { + return ( +
+ + No targets +
+ ); + } + + const monitoredTargets = targets.filter(t => t.enabled && t.healthStatus && t.healthStatus !== 'unknown'); + const unknownTargets = targets.filter(t => !t.enabled || !t.healthStatus || t.healthStatus === 'unknown'); + + return ( + + + + + + {monitoredTargets.length > 0 && ( + <> + {monitoredTargets.map((target) => ( + +
+ + +
+ + {target.healthStatus} + +
+ ))} + + )} + {unknownTargets.length > 0 && ( + <> + {unknownTargets.map((target) => ( + +
+ + +
+ + {!target.enabled ? 'Disabled' : 'Not monitored'} + +
+ ))} + + )} +
+
+ ); + } + + const proxyColumns: ColumnDef[] = [ { accessorKey: "name", @@ -403,8 +530,8 @@ export default function ResourcesTable({ } }, { - id: "target", - accessorKey: "target", + id: "status", + accessorKey: "status", header: ({ column }) => { return ( ); }, cell: ({ row }) => { - const resourceRow = row.original as ResourceRow & { - targets?: { ip: string; port: number }[]; - }; - - const targets = resourceRow.targets ?? []; - - if (targets.length === 0) { - return -; - } - - const count = targets.length; - - return ( - - - - - - - {targets.map((target, idx) => { - return ( - - - - ); - })} - - - ); + const resourceRow = row.original; + return ; }, + sortingFn: (rowA, rowB) => { + const statusA = getOverallHealthStatus(rowA.original.targets); + const statusB = getOverallHealthStatus(rowB.original.targets); + const statusOrder = { online: 3, degraded: 2, offline: 1, unknown: 0 }; + return statusOrder[statusA] - statusOrder[statusB]; + } }, { accessorKey: "domain", From 301654b63e7c43860466a1bf1f31f07293ff194a Mon Sep 17 00:00:00 2001 From: Owen Date: Wed, 5 Nov 2025 11:38:14 -0800 Subject: [PATCH 08/12] Fix styling --- src/components/ResourcesTable.tsx | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/components/ResourcesTable.tsx b/src/components/ResourcesTable.tsx index 9faee629..32661b65 100644 --- a/src/components/ResourcesTable.tsx +++ b/src/components/ResourcesTable.tsx @@ -35,6 +35,8 @@ import { Clock, Wifi, WifiOff, + CheckCircle2, + XCircle, } from "lucide-react"; import Link from "next/link"; import { useRouter } from "next/navigation"; @@ -132,11 +134,11 @@ function StatusIcon({ status, className = "" }: { switch (status) { case 'online': - return ; + return ; case 'degraded': - return ; + return ; case 'offline': - return ; + return ; case 'unknown': return ; default: @@ -457,9 +459,9 @@ export default function ResourcesTable({ status={target.healthStatus === 'healthy' ? 'online' : 'offline'} className="h-3 w-3" /> - + {`${target.ip}:${target.port}`} - {target.healthStatus} @@ -473,9 +475,9 @@ export default function ResourcesTable({
- + {`${target.ip}:${target.port}`}
- + {!target.enabled ? 'Disabled' : 'Not monitored'}
From 6ddfc9b8fe5cee6806bb83ff6aae315982103d86 Mon Sep 17 00:00:00 2001 From: Owen Date: Wed, 5 Nov 2025 11:41:07 -0800 Subject: [PATCH 09/12] Revert columns --- src/components/DataTablePagination.tsx | 9 +--- src/components/ui/data-table.tsx | 59 ++------------------------ 2 files changed, 5 insertions(+), 63 deletions(-) diff --git a/src/components/DataTablePagination.tsx b/src/components/DataTablePagination.tsx index 79b09f20..70d64f0c 100644 --- a/src/components/DataTablePagination.tsx +++ b/src/components/DataTablePagination.tsx @@ -24,7 +24,6 @@ interface DataTablePaginationProps { isServerPagination?: boolean; isLoading?: boolean; disabled?: boolean; - renderAdditionalControls?: () => React.ReactNode; } export function DataTablePagination({ @@ -34,8 +33,7 @@ export function DataTablePagination({ totalCount, isServerPagination = false, isLoading = false, - disabled = false, - renderAdditionalControls + disabled = false }: DataTablePaginationProps) { const t = useTranslations(); @@ -115,11 +113,6 @@ export function DataTablePagination({ ))} - {renderAdditionalControls && ( -
- {renderAdditionalControls()} -
- )}
diff --git a/src/components/ui/data-table.tsx b/src/components/ui/data-table.tsx index 9c2cab88..ae94b12e 100644 --- a/src/components/ui/data-table.tsx +++ b/src/components/ui/data-table.tsx @@ -9,9 +9,7 @@ import { SortingState, getSortedRowModel, ColumnFiltersState, - getFilteredRowModel, - VisibilityState, - Column + getFilteredRowModel } from "@tanstack/react-table"; import { Table, @@ -25,7 +23,7 @@ import { Button } from "@app/components/ui/button"; import { useEffect, useMemo, useState } from "react"; import { Input } from "@app/components/ui/input"; import { DataTablePagination } from "@app/components/DataTablePagination"; -import { Plus, Search, RefreshCw, Settings2 } from "lucide-react"; +import { Plus, Search, RefreshCw } from "lucide-react"; import { Card, CardContent, @@ -34,12 +32,6 @@ import { } from "@app/components/ui/card"; import { Tabs, TabsList, TabsTrigger } from "@app/components/ui/tabs"; import { useTranslations } from "next-intl"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuCheckboxItem, - DropdownMenuTrigger -} from "@app/components/ui/dropdown-menu"; const STORAGE_KEYS = { PAGE_SIZE: 'datatable-page-size', @@ -101,7 +93,6 @@ type DataTableProps = { defaultTab?: string; persistPageSize?: boolean | string; defaultPageSize?: number; - enableColumnToggle?: boolean; }; export function DataTable({ @@ -118,8 +109,7 @@ export function DataTable({ tabs, defaultTab, persistPageSize = false, - defaultPageSize = 20, - enableColumnToggle = true + defaultPageSize = 20 }: DataTableProps) { const t = useTranslations(); @@ -139,7 +129,6 @@ export function DataTable({ ); const [columnFilters, setColumnFilters] = useState([]); const [globalFilter, setGlobalFilter] = useState([]); - const [columnVisibility, setColumnVisibility] = useState({}); const [activeTab, setActiveTab] = useState( defaultTab || tabs?.[0]?.id || "" ); @@ -168,7 +157,6 @@ export function DataTable({ onColumnFiltersChange: setColumnFilters, getFilteredRowModel: getFilteredRowModel(), onGlobalFilterChange: setGlobalFilter, - onColumnVisibilityChange: setColumnVisibility, initialState: { pagination: { pageSize: pageSize, @@ -178,8 +166,7 @@ export function DataTable({ state: { sorting, columnFilters, - globalFilter, - columnVisibility + globalFilter } }); @@ -212,43 +199,6 @@ export function DataTable({ } }; - const getColumnLabel = (column: Column) => { - return typeof column.columnDef.header === "string" ? - column.columnDef.header : - column.id; // fallback to id if header is JSX - }; - - - const renderColumnToggle = () => { - if (!enableColumnToggle) return null; - - return ( - - - - - - {table.getAllColumns() - .filter((column) => column.getCanHide()) - .map((column) => ( - column.toggleVisibility(!!value)} - > - {getColumnLabel(column)} - - ))} - - - ); - }; - - return (
@@ -362,7 +312,6 @@ export function DataTable({
From 0a9f37c44ddf3035b8dfb626b271756d82cd9c18 Mon Sep 17 00:00:00 2001 From: Pallavi Kumari Date: Thu, 6 Nov 2025 22:57:03 +0530 Subject: [PATCH 10/12] revert column from resource table --- src/components/ResourcesTable.tsx | 56 ------------------------------- 1 file changed, 56 deletions(-) diff --git a/src/components/ResourcesTable.tsx b/src/components/ResourcesTable.tsx index 32661b65..0e613da8 100644 --- a/src/components/ResourcesTable.tsx +++ b/src/components/ResourcesTable.tsx @@ -1040,34 +1040,6 @@ export default function ResourcesTable({ ( - - - - - - {proxyTable.getAllColumns() - .filter(column => column.getCanHide()) - .map(column => ( - column.toggleVisibility(!!value)} - > - {column.id === "target" ? t("target") : - column.id === "authState" ? t("authentication") : - column.id === "enabled" ? t("enabled") : - column.id === "status" ? t("status") : - column.id} - - ))} - - - )} />
@@ -1169,34 +1141,6 @@ export default function ResourcesTable({ ( - - - - - - {internalTable.getAllColumns() - .filter(column => column.getCanHide()) - .map(column => ( - column.toggleVisibility(!!value)} - > - {column.id === "target" ? t("target") : - column.id === "authState" ? t("authentication") : - column.id === "enabled" ? t("enabled") : - column.id === "status" ? t("status") : - column.id} - - ))} - - - )} /> From fce887436d5a195cdb5ea9008a782efa0bb942ab Mon Sep 17 00:00:00 2001 From: miloschwartz Date: Thu, 6 Nov 2025 15:46:54 -0800 Subject: [PATCH 11/12] fix bug causing auto provision to override manually created users --- server/routers/idp/validateOidcCallback.ts | 42 +++++++++++++++------- 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/server/routers/idp/validateOidcCallback.ts b/server/routers/idp/validateOidcCallback.ts index 98bdfe44..376dd7bc 100644 --- a/server/routers/idp/validateOidcCallback.ts +++ b/server/routers/idp/validateOidcCallback.ts @@ -352,20 +352,38 @@ export async function validateOidcCallback( if (!userOrgInfo.length) { if (existingUser) { - // delete the user - // cascade will also delete org users + // get existing user orgs + const existingUserOrgs = await db + .select() + .from(userOrgs) + .where( + and( + eq(userOrgs.userId, existingUser.userId), + eq(userOrgs.autoProvisioned, false) + ) + ); - await db - .delete(users) - .where(eq(users.userId, existingUser.userId)); + if (!existingUserOrgs.length) { + // delete the user + await db + .delete(users) + .where(eq(users.userId, existingUser.userId)); + return next( + createHttpError( + HttpCode.UNAUTHORIZED, + `No policies matched for ${userIdentifier}. This user must be added to an organization before logging in.` + ) + ); + } + } else { + // no orgs to provision and user doesn't exist + return next( + createHttpError( + HttpCode.UNAUTHORIZED, + `No policies matched for ${userIdentifier}. This user must be added to an organization before logging in.` + ) + ); } - - return next( - createHttpError( - HttpCode.UNAUTHORIZED, - `No policies matched for ${userIdentifier}. This user must be added to an organization before logging in.` - ) - ); } const orgUserCounts: { orgId: string; userCount: number }[] = []; From 2a7529c39e9baa7eb3fb7dfcdacc289903175175 Mon Sep 17 00:00:00 2001 From: miloschwartz Date: Thu, 6 Nov 2025 16:48:53 -0800 Subject: [PATCH 12/12] don't delete user --- server/routers/idp/validateOidcCallback.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/server/routers/idp/validateOidcCallback.ts b/server/routers/idp/validateOidcCallback.ts index 376dd7bc..7d1da1c5 100644 --- a/server/routers/idp/validateOidcCallback.ts +++ b/server/routers/idp/validateOidcCallback.ts @@ -365,9 +365,9 @@ export async function validateOidcCallback( if (!existingUserOrgs.length) { // delete the user - await db - .delete(users) - .where(eq(users.userId, existingUser.userId)); + // await db + // .delete(users) + // .where(eq(users.userId, existingUser.userId)); return next( createHttpError( HttpCode.UNAUTHORIZED,