mirror of
https://github.com/fosrl/pangolin.git
synced 2026-06-27 17:49:52 +00:00
Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c9cc9581b1 | ||
|
|
eac7c67dcc | ||
|
|
633d9031af | ||
|
|
05dc558c4a | ||
|
|
ea3f1c341b | ||
|
|
35dffe71cb | ||
|
|
2e628fe0e4 |
@@ -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")
|
||||
|
||||
@@ -276,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)
|
||||
@@ -340,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(
|
||||
@@ -384,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
|
||||
|
||||
@@ -172,7 +172,9 @@ export async function applyBlueprint({
|
||||
} catch (err) {
|
||||
blueprintSucceeded = false;
|
||||
blueprintMessage = `Blueprint applied with errors: ${err}`;
|
||||
logger.error(blueprintMessage);
|
||||
logger.debug(
|
||||
`Org ${orgId} blueprint apply issues: ${blueprintMessage}`
|
||||
);
|
||||
error = err;
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ type ClientRow = typeof clients.$inferSelect;
|
||||
function runQueuedClientAssociationRebuilds(
|
||||
userId: string,
|
||||
queuedClients: ClientRow[]
|
||||
): void {
|
||||
) {
|
||||
if (queuedClients.length === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -39,425 +39,403 @@ function runQueuedClientAssociationRebuilds(
|
||||
uniqueClientsById.set(client.clientId, client);
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
for (const client of uniqueClientsById.values()) {
|
||||
try {
|
||||
await rebuildClientAssociationsFromClient(client);
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`Failed rebuilding associations for client ${client.clientId} (user ${userId}): ${String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
for (const client of uniqueClientsById.values()) {
|
||||
rebuildClientAssociationsFromClient(client).catch((error) => {
|
||||
logger.error(
|
||||
`Error rebuilding client associations for client ${client.clientId} (user ${userId}): ${String(
|
||||
error
|
||||
)}`
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
logger.debug(
|
||||
`Queued association rebuild completed for ${uniqueClientsById.size} client(s) (user ${userId})`
|
||||
);
|
||||
})();
|
||||
logger.debug(
|
||||
`Queued association rebuild completed for ${uniqueClientsById.size} client(s) (user ${userId})`
|
||||
);
|
||||
}
|
||||
|
||||
export async function calculateUserClientsForOrgs(
|
||||
userId: string
|
||||
): Promise<void> {
|
||||
const trx = primaryDb;
|
||||
|
||||
const queuedAssociationRebuilds: ClientRow[] = [];
|
||||
const orgCache = new Map<string, typeof orgs.$inferSelect | null>();
|
||||
const adminRoleCache = new Map<string, typeof roles.$inferSelect | null>();
|
||||
const exitNodesCache = new Map<
|
||||
string,
|
||||
Awaited<ReturnType<typeof listExitNodes>>
|
||||
>();
|
||||
const isOrgLicensedCache = new Map<string, boolean>();
|
||||
const existingClientCache = new Map<
|
||||
string,
|
||||
typeof clients.$inferSelect | null
|
||||
>();
|
||||
const roleClientAccessCache = new Map<string, boolean>();
|
||||
const userClientAccessCache = new Map<string, boolean>();
|
||||
|
||||
const execute = async (transaction: Transaction | typeof db) => {
|
||||
const orgCache = new Map<string, typeof orgs.$inferSelect | null>();
|
||||
const adminRoleCache = new Map<
|
||||
string,
|
||||
typeof roles.$inferSelect | null
|
||||
>();
|
||||
const exitNodesCache = new Map<
|
||||
string,
|
||||
Awaited<ReturnType<typeof listExitNodes>>
|
||||
>();
|
||||
const isOrgLicensedCache = new Map<string, boolean>();
|
||||
const existingClientCache = new Map<
|
||||
string,
|
||||
typeof clients.$inferSelect | null
|
||||
>();
|
||||
const roleClientAccessCache = new Map<string, boolean>();
|
||||
const userClientAccessCache = new Map<string, boolean>();
|
||||
const getOrgOlmKey = (orgId: string, olmId: string) => `${orgId}:${olmId}`;
|
||||
const getRoleClientKey = (roleId: number, clientId: number) =>
|
||||
`${roleId}:${clientId}`;
|
||||
const getUserClientKey = (cachedUserId: string, clientId: number) =>
|
||||
`${cachedUserId}:${clientId}`;
|
||||
|
||||
const getOrgOlmKey = (orgId: string, olmId: string) =>
|
||||
`${orgId}:${olmId}`;
|
||||
const getRoleClientKey = (roleId: number, clientId: number) =>
|
||||
`${roleId}:${clientId}`;
|
||||
const getUserClientKey = (cachedUserId: string, clientId: number) =>
|
||||
`${cachedUserId}:${clientId}`;
|
||||
|
||||
const getOrg = async (orgId: string) => {
|
||||
if (orgCache.has(orgId)) {
|
||||
return orgCache.get(orgId) ?? null;
|
||||
}
|
||||
|
||||
const [org] = await transaction
|
||||
.select()
|
||||
.from(orgs)
|
||||
.where(eq(orgs.orgId, orgId));
|
||||
orgCache.set(orgId, org ?? null);
|
||||
|
||||
return org ?? null;
|
||||
};
|
||||
|
||||
const getAdminRole = async (orgId: string) => {
|
||||
if (adminRoleCache.has(orgId)) {
|
||||
return adminRoleCache.get(orgId) ?? null;
|
||||
}
|
||||
|
||||
const [adminRole] = await transaction
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(and(eq(roles.isAdmin, true), eq(roles.orgId, orgId)))
|
||||
.limit(1);
|
||||
adminRoleCache.set(orgId, adminRole ?? null);
|
||||
|
||||
return adminRole ?? null;
|
||||
};
|
||||
|
||||
const getExitNodes = async (orgId: string) => {
|
||||
if (exitNodesCache.has(orgId)) {
|
||||
return exitNodesCache.get(orgId)!;
|
||||
}
|
||||
|
||||
const exitNodes = await listExitNodes(orgId);
|
||||
exitNodesCache.set(orgId, exitNodes);
|
||||
|
||||
return exitNodes;
|
||||
};
|
||||
|
||||
const getIsOrgLicensed = async (orgId: string) => {
|
||||
if (isOrgLicensedCache.has(orgId)) {
|
||||
return isOrgLicensedCache.get(orgId)!;
|
||||
}
|
||||
|
||||
const isOrgLicensed = await isLicensedOrSubscribed(
|
||||
orgId,
|
||||
tierMatrix.deviceApprovals
|
||||
);
|
||||
isOrgLicensedCache.set(orgId, isOrgLicensed);
|
||||
|
||||
return isOrgLicensed;
|
||||
};
|
||||
|
||||
const getExistingClient = async (orgId: string, olmId: string) => {
|
||||
const key = getOrgOlmKey(orgId, olmId);
|
||||
if (existingClientCache.has(key)) {
|
||||
return existingClientCache.get(key) ?? null;
|
||||
}
|
||||
|
||||
const [existingClient] = await transaction
|
||||
.select()
|
||||
.from(clients)
|
||||
.where(
|
||||
and(
|
||||
eq(clients.userId, userId),
|
||||
eq(clients.orgId, orgId),
|
||||
eq(clients.olmId, olmId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
existingClientCache.set(key, existingClient ?? null);
|
||||
|
||||
return existingClient ?? null;
|
||||
};
|
||||
|
||||
const hasRoleClientAccess = async (
|
||||
roleId: number,
|
||||
clientId: number
|
||||
) => {
|
||||
const key = getRoleClientKey(roleId, clientId);
|
||||
if (roleClientAccessCache.has(key)) {
|
||||
return roleClientAccessCache.get(key)!;
|
||||
}
|
||||
|
||||
const [existingRoleClient] = await transaction
|
||||
.select()
|
||||
.from(roleClients)
|
||||
.where(
|
||||
and(
|
||||
eq(roleClients.roleId, roleId),
|
||||
eq(roleClients.clientId, clientId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
const hasAccess = Boolean(existingRoleClient);
|
||||
roleClientAccessCache.set(key, hasAccess);
|
||||
|
||||
return hasAccess;
|
||||
};
|
||||
|
||||
const hasUserClientAccess = async (
|
||||
cachedUserId: string,
|
||||
clientId: number
|
||||
) => {
|
||||
const key = getUserClientKey(cachedUserId, clientId);
|
||||
if (userClientAccessCache.has(key)) {
|
||||
return userClientAccessCache.get(key)!;
|
||||
}
|
||||
|
||||
const [existingUserClient] = await transaction
|
||||
.select()
|
||||
.from(userClients)
|
||||
.where(
|
||||
and(
|
||||
eq(userClients.userId, cachedUserId),
|
||||
eq(userClients.clientId, clientId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
const hasAccess = Boolean(existingUserClient);
|
||||
userClientAccessCache.set(key, hasAccess);
|
||||
|
||||
return hasAccess;
|
||||
};
|
||||
|
||||
// Get all OLMs for this user
|
||||
const userOlms = await transaction
|
||||
.select()
|
||||
.from(olms)
|
||||
.where(eq(olms.userId, userId));
|
||||
|
||||
if (userOlms.length === 0) {
|
||||
// No OLMs for this user, but we should still clean up any orphaned clients
|
||||
await cleanupOrphanedClients(
|
||||
userId,
|
||||
transaction,
|
||||
[],
|
||||
queuedAssociationRebuilds
|
||||
);
|
||||
return;
|
||||
const getOrg = async (orgId: string) => {
|
||||
if (orgCache.has(orgId)) {
|
||||
return orgCache.get(orgId) ?? null;
|
||||
}
|
||||
|
||||
// Get all user orgs with all roles (for org list and role-based logic)
|
||||
const userOrgRoleRows = await transaction
|
||||
const [org] = await trx
|
||||
.select()
|
||||
.from(userOrgs)
|
||||
.innerJoin(
|
||||
userOrgRoles,
|
||||
.from(orgs)
|
||||
.where(eq(orgs.orgId, orgId));
|
||||
orgCache.set(orgId, org ?? null);
|
||||
|
||||
return org ?? null;
|
||||
};
|
||||
|
||||
const getAdminRole = async (orgId: string) => {
|
||||
if (adminRoleCache.has(orgId)) {
|
||||
return adminRoleCache.get(orgId) ?? null;
|
||||
}
|
||||
|
||||
const [adminRole] = await trx
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(and(eq(roles.isAdmin, true), eq(roles.orgId, orgId)))
|
||||
.limit(1);
|
||||
adminRoleCache.set(orgId, adminRole ?? null);
|
||||
|
||||
return adminRole ?? null;
|
||||
};
|
||||
|
||||
const getExitNodes = async (orgId: string) => {
|
||||
if (exitNodesCache.has(orgId)) {
|
||||
return exitNodesCache.get(orgId)!;
|
||||
}
|
||||
|
||||
const exitNodes = await listExitNodes(orgId);
|
||||
exitNodesCache.set(orgId, exitNodes);
|
||||
|
||||
return exitNodes;
|
||||
};
|
||||
|
||||
const getIsOrgLicensed = async (orgId: string) => {
|
||||
if (isOrgLicensedCache.has(orgId)) {
|
||||
return isOrgLicensedCache.get(orgId)!;
|
||||
}
|
||||
|
||||
const isOrgLicensed = await isLicensedOrSubscribed(
|
||||
orgId,
|
||||
tierMatrix.deviceApprovals
|
||||
);
|
||||
isOrgLicensedCache.set(orgId, isOrgLicensed);
|
||||
|
||||
return isOrgLicensed;
|
||||
};
|
||||
|
||||
const getExistingClient = async (orgId: string, olmId: string) => {
|
||||
const key = getOrgOlmKey(orgId, olmId);
|
||||
if (existingClientCache.has(key)) {
|
||||
return existingClientCache.get(key) ?? null;
|
||||
}
|
||||
|
||||
const [existingClient] = await trx
|
||||
.select()
|
||||
.from(clients)
|
||||
.where(
|
||||
and(
|
||||
eq(userOrgs.userId, userOrgRoles.userId),
|
||||
eq(userOrgs.orgId, userOrgRoles.orgId)
|
||||
eq(clients.userId, userId),
|
||||
eq(clients.orgId, orgId),
|
||||
eq(clients.olmId, olmId)
|
||||
)
|
||||
)
|
||||
.innerJoin(roles, eq(userOrgRoles.roleId, roles.roleId))
|
||||
.where(eq(userOrgs.userId, userId));
|
||||
.limit(1);
|
||||
|
||||
const userOrgIds = [
|
||||
...new Set(userOrgRoleRows.map((r) => r.userOrgs.orgId))
|
||||
];
|
||||
const orgIdToRoleRows = new Map<
|
||||
string,
|
||||
(typeof userOrgRoleRows)[0][]
|
||||
>();
|
||||
for (const r of userOrgRoleRows) {
|
||||
const list = orgIdToRoleRows.get(r.userOrgs.orgId) ?? [];
|
||||
list.push(r);
|
||||
orgIdToRoleRows.set(r.userOrgs.orgId, list);
|
||||
}
|
||||
const orgRequiresDeviceApprovalRole = new Map<string, boolean>();
|
||||
for (const [orgId, roleRowsForOrg] of orgIdToRoleRows.entries()) {
|
||||
orgRequiresDeviceApprovalRole.set(
|
||||
orgId,
|
||||
roleRowsForOrg.some((r) => r.roles.requireDeviceApproval)
|
||||
);
|
||||
existingClientCache.set(key, existingClient ?? null);
|
||||
|
||||
return existingClient ?? null;
|
||||
};
|
||||
|
||||
const hasRoleClientAccess = async (roleId: number, clientId: number) => {
|
||||
const key = getRoleClientKey(roleId, clientId);
|
||||
if (roleClientAccessCache.has(key)) {
|
||||
return roleClientAccessCache.get(key)!;
|
||||
}
|
||||
|
||||
// For each OLM, ensure there's a client in each org the user is in
|
||||
for (const olm of userOlms) {
|
||||
for (const orgId of orgIdToRoleRows.keys()) {
|
||||
const roleRowsForOrg = orgIdToRoleRows.get(orgId)!;
|
||||
const userOrg = roleRowsForOrg[0].userOrgs;
|
||||
const [existingRoleClient] = await trx
|
||||
.select()
|
||||
.from(roleClients)
|
||||
.where(
|
||||
and(
|
||||
eq(roleClients.roleId, roleId),
|
||||
eq(roleClients.clientId, clientId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
const org = await getOrg(orgId);
|
||||
const hasAccess = Boolean(existingRoleClient);
|
||||
roleClientAccessCache.set(key, hasAccess);
|
||||
|
||||
if (!org) {
|
||||
logger.warn(
|
||||
`Skipping org ${orgId} for OLM ${olm.olmId} (user ${userId}): org not found`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
return hasAccess;
|
||||
};
|
||||
|
||||
if (!org.subnet) {
|
||||
logger.warn(
|
||||
`Skipping org ${orgId} for OLM ${olm.olmId} (user ${userId}): org has no subnet configured`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get admin role for this org (needed for access grants)
|
||||
const adminRole = await getAdminRole(orgId);
|
||||
|
||||
if (!adminRole) {
|
||||
logger.warn(
|
||||
`Skipping org ${orgId} for OLM ${olm.olmId} (user ${userId}): no admin role found`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if a client already exists for this OLM+user+org combination
|
||||
const existingClient = await getExistingClient(
|
||||
orgId,
|
||||
olm.olmId
|
||||
);
|
||||
|
||||
if (existingClient) {
|
||||
// Ensure admin role has access to the client
|
||||
const hasRoleAccess = await hasRoleClientAccess(
|
||||
adminRole.roleId,
|
||||
existingClient.clientId
|
||||
);
|
||||
|
||||
if (!hasRoleAccess) {
|
||||
await transaction.insert(roleClients).values({
|
||||
roleId: adminRole.roleId,
|
||||
clientId: existingClient.clientId
|
||||
});
|
||||
roleClientAccessCache.set(
|
||||
getRoleClientKey(
|
||||
adminRole.roleId,
|
||||
existingClient.clientId
|
||||
),
|
||||
true
|
||||
);
|
||||
logger.debug(
|
||||
`Granted admin role access to existing client ${existingClient.clientId} for OLM ${olm.olmId} in org ${orgId} (user ${userId})`
|
||||
);
|
||||
}
|
||||
|
||||
// Ensure user has access to the client
|
||||
const hasUserAccess = await hasUserClientAccess(
|
||||
userId,
|
||||
existingClient.clientId
|
||||
);
|
||||
|
||||
if (!hasUserAccess) {
|
||||
await transaction.insert(userClients).values({
|
||||
userId,
|
||||
clientId: existingClient.clientId
|
||||
});
|
||||
userClientAccessCache.set(
|
||||
getUserClientKey(userId, existingClient.clientId),
|
||||
true
|
||||
);
|
||||
logger.debug(
|
||||
`Granted user access to existing client ${existingClient.clientId} for OLM ${olm.olmId} in org ${orgId} (user ${userId})`
|
||||
);
|
||||
}
|
||||
|
||||
logger.debug(
|
||||
`Client already exists for OLM ${olm.olmId} in org ${orgId} (user ${userId}), skipping creation`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get exit nodes for this org
|
||||
const exitNodesList = await getExitNodes(orgId);
|
||||
|
||||
if (exitNodesList.length === 0) {
|
||||
logger.warn(
|
||||
`Skipping org ${orgId} for OLM ${olm.olmId} (user ${userId}): no exit nodes found`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const randomExitNode =
|
||||
exitNodesList[
|
||||
Math.floor(Math.random() * exitNodesList.length)
|
||||
];
|
||||
|
||||
// Get next available subnet
|
||||
const { value: newSubnet, release: releaseSubnetLock } =
|
||||
await getNextAvailableClientSubnet(orgId, transaction);
|
||||
|
||||
const subnet = newSubnet.split("/")[0];
|
||||
const updatedSubnet = `${subnet}/${org.subnet.split("/")[1]}`;
|
||||
|
||||
const niceId = await getUniqueClientName(orgId);
|
||||
|
||||
const isOrgLicensed = await getIsOrgLicensed(userOrg.orgId);
|
||||
const requireApproval =
|
||||
build !== "oss" &&
|
||||
isOrgLicensed &&
|
||||
orgRequiresDeviceApprovalRole.get(orgId) === true;
|
||||
|
||||
const newClientData: InferInsertModel<typeof clients> = {
|
||||
userId,
|
||||
orgId: userOrg.orgId,
|
||||
exitNodeId: randomExitNode.exitNodeId,
|
||||
name: olm.name || "User Client",
|
||||
subnet: updatedSubnet,
|
||||
olmId: olm.olmId,
|
||||
type: "olm",
|
||||
niceId,
|
||||
approvalState: requireApproval ? "pending" : null
|
||||
};
|
||||
|
||||
// Create the client
|
||||
const [newClient] = await transaction
|
||||
.insert(clients)
|
||||
.values(newClientData)
|
||||
.returning();
|
||||
await releaseSubnetLock();
|
||||
existingClientCache.set(
|
||||
getOrgOlmKey(orgId, olm.olmId),
|
||||
newClient
|
||||
);
|
||||
|
||||
// create approval request
|
||||
if (requireApproval) {
|
||||
await transaction
|
||||
.insert(approvals)
|
||||
.values({
|
||||
timestamp: Math.floor(new Date().getTime() / 1000),
|
||||
orgId: userOrg.orgId,
|
||||
clientId: newClient.clientId,
|
||||
userId,
|
||||
type: "user_device"
|
||||
})
|
||||
.returning();
|
||||
}
|
||||
|
||||
queuedAssociationRebuilds.push(newClient);
|
||||
|
||||
// Grant admin role access to the client
|
||||
await transaction.insert(roleClients).values({
|
||||
roleId: adminRole.roleId,
|
||||
clientId: newClient.clientId
|
||||
});
|
||||
roleClientAccessCache.set(
|
||||
getRoleClientKey(adminRole.roleId, newClient.clientId),
|
||||
true
|
||||
);
|
||||
|
||||
// Grant user access to the client
|
||||
await transaction.insert(userClients).values({
|
||||
userId,
|
||||
clientId: newClient.clientId
|
||||
});
|
||||
userClientAccessCache.set(
|
||||
getUserClientKey(userId, newClient.clientId),
|
||||
true
|
||||
);
|
||||
|
||||
logger.debug(
|
||||
`Created client for OLM ${olm.olmId} in org ${orgId} (user ${userId}) with access granted to admin role and user`
|
||||
);
|
||||
}
|
||||
const hasUserClientAccess = async (
|
||||
cachedUserId: string,
|
||||
clientId: number
|
||||
) => {
|
||||
const key = getUserClientKey(cachedUserId, clientId);
|
||||
if (userClientAccessCache.has(key)) {
|
||||
return userClientAccessCache.get(key)!;
|
||||
}
|
||||
|
||||
// Clean up clients in orgs the user is no longer in
|
||||
const [existingUserClient] = await trx
|
||||
.select()
|
||||
.from(userClients)
|
||||
.where(
|
||||
and(
|
||||
eq(userClients.userId, cachedUserId),
|
||||
eq(userClients.clientId, clientId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
const hasAccess = Boolean(existingUserClient);
|
||||
userClientAccessCache.set(key, hasAccess);
|
||||
|
||||
return hasAccess;
|
||||
};
|
||||
|
||||
// Get all OLMs for this user
|
||||
const userOlms = await trx
|
||||
.select()
|
||||
.from(olms)
|
||||
.where(eq(olms.userId, userId));
|
||||
|
||||
if (userOlms.length === 0) {
|
||||
// No OLMs for this user, but we should still clean up any orphaned clients
|
||||
await cleanupOrphanedClients(
|
||||
userId,
|
||||
transaction,
|
||||
userOrgIds,
|
||||
trx,
|
||||
[],
|
||||
queuedAssociationRebuilds
|
||||
);
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
// Get all user orgs with all roles (for org list and role-based logic)
|
||||
const userOrgRoleRows = await trx
|
||||
.select()
|
||||
.from(userOrgs)
|
||||
.innerJoin(
|
||||
userOrgRoles,
|
||||
and(
|
||||
eq(userOrgs.userId, userOrgRoles.userId),
|
||||
eq(userOrgs.orgId, userOrgRoles.orgId)
|
||||
)
|
||||
)
|
||||
.innerJoin(roles, eq(userOrgRoles.roleId, roles.roleId))
|
||||
.where(eq(userOrgs.userId, userId));
|
||||
|
||||
const userOrgIds = [
|
||||
...new Set(userOrgRoleRows.map((r) => r.userOrgs.orgId))
|
||||
];
|
||||
const orgIdToRoleRows = new Map<string, (typeof userOrgRoleRows)[0][]>();
|
||||
for (const r of userOrgRoleRows) {
|
||||
const list = orgIdToRoleRows.get(r.userOrgs.orgId) ?? [];
|
||||
list.push(r);
|
||||
orgIdToRoleRows.set(r.userOrgs.orgId, list);
|
||||
}
|
||||
const orgRequiresDeviceApprovalRole = new Map<string, boolean>();
|
||||
for (const [orgId, roleRowsForOrg] of orgIdToRoleRows.entries()) {
|
||||
orgRequiresDeviceApprovalRole.set(
|
||||
orgId,
|
||||
roleRowsForOrg.some((r) => r.roles.requireDeviceApproval)
|
||||
);
|
||||
}
|
||||
|
||||
// For each OLM, ensure there's a client in each org the user is in
|
||||
for (const olm of userOlms) {
|
||||
for (const orgId of orgIdToRoleRows.keys()) {
|
||||
const roleRowsForOrg = orgIdToRoleRows.get(orgId)!;
|
||||
const userOrg = roleRowsForOrg[0].userOrgs;
|
||||
|
||||
const org = await getOrg(orgId);
|
||||
|
||||
if (!org) {
|
||||
logger.warn(
|
||||
`Skipping org ${orgId} for OLM ${olm.olmId} (user ${userId}): org not found`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!org.subnet) {
|
||||
logger.warn(
|
||||
`Skipping org ${orgId} for OLM ${olm.olmId} (user ${userId}): org has no subnet configured`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get admin role for this org (needed for access grants)
|
||||
const adminRole = await getAdminRole(orgId);
|
||||
|
||||
if (!adminRole) {
|
||||
logger.warn(
|
||||
`Skipping org ${orgId} for OLM ${olm.olmId} (user ${userId}): no admin role found`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if a client already exists for this OLM+user+org combination
|
||||
const existingClient = await getExistingClient(orgId, olm.olmId);
|
||||
|
||||
if (existingClient) {
|
||||
// Ensure admin role has access to the client
|
||||
const hasRoleAccess = await hasRoleClientAccess(
|
||||
adminRole.roleId,
|
||||
existingClient.clientId
|
||||
);
|
||||
|
||||
if (!hasRoleAccess) {
|
||||
await trx.insert(roleClients).values({
|
||||
roleId: adminRole.roleId,
|
||||
clientId: existingClient.clientId
|
||||
});
|
||||
roleClientAccessCache.set(
|
||||
getRoleClientKey(
|
||||
adminRole.roleId,
|
||||
existingClient.clientId
|
||||
),
|
||||
true
|
||||
);
|
||||
logger.debug(
|
||||
`Granted admin role access to existing client ${existingClient.clientId} for OLM ${olm.olmId} in org ${orgId} (user ${userId})`
|
||||
);
|
||||
}
|
||||
|
||||
// Ensure user has access to the client
|
||||
const hasUserAccess = await hasUserClientAccess(
|
||||
userId,
|
||||
existingClient.clientId
|
||||
);
|
||||
|
||||
if (!hasUserAccess) {
|
||||
await trx.insert(userClients).values({
|
||||
userId,
|
||||
clientId: existingClient.clientId
|
||||
});
|
||||
userClientAccessCache.set(
|
||||
getUserClientKey(userId, existingClient.clientId),
|
||||
true
|
||||
);
|
||||
logger.debug(
|
||||
`Granted user access to existing client ${existingClient.clientId} for OLM ${olm.olmId} in org ${orgId} (user ${userId})`
|
||||
);
|
||||
}
|
||||
|
||||
logger.debug(
|
||||
`Client already exists for OLM ${olm.olmId} in org ${orgId} (user ${userId}), skipping creation`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get exit nodes for this org
|
||||
const exitNodesList = await getExitNodes(orgId);
|
||||
|
||||
if (exitNodesList.length === 0) {
|
||||
logger.warn(
|
||||
`Skipping org ${orgId} for OLM ${olm.olmId} (user ${userId}): no exit nodes found`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const randomExitNode =
|
||||
exitNodesList[Math.floor(Math.random() * exitNodesList.length)];
|
||||
|
||||
// Get next available subnet
|
||||
const { value: newSubnet, release: releaseSubnetLock } =
|
||||
await getNextAvailableClientSubnet(orgId, trx);
|
||||
|
||||
const subnet = newSubnet.split("/")[0];
|
||||
const updatedSubnet = `${subnet}/${org.subnet.split("/")[1]}`;
|
||||
|
||||
const niceId = await getUniqueClientName(orgId);
|
||||
|
||||
const isOrgLicensed = await getIsOrgLicensed(userOrg.orgId);
|
||||
const requireApproval =
|
||||
build !== "oss" &&
|
||||
isOrgLicensed &&
|
||||
orgRequiresDeviceApprovalRole.get(orgId) === true;
|
||||
|
||||
const newClientData: InferInsertModel<typeof clients> = {
|
||||
userId,
|
||||
orgId: userOrg.orgId,
|
||||
exitNodeId: randomExitNode.exitNodeId,
|
||||
name: olm.name || "User Client",
|
||||
subnet: updatedSubnet,
|
||||
olmId: olm.olmId,
|
||||
type: "olm",
|
||||
niceId,
|
||||
approvalState: requireApproval ? "pending" : null
|
||||
};
|
||||
|
||||
// Create the client
|
||||
const [newClient] = await trx
|
||||
.insert(clients)
|
||||
.values(newClientData)
|
||||
.returning();
|
||||
await releaseSubnetLock();
|
||||
existingClientCache.set(getOrgOlmKey(orgId, olm.olmId), newClient);
|
||||
|
||||
// create approval request
|
||||
if (requireApproval) {
|
||||
await trx
|
||||
.insert(approvals)
|
||||
.values({
|
||||
timestamp: Math.floor(new Date().getTime() / 1000),
|
||||
orgId: userOrg.orgId,
|
||||
clientId: newClient.clientId,
|
||||
userId,
|
||||
type: "user_device"
|
||||
})
|
||||
.returning();
|
||||
}
|
||||
|
||||
queuedAssociationRebuilds.push(newClient);
|
||||
|
||||
// Grant admin role access to the client
|
||||
await trx.insert(roleClients).values({
|
||||
roleId: adminRole.roleId,
|
||||
clientId: newClient.clientId
|
||||
});
|
||||
roleClientAccessCache.set(
|
||||
getRoleClientKey(adminRole.roleId, newClient.clientId),
|
||||
true
|
||||
);
|
||||
|
||||
// Grant user access to the client
|
||||
await trx.insert(userClients).values({
|
||||
userId,
|
||||
clientId: newClient.clientId
|
||||
});
|
||||
userClientAccessCache.set(
|
||||
getUserClientKey(userId, newClient.clientId),
|
||||
true
|
||||
);
|
||||
|
||||
logger.debug(
|
||||
`Created client for OLM ${olm.olmId} in org ${orgId} (user ${userId}) with access granted to admin role and user`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up clients in orgs the user is no longer in
|
||||
await cleanupOrphanedClients(
|
||||
userId,
|
||||
trx,
|
||||
userOrgIds,
|
||||
queuedAssociationRebuilds
|
||||
);
|
||||
|
||||
runQueuedClientAssociationRebuilds(userId, queuedAssociationRebuilds);
|
||||
}
|
||||
@@ -496,7 +474,7 @@ async function cleanupOrphanedClients(
|
||||
)
|
||||
.returning();
|
||||
|
||||
// Queue deleted clients for post-transaction association cleanup.
|
||||
// Queue deleted clients for post-trx association cleanup.
|
||||
for (const deletedClient of deletedClients) {
|
||||
queuedAssociationRebuilds.push(deletedClient);
|
||||
|
||||
|
||||
@@ -329,6 +329,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,
|
||||
|
||||
@@ -23,3 +23,7 @@ export * from "./pickRemoteExitNodeDefaults";
|
||||
export * from "./quickStartRemoteExitNode";
|
||||
export * from "./offlineChecker";
|
||||
export * from "./exitNodeReconnectScheduler";
|
||||
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,155 @@
|
||||
/*
|
||||
* 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,
|
||||
newts,
|
||||
remoteExitNodeResources,
|
||||
remoteExitNodes,
|
||||
sites
|
||||
} 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";
|
||||
import { sendToClientsBatch } from "#private/routers/ws";
|
||||
|
||||
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)
|
||||
);
|
||||
|
||||
// Notify all newts connected to this remote exit node's exit node
|
||||
if (remoteExitNode.exitNodeId) {
|
||||
const connectedNewts = await db
|
||||
.select({ newtId: newts.newtId })
|
||||
.from(newts)
|
||||
.innerJoin(sites, eq(newts.siteId, sites.siteId))
|
||||
.where(eq(sites.exitNodeId, remoteExitNode.exitNodeId));
|
||||
|
||||
await sendToClientsBatch(
|
||||
connectedNewts.map(({ newtId }) => ({
|
||||
clientId: newtId,
|
||||
message: {
|
||||
type: "newt/wg/subnets/update",
|
||||
data: { subnets: destinations }
|
||||
}
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
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")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
db,
|
||||
ExitNode,
|
||||
networks,
|
||||
remoteExitNodeResources,
|
||||
resources,
|
||||
Site,
|
||||
siteNetworks,
|
||||
@@ -223,7 +224,8 @@ export async function buildClientConfigurationForNewtClient(
|
||||
|
||||
export async function buildTargetConfigurationForNewtClient(
|
||||
siteId: number,
|
||||
version?: string | null
|
||||
version?: string | null,
|
||||
remoteExitNodeId?: string
|
||||
) {
|
||||
// Get all enabled targets with their resource mode information
|
||||
const allTargets = await db
|
||||
@@ -379,10 +381,24 @@ export async function buildTargetConfigurationForNewtClient(
|
||||
};
|
||||
});
|
||||
|
||||
let remoteExitNodeSubnets: string[] = [];
|
||||
if (remoteExitNodeId) {
|
||||
const remoteNodeResources = await db
|
||||
.select()
|
||||
.from(remoteExitNodeResources)
|
||||
.where(
|
||||
eq(remoteExitNodeResources.remoteExitNodeId, remoteExitNodeId)
|
||||
);
|
||||
|
||||
// filter through these and provide the subnets
|
||||
remoteExitNodeSubnets = remoteNodeResources.map((r) => r.destination);
|
||||
}
|
||||
|
||||
return {
|
||||
validHealthCheckTargets,
|
||||
tcpTargets,
|
||||
udpTargets,
|
||||
browserGatewayTargets
|
||||
browserGatewayTargets,
|
||||
remoteExitNodeSubnets
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { db, ExitNode, newts, Transaction } from "@server/db";
|
||||
import { db, ExitNode, newts, remoteExitNodes, Transaction } from "@server/db";
|
||||
import { MessageHandler } from "@server/routers/ws";
|
||||
import { exitNodes, Newt, sites } from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
@@ -196,12 +196,29 @@ export const handleNewtRegisterMessage: MessageHandler = async (context) => {
|
||||
.where(eq(newts.newtId, newt.newtId));
|
||||
}
|
||||
|
||||
let remoteExitNodeId: string | undefined;
|
||||
if (exitNode.type == "remoteExitNode") {
|
||||
// get the remote exit node ID associated with this exit node
|
||||
const [remoteExitNode] = await db
|
||||
.select()
|
||||
.from(remoteExitNodes)
|
||||
.where(eq(remoteExitNodes.exitNodeId, exitNode.exitNodeId))
|
||||
.limit(1);
|
||||
|
||||
remoteExitNodeId = remoteExitNode?.remoteExitNodeId;
|
||||
}
|
||||
|
||||
const {
|
||||
tcpTargets,
|
||||
udpTargets,
|
||||
validHealthCheckTargets,
|
||||
browserGatewayTargets
|
||||
} = await buildTargetConfigurationForNewtClient(siteId, newtVersion);
|
||||
browserGatewayTargets,
|
||||
remoteExitNodeSubnets
|
||||
} = await buildTargetConfigurationForNewtClient(
|
||||
siteId,
|
||||
newtVersion,
|
||||
remoteExitNodeId // this is for the remote node resources
|
||||
);
|
||||
|
||||
logger.debug(
|
||||
`Sending health check targets to newt ${newt.newtId}: ${JSON.stringify(validHealthCheckTargets)}`
|
||||
@@ -222,6 +239,7 @@ export const handleNewtRegisterMessage: MessageHandler = async (context) => {
|
||||
},
|
||||
healthCheckTargets: validHealthCheckTargets,
|
||||
browserGatewayTargets: browserGatewayTargets,
|
||||
remoteExitNodeSubnets: remoteExitNodeSubnets,
|
||||
chainId: chainId
|
||||
}
|
||||
},
|
||||
|
||||
@@ -76,6 +76,15 @@ export async function setResourcePolicyHeaderAuth(
|
||||
const { resourcePolicyId } = parsedParams.data;
|
||||
const { headerAuth } = parsedBody.data;
|
||||
|
||||
const headerAuthHash =
|
||||
headerAuth !== null
|
||||
? await hashPassword(
|
||||
Buffer.from(
|
||||
`${headerAuth.user}:${headerAuth.password}`
|
||||
).toString("base64")
|
||||
)
|
||||
: null;
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
await trx
|
||||
.delete(resourcePolicyHeaderAuth)
|
||||
@@ -86,13 +95,7 @@ export async function setResourcePolicyHeaderAuth(
|
||||
)
|
||||
);
|
||||
|
||||
if (headerAuth !== null) {
|
||||
const headerAuthHash = await hashPassword(
|
||||
Buffer.from(
|
||||
`${headerAuth.user}:${headerAuth.password}`
|
||||
).toString("base64")
|
||||
);
|
||||
|
||||
if (headerAuth !== null && headerAuthHash !== null) {
|
||||
await trx.insert(resourcePolicyHeaderAuth).values({
|
||||
resourcePolicyId,
|
||||
headerAuthHash,
|
||||
|
||||
@@ -107,6 +107,13 @@ export async function setResourceHeaderAuth(
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
const headerAuthHash =
|
||||
user && password && extendedCompatibility !== null
|
||||
? await hashPassword(
|
||||
Buffer.from(`${user}:${password}`).toString("base64")
|
||||
)
|
||||
: null;
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
if (isInlinePolicy) {
|
||||
const policyId = resource.defaultResourcePolicyId!;
|
||||
@@ -116,11 +123,7 @@ export async function setResourceHeaderAuth(
|
||||
eq(resourcePolicyHeaderAuth.resourcePolicyId, policyId)
|
||||
);
|
||||
|
||||
if (user && password && extendedCompatibility !== null) {
|
||||
const headerAuthHash = await hashPassword(
|
||||
Buffer.from(`${user}:${password}`).toString("base64")
|
||||
);
|
||||
|
||||
if (headerAuthHash !== null && extendedCompatibility !== null) {
|
||||
await trx.insert(resourcePolicyHeaderAuth).values({
|
||||
resourcePolicyId: policyId,
|
||||
headerAuthHash,
|
||||
@@ -140,11 +143,7 @@ export async function setResourceHeaderAuth(
|
||||
)
|
||||
);
|
||||
|
||||
if (user && password && extendedCompatibility !== null) {
|
||||
const headerAuthHash = await hashPassword(
|
||||
Buffer.from(`${user}:${password}`).toString("base64")
|
||||
);
|
||||
|
||||
if (headerAuthHash !== null && extendedCompatibility !== null) {
|
||||
await Promise.all([
|
||||
trx
|
||||
.insert(resourceHeaderAuth)
|
||||
|
||||
@@ -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,7 +66,17 @@ export function MultiSelectTagInput<T extends TagValue>({
|
||||
)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<span>{option.text}</span>
|
||||
{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>
|
||||
{isLocked ? (
|
||||
<span className="p-0.5 flex-none">
|
||||
<LockIcon className="size-3" />
|
||||
|
||||
Reference in New Issue
Block a user