fosrl.pangolin/server/routers/target/updateTarget.ts

187 lines
5.5 KiB
TypeScript
Raw Normal View History

import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
2024-11-19 21:36:56 -05:00
import { newts, resources, sites, targets } from "@server/db/schema";
import { eq } from "drizzle-orm";
2025-01-01 21:41:31 -05:00
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { addPeer } from "../gerbil/peers";
2024-11-19 21:36:56 -05:00
import { addTargets } from "../newt/targets";
2025-01-20 21:07:02 -05:00
import { pickPort } from "./ports";
2024-10-01 21:53:49 -04:00
// Regular expressions for validation
const DOMAIN_REGEX =
/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
const IPV4_REGEX =
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
const IPV6_REGEX = /^(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}$/i;
// Schema for domain names and IP addresses
const domainSchema = z
.string()
.min(1, "Domain cannot be empty")
.max(255, "Domain name too long")
.refine(
(value) => {
// Check if it's a valid IP address (v4 or v6)
if (IPV4_REGEX.test(value) || IPV6_REGEX.test(value)) {
return true;
}
// Check if it's a valid domain name
return DOMAIN_REGEX.test(value);
},
{
message: "Invalid domain name or IP address format",
path: ["domain"]
}
);
2024-12-21 21:01:12 -05:00
const updateTargetParamsSchema = z
.object({
targetId: z.string().transform(Number).pipe(z.number().int().positive())
})
.strict();
2024-10-01 21:53:49 -04:00
const updateTargetBodySchema = z
.object({
ip: domainSchema.optional(),
method: z.string().min(1).max(10).optional(),
port: z.number().int().min(1).max(65535).optional(),
2024-12-21 21:01:12 -05:00
enabled: z.boolean().optional()
})
.strict()
.refine((data) => Object.keys(data).length > 0, {
2024-12-21 21:01:12 -05:00
message: "At least one field must be provided for update"
});
2024-10-01 21:34:07 -04:00
export async function updateTarget(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
2024-10-06 18:05:20 -04:00
try {
const parsedParams = updateTargetParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
2024-10-06 18:05:20 -04:00
)
);
}
2024-10-01 21:53:49 -04:00
2024-10-06 18:05:20 -04:00
const parsedBody = updateTargetBodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
2024-10-06 18:05:20 -04:00
)
);
}
2024-10-01 21:53:49 -04:00
2024-10-06 18:05:20 -04:00
const { targetId } = parsedParams.data;
2024-11-19 21:36:56 -05:00
2025-01-20 21:07:02 -05:00
const [target] = await db
.select()
.from(targets)
2024-10-06 18:05:20 -04:00
.where(eq(targets.targetId, targetId))
2025-01-20 21:07:02 -05:00
.limit(1);
2024-10-01 21:53:49 -04:00
2025-01-20 21:07:02 -05:00
if (!target) {
2024-10-06 18:05:20 -04:00
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Target with ID ${targetId} not found`
)
);
}
2024-10-01 21:53:49 -04:00
2024-11-19 21:36:56 -05:00
// get the resource
const [resource] = await db
.select({
2024-12-21 21:01:12 -05:00
siteId: resources.siteId
2024-11-19 21:36:56 -05:00
})
.from(resources)
2025-01-20 21:07:02 -05:00
.where(eq(resources.resourceId, target.resourceId!));
2024-11-19 21:36:56 -05:00
if (!resource) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
2025-01-20 21:07:02 -05:00
`Resource with ID ${target.resourceId} not found`
2024-11-19 21:36:56 -05:00
)
);
2024-11-19 21:36:56 -05:00
}
2024-11-19 21:36:56 -05:00
const [site] = await db
.select()
.from(sites)
.where(eq(sites.siteId, resource.siteId!))
.limit(1);
if (!site) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Site with ID ${resource.siteId} not found`
)
);
}
2025-01-20 21:07:02 -05:00
const { internalPort, targetIps } = await pickPort(site.siteId!);
2024-11-19 21:36:56 -05:00
2025-01-20 21:07:02 -05:00
if (!internalPort) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
`No available internal port`
)
);
}
const [updatedTarget] = await db
.update(targets)
.set({
...parsedBody.data,
internalPort
})
.where(eq(targets.targetId, targetId))
.returning();
if (site.pubKey) {
if (site.type == "wireguard") {
2024-11-19 21:36:56 -05:00
await addPeer(site.exitNodeId!, {
publicKey: site.pubKey,
2024-12-21 21:01:12 -05:00
allowedIps: targetIps.flat()
2024-11-19 21:36:56 -05:00
});
} else if (site.type == "newt") {
// get the newt on the site by querying the newt table for siteId
const [newt] = await db
.select()
.from(newts)
.where(eq(newts.siteId, site.siteId))
.limit(1);
addTargets(newt.newtId, [updatedTarget]);
}
}
2024-10-06 18:05:20 -04:00
return response(res, {
data: updatedTarget,
2024-10-06 18:05:20 -04:00
success: true,
error: false,
message: "Target updated successfully",
2024-12-21 21:01:12 -05:00
status: HttpCode.OK
2024-10-06 18:05:20 -04:00
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
2024-10-06 18:05:20 -04:00
}
}