mirror of
https://github.com/fosrl/pangolin.git
synced 2026-01-28 22:00:51 +00:00
Merge branch 'dev' into feat/login-page-customization
This commit is contained in:
@@ -13,9 +13,12 @@ function createDb() {
|
||||
connection_string: process.env.POSTGRES_CONNECTION_STRING
|
||||
};
|
||||
if (process.env.POSTGRES_REPLICA_CONNECTION_STRINGS) {
|
||||
const replicas = process.env.POSTGRES_REPLICA_CONNECTION_STRINGS.split(",").map((conn) => ({
|
||||
connection_string: conn.trim()
|
||||
}));
|
||||
const replicas =
|
||||
process.env.POSTGRES_REPLICA_CONNECTION_STRINGS.split(
|
||||
","
|
||||
).map((conn) => ({
|
||||
connection_string: conn.trim()
|
||||
}));
|
||||
config.postgres.replicas = replicas;
|
||||
}
|
||||
} else {
|
||||
@@ -40,28 +43,44 @@ function createDb() {
|
||||
connectionString,
|
||||
max: poolConfig?.max_connections || 20,
|
||||
idleTimeoutMillis: poolConfig?.idle_timeout_ms || 30000,
|
||||
connectionTimeoutMillis: poolConfig?.connection_timeout_ms || 5000,
|
||||
connectionTimeoutMillis: poolConfig?.connection_timeout_ms || 5000
|
||||
});
|
||||
|
||||
const replicas = [];
|
||||
|
||||
if (!replicaConnections.length) {
|
||||
replicas.push(DrizzlePostgres(primaryPool));
|
||||
replicas.push(
|
||||
DrizzlePostgres(primaryPool, {
|
||||
logger: process.env.NODE_ENV === "development"
|
||||
})
|
||||
);
|
||||
} else {
|
||||
for (const conn of replicaConnections) {
|
||||
const replicaPool = new Pool({
|
||||
connectionString: conn.connection_string,
|
||||
max: poolConfig?.max_replica_connections || 20,
|
||||
idleTimeoutMillis: poolConfig?.idle_timeout_ms || 30000,
|
||||
connectionTimeoutMillis: poolConfig?.connection_timeout_ms || 5000,
|
||||
connectionTimeoutMillis:
|
||||
poolConfig?.connection_timeout_ms || 5000
|
||||
});
|
||||
replicas.push(DrizzlePostgres(replicaPool));
|
||||
replicas.push(
|
||||
DrizzlePostgres(replicaPool, {
|
||||
logger: process.env.NODE_ENV === "development"
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return withReplicas(DrizzlePostgres(primaryPool), replicas as any);
|
||||
return withReplicas(
|
||||
DrizzlePostgres(primaryPool, {
|
||||
logger: process.env.NODE_ENV === "development"
|
||||
}),
|
||||
replicas as any
|
||||
);
|
||||
}
|
||||
|
||||
export const db = createDb();
|
||||
export default db;
|
||||
export type Transaction = Parameters<Parameters<typeof db["transaction"]>[0]>[0];
|
||||
export type Transaction = Parameters<
|
||||
Parameters<(typeof db)["transaction"]>[0]
|
||||
>[0];
|
||||
|
||||
@@ -176,7 +176,8 @@ export const targetHealthCheck = pgTable("targetHealthCheck", {
|
||||
hcFollowRedirects: boolean("hcFollowRedirects").default(true),
|
||||
hcMethod: varchar("hcMethod").default("GET"),
|
||||
hcStatus: integer("hcStatus"), // http code
|
||||
hcHealth: text("hcHealth").default("unknown") // "unknown", "healthy", "unhealthy"
|
||||
hcHealth: text("hcHealth").default("unknown"), // "unknown", "healthy", "unhealthy"
|
||||
hcTlsServerName: text("hcTlsServerName"),
|
||||
});
|
||||
|
||||
export const exitNodes = pgTable("exitNodes", {
|
||||
|
||||
@@ -201,7 +201,8 @@ export const targetHealthCheck = sqliteTable("targetHealthCheck", {
|
||||
}).default(true),
|
||||
hcMethod: text("hcMethod").default("GET"),
|
||||
hcStatus: integer("hcStatus"), // http code
|
||||
hcHealth: text("hcHealth").default("unknown") // "unknown", "healthy", "unhealthy"
|
||||
hcHealth: text("hcHealth").default("unknown"), // "unknown", "healthy", "unhealthy"
|
||||
hcTlsServerName: text("hcTlsServerName"),
|
||||
});
|
||||
|
||||
export const exitNodes = sqliteTable("exitNodes", {
|
||||
|
||||
@@ -16,7 +16,7 @@ import privateConfig from "#private/lib/config";
|
||||
import logger from "@server/logger";
|
||||
|
||||
export enum AudienceIds {
|
||||
SignUps = "5cfbf99b-c592-40a9-9b8a-577a4681c158",
|
||||
SignUps = "6c4e77b2-0851-4bd6-bac8-f51f91360f1a",
|
||||
Subscribed = "870b43fd-387f-44de-8fc1-707335f30b20",
|
||||
Churned = "f3ae92bd-2fdb-4d77-8746-2118afd62549",
|
||||
Newsletter = "5500c431-191c-42f0-a5d4-8b6d445b4ea0"
|
||||
|
||||
@@ -40,7 +40,12 @@ export const queryAccessAuditLogsQuery = z.object({
|
||||
})
|
||||
.transform((val) => Math.floor(new Date(val).getTime() / 1000))
|
||||
.optional()
|
||||
.prefault(new Date().toISOString()),
|
||||
.prefault(new Date().toISOString())
|
||||
.openapi({
|
||||
type: "string",
|
||||
format: "date-time",
|
||||
description: "End time as ISO date string (defaults to current time)"
|
||||
}),
|
||||
action: z
|
||||
.union([z.boolean(), z.string()])
|
||||
.transform((val) => (typeof val === "string" ? val === "true" : val))
|
||||
|
||||
@@ -40,7 +40,12 @@ export const queryActionAuditLogsQuery = z.object({
|
||||
})
|
||||
.transform((val) => Math.floor(new Date(val).getTime() / 1000))
|
||||
.optional()
|
||||
.prefault(new Date().toISOString()),
|
||||
.prefault(new Date().toISOString())
|
||||
.openapi({
|
||||
type: "string",
|
||||
format: "date-time",
|
||||
description: "End time as ISO date string (defaults to current time)"
|
||||
}),
|
||||
action: z.string().optional(),
|
||||
actorType: z.string().optional(),
|
||||
actorId: z.string().optional(),
|
||||
|
||||
@@ -6,7 +6,11 @@ import createHttpError from "http-errors";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import logger from "@server/logger";
|
||||
import { queryAccessAuditLogsQuery, queryRequestAuditLogsParams, queryRequest } from "./queryRequstAuditLog";
|
||||
import {
|
||||
queryAccessAuditLogsQuery,
|
||||
queryRequestAuditLogsParams,
|
||||
queryRequest
|
||||
} from "./queryRequestAuditLog";
|
||||
import { generateCSV } from "./generateCSV";
|
||||
|
||||
registry.registerPath({
|
||||
@@ -54,10 +58,13 @@ export async function exportRequestAuditLogs(
|
||||
const log = await baseQuery.limit(data.limit).offset(data.offset);
|
||||
|
||||
const csvData = generateCSV(log);
|
||||
|
||||
res.setHeader('Content-Type', 'text/csv');
|
||||
res.setHeader('Content-Disposition', `attachment; filename="request-audit-logs-${data.orgId}-${Date.now()}.csv"`);
|
||||
|
||||
|
||||
res.setHeader("Content-Type", "text/csv");
|
||||
res.setHeader(
|
||||
"Content-Disposition",
|
||||
`attachment; filename="request-audit-logs-${data.orgId}-${Date.now()}.csv"`
|
||||
);
|
||||
|
||||
return res.send(csvData);
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from "./queryRequstAuditLog";
|
||||
export * from "./exportRequstAuditLog";
|
||||
export * from "./queryRequestAuditLog";
|
||||
export * from "./queryRequestAnalytics";
|
||||
export * from "./exportRequestAuditLog";
|
||||
|
||||
192
server/routers/auditLogs/queryRequestAnalytics.ts
Normal file
192
server/routers/auditLogs/queryRequestAnalytics.ts
Normal file
@@ -0,0 +1,192 @@
|
||||
import { db, requestAuditLog, driver } from "@server/db";
|
||||
import { registry } from "@server/openApi";
|
||||
import { NextFunction } from "express";
|
||||
import { Request, Response } from "express";
|
||||
import { eq, gt, lt, and, count, sql, desc, not, isNull } from "drizzle-orm";
|
||||
import { OpenAPITags } from "@server/openApi";
|
||||
import { z } from "zod";
|
||||
import createHttpError from "http-errors";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import response from "@server/lib/response";
|
||||
import logger from "@server/logger";
|
||||
|
||||
const queryAccessAuditLogsQuery = z.object({
|
||||
// iso string just validate its a parseable date
|
||||
timeStart: z
|
||||
.string()
|
||||
.refine((val) => !isNaN(Date.parse(val)), {
|
||||
error: "timeStart must be a valid ISO date string"
|
||||
})
|
||||
.transform((val) => Math.floor(new Date(val).getTime() / 1000))
|
||||
.optional(),
|
||||
timeEnd: z
|
||||
.string()
|
||||
.refine((val) => !isNaN(Date.parse(val)), {
|
||||
error: "timeEnd must be a valid ISO date string"
|
||||
})
|
||||
.transform((val) => Math.floor(new Date(val).getTime() / 1000))
|
||||
.optional()
|
||||
.prefault(new Date().toISOString())
|
||||
.openapi({
|
||||
type: "string",
|
||||
format: "date-time",
|
||||
description:
|
||||
"End time as ISO date string (defaults to current time)"
|
||||
}),
|
||||
resourceId: z
|
||||
.string()
|
||||
.optional()
|
||||
.transform(Number)
|
||||
.pipe(z.int().positive())
|
||||
.optional()
|
||||
});
|
||||
|
||||
const queryRequestAuditLogsParams = z.object({
|
||||
orgId: z.string()
|
||||
});
|
||||
|
||||
const queryRequestAuditLogsCombined = queryAccessAuditLogsQuery.merge(
|
||||
queryRequestAuditLogsParams
|
||||
);
|
||||
|
||||
type Q = z.infer<typeof queryRequestAuditLogsCombined>;
|
||||
|
||||
async function query(query: Q) {
|
||||
let baseConditions = and(
|
||||
eq(requestAuditLog.orgId, query.orgId),
|
||||
lt(requestAuditLog.timestamp, query.timeEnd)
|
||||
);
|
||||
|
||||
if (query.timeStart) {
|
||||
baseConditions = and(
|
||||
baseConditions,
|
||||
gt(requestAuditLog.timestamp, query.timeStart)
|
||||
);
|
||||
}
|
||||
if (query.resourceId) {
|
||||
baseConditions = and(
|
||||
baseConditions,
|
||||
eq(requestAuditLog.resourceId, query.resourceId)
|
||||
);
|
||||
}
|
||||
|
||||
const [all] = await db
|
||||
.select({ total: count() })
|
||||
.from(requestAuditLog)
|
||||
.where(baseConditions);
|
||||
|
||||
const [blocked] = await db
|
||||
.select({ total: count() })
|
||||
.from(requestAuditLog)
|
||||
.where(and(baseConditions, eq(requestAuditLog.action, false)));
|
||||
|
||||
const totalQ = sql<number>`count(${requestAuditLog.id})`
|
||||
.mapWith(Number)
|
||||
.as("total");
|
||||
|
||||
const requestsPerCountry = await db
|
||||
.selectDistinct({
|
||||
code: requestAuditLog.location,
|
||||
count: totalQ
|
||||
})
|
||||
.from(requestAuditLog)
|
||||
.where(and(baseConditions, not(isNull(requestAuditLog.location))))
|
||||
.groupBy(requestAuditLog.location)
|
||||
.orderBy(desc(totalQ));
|
||||
|
||||
const groupByDayFunction =
|
||||
driver === "pg"
|
||||
? sql<string>`DATE_TRUNC('day', TO_TIMESTAMP(${requestAuditLog.timestamp}))`
|
||||
: sql<string>`DATE(${requestAuditLog.timestamp}, 'unixepoch')`;
|
||||
|
||||
const booleanTrue = driver === "pg" ? sql`true` : sql`1`;
|
||||
const booleanFalse = driver === "pg" ? sql`false` : sql`0`;
|
||||
|
||||
const requestsPerDay = await db
|
||||
.select({
|
||||
day: groupByDayFunction.as("day"),
|
||||
allowedCount:
|
||||
sql<number>`SUM(CASE WHEN ${requestAuditLog.action} = ${booleanTrue} THEN 1 ELSE 0 END)`.as(
|
||||
"allowed_count"
|
||||
),
|
||||
blockedCount:
|
||||
sql<number>`SUM(CASE WHEN ${requestAuditLog.action} = ${booleanFalse} THEN 1 ELSE 0 END)`.as(
|
||||
"blocked_count"
|
||||
),
|
||||
totalCount: sql<number>`COUNT(*)`.as("total_count")
|
||||
})
|
||||
.from(requestAuditLog)
|
||||
.where(and(baseConditions))
|
||||
.groupBy(groupByDayFunction)
|
||||
.orderBy(groupByDayFunction);
|
||||
|
||||
return {
|
||||
requestsPerCountry: requestsPerCountry as Array<{
|
||||
code: string;
|
||||
count: number;
|
||||
}>,
|
||||
requestsPerDay,
|
||||
totalBlocked: blocked.total,
|
||||
totalRequests: all.total
|
||||
};
|
||||
}
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/org/{orgId}/logs/analytics",
|
||||
description: "Query the request audit analytics for an organization",
|
||||
tags: [OpenAPITags.Org],
|
||||
request: {
|
||||
query: queryAccessAuditLogsQuery,
|
||||
params: queryRequestAuditLogsParams
|
||||
},
|
||||
responses: {}
|
||||
});
|
||||
|
||||
export type QueryRequestAnalyticsResponse = Awaited<ReturnType<typeof query>>;
|
||||
|
||||
export async function queryRequestAnalytics(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedQuery = queryAccessAuditLogsQuery.safeParse(req.query);
|
||||
if (!parsedQuery.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedQuery.error)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const parsedParams = queryRequestAuditLogsParams.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const params = { ...parsedQuery.data, ...parsedParams.data };
|
||||
|
||||
const data = await query(params);
|
||||
|
||||
return response<QueryRequestAnalyticsResponse>(res, {
|
||||
data,
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Request audit analytics retrieved successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,13 @@ export const queryAccessAuditLogsQuery = z.object({
|
||||
})
|
||||
.transform((val) => Math.floor(new Date(val).getTime() / 1000))
|
||||
.optional()
|
||||
.prefault(new Date().toISOString()),
|
||||
.prefault(new Date().toISOString())
|
||||
.openapi({
|
||||
type: "string",
|
||||
format: "date-time",
|
||||
description:
|
||||
"End time as ISO date string (defaults to current time)"
|
||||
}),
|
||||
action: z
|
||||
.union([z.boolean(), z.string()])
|
||||
.transform((val) => (typeof val === "string" ? val === "true" : val))
|
||||
@@ -67,8 +73,9 @@ export const queryRequestAuditLogsParams = z.object({
|
||||
orgId: z.string()
|
||||
});
|
||||
|
||||
export const queryRequestAuditLogsCombined =
|
||||
queryAccessAuditLogsQuery.merge(queryRequestAuditLogsParams);
|
||||
export const queryRequestAuditLogsCombined = queryAccessAuditLogsQuery.merge(
|
||||
queryRequestAuditLogsParams
|
||||
);
|
||||
type Q = z.infer<typeof queryRequestAuditLogsCombined>;
|
||||
|
||||
function getWhere(data: Q) {
|
||||
@@ -204,11 +211,21 @@ async function queryUniqueFilterAttributes(
|
||||
.where(baseConditions);
|
||||
|
||||
return {
|
||||
actors: uniqueActors.map(row => row.actor).filter((actor): actor is string => actor !== null),
|
||||
resources: uniqueResources.filter((row): row is { id: number; name: string | null } => row.id !== null),
|
||||
locations: uniqueLocations.map(row => row.locations).filter((location): location is string => location !== null),
|
||||
hosts: uniqueHosts.map(row => row.hosts).filter((host): host is string => host !== null),
|
||||
paths: uniquePaths.map(row => row.paths).filter((path): path is string => path !== null)
|
||||
actors: uniqueActors
|
||||
.map((row) => row.actor)
|
||||
.filter((actor): actor is string => actor !== null),
|
||||
resources: uniqueResources.filter(
|
||||
(row): row is { id: number; name: string | null } => row.id !== null
|
||||
),
|
||||
locations: uniqueLocations
|
||||
.map((row) => row.locations)
|
||||
.filter((location): location is string => location !== null),
|
||||
hosts: uniqueHosts
|
||||
.map((row) => row.hosts)
|
||||
.filter((host): host is string => host !== null),
|
||||
paths: uniquePaths
|
||||
.map((row) => row.paths)
|
||||
.filter((path): path is string => path !== null)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -265,7 +282,7 @@ export async function queryRequestAuditLogs(
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Action audit logs retrieved successfully",
|
||||
message: "Request audit logs retrieved successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -30,7 +30,8 @@ export const signupBodySchema = z.object({
|
||||
password: passwordSchema,
|
||||
inviteToken: z.string().optional(),
|
||||
inviteId: z.string().optional(),
|
||||
termsAcceptedTimestamp: z.string().nullable().optional()
|
||||
termsAcceptedTimestamp: z.string().nullable().optional(),
|
||||
marketingEmailConsent: z.boolean().optional()
|
||||
});
|
||||
|
||||
export type SignUpBody = z.infer<typeof signupBodySchema>;
|
||||
@@ -55,7 +56,7 @@ export async function signup(
|
||||
);
|
||||
}
|
||||
|
||||
const { email, password, inviteToken, inviteId, termsAcceptedTimestamp } =
|
||||
const { email, password, inviteToken, inviteId, termsAcceptedTimestamp, marketingEmailConsent } =
|
||||
parsedBody.data;
|
||||
|
||||
const passwordHash = await hashPassword(password);
|
||||
@@ -220,8 +221,8 @@ export async function signup(
|
||||
new Date(sess.expiresAt)
|
||||
);
|
||||
res.appendHeader("Set-Cookie", cookie);
|
||||
|
||||
if (build == "saas") {
|
||||
if (build == "saas" && marketingEmailConsent) {
|
||||
logger.debug(`User ${email} opted in to marketing emails during signup.`);
|
||||
moveEmailToAudience(email, AudienceIds.SignUps);
|
||||
}
|
||||
|
||||
|
||||
@@ -178,7 +178,6 @@ authenticated.post(
|
||||
client.updateClient
|
||||
);
|
||||
|
||||
|
||||
// authenticated.get(
|
||||
// "/site/:siteId/roles",
|
||||
// verifySiteAccess,
|
||||
@@ -308,6 +307,13 @@ authenticated.get(
|
||||
resource.listResources
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/resource-names",
|
||||
verifyOrgAccess,
|
||||
verifyUserHasAction(ActionsEnum.listResources),
|
||||
resource.listAllResourceNames
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/user-resources",
|
||||
verifyOrgAccess,
|
||||
@@ -890,6 +896,13 @@ authenticated.get(
|
||||
logs.queryRequestAuditLogs
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/logs/analytics",
|
||||
verifyOrgAccess,
|
||||
verifyUserHasAction(ActionsEnum.viewLogs),
|
||||
logs.queryRequestAnalytics
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/logs/request/export",
|
||||
verifyOrgAccess,
|
||||
|
||||
@@ -272,7 +272,8 @@ export const handleNewtRegisterMessage: MessageHandler = async (context) => {
|
||||
hcUnhealthyInterval: targetHealthCheck.hcUnhealthyInterval,
|
||||
hcTimeout: targetHealthCheck.hcTimeout,
|
||||
hcHeaders: targetHealthCheck.hcHeaders,
|
||||
hcMethod: targetHealthCheck.hcMethod
|
||||
hcMethod: targetHealthCheck.hcMethod,
|
||||
hcTlsServerName: targetHealthCheck.hcTlsServerName,
|
||||
})
|
||||
.from(targets)
|
||||
.innerJoin(resources, eq(targets.resourceId, resources.resourceId))
|
||||
@@ -344,7 +345,8 @@ export const handleNewtRegisterMessage: MessageHandler = async (context) => {
|
||||
hcUnhealthyInterval: target.hcUnhealthyInterval, // in seconds
|
||||
hcTimeout: target.hcTimeout, // in seconds
|
||||
hcHeaders: hcHeadersSend,
|
||||
hcMethod: target.hcMethod
|
||||
hcMethod: target.hcMethod,
|
||||
hcTlsServerName: target.hcTlsServerName,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -66,7 +66,8 @@ export async function addTargets(
|
||||
hcUnhealthyInterval: hc.hcUnhealthyInterval, // in seconds
|
||||
hcTimeout: hc.hcTimeout, // in seconds
|
||||
hcHeaders: hcHeadersSend,
|
||||
hcMethod: hc.hcMethod
|
||||
hcMethod: hc.hcMethod,
|
||||
hcTlsServerName: hc.hcTlsServerName,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -25,3 +25,4 @@ export * from "./getUserResources";
|
||||
export * from "./setResourceHeaderAuth";
|
||||
export * from "./addEmailToResourceWhitelist";
|
||||
export * from "./removeEmailFromResourceWhitelist";
|
||||
export * from "./listAllResourceNames";
|
||||
|
||||
90
server/routers/resource/listAllResourceNames.ts
Normal file
90
server/routers/resource/listAllResourceNames.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, resourceHeaderAuth } from "@server/db";
|
||||
import {
|
||||
resources,
|
||||
userResources,
|
||||
roleResources,
|
||||
resourcePassword,
|
||||
resourcePincode,
|
||||
targets,
|
||||
targetHealthCheck
|
||||
} from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import { sql, eq, or, inArray, and, count } from "drizzle-orm";
|
||||
import logger from "@server/logger";
|
||||
import { fromZodError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import type {
|
||||
ResourceWithTargets,
|
||||
ListResourcesResponse
|
||||
} from "./listResources";
|
||||
|
||||
const listResourcesParamsSchema = z.strictObject({
|
||||
orgId: z.string()
|
||||
});
|
||||
|
||||
function queryResourceNames(orgId: string) {
|
||||
return db
|
||||
.select({
|
||||
resourceId: resources.resourceId,
|
||||
name: resources.name
|
||||
})
|
||||
.from(resources)
|
||||
|
||||
.where(eq(resources.orgId, orgId));
|
||||
}
|
||||
|
||||
export type ListResourceNamesResponse = Awaited<
|
||||
ReturnType<typeof queryResourceNames>
|
||||
>;
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/org/{orgId}/resources-names",
|
||||
description: "List all resource names for an organization.",
|
||||
tags: [OpenAPITags.Org, OpenAPITags.Resource],
|
||||
request: {
|
||||
params: z.object({
|
||||
orgId: z.string()
|
||||
})
|
||||
},
|
||||
responses: {}
|
||||
});
|
||||
|
||||
export async function listAllResourceNames(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = listResourcesParamsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromZodError(parsedParams.error)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const orgId = parsedParams.data.orgId;
|
||||
|
||||
const data = await queryResourceNames(orgId);
|
||||
|
||||
return response<ListResourceNamesResponse>(res, {
|
||||
data,
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Resource Names retrieved successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,21 +8,19 @@ import {
|
||||
resourcePassword,
|
||||
resourcePincode,
|
||||
targets,
|
||||
targetHealthCheck,
|
||||
targetHealthCheck
|
||||
} from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import { sql, eq, or, inArray, and, count } from "drizzle-orm";
|
||||
import logger from "@server/logger";
|
||||
import stoi from "@server/lib/stoi";
|
||||
import { fromZodError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { warn } from "console";
|
||||
|
||||
const listResourcesParamsSchema = z.strictObject({
|
||||
orgId: z.string()
|
||||
});
|
||||
orgId: z.string()
|
||||
});
|
||||
|
||||
const listResourcesSchema = z.object({
|
||||
limit: z
|
||||
@@ -67,7 +65,7 @@ type JoinedRow = {
|
||||
hcEnabled: boolean | null;
|
||||
};
|
||||
|
||||
// grouped by resource with targets[])
|
||||
// grouped by resource with targets[])
|
||||
export type ResourceWithTargets = {
|
||||
resourceId: number;
|
||||
name: string;
|
||||
@@ -89,7 +87,7 @@ export type ResourceWithTargets = {
|
||||
ip: string;
|
||||
port: number;
|
||||
enabled: boolean;
|
||||
healthStatus?: 'healthy' | 'unhealthy' | 'unknown';
|
||||
healthStatus?: "healthy" | "unhealthy" | "unknown";
|
||||
}>;
|
||||
};
|
||||
|
||||
@@ -118,7 +116,7 @@ function queryResources(accessibleResourceIds: number[], orgId: string) {
|
||||
targetEnabled: targets.enabled,
|
||||
|
||||
hcHealth: targetHealthCheck.hcHealth,
|
||||
hcEnabled: targetHealthCheck.hcEnabled,
|
||||
hcEnabled: targetHealthCheck.hcEnabled
|
||||
})
|
||||
.from(resources)
|
||||
.leftJoin(
|
||||
@@ -273,16 +271,25 @@ export async function listResources(
|
||||
enabled: row.enabled,
|
||||
domainId: row.domainId,
|
||||
headerAuthId: row.headerAuthId,
|
||||
targets: [],
|
||||
targets: []
|
||||
};
|
||||
map.set(row.resourceId, entry);
|
||||
}
|
||||
|
||||
if (row.targetId != null && row.targetIp && row.targetPort != null && row.targetEnabled != null) {
|
||||
let healthStatus: 'healthy' | 'unhealthy' | 'unknown' = 'unknown';
|
||||
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';
|
||||
healthStatus = row.hcHealth as
|
||||
| "healthy"
|
||||
| "unhealthy"
|
||||
| "unknown";
|
||||
}
|
||||
|
||||
entry.targets.push({
|
||||
@@ -290,7 +297,7 @@ export async function listResources(
|
||||
ip: row.targetIp,
|
||||
port: row.targetPort,
|
||||
enabled: row.targetEnabled,
|
||||
healthStatus: healthStatus,
|
||||
healthStatus: healthStatus
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +48,7 @@ const createTargetSchema = z.strictObject({
|
||||
hcFollowRedirects: z.boolean().optional().nullable(),
|
||||
hcMethod: z.string().min(1).optional().nullable(),
|
||||
hcStatus: z.int().optional().nullable(),
|
||||
hcTlsServerName: z.string().optional().nullable(),
|
||||
path: z.string().optional().nullable(),
|
||||
pathMatchType: z
|
||||
.enum(["exact", "prefix", "regex"])
|
||||
@@ -247,7 +248,8 @@ export async function createTarget(
|
||||
hcFollowRedirects: targetData.hcFollowRedirects ?? null,
|
||||
hcMethod: targetData.hcMethod ?? null,
|
||||
hcStatus: targetData.hcStatus ?? null,
|
||||
hcHealth: "unknown"
|
||||
hcHealth: "unknown",
|
||||
hcTlsServerName: targetData.hcTlsServerName ?? null
|
||||
})
|
||||
.returning();
|
||||
|
||||
|
||||
@@ -57,6 +57,7 @@ function queryTargets(resourceId: number) {
|
||||
hcMethod: targetHealthCheck.hcMethod,
|
||||
hcStatus: targetHealthCheck.hcStatus,
|
||||
hcHealth: targetHealthCheck.hcHealth,
|
||||
hcTlsServerName: targetHealthCheck.hcTlsServerName,
|
||||
path: targets.path,
|
||||
pathMatchType: targets.pathMatchType,
|
||||
rewritePath: targets.rewritePath,
|
||||
|
||||
@@ -42,6 +42,7 @@ const updateTargetBodySchema = z.strictObject({
|
||||
hcFollowRedirects: z.boolean().optional().nullable(),
|
||||
hcMethod: z.string().min(1).optional().nullable(),
|
||||
hcStatus: z.int().optional().nullable(),
|
||||
hcTlsServerName: z.string().optional().nullable(),
|
||||
path: z.string().optional().nullable(),
|
||||
pathMatchType: z.enum(["exact", "prefix", "regex"]).optional().nullable(),
|
||||
rewritePath: z.string().optional().nullable(),
|
||||
@@ -217,7 +218,8 @@ export async function updateTarget(
|
||||
hcHeaders: hcHeaders,
|
||||
hcFollowRedirects: parsedBody.data.hcFollowRedirects,
|
||||
hcMethod: parsedBody.data.hcMethod,
|
||||
hcStatus: parsedBody.data.hcStatus
|
||||
hcStatus: parsedBody.data.hcStatus,
|
||||
hcTlsServerName: parsedBody.data.hcTlsServerName,
|
||||
})
|
||||
.where(eq(targetHealthCheck.targetId, targetId))
|
||||
.returning();
|
||||
|
||||
Reference in New Issue
Block a user