mirror of
https://github.com/fosrl/pangolin.git
synced 2026-06-05 07:16:24 +00:00
Compare commits
2 Commits
dependabot
...
backhaul
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff6c23e3e4 | ||
|
|
726deb4152 |
@@ -2,6 +2,7 @@ import {
|
||||
pgTable,
|
||||
serial,
|
||||
varchar,
|
||||
unique,
|
||||
boolean,
|
||||
integer,
|
||||
bigint,
|
||||
@@ -19,12 +20,13 @@ import {
|
||||
roles,
|
||||
users,
|
||||
exitNodes,
|
||||
sessions,
|
||||
clients,
|
||||
resources,
|
||||
siteResources,
|
||||
targetHealthCheck,
|
||||
sites
|
||||
sites,
|
||||
clients,
|
||||
sessions,
|
||||
labels
|
||||
} from "./schema";
|
||||
|
||||
export const certificates = pgTable("certificates", {
|
||||
@@ -197,6 +199,42 @@ export const remoteExitNodes = pgTable("remoteExitNode", {
|
||||
})
|
||||
});
|
||||
|
||||
export const remoteExitNodeResources = pgTable("remoteExitNodeResources", {
|
||||
remoteExitNodeResourceId: serial("remoteExitNodeResourceId").primaryKey(),
|
||||
remoteExitNodeId: varchar("remoteExitNodeId")
|
||||
.notNull()
|
||||
.references(() => remoteExitNodes.remoteExitNodeId, {
|
||||
onDelete: "cascade"
|
||||
}),
|
||||
destination: varchar("destination").notNull() // a cidr range
|
||||
});
|
||||
|
||||
export const remoteExitNodePreferenceLabels = pgTable(
|
||||
// this controls what sites are enforced to connect to this node
|
||||
"remoteExitNodePreferenceLabels",
|
||||
{
|
||||
remoteExitNodePreferenceLabelId: serial(
|
||||
"remoteExitNodePreferenceLabelId"
|
||||
).primaryKey(),
|
||||
remoteExitNode: integer("remoteExitNode")
|
||||
.references(() => remoteExitNodes.remoteExitNodeId, {
|
||||
onDelete: "cascade"
|
||||
})
|
||||
.notNull(),
|
||||
labelId: integer("labelId")
|
||||
.references(() => labels.labelId, {
|
||||
onDelete: "cascade"
|
||||
})
|
||||
.notNull()
|
||||
},
|
||||
(t) => [
|
||||
unique("remote_exit_node_preference_label_uniq").on(
|
||||
t.remoteExitNode,
|
||||
t.labelId
|
||||
)
|
||||
]
|
||||
);
|
||||
|
||||
export const remoteExitNodeSessions = pgTable("remoteExitNodeSession", {
|
||||
sessionId: varchar("id").primaryKey(),
|
||||
remoteExitNodeId: varchar("remoteExitNodeId")
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
clients,
|
||||
domains,
|
||||
exitNodes,
|
||||
labels,
|
||||
orgs,
|
||||
resources,
|
||||
roles,
|
||||
@@ -21,9 +22,6 @@ import {
|
||||
targetHealthCheck,
|
||||
users
|
||||
} from "./schema";
|
||||
import { serial, varchar } from "drizzle-orm/mysql-core";
|
||||
import { pgTable } from "drizzle-orm/pg-core";
|
||||
import { bigint } from "zod";
|
||||
|
||||
export const certificates = sqliteTable("certificates", {
|
||||
certId: integer("certId").primaryKey({ autoIncrement: true }),
|
||||
@@ -195,6 +193,44 @@ export const remoteExitNodes = sqliteTable("remoteExitNode", {
|
||||
})
|
||||
});
|
||||
|
||||
export const remoteExitNodeResources = sqliteTable("remoteExitNodeResources", {
|
||||
remoteExitNodeResourceId: integer("remoteExitNodeResourceId").primaryKey({
|
||||
autoIncrement: true
|
||||
}),
|
||||
remoteExitNodeId: text("remoteExitNodeId")
|
||||
.notNull()
|
||||
.references(() => remoteExitNodes.remoteExitNodeId, {
|
||||
onDelete: "cascade"
|
||||
}),
|
||||
destination: text("destination").notNull() // a cidr range
|
||||
});
|
||||
|
||||
export const remoteExitNodePreferenceLabels = sqliteTable(
|
||||
// this controls what sites are enforced to connect to this node
|
||||
"remoteExitNodePreferenceLabels",
|
||||
{
|
||||
remoteExitNodePreferenceLabelId: integer(
|
||||
"remoteExitNodePreferenceLabelId"
|
||||
).primaryKey({ autoIncrement: true }),
|
||||
remoteExitNodeId: text("remoteExitNodeId")
|
||||
.references(() => remoteExitNodes.remoteExitNodeId, {
|
||||
onDelete: "cascade"
|
||||
})
|
||||
.notNull(),
|
||||
labelId: integer("labelId")
|
||||
.references(() => labels.labelId, {
|
||||
onDelete: "cascade"
|
||||
})
|
||||
.notNull()
|
||||
},
|
||||
(t) => [
|
||||
uniqueIndex("remote_exit_node_preference_label_uniq").on(
|
||||
t.remoteExitNodeId,
|
||||
t.labelId
|
||||
)
|
||||
]
|
||||
);
|
||||
|
||||
export const remoteExitNodeSessions = sqliteTable("remoteExitNodeSession", {
|
||||
sessionId: text("id").primaryKey(),
|
||||
remoteExitNodeId: text("remoteExitNodeId")
|
||||
|
||||
@@ -22,7 +22,6 @@ export function noop() {
|
||||
}
|
||||
|
||||
export class UsageService {
|
||||
|
||||
constructor() {
|
||||
if (noop()) {
|
||||
return;
|
||||
@@ -57,7 +56,10 @@ export class UsageService {
|
||||
try {
|
||||
let usage;
|
||||
if (transaction) {
|
||||
const orgIdToUse = await this.getBillingOrg(orgId, transaction);
|
||||
const orgIdToUse = await this.getBillingOrg(
|
||||
orgId,
|
||||
transaction
|
||||
);
|
||||
usage = await this.internalAddUsage(
|
||||
orgIdToUse,
|
||||
featureId,
|
||||
@@ -274,11 +276,12 @@ export class UsageService {
|
||||
return null;
|
||||
}
|
||||
|
||||
const orgIdToUse = await this.getBillingOrg(orgId, trx);
|
||||
|
||||
const usageId = `${orgIdToUse}-${featureId}`;
|
||||
|
||||
let orgIdToUse = orgId;
|
||||
try {
|
||||
orgIdToUse = await this.getBillingOrg(orgId, trx);
|
||||
|
||||
const usageId = `${orgIdToUse}-${featureId}`;
|
||||
|
||||
const [result] = await trx
|
||||
.select()
|
||||
.from(usage)
|
||||
@@ -338,8 +341,12 @@ export class UsageService {
|
||||
`Failed to get usage for ${orgIdToUse}/${featureId}:`,
|
||||
error
|
||||
);
|
||||
throw error;
|
||||
if (process.env.NODE_ENV !== "development") {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public async getBillingOrg(
|
||||
@@ -382,13 +389,13 @@ export class UsageService {
|
||||
return false;
|
||||
}
|
||||
|
||||
const orgIdToUse = await this.getBillingOrg(orgId, trx);
|
||||
|
||||
// This method should check the current usage against the limits set for the organization
|
||||
// and kick out all of the sites on the org
|
||||
let hasExceededLimits = false;
|
||||
|
||||
let orgIdToUse = orgId;
|
||||
try {
|
||||
orgIdToUse = await this.getBillingOrg(orgId, trx);
|
||||
|
||||
let orgLimits: Limit[] = [];
|
||||
if (featureId) {
|
||||
// Get all limits set for this organization
|
||||
|
||||
@@ -330,6 +330,44 @@ authenticated.delete(
|
||||
remoteExitNode.deleteRemoteExitNode
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/remote-exit-node/:remoteExitNodeId/resources",
|
||||
verifyValidLicense,
|
||||
verifyOrgAccess,
|
||||
verifyRemoteExitNodeAccess,
|
||||
verifyUserHasAction(ActionsEnum.getRemoteExitNode),
|
||||
remoteExitNode.listRemoteExitNodeResources
|
||||
);
|
||||
|
||||
authenticated.post(
|
||||
"/org/:orgId/remote-exit-node/:remoteExitNodeId/resources",
|
||||
verifyValidLicense,
|
||||
verifyOrgAccess,
|
||||
verifyRemoteExitNodeAccess,
|
||||
verifyUserHasAction(ActionsEnum.updateRemoteExitNode),
|
||||
logActionAudit(ActionsEnum.updateRemoteExitNode),
|
||||
remoteExitNode.setRemoteExitNodeResources
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/remote-exit-node/:remoteExitNodeId/preference-labels",
|
||||
verifyValidLicense,
|
||||
verifyOrgAccess,
|
||||
verifyRemoteExitNodeAccess,
|
||||
verifyUserHasAction(ActionsEnum.getRemoteExitNode),
|
||||
remoteExitNode.listRemoteExitNodePreferenceLabels
|
||||
);
|
||||
|
||||
authenticated.post(
|
||||
"/org/:orgId/remote-exit-node/:remoteExitNodeId/preference-labels",
|
||||
verifyValidLicense,
|
||||
verifyOrgAccess,
|
||||
verifyRemoteExitNodeAccess,
|
||||
verifyUserHasAction(ActionsEnum.updateRemoteExitNode),
|
||||
logActionAudit(ActionsEnum.updateRemoteExitNode),
|
||||
remoteExitNode.setRemoteExitNodePreferenceLabels
|
||||
);
|
||||
|
||||
authenticated.put(
|
||||
"/org/:orgId/login-page",
|
||||
verifyValidLicense,
|
||||
|
||||
@@ -22,3 +22,7 @@ export * from "./listRemoteExitNodes";
|
||||
export * from "./pickRemoteExitNodeDefaults";
|
||||
export * from "./quickStartRemoteExitNode";
|
||||
export * from "./offlineChecker";
|
||||
export * from "./listRemoteExitNodeResources";
|
||||
export * from "./setRemoteExitNodeResources";
|
||||
export * from "./listRemoteExitNodePreferenceLabels";
|
||||
export * from "./setRemoteExitNodePreferenceLabels";
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
* This file is part of a proprietary work.
|
||||
*
|
||||
* Copyright (c) 2025-2026 Fossorial, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This file is licensed under the Fossorial Commercial License.
|
||||
* You may not use this file except in compliance with the License.
|
||||
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
|
||||
*
|
||||
* This file is not licensed under the AGPLv3.
|
||||
*/
|
||||
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
db,
|
||||
labels,
|
||||
remoteExitNodePreferenceLabels,
|
||||
remoteExitNodes
|
||||
} from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
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";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().min(1),
|
||||
remoteExitNodeId: z.string().min(1)
|
||||
});
|
||||
|
||||
export type ListRemoteExitNodePreferenceLabelsResponse = {
|
||||
labels: {
|
||||
remoteExitNodePreferenceLabelId: number;
|
||||
labelId: number;
|
||||
name: string;
|
||||
color: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
export async function listRemoteExitNodePreferenceLabels(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = paramsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { remoteExitNodeId } = parsedParams.data;
|
||||
|
||||
const [remoteExitNode] = await db
|
||||
.select()
|
||||
.from(remoteExitNodes)
|
||||
.where(eq(remoteExitNodes.remoteExitNodeId, remoteExitNodeId))
|
||||
.limit(1);
|
||||
|
||||
if (!remoteExitNode) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Remote exit node with ID ${remoteExitNodeId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
remoteExitNodePreferenceLabelId:
|
||||
remoteExitNodePreferenceLabels.remoteExitNodePreferenceLabelId,
|
||||
labelId: remoteExitNodePreferenceLabels.labelId,
|
||||
name: labels.name,
|
||||
color: labels.color
|
||||
})
|
||||
.from(remoteExitNodePreferenceLabels)
|
||||
.innerJoin(
|
||||
labels,
|
||||
eq(labels.labelId, remoteExitNodePreferenceLabels.labelId)
|
||||
)
|
||||
.where(
|
||||
eq(
|
||||
remoteExitNodePreferenceLabels.remoteExitNodeId,
|
||||
remoteExitNodeId
|
||||
)
|
||||
);
|
||||
|
||||
return response<ListRemoteExitNodePreferenceLabelsResponse>(res, {
|
||||
data: { labels: rows },
|
||||
success: true,
|
||||
error: false,
|
||||
message:
|
||||
"Remote exit node preference labels retrieved successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* This file is part of a proprietary work.
|
||||
*
|
||||
* Copyright (c) 2025-2026 Fossorial, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This file is licensed under the Fossorial Commercial License.
|
||||
* You may not use this file except in compliance with the License.
|
||||
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
|
||||
*
|
||||
* This file is not licensed under the AGPLv3.
|
||||
*/
|
||||
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, remoteExitNodeResources, remoteExitNodes } from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
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";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().min(1),
|
||||
remoteExitNodeId: z.string().min(1)
|
||||
});
|
||||
|
||||
export type ListRemoteExitNodeResourcesResponse = {
|
||||
resources: {
|
||||
remoteExitNodeResourceId: number;
|
||||
remoteExitNodeId: string;
|
||||
destination: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
export async function listRemoteExitNodeResources(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = paramsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { remoteExitNodeId } = parsedParams.data;
|
||||
|
||||
const [remoteExitNode] = await db
|
||||
.select()
|
||||
.from(remoteExitNodes)
|
||||
.where(eq(remoteExitNodes.remoteExitNodeId, remoteExitNodeId))
|
||||
.limit(1);
|
||||
|
||||
if (!remoteExitNode) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Remote exit node with ID ${remoteExitNodeId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const resources = await db
|
||||
.select()
|
||||
.from(remoteExitNodeResources)
|
||||
.where(
|
||||
eq(remoteExitNodeResources.remoteExitNodeId, remoteExitNodeId)
|
||||
);
|
||||
|
||||
return response<ListRemoteExitNodeResourcesResponse>(res, {
|
||||
data: { resources },
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Remote exit node resources retrieved successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
/*
|
||||
* This file is part of a proprietary work.
|
||||
*
|
||||
* Copyright (c) 2025-2026 Fossorial, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This file is licensed under the Fossorial Commercial License.
|
||||
* You may not use this file except in compliance with the License.
|
||||
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
|
||||
*
|
||||
* This file is not licensed under the AGPLv3.
|
||||
*/
|
||||
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
db,
|
||||
labels,
|
||||
remoteExitNodePreferenceLabels,
|
||||
remoteExitNodes
|
||||
} from "@server/db";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
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";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().min(1),
|
||||
remoteExitNodeId: z.string().min(1)
|
||||
});
|
||||
|
||||
const bodySchema = z.strictObject({
|
||||
labelIds: z.array(z.number().int().positive())
|
||||
});
|
||||
|
||||
export type SetRemoteExitNodePreferenceLabelsBody = z.infer<typeof bodySchema>;
|
||||
|
||||
export type SetRemoteExitNodePreferenceLabelsResponse = {
|
||||
labels: {
|
||||
remoteExitNodePreferenceLabelId: number;
|
||||
labelId: number;
|
||||
name: string;
|
||||
color: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
export async function setRemoteExitNodePreferenceLabels(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = paramsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { orgId, remoteExitNodeId } = parsedParams.data;
|
||||
|
||||
const parsedBody = bodySchema.safeParse(req.body);
|
||||
if (!parsedBody.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedBody.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { labelIds } = parsedBody.data;
|
||||
|
||||
const [remoteExitNode] = await db
|
||||
.select()
|
||||
.from(remoteExitNodes)
|
||||
.where(eq(remoteExitNodes.remoteExitNodeId, remoteExitNodeId))
|
||||
.limit(1);
|
||||
|
||||
if (!remoteExitNode) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Remote exit node with ID ${remoteExitNodeId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Validate all provided labelIds belong to this org
|
||||
if (labelIds.length > 0) {
|
||||
const existingLabels = await db
|
||||
.select({ labelId: labels.labelId })
|
||||
.from(labels)
|
||||
.where(
|
||||
and(
|
||||
eq(labels.orgId, orgId),
|
||||
inArray(labels.labelId, labelIds)
|
||||
)
|
||||
);
|
||||
|
||||
if (existingLabels.length !== labelIds.length) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"One or more label IDs are invalid or do not belong to this organization"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Replace all preference labels atomically
|
||||
await db
|
||||
.delete(remoteExitNodePreferenceLabels)
|
||||
.where(
|
||||
eq(
|
||||
remoteExitNodePreferenceLabels.remoteExitNodeId,
|
||||
remoteExitNodeId
|
||||
)
|
||||
);
|
||||
|
||||
if (labelIds.length > 0) {
|
||||
await db.insert(remoteExitNodePreferenceLabels).values(
|
||||
labelIds.map((labelId) => ({
|
||||
remoteExitNodeId,
|
||||
labelId
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
remoteExitNodePreferenceLabelId:
|
||||
remoteExitNodePreferenceLabels.remoteExitNodePreferenceLabelId,
|
||||
labelId: remoteExitNodePreferenceLabels.labelId,
|
||||
name: labels.name,
|
||||
color: labels.color
|
||||
})
|
||||
.from(remoteExitNodePreferenceLabels)
|
||||
.innerJoin(
|
||||
labels,
|
||||
eq(labels.labelId, remoteExitNodePreferenceLabels.labelId)
|
||||
)
|
||||
.where(
|
||||
eq(
|
||||
remoteExitNodePreferenceLabels.remoteExitNodeId,
|
||||
remoteExitNodeId
|
||||
)
|
||||
);
|
||||
|
||||
return response<SetRemoteExitNodePreferenceLabelsResponse>(res, {
|
||||
data: { labels: rows },
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Remote exit node preference labels updated successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
* This file is part of a proprietary work.
|
||||
*
|
||||
* Copyright (c) 2025-2026 Fossorial, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This file is licensed under the Fossorial Commercial License.
|
||||
* You may not use this file except in compliance with the License.
|
||||
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
|
||||
*
|
||||
* This file is not licensed under the AGPLv3.
|
||||
*/
|
||||
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, remoteExitNodeResources, remoteExitNodes } from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
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";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().min(1),
|
||||
remoteExitNodeId: z.string().min(1)
|
||||
});
|
||||
|
||||
const cidrRegex =
|
||||
/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$|^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]+|::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9]))(\/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))$/;
|
||||
|
||||
const bodySchema = z.strictObject({
|
||||
destinations: z.array(
|
||||
z.string().regex(cidrRegex, "Must be a valid CIDR range")
|
||||
)
|
||||
});
|
||||
|
||||
export type SetRemoteExitNodeResourcesBody = z.infer<typeof bodySchema>;
|
||||
|
||||
export type SetRemoteExitNodeResourcesResponse = {
|
||||
resources: {
|
||||
remoteExitNodeResourceId: number;
|
||||
remoteExitNodeId: string;
|
||||
destination: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
export async function setRemoteExitNodeResources(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = paramsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { remoteExitNodeId } = parsedParams.data;
|
||||
|
||||
const parsedBody = bodySchema.safeParse(req.body);
|
||||
if (!parsedBody.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedBody.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { destinations } = parsedBody.data;
|
||||
|
||||
const [remoteExitNode] = await db
|
||||
.select()
|
||||
.from(remoteExitNodes)
|
||||
.where(eq(remoteExitNodes.remoteExitNodeId, remoteExitNodeId))
|
||||
.limit(1);
|
||||
|
||||
if (!remoteExitNode) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Remote exit node with ID ${remoteExitNodeId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Replace all resources atomically
|
||||
await db
|
||||
.delete(remoteExitNodeResources)
|
||||
.where(
|
||||
eq(remoteExitNodeResources.remoteExitNodeId, remoteExitNodeId)
|
||||
);
|
||||
|
||||
if (destinations.length > 0) {
|
||||
await db.insert(remoteExitNodeResources).values(
|
||||
destinations.map((destination) => ({
|
||||
remoteExitNodeId,
|
||||
destination
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
const resources = await db
|
||||
.select()
|
||||
.from(remoteExitNodeResources)
|
||||
.where(
|
||||
eq(remoteExitNodeResources.remoteExitNodeId, remoteExitNodeId)
|
||||
);
|
||||
|
||||
return response<SetRemoteExitNodeResourcesResponse>(res, {
|
||||
data: { resources },
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Remote exit node resources updated successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,10 @@ export default async function SettingsLayout(props: SettingsLayoutProps) {
|
||||
const t = await getTranslations();
|
||||
|
||||
const navItems = [
|
||||
{
|
||||
title: "Networking",
|
||||
href: "/{orgId}/settings/remote-exit-nodes/{remoteExitNodeId}/networking"
|
||||
},
|
||||
{
|
||||
title: t("credentials"),
|
||||
href: "/{orgId}/settings/remote-exit-nodes/{remoteExitNodeId}/credentials"
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
SettingsContainer,
|
||||
SettingsSection,
|
||||
SettingsSectionBody,
|
||||
SettingsSectionDescription,
|
||||
SettingsSectionFooter,
|
||||
SettingsSectionHeader,
|
||||
SettingsSectionTitle
|
||||
} from "@app/components/Settings";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import { createApiClient, formatAxiosError } from "@app/lib/api";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import { useParams } from "next/navigation";
|
||||
import { AxiosResponse } from "axios";
|
||||
import { useRemoteExitNodeContext } from "@app/hooks/useRemoteExitNodeContext";
|
||||
import { TagInput, type Tag } from "@app/components/tags/tag-input";
|
||||
import { MultiSelectTagInput } from "@app/components/multi-select/multi-select-tag-input";
|
||||
import type { TagValue } from "@app/components/multi-select/multi-select-content";
|
||||
import { orgQueries } from "@app/lib/queries";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useDebounce } from "use-debounce";
|
||||
import type { ListRemoteExitNodeResourcesResponse } from "@server/private/routers/remoteExitNode/listRemoteExitNodeResources";
|
||||
import type { SetRemoteExitNodeResourcesResponse } from "@server/private/routers/remoteExitNode/setRemoteExitNodeResources";
|
||||
import type { ListRemoteExitNodePreferenceLabelsResponse } from "@server/private/routers/remoteExitNode/listRemoteExitNodePreferenceLabels";
|
||||
import type { SetRemoteExitNodePreferenceLabelsResponse } from "@server/private/routers/remoteExitNode/setRemoteExitNodePreferenceLabels";
|
||||
|
||||
const cidrRegex =
|
||||
/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$|^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]+|::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9]))(\/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))$/;
|
||||
|
||||
export default function NetworkingPage() {
|
||||
const { env } = useEnvContext();
|
||||
const api = createApiClient({ env });
|
||||
const { orgId } = useParams<{
|
||||
orgId: string;
|
||||
remoteExitNodeId: string;
|
||||
}>();
|
||||
const { remoteExitNode } = useRemoteExitNodeContext();
|
||||
|
||||
// Subnets state
|
||||
const [subnets, setSubnets] = useState<Tag[]>([]);
|
||||
const [activeTagIndex, setActiveTagIndex] = useState<number | null>(null);
|
||||
const [loadingSubnets, setLoadingSubnets] = useState(true);
|
||||
const [savingSubnets, setSavingSubnets] = useState(false);
|
||||
|
||||
// Labels state
|
||||
const [selectedLabels, setSelectedLabels] = useState<TagValue[]>([]);
|
||||
const [labelSearchQuery, setLabelSearchQuery] = useState("");
|
||||
const [loadingLabels, setLoadingLabels] = useState(true);
|
||||
const [savingLabels, setSavingLabels] = useState(false);
|
||||
|
||||
const [debouncedLabelQuery] = useDebounce(labelSearchQuery, 150);
|
||||
|
||||
const { data: availableLabels = [] } = useQuery(
|
||||
orgQueries.labels({ orgId, query: debouncedLabelQuery, perPage: 10 })
|
||||
);
|
||||
|
||||
const labelsShown = useMemo<TagValue[]>(() => {
|
||||
const base: TagValue[] = availableLabels.map((l) => ({
|
||||
id: l.labelId.toString(),
|
||||
text: l.name,
|
||||
color: l.color
|
||||
}));
|
||||
if (debouncedLabelQuery.trim().length === 0) {
|
||||
for (const sel of selectedLabels) {
|
||||
if (!base.find((b) => b.id === sel.id)) {
|
||||
base.unshift(sel);
|
||||
}
|
||||
}
|
||||
}
|
||||
return base;
|
||||
}, [availableLabels, selectedLabels, debouncedLabelQuery]);
|
||||
|
||||
useEffect(() => {
|
||||
async function loadSubnets() {
|
||||
try {
|
||||
const res = await api.get<
|
||||
AxiosResponse<ListRemoteExitNodeResourcesResponse>
|
||||
>(
|
||||
`/org/${orgId}/remote-exit-node/${remoteExitNode.remoteExitNodeId}/resources`
|
||||
);
|
||||
setSubnets(
|
||||
res.data.data.resources.map((r) => ({
|
||||
id: r.destination,
|
||||
text: r.destination
|
||||
}))
|
||||
);
|
||||
} catch (error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description:
|
||||
formatAxiosError(error) || "Failed to load subnets"
|
||||
});
|
||||
} finally {
|
||||
setLoadingSubnets(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadLabels() {
|
||||
try {
|
||||
const res = await api.get<
|
||||
AxiosResponse<ListRemoteExitNodePreferenceLabelsResponse>
|
||||
>(
|
||||
`/org/${orgId}/remote-exit-node/${remoteExitNode.remoteExitNodeId}/preference-labels`
|
||||
);
|
||||
setSelectedLabels(
|
||||
res.data.data.labels.map((l) => ({
|
||||
id: l.labelId.toString(),
|
||||
text: l.name,
|
||||
color: l.color
|
||||
}))
|
||||
);
|
||||
} catch (error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description:
|
||||
formatAxiosError(error) || "Failed to load labels"
|
||||
});
|
||||
} finally {
|
||||
setLoadingLabels(false);
|
||||
}
|
||||
}
|
||||
|
||||
loadSubnets();
|
||||
loadLabels();
|
||||
}, [remoteExitNode.remoteExitNodeId]);
|
||||
|
||||
const handleSaveSubnets = async () => {
|
||||
setSavingSubnets(true);
|
||||
try {
|
||||
await api.post<AxiosResponse<SetRemoteExitNodeResourcesResponse>>(
|
||||
`/org/${orgId}/remote-exit-node/${remoteExitNode.remoteExitNodeId}/resources`,
|
||||
{ destinations: subnets.map((s) => s.text) }
|
||||
);
|
||||
toast({
|
||||
title: "Subnets saved",
|
||||
description: "Remote subnets have been updated successfully."
|
||||
});
|
||||
} catch (error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: formatAxiosError(error) || "Failed to save subnets"
|
||||
});
|
||||
} finally {
|
||||
setSavingSubnets(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveLabels = async () => {
|
||||
setSavingLabels(true);
|
||||
try {
|
||||
await api.post<
|
||||
AxiosResponse<SetRemoteExitNodePreferenceLabelsResponse>
|
||||
>(
|
||||
`/org/${orgId}/remote-exit-node/${remoteExitNode.remoteExitNodeId}/preference-labels`,
|
||||
{ labelIds: selectedLabels.map((l) => parseInt(l.id)) }
|
||||
);
|
||||
toast({
|
||||
title: "Labels saved",
|
||||
description: "Preference labels have been updated successfully."
|
||||
});
|
||||
} catch (error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: formatAxiosError(error) || "Failed to save labels"
|
||||
});
|
||||
} finally {
|
||||
setSavingLabels(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsContainer>
|
||||
<SettingsSection>
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>Remote Subnets</SettingsSectionTitle>
|
||||
<SettingsSectionDescription>
|
||||
Define the CIDR ranges that this remote exit node will
|
||||
route traffic to. Type a valid CIDR (e.g.{" "}
|
||||
<code>10.0.0.0/8</code>) and press Enter to add.
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsSectionBody>
|
||||
<TagInput
|
||||
tags={subnets}
|
||||
setTags={setSubnets}
|
||||
placeholder="Add a CIDR range (e.g. 10.0.0.0/8)"
|
||||
validateTag={(tag) => cidrRegex.test(tag.trim())}
|
||||
activeTagIndex={activeTagIndex}
|
||||
setActiveTagIndex={setActiveTagIndex}
|
||||
disabled={loadingSubnets}
|
||||
allowDuplicates={false}
|
||||
inlineTags={true}
|
||||
/>
|
||||
</SettingsSectionBody>
|
||||
<SettingsSectionFooter>
|
||||
<Button onClick={handleSaveSubnets} loading={savingSubnets}>
|
||||
Save Subnets
|
||||
</Button>
|
||||
</SettingsSectionFooter>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection>
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>
|
||||
Preference Labels
|
||||
</SettingsSectionTitle>
|
||||
<SettingsSectionDescription>
|
||||
Sites with these labels will be enforced to connect
|
||||
through this remote exit node.
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsSectionBody>
|
||||
<MultiSelectTagInput
|
||||
value={selectedLabels}
|
||||
options={labelsShown}
|
||||
onChange={setSelectedLabels}
|
||||
onSearch={setLabelSearchQuery}
|
||||
searchQuery={labelSearchQuery}
|
||||
disabled={loadingLabels}
|
||||
buttonText="Select labels..."
|
||||
searchPlaceholder="Search labels..."
|
||||
/>
|
||||
</SettingsSectionBody>
|
||||
<SettingsSectionFooter>
|
||||
<Button onClick={handleSaveLabels} loading={savingLabels}>
|
||||
Save Labels
|
||||
</Button>
|
||||
</SettingsSectionFooter>
|
||||
</SettingsSection>
|
||||
</SettingsContainer>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,6 @@ export default async function RemoteExitNodePage(props: {
|
||||
}) {
|
||||
const params = await props.params;
|
||||
redirect(
|
||||
`/${params.orgId}/settings/remote-exit-nodes/${params.remoteExitNodeId}/credentials`
|
||||
`/${params.orgId}/settings/remote-exit-nodes/${params.remoteExitNodeId}/networking`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -35,8 +35,6 @@ import { toast } from "@app/hooks/useToast";
|
||||
import { AxiosResponse } from "axios";
|
||||
import { useParams, useRouter, useSearchParams } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@app/components/ui/alert";
|
||||
import { InfoIcon } from "lucide-react";
|
||||
import HeaderTitle from "@app/components/SettingsSectionTitle";
|
||||
import { StrategySelect } from "@app/components/StrategySelect";
|
||||
|
||||
|
||||
@@ -12,7 +12,12 @@ import { CheckIcon } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Checkbox } from "../ui/checkbox";
|
||||
|
||||
export type TagValue = { text: string; id: string; isAdmin?: boolean };
|
||||
export type TagValue = {
|
||||
text: string;
|
||||
id: string;
|
||||
isAdmin?: boolean;
|
||||
color?: string;
|
||||
};
|
||||
|
||||
export type MultiSelectTagsProps<T extends TagValue> = {
|
||||
emptyPlaceholder?: string;
|
||||
@@ -77,6 +82,14 @@ export function MultiSelectContent<T extends TagValue>({
|
||||
aria-hidden
|
||||
tabIndex={-1}
|
||||
/>
|
||||
{option.color && (
|
||||
<span
|
||||
className="size-2 rounded-full flex-none"
|
||||
style={{
|
||||
backgroundColor: option.color
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{`${option.text}`}
|
||||
</CommandItem>
|
||||
);
|
||||
|
||||
@@ -66,6 +66,14 @@ export function MultiSelectTagInput<T extends TagValue>({
|
||||
)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{option.color && (
|
||||
<span
|
||||
className="size-2 rounded-full flex-none ml-1"
|
||||
style={{
|
||||
backgroundColor: option.color
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<span className="max-w-40 text-ellipsis overflow-hidden">
|
||||
{option.text}
|
||||
</span>
|
||||
|
||||
Reference in New Issue
Block a user