Merge branch 'dev' into refactor/show-if-client-needs-update

This commit is contained in:
Fred KISSIE
2026-06-11 21:05:31 +02:00
199 changed files with 3020 additions and 2228 deletions
@@ -28,7 +28,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -61,7 +61,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -135,7 +135,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -164,7 +164,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -28,7 +28,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -42,7 +42,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -35,7 +35,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -162,7 +162,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -1,4 +1,11 @@
import { logsDb, requestAuditLog, resources, siteResources, db, primaryDb } from "@server/db";
import {
logsDb,
requestAuditLog,
resources,
siteResources,
db,
primaryDb
} from "@server/db";
import { registry } from "@server/openApi";
import { NextFunction } from "express";
import { Request, Response } from "express";
@@ -127,16 +134,16 @@ export function queryRequest(data: Q) {
return logsDb
.select({
id: requestAuditLog.id,
timestamp: requestAuditLog.timestamp,
orgId: requestAuditLog.orgId,
action: requestAuditLog.action,
reason: requestAuditLog.reason,
actorType: requestAuditLog.actorType,
actor: requestAuditLog.actor,
actorId: requestAuditLog.actorId,
resourceId: requestAuditLog.resourceId,
siteResourceId: requestAuditLog.siteResourceId,
ip: requestAuditLog.ip,
timestamp: requestAuditLog.timestamp,
orgId: requestAuditLog.orgId,
action: requestAuditLog.action,
reason: requestAuditLog.reason,
actorType: requestAuditLog.actorType,
actor: requestAuditLog.actor,
actorId: requestAuditLog.actorId,
resourceId: requestAuditLog.resourceId,
siteResourceId: requestAuditLog.siteResourceId,
ip: requestAuditLog.ip,
location: requestAuditLog.location,
userAgent: requestAuditLog.userAgent,
metadata: requestAuditLog.metadata,
@@ -154,21 +161,30 @@ export function queryRequest(data: Q) {
.orderBy(desc(requestAuditLog.timestamp));
}
async function enrichWithResourceDetails(logs: Awaited<ReturnType<typeof queryRequest>>) {
async function enrichWithResourceDetails(
logs: Awaited<ReturnType<typeof queryRequest>>
) {
const resourceIds = logs
.map(log => log.resourceId)
.map((log) => log.resourceId)
.filter((id): id is number => id !== null && id !== undefined);
const siteResourceIds = logs
.filter(log => log.resourceId == null && log.siteResourceId != null)
.map(log => log.siteResourceId)
.filter((log) => log.resourceId == null && log.siteResourceId != null)
.map((log) => log.siteResourceId)
.filter((id): id is number => id !== null && id !== undefined);
if (resourceIds.length === 0 && siteResourceIds.length === 0) {
return logs.map(log => ({ ...log, resourceName: null, resourceNiceId: null }));
return logs.map((log) => ({
...log,
resourceName: null,
resourceNiceId: null
}));
}
const resourceMap = new Map<number, { name: string | null; niceId: string | null }>();
const resourceMap = new Map<
number,
{ name: string | null; niceId: string | null }
>();
if (resourceIds.length > 0) {
const resourceDetails = await primaryDb
@@ -185,7 +201,10 @@ async function enrichWithResourceDetails(logs: Awaited<ReturnType<typeof queryRe
}
}
const siteResourceMap = new Map<number, { name: string | null; niceId: string | null }>();
const siteResourceMap = new Map<
number,
{ name: string | null; niceId: string | null }
>();
if (siteResourceIds.length > 0) {
const siteResourceDetails = await primaryDb
@@ -198,12 +217,15 @@ async function enrichWithResourceDetails(logs: Awaited<ReturnType<typeof queryRe
.where(inArray(siteResources.siteResourceId, siteResourceIds));
for (const r of siteResourceDetails) {
siteResourceMap.set(r.siteResourceId, { name: r.name, niceId: r.niceId });
siteResourceMap.set(r.siteResourceId, {
name: r.name,
niceId: r.niceId
});
}
}
// Enrich logs with resource details
return logs.map(log => {
return logs.map((log) => {
if (log.resourceId != null) {
const details = resourceMap.get(log.resourceId);
return {
@@ -247,7 +269,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -333,11 +355,11 @@ async function queryUniqueFilterAttributes(
// Fetch resource names from main database for the unique resource IDs
const resourceIds = uniqueResources
.map(row => row.id)
.map((row) => row.id)
.filter((id): id is number => id !== null);
const siteResourceIds = uniqueSiteResources
.map(row => row.id)
.map((row) => row.id)
.filter((id): id is number => id !== null);
let resourcesWithNames: Array<{ id: number; name: string | null }> = [];
@@ -353,7 +375,7 @@ async function queryUniqueFilterAttributes(
resourcesWithNames = [
...resourcesWithNames,
...resourceDetails.map(r => ({
...resourceDetails.map((r) => ({
id: r.resourceId,
name: r.name
}))
@@ -371,7 +393,7 @@ async function queryUniqueFilterAttributes(
resourcesWithNames = [
...resourcesWithNames,
...siteResourceDetails.map(r => ({
...siteResourceDetails.map((r) => ({
id: r.siteResourceId,
name: r.name
}))
+41 -40
View File
@@ -1,14 +1,7 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import {
users,
userOrgs,
orgs,
idpOrg,
idp,
idpOidcConfig
} from "@server/db";
import { users, userOrgs, orgs, idpOrg, idp, idpOidcConfig } from "@server/db";
import { eq, or, sql, and, isNotNull, inArray } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
@@ -57,7 +50,7 @@ export type LookupUserResponse = {
// content: {
// "application/json": {
// schema: z.object({
// data: z.unknown().nullable(),
// data: z.record(z.string(), z.any()).nullable(),
// success: z.boolean(),
// error: z.boolean(),
// message: z.string(),
@@ -169,46 +162,54 @@ export async function lookupUser(
);
// Deduplicate orgs (user might have multiple memberships in same org)
const uniqueOrgs = new Map<string, typeof userOrgMemberships[0]>();
const uniqueOrgs = new Map<
string,
(typeof userOrgMemberships)[0]
>();
for (const membership of userOrgMemberships) {
if (!uniqueOrgs.has(membership.orgId)) {
uniqueOrgs.set(membership.orgId, membership);
}
}
const orgsData = Array.from(uniqueOrgs.values()).map((membership) => {
// Get IdPs for this org where the user (with the exact identifier) is authenticated via that IdP
// Only show IdPs where the user's idpId matches
// Internal users don't have an idpId, so they won't see any IdPs
const orgIdpsList = orgIdps
.filter((idp) => {
if (idp.orgId !== membership.orgId) {
const orgsData = Array.from(uniqueOrgs.values()).map(
(membership) => {
// Get IdPs for this org where the user (with the exact identifier) is authenticated via that IdP
// Only show IdPs where the user's idpId matches
// Internal users don't have an idpId, so they won't see any IdPs
const orgIdpsList = orgIdps
.filter((idp) => {
if (idp.orgId !== membership.orgId) {
return false;
}
// Only show IdPs where the user (with exact identifier) is authenticated via that IdP
// This means user.idpId must match idp.idpId
if (
user.idpId !== null &&
user.idpId === idp.idpId
) {
return true;
}
return false;
}
// Only show IdPs where the user (with exact identifier) is authenticated via that IdP
// This means user.idpId must match idp.idpId
if (user.idpId !== null && user.idpId === idp.idpId) {
return true;
}
return false;
})
.map((idp) => ({
idpId: idp.idpId,
name: idp.idpName,
variant: idp.variant
}));
})
.map((idp) => ({
idpId: idp.idpId,
name: idp.idpName,
variant: idp.variant
}));
// Check if user has internal auth for this org
// User has internal auth if they have an internal account type
const orgHasInternalAuth = hasInternalAuth;
// Check if user has internal auth for this org
// User has internal auth if they have an internal account type
const orgHasInternalAuth = hasInternalAuth;
return {
orgId: membership.orgId,
orgName: membership.orgName,
idps: orgIdpsList,
hasInternalAuth: orgHasInternalAuth
};
});
return {
orgId: membership.orgId,
orgName: membership.orgName,
idps: orgIdpsList,
hasInternalAuth: orgHasInternalAuth
};
}
);
accounts.push({
userId: user.userId,
+3 -3
View File
@@ -145,9 +145,9 @@ export async function verifyResourceSession(
| ResourcePolicyHeaderAuth
| null;
headerAuthExtendedCompatibility: ResourceHeaderAuthExtendedCompatibility | null;
applyRules: boolean;
sso: boolean;
emailWhitelistEnabled: boolean;
applyRules: boolean | null;
sso: boolean | null;
emailWhitelistEnabled: boolean | null;
org: Org;
}
| undefined = localCache.get(resourceCacheKey);
@@ -37,7 +37,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -60,7 +60,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -62,7 +62,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -80,7 +80,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -28,7 +28,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+6 -2
View File
@@ -30,7 +30,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -94,7 +94,11 @@ export async function blockClient(
// Send terminate signal if there's an associated OLM and it's connected
if (client.olmId && client.online) {
await sendTerminateClient(client.clientId, OlmErrorCodes.TERMINATED_BLOCKED, client.olmId);
await sendTerminateClient(
client.clientId,
OlmErrorCodes.TERMINATED_BLOCKED,
client.olmId
);
}
});
+1 -1
View File
@@ -65,7 +65,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -66,7 +66,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -31,7 +31,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+14 -14
View File
@@ -259,7 +259,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -287,7 +287,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -340,18 +340,18 @@ export async function getClient(
// Build fingerprint data if available
const fingerprintData = client.currentFingerprint
? {
username: client.currentFingerprint.username || null,
hostname: client.currentFingerprint.hostname || null,
platform: client.currentFingerprint.platform || null,
osVersion: client.currentFingerprint.osVersion || null,
kernelVersion:
client.currentFingerprint.kernelVersion || null,
arch: client.currentFingerprint.arch || null,
deviceModel: client.currentFingerprint.deviceModel || null,
serialNumber: client.currentFingerprint.serialNumber || null,
firstSeen: client.currentFingerprint.firstSeen || null,
lastSeen: client.currentFingerprint.lastSeen || null
}
username: client.currentFingerprint.username || null,
hostname: client.currentFingerprint.hostname || null,
platform: client.currentFingerprint.platform || null,
osVersion: client.currentFingerprint.osVersion || null,
kernelVersion:
client.currentFingerprint.kernelVersion || null,
arch: client.currentFingerprint.arch || null,
deviceModel: client.currentFingerprint.deviceModel || null,
serialNumber: client.currentFingerprint.serialNumber || null,
firstSeen: client.currentFingerprint.firstSeen || null,
lastSeen: client.currentFingerprint.lastSeen || null
}
: null;
// Build posture data if available (platform-specific)
+1 -1
View File
@@ -218,7 +218,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -219,7 +219,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+3 -3
View File
@@ -13,7 +13,7 @@ import semver from "semver";
const NEWT_V2_TARGETS_VERSION = ">=1.10.3";
export async function convertTargetsIfNessicary(
export async function convertTargetsIfNecessary(
newtId: string,
targets: SubnetProxyTarget[] | SubnetProxyTargetV2[]
) {
@@ -47,7 +47,7 @@ export async function addTargets(
targets: SubnetProxyTarget[] | SubnetProxyTargetV2[],
version?: string | null
) {
targets = await convertTargetsIfNessicary(newtId, targets);
targets = await convertTargetsIfNecessary(newtId, targets);
await sendToClient(
newtId,
@@ -64,7 +64,7 @@ export async function removeTargets(
targets: SubnetProxyTarget[] | SubnetProxyTargetV2[],
version?: string | null
) {
targets = await convertTargetsIfNessicary(newtId, targets);
targets = await convertTargetsIfNecessary(newtId, targets);
await sendToClient(
newtId,
+1 -1
View File
@@ -28,7 +28,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -28,7 +28,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -42,7 +42,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -43,7 +43,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -44,7 +44,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -31,7 +31,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -29,7 +29,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -44,7 +44,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+2 -4
View File
@@ -1,6 +1,6 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db, Org } from "@server/db";
import { db, Org, primaryDb } from "@server/db";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
@@ -635,9 +635,7 @@ export async function validateOidcCallback(
}
});
db.transaction(async (trx) => {
await calculateUserClientsForOrgs(userId!, trx);
}).catch((err) => {
calculateUserClientsForOrgs(userId!, primaryDb).catch((err) => {
logger.error(
"Error calculating user clients after syncing orgs and roles for OIDC user",
{ error: err }
+55 -25
View File
@@ -152,34 +152,64 @@ export async function buildClientConfigurationForNewtClient(
const targetsToSend: SubnetProxyTargetV2[] = [];
for (const resource of allSiteResources) {
// Get clients associated with this specific resource
const resourceClients = await db
.select({
clientId: clients.clientId,
pubKey: clients.pubKey,
subnet: clients.subnet
})
.from(clients)
.innerJoin(
clientSiteResourcesAssociationsCache,
eq(
clients.clientId,
clientSiteResourcesAssociationsCache.clientId
)
)
.where(
eq(
clientSiteResourcesAssociationsCache.siteResourceId,
resource.siteResourceId
)
);
if (allSiteResources.length === 0) {
return {
peers: validPeers,
targets: targetsToSend
};
}
const resourceTargets = await generateSubnetProxyTargetV2(
resource,
resourceClients
// Batch fetch all client associations for every site resource in one query
// to avoid an N+1 lookup that would issue thousands of queries when a site
// has many resources.
const siteResourceIds = allSiteResources.map((r) => r.siteResourceId);
const resourceClientRows = await db
.select({
siteResourceId: clientSiteResourcesAssociationsCache.siteResourceId,
clientId: clients.clientId,
pubKey: clients.pubKey,
subnet: clients.subnet
})
.from(clients)
.innerJoin(
clientSiteResourcesAssociationsCache,
eq(clients.clientId, clientSiteResourcesAssociationsCache.clientId)
)
.where(
inArray(
clientSiteResourcesAssociationsCache.siteResourceId,
siteResourceIds
)
);
const clientsByResourceId = new Map<
number,
{ clientId: number; pubKey: string | null; subnet: string | null }[]
>();
for (const row of resourceClientRows) {
let list = clientsByResourceId.get(row.siteResourceId);
if (!list) {
list = [];
clientsByResourceId.set(row.siteResourceId, list);
}
list.push({
clientId: row.clientId,
pubKey: row.pubKey,
subnet: row.subnet
});
}
const resourceTargetsArr = await Promise.all(
allSiteResources.map((resource) =>
generateSubnetProxyTargetV2(
resource,
clientsByResourceId.get(resource.siteResourceId) ?? []
)
)
);
for (const resourceTargets of resourceTargetsArr) {
if (resourceTargets) {
targetsToSend.push(...resourceTargets);
}
+7 -2
View File
@@ -56,13 +56,18 @@ async function getLatestReleaseInfo(): Promise<ReleaseInfo | null> {
return staleReleaseInfo;
}
// Drop drafts, pre-releases, and anything with "rc" in the tag name.
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
// Drop drafts, pre-releases, anything with "rc" in the tag name,
// and releases published less than 1 day ago.
releases = releases.filter(
(r: any) =>
!r.draft &&
!r.prerelease &&
!r.tag_name.includes("rc") &&
!r.tag_name.includes("v")
!r.tag_name.includes("v") &&
r.published_at &&
new Date(r.published_at) <= oneDayAgo
);
// Sort descending by semver to find the true latest stable release.
@@ -6,7 +6,7 @@ import { db, ExitNode, exitNodes, Newt, sites } from "@server/db";
import { eq } from "drizzle-orm";
import { sendToExitNode } from "#dynamic/lib/exitNodes";
import { buildClientConfigurationForNewtClient } from "./buildConfiguration";
import { convertTargetsIfNessicary } from "../client/targets";
import { convertTargetsIfNecessary } from "../client/targets";
import { canCompress } from "@server/lib/clientVersionChecks";
import config from "@server/lib/config";
@@ -113,7 +113,7 @@ export const handleNewtGetConfigMessage: MessageHandler = async (context) => {
exitNode
);
const targetsToSend = await convertTargetsIfNessicary(newt.newtId, targets); // for backward compatibility with old newt versions that don't support the new target format
const targetsToSend = await convertTargetsIfNecessary(newt.newtId, targets); // for backward compatibility with old newt versions that don't support the new target format
return {
message: {
+1 -1
View File
@@ -49,7 +49,7 @@ export type CreateOlmResponse = {
// content: {
// "application/json": {
// schema: z.object({
// data: z.unknown().nullable(),
// data: z.record(z.string(), z.any()).nullable(),
// success: z.boolean(),
// error: z.boolean(),
// message: z.string(),
+1 -1
View File
@@ -34,7 +34,7 @@ const paramsSchema = z
// content: {
// "application/json": {
// schema: z.object({
// data: z.unknown().nullable(),
// data: z.record(z.string(), z.any()).nullable(),
// success: z.boolean(),
// error: z.boolean(),
// message: z.string(),
+1 -1
View File
@@ -36,7 +36,7 @@ const querySchema = z.object({
// content: {
// "application/json": {
// schema: z.object({
// data: z.unknown().nullable(),
// data: z.record(z.string(), z.any()).nullable(),
// success: z.boolean(),
// error: z.boolean(),
// message: z.string(),
+1 -1
View File
@@ -47,7 +47,7 @@ const paramsSchema = z
// content: {
// "application/json": {
// schema: z.object({
// data: z.unknown().nullable(),
// data: z.record(z.string(), z.any()).nullable(),
// success: z.boolean(),
// error: z.boolean(),
// message: z.string(),
+2 -5
View File
@@ -49,10 +49,7 @@ async function queryUser(orgId: string, userId: string) {
.from(userOrgRoles)
.leftJoin(roles, eq(userOrgRoles.roleId, roles.roleId))
.where(
and(
eq(userOrgRoles.userId, userId),
eq(userOrgRoles.orgId, orgId)
)
and(eq(userOrgRoles.userId, userId), eq(userOrgRoles.orgId, orgId))
);
const isAdmin = roleRows.some((r) => r.isAdmin);
@@ -89,7 +86,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -80,7 +80,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -30,7 +30,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -43,7 +43,7 @@ const listOrgsSchema = z.object({
// content: {
// "application/json": {
// schema: z.object({
// data: z.unknown().nullable(),
// data: z.record(z.string(), z.any()).nullable(),
// success: z.boolean(),
// error: z.boolean(),
// message: z.string(),
+1 -1
View File
@@ -27,7 +27,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -68,7 +68,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -46,7 +46,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+3 -2
View File
@@ -28,7 +28,8 @@ const addRoleToResourceParamsSchema = z
registry.registerPath({
method: "post",
path: "/resource/{resourceId}/roles/add",
description: "Add a single role to a resource.",
description:
"Add a single role to a resource. When the resource has an inline policy defined (no shared resource policy assigned), the role is added to the inline policy instead of directly to the resource.",
tags: [OpenAPITags.PublicResource, OpenAPITags.Role],
request: {
params: addRoleToResourceParamsSchema,
@@ -46,7 +47,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+3 -2
View File
@@ -28,7 +28,8 @@ const addUserToResourceParamsSchema = z
registry.registerPath({
method: "post",
path: "/resource/{resourceId}/users/add",
description: "Add a single user to a resource.",
description:
"Add a single user to a resource. When the resource has an inline policy defined (no shared resource policy assigned), the user is added to the inline policy instead of directly to the resource.",
tags: [OpenAPITags.PublicResource, OpenAPITags.User],
request: {
params: addUserToResourceParamsSchema,
@@ -46,7 +47,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -168,7 +168,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -49,7 +49,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -37,7 +37,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -29,7 +29,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+35 -7
View File
@@ -1,4 +1,4 @@
import { db, resources } from "@server/db";
import { db, resourcePolicies, resources } from "@server/db";
import response from "@server/lib/response";
import stoi from "@server/lib/stoi";
import logger from "@server/logger";
@@ -41,6 +41,15 @@ async function query(resourceId?: number, niceId?: string, orgId?: string) {
}
}
async function queryInlinePolicy(resourcePolicyId: number) {
const [res] = await db
.select()
.from(resourcePolicies)
.where(eq(resourcePolicies.resourcePolicyId, resourcePolicyId))
.limit(1);
return res;
}
export type GetResourceResponse = Omit<
NonNullable<Awaited<ReturnType<typeof query>>>,
"headers"
@@ -66,7 +75,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -94,7 +103,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -132,12 +141,31 @@ export async function getResource(
);
}
const isInlinePolicy =
resource.resourcePolicyId === null &&
resource.defaultResourcePolicyId !== null;
let returnData = resource;
if (isInlinePolicy) {
// get the policy
const policy = await queryInlinePolicy(
resource.defaultResourcePolicyId!
);
returnData = {
...returnData,
sso: policy?.sso || null,
emailWhitelistEnabled: policy?.emailWhitelistEnabled || null,
applyRules: policy?.applyRules || null,
skipToIdpId: policy?.idpId || null
};
}
return response<GetResourceResponse>(res, {
data: {
...resource,
headers: resource.headers
? JSON.parse(resource.headers)
: resource.headers
...returnData,
headers: returnData.headers
? JSON.parse(returnData.headers)
: returnData.headers
},
success: true,
error: false,
@@ -54,7 +54,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+2 -2
View File
@@ -203,9 +203,9 @@ export async function getUserResources(
fullDomain: string | null;
ssl: boolean;
enabled: boolean;
sso: boolean;
sso: boolean | null;
mode: string;
emailWhitelistEnabled: boolean;
emailWhitelistEnabled: boolean | null;
policyEmailWhitelistEnabled: boolean | null;
}> = [];
if (uniqueResourceIds.length > 0) {
@@ -45,7 +45,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -58,7 +58,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -82,7 +82,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -48,7 +48,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+34 -1
View File
@@ -123,6 +123,16 @@ const listResourcesSchema = z.object({
description:
"Filter resources based on health status of their targets. `healthy` means all targets are healthy. `degraded` means at least one target is unhealthy, but not all are unhealthy. `offline` means all targets are unhealthy. `unknown` means all targets have unknown health status."
}),
protocol: z
.enum(["http", "https", "tcp", "udp", "ssh", "rdp", "vnc"])
.optional()
.catch(undefined)
.openapi({
type: "string",
enum: ["http", "https", "tcp", "udp", "ssh", "rdp", "vnc"],
description:
"Filter resources by protocol. `http` and `https` match HTTP resources without and with SSL respectively."
}),
siteId: z.coerce.number<string>().int().positive().optional().openapi({
type: "integer",
description:
@@ -403,7 +413,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -437,6 +447,7 @@ export async function listResources(
enabled,
query,
healthStatus,
protocol,
sort_by,
order,
siteId,
@@ -632,6 +643,28 @@ export async function listResources(
if (typeof healthStatus !== "undefined") {
conditions.push(eq(resources.health, healthStatus));
}
if (typeof protocol !== "undefined") {
switch (protocol) {
case "http":
conditions.push(
and(
eq(resources.mode, "http"),
eq(resources.ssl, false)
)
);
break;
case "https":
conditions.push(
and(eq(resources.mode, "http"), eq(resources.ssl, true))
);
break;
default:
conditions.push(eq(resources.mode, protocol));
break;
}
}
if (siteId != null) {
const resourcesWithSite = db
.select({ resourceId: targets.resourceId })
@@ -7,7 +7,7 @@ import {
userOrgRoles,
userOrgs
} from "@server/db";
import { and, eq, inArray, asc, isNotNull, ne } from "drizzle-orm";
import { and, eq, inArray, asc, isNotNull, ne, or } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import response from "@server/lib/response";
@@ -82,7 +82,7 @@ export type ListUserResourceAliasesResponse = PaginatedResponse<{
// content: {
// "application/json": {
// schema: z.object({
// data: z.unknown().nullable(),
// data: z.record(z.string(), z.any()).nullable(),
// success: z.boolean(),
// error: z.boolean(),
// message: z.string(),
@@ -224,7 +224,7 @@ export async function listUserResourceAliases(
const whereClause = and(
eq(siteResources.orgId, orgId),
eq(siteResources.enabled, true),
eq(siteResources.mode, "host"),
or(eq(siteResources.mode, "host"), eq(siteResources.mode, "ssh")),
isNotNull(siteResources.alias),
ne(siteResources.alias, ""),
inArray(siteResources.siteResourceId, accessibleSiteResourceIds)
@@ -46,7 +46,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -46,7 +46,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -46,7 +46,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -48,7 +48,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -46,7 +46,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -46,7 +46,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+2 -2
View File
@@ -22,7 +22,7 @@ registry.registerPath({
method: "post",
path: "/resource/{resourceId}/roles",
description:
"Set roles for a resource. This will replace all existing roles.",
"Set roles for a resource. This will replace all existing roles. When the resource has an inline policy defined (no shared resource policy assigned), roles are set on the inline policy instead of directly on the resource.",
tags: [OpenAPITags.PublicResource, OpenAPITags.Role],
request: {
params: setResourceRolesParamsSchema,
@@ -40,7 +40,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+2 -2
View File
@@ -22,7 +22,7 @@ registry.registerPath({
method: "post",
path: "/resource/{resourceId}/users",
description:
"Set users for a resource. This will replace all existing users.",
"Set users for a resource. This will replace all existing users. When the resource has an inline policy defined (no shared resource policy assigned), users are set on the inline policy instead of directly on the resource.",
tags: [OpenAPITags.PublicResource, OpenAPITags.User],
request: {
params: setUserResourcesParamsSchema,
@@ -40,7 +40,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -54,7 +54,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+130 -85
View File
@@ -9,7 +9,11 @@ import {
resourcePassword,
resourcePincode,
resourceRules,
resourceWhitelist
resourceWhitelist,
roleResources,
roles,
Transaction,
userResources
} from "@server/db";
import {
domains,
@@ -62,16 +66,38 @@ const updateHttpResourceBodySchema = z
.optional(),
subdomain: z.string().nullable().optional(),
ssl: z.boolean().optional(),
sso: z.boolean().optional(),
sso: z
.boolean()
.optional()
.describe(
"When no shared resource policy is assigned (resourcePolicyId is null), updates the resource's inline policy. When a shared policy is assigned, this value overrides the shared policy for this resource."
),
blockAccess: z.boolean().optional(),
emailWhitelistEnabled: z.boolean().optional(),
applyRules: z.boolean().optional(),
emailWhitelistEnabled: z
.boolean()
.optional()
.describe(
"When no shared resource policy is assigned (resourcePolicyId is null), updates the resource's inline policy. When a shared policy is assigned, this value overrides the shared policy for this resource."
),
applyRules: z
.boolean()
.optional()
.describe(
"When no shared resource policy is assigned (resourcePolicyId is null), updates the resource's inline policy. When a shared policy is assigned, this value overrides the shared policy for this resource."
),
domainId: z.string().optional(),
enabled: z.boolean().optional(),
stickySession: z.boolean().optional(),
tlsServerName: z.string().nullable().optional(),
setHostHeader: z.string().nullable().optional(),
skipToIdpId: z.int().positive().nullable().optional(),
skipToIdpId: z
.int()
.positive()
.nullable()
.optional()
.describe(
"When no shared resource policy is assigned (resourcePolicyId is null), updates the resource's inline policy. When a shared policy is assigned, this value overrides the shared policy for this resource."
),
headers: z
.array(z.strictObject({ name: z.string(), value: z.string() }))
.nullable()
@@ -87,7 +113,13 @@ const updateHttpResourceBodySchema = z
pamMode: z.enum(["passthrough", "push"]).optional(),
authDaemonMode: z.enum(["site", "remote", "native"]).optional(),
authDaemonPort: z.int().min(1).max(65535).nullable().optional(),
resourcePolicyId: z.number().nullable().optional()
resourcePolicyId: z
.number()
.nullable()
.optional()
.describe(
"ID of the resource policy to apply to this resource. Set to null to remove the resource policy and fall back to the inline policy settings."
)
})
.refine((data) => Object.keys(data).length > 0, {
error: "At least one field must be provided for update"
@@ -207,7 +239,8 @@ const updateRawResourceBodySchema = z
registry.registerPath({
method: "post",
path: "/resource/{resourceId}",
description: "Update a resource.",
description:
"Update a resource. Policy fields (sso, mfa, pincode, password, whitelist) update the inline policy when no shared resource policy is assigned; when a shared policy is assigned those fields override the shared policy for this resource only.",
tags: [OpenAPITags.PublicResource],
request: {
params: updateResourceParamsSchema,
@@ -227,7 +260,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -310,6 +343,61 @@ export async function updateResource(
}
}
async function clearResourceSpecificSettings(
resourceId: number,
orgId: string,
trx: Transaction | typeof db
) {
const adminRole = await db
.select()
.from(roles)
.where(and(eq(roles.isAdmin, true), eq(roles.orgId, orgId)))
.limit(1);
if (adminRole.length === 0) {
throw new Error(`Admin role not found for org ${orgId}`);
}
// remove the resource specific pincode, password, header auth, rules, nad whitelist entries so that the resource will fall back to the policy settings
await Promise.all([
trx
.delete(resourcePassword)
.where(eq(resourcePassword.resourceId, resourceId)),
trx
.delete(resourcePincode)
.where(eq(resourcePincode.resourceId, resourceId)),
trx
.delete(resourceHeaderAuth)
.where(eq(resourceHeaderAuth.resourceId, resourceId)),
trx
.delete(resourceHeaderAuthExtendedCompatibility)
.where(
eq(
resourceHeaderAuthExtendedCompatibility.resourceId,
resourceId
)
),
trx
.delete(resourceWhitelist)
.where(eq(resourceWhitelist.resourceId, resourceId)),
trx
.delete(resourceRules)
.where(eq(resourceRules.resourceId, resourceId)),
// delete the roles and the users as well
trx
.delete(userResources)
.where(eq(userResources.resourceId, resourceId)),
// except the admin role
trx
.delete(roleResources)
.where(
and(
eq(roleResources.resourceId, resourceId),
ne(roleResources.roleId, adminRole[0].roleId)
)
)
]);
}
async function updateHttpResource(
route: {
req: Request;
@@ -372,6 +460,15 @@ async function updateHttpResource(
}
}
// catch when the resource policy changes or gets cleared
if (resource.resourcePolicyId != updateData.resourcePolicyId) {
await clearResourceSpecificSettings(
resource.resourceId,
resource.orgId,
db
);
}
if (updateData.niceId) {
const [existingResource] = await db
.select()
@@ -560,9 +657,17 @@ async function updateHttpResource(
emailWhitelistEnabled,
applyRules,
skipToIdpId,
...resourceOnlyData
...resourceOnlyDataRest
} = updateData;
const resourceOnlyData = {
...resourceOnlyDataRest,
sso: null, // reset these because they are controlled by the inline policy
emailWhitelistEnabled: null,
applyRules: null,
skipToIdpId: null
};
const policyUpdate: Record<string, unknown> = {};
if (sso !== undefined) policyUpdate.sso = sso;
if (emailWhitelistEnabled !== undefined)
@@ -659,81 +764,6 @@ async function updateRawResource(
.limit(1);
await db.transaction(async (trx) => {
if (updateData.resourcePolicyId != null) {
const [existingPolicy] = await trx
.select()
.from(resourcePolicies)
.where(
eq(
resourcePolicies.resourcePolicyId,
updateData.resourcePolicyId
)
)
.limit(1);
if (!existingPolicy) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Resource policy with ID ${updateData.resourcePolicyId} not found`
)
);
}
} else {
// we are in an inline policy and we need to clear out the old tables
await Promise.all([
trx
.delete(resourcePassword)
.where(
eq(
resourcePassword.resourceId,
existingResource.resourceId
)
),
trx
.delete(resourcePincode)
.where(
eq(
resourcePincode.resourceId,
existingResource.resourceId
)
),
trx
.delete(resourceHeaderAuth)
.where(
eq(
resourceHeaderAuth.resourceId,
existingResource.resourceId
)
),
trx
.delete(resourceHeaderAuthExtendedCompatibility)
.where(
eq(
resourceHeaderAuthExtendedCompatibility.resourceId,
existingResource.resourceId
)
),
trx
.delete(resourceWhitelist)
.where(
eq(
resourceWhitelist.resourceId,
existingResource.resourceId
)
),
trx
.delete(resourceRules)
.where(
eq(
resourceRules.resourceId,
existingResource.resourceId
)
)
]);
}
if (updateData.niceId) {
const [existingResourceConflict] = await trx
.select()
@@ -758,9 +788,24 @@ async function updateRawResource(
}
}
await clearResourceSpecificSettings(
resource.resourceId,
resource.orgId,
trx
); // none of these are supported on raw resources
// we should make sure sso, emailWhitelistEnabled, and applyRules are null because this is a raw resource
const realUpdateData = {
...updateData,
sso: null,
emailWhitelistEnabled: null,
applyRules: null,
skipToIdpId: null
};
[updatedResource] = await trx
.update(resources)
.set(updateData)
.set(realUpdateData)
.where(eq(resources.resourceId, resource.resourceId))
.returning();
});
@@ -58,7 +58,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -62,7 +62,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -39,7 +39,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -28,7 +28,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -104,7 +104,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -59,7 +59,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -84,7 +84,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+1 -1
View File
@@ -33,7 +33,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+2 -2
View File
@@ -67,7 +67,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -95,7 +95,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
+45 -44
View File
@@ -1,20 +1,21 @@
import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed";
import {
db,
exitNodes,
labels,
newts,
orgs,
remoteExitNodes,
roleSites,
siteLabels,
siteNetworks,
siteResources,
targets,
sites,
targets,
userSites,
labels,
siteLabels,
type Label
} from "@server/db";
import cache from "#dynamic/lib/cache";
import { tierMatrix } from "@server/lib/billing/tierMatrix";
import response from "@server/lib/response";
import logger from "@server/logger";
import { OpenAPITags, registry } from "@server/openApi";
@@ -23,11 +24,8 @@ import type { PaginatedResponse } from "@server/types/Pagination";
import { and, asc, desc, eq, inArray, like, or, sql } from "drizzle-orm";
import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors";
import semver from "semver";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed";
import { tierMatrix } from "@server/lib/billing/tierMatrix";
const listSitesParamsSchema = z.strictObject({
orgId: z.string()
@@ -189,7 +187,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -236,27 +234,6 @@ export async function listSites(
);
}
let accessibleSites;
if (req.user) {
accessibleSites = await db
.select({
siteId: sql<number>`COALESCE(${userSites.siteId}, ${roleSites.siteId})`
})
.from(userSites)
.fullJoin(roleSites, eq(userSites.siteId, roleSites.siteId))
.where(
or(
eq(userSites.userId, req.user!.userId),
inArray(roleSites.roleId, req.userOrgRoleIds!)
)
);
} else {
accessibleSites = await db
.select({ siteId: sites.siteId })
.from(sites)
.where(eq(sites.orgId, orgId));
}
const isLabelFeatureEnabled = await isLicensedOrSubscribed(
orgId,
tierMatrix.labels
@@ -273,14 +250,38 @@ export async function listSites(
labels: labelFilter
} = parsedQuery.data;
const accessibleSiteIds = accessibleSites.map((site) => site.siteId);
const conditions = [eq(sites.orgId, orgId)];
const conditions = [
and(
inArray(sites.siteId, accessibleSiteIds),
eq(sites.orgId, orgId)
)
];
if (req.user) {
const userAccessConditions = [
inArray(
sites.siteId,
db
.select({ siteId: userSites.siteId })
.from(userSites)
.where(eq(userSites.userId, req.user.userId))
)
];
const roleIds = req.userOrgRoleIds ?? [];
if (roleIds.length > 0) {
userAccessConditions.push(
inArray(
sites.siteId,
db
.select({ siteId: roleSites.siteId })
.from(roleSites)
.where(inArray(roleSites.roleId, roleIds))
)
);
}
conditions.push(
userAccessConditions.length === 1
? userAccessConditions[0]
: or(...userAccessConditions)!
);
}
if (typeof online !== "undefined") {
conditions.push(eq(sites.online, online));
@@ -327,17 +328,15 @@ export async function listSites(
)
);
}
conditions.push(or(...queryList));
conditions.push(or(...queryList)!);
}
const baseQuery = querySitesBase().where(and(...conditions));
// we need to add `as` so that drizzle filters the result as a subquery
const countQuery = db.$count(
querySitesBase()
.where(and(...conditions))
.as("filtered_sites")
);
const countQuery = db
.select({ count: sql<number>`count(*)` })
.from(sites)
.where(and(...conditions));
const siteListQuery = baseQuery
.limit(pageSize)
@@ -350,11 +349,13 @@ export async function listSites(
: asc(sites.name)
);
const [totalCount, rows] = await Promise.all([
const [countRows, rows] = await Promise.all([
countQuery,
siteListQuery
]);
const totalCount = Number(countRows[0]?.count ?? 0);
const siteIds = rows.map((site) => site.siteId);
let labelsForSites: Array<{
+1 -1
View File
@@ -50,7 +50,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -47,7 +47,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -47,7 +47,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -47,7 +47,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -52,7 +52,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -219,7 +219,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -445,7 +445,7 @@ export async function createSiteResource(
let aliasAddress: string | null = null;
let releaseAliasLock: (() => Promise<void>) | null = null;
if (mode === "host" || mode === "http") {
if (mode === "host" || mode === "http" || mode === "ssh") {
const { value, release } =
await getNextAvailableAliasAddress(orgId);
aliasAddress = value;
@@ -33,7 +33,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -21,11 +21,7 @@ const getSiteResourceParamsSchema = z.strictObject({
orgId: z.string()
});
async function query(
siteResourceId?: number,
niceId?: string,
orgId?: string
) {
async function query(siteResourceId?: number, niceId?: string, orgId?: string) {
if (siteResourceId && orgId) {
const [siteResource] = await db
.select()
@@ -75,7 +71,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -104,7 +100,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -232,7 +232,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -49,7 +49,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -50,7 +50,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -53,7 +53,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -69,7 +69,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -47,7 +47,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -47,7 +47,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -47,7 +47,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -47,7 +47,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -48,7 +48,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),
@@ -48,7 +48,7 @@ registry.registerPath({
content: {
"application/json": {
schema: z.object({
data: z.unknown().nullable(),
data: z.record(z.string(), z.any()).nullable(),
success: z.boolean(),
error: z.boolean(),
message: z.string(),

Some files were not shown because too many files have changed in this diff Show More