BREAKING CHANGE(vpn): replace tag-based VPN access control with source and target profiles

This commit is contained in:
2026-04-05 00:37:37 +00:00
parent 25365678e0
commit 1ddf83b28d
38 changed files with 1546 additions and 321 deletions

View File

@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@serve.zone/dcrouter',
version: '12.10.0',
version: '13.0.0',
description: 'A multifaceted routing service handling mail and SMS delivery functions.'
}

View File

@@ -21,7 +21,7 @@ import { MetricsManager } from './monitoring/index.js';
import { RadiusServer, type IRadiusServerConfig } from './radius/index.js';
import { RemoteIngressManager, TunnelManager } from './remoteingress/index.js';
import { VpnManager, type IVpnManagerConfig } from './vpn/index.js';
import { RouteConfigManager, ApiTokenManager, ReferenceResolver, DbSeeder } from './config/index.js';
import { RouteConfigManager, ApiTokenManager, ReferenceResolver, DbSeeder, TargetProfileManager } from './config/index.js';
import { SecurityLogger, ContentScanner, IPReputationChecker } from './security/index.js';
import { type IHttp3Config, augmentRoutesWithHttp3 } from './http3/index.js';
@@ -180,8 +180,8 @@ export interface IDcRouterOptions {
/**
* VPN server configuration.
* Enables VPN-based access control: routes with vpn.enabled are only
* accessible from VPN clients. Supports WireGuard + native (WS/QUIC) transports.
* Enables VPN-based access control: routes with vpnOnly are only
* accessible from VPN clients whose TargetProfile matches. Supports WireGuard + native (WS/QUIC) transports.
*/
vpnConfig?: {
/** Enable VPN server (default: false) */
@@ -197,7 +197,7 @@ export interface IDcRouterOptions {
/** Pre-defined VPN clients created on startup */
clients?: Array<{
clientId: string;
serverDefinedClientTags?: string[];
targetProfileIds?: string[];
description?: string;
}>;
/** Destination routing policy for VPN client traffic.
@@ -274,6 +274,7 @@ export class DcRouter {
public routeConfigManager?: RouteConfigManager;
public apiTokenManager?: ApiTokenManager;
public referenceResolver?: ReferenceResolver;
public targetProfileManager?: TargetProfileManager;
// Auto-discovered public IP (populated by generateAuthoritativeRecords)
public detectedPublicIp: string | null = null;
@@ -465,16 +466,22 @@ export class DcRouter {
this.referenceResolver = new ReferenceResolver();
await this.referenceResolver.initialize();
// Initialize target profile manager
this.targetProfileManager = new TargetProfileManager();
await this.targetProfileManager.initialize();
this.routeConfigManager = new RouteConfigManager(
() => this.getConstructorRoutes(),
() => this.smartProxy,
() => this.options.http3,
this.options.vpnConfig?.enabled
? (tags?: string[]) => {
if (tags?.length && this.vpnManager) {
return this.vpnManager.getClientIpsForServerDefinedTags(tags);
? (route: import('../ts_interfaces/data/remoteingress.js').IDcRouterRouteConfig, routeId?: string) => {
if (!this.vpnManager || !this.targetProfileManager) {
return [this.options.vpnConfig?.subnet || '10.8.0.0/24'];
}
return [this.options.vpnConfig?.subnet || '10.8.0.0/24'];
return this.targetProfileManager.getMatchingClientIps(
route, routeId, this.vpnManager.listClients(),
);
}
: undefined,
this.referenceResolver,
@@ -504,6 +511,7 @@ export class DcRouter {
this.routeConfigManager = undefined;
this.apiTokenManager = undefined;
this.referenceResolver = undefined;
this.targetProfileManager = undefined;
})
.withRetry({ maxRetries: 2, baseDelayMs: 1000 }),
);
@@ -2137,56 +2145,31 @@ export class DcRouter {
bridgeIpRangeStart: this.options.vpnConfig.bridgeIpRangeStart,
bridgeIpRangeEnd: this.options.vpnConfig.bridgeIpRangeEnd,
onClientChanged: () => {
// Re-apply routes so tag-based ipAllowLists get updated
// Re-apply routes so profile-based ipAllowLists get updated
this.routeConfigManager?.applyRoutes();
},
getClientAllowedIPs: async (clientTags: string[]) => {
getClientAllowedIPs: async (targetProfileIds: string[]) => {
const subnet = this.options.vpnConfig?.subnet || '10.8.0.0/24';
const ips = new Set<string>([subnet]);
// Check routes for VPN-gated tag match and collect domains
const routes = this.options.smartProxyConfig?.routes || [];
const domainsToResolve = new Set<string>();
for (const route of routes) {
const dcRoute = route as import('../ts_interfaces/data/remoteingress.js').IDcRouterRouteConfig;
if (!dcRoute.vpn?.enabled) continue;
if (!this.targetProfileManager) return [...ips];
const routeTags = dcRoute.vpn.allowedServerDefinedClientTags;
if (!routeTags?.length || clientTags.some(t => routeTags.includes(t))) {
// Collect domains from this route
const domains = (route.match as any)?.domains;
if (Array.isArray(domains)) {
for (const d of domains) {
// Strip wildcard prefix for DNS resolution (*.example.com → example.com)
domainsToResolve.add(d.replace(/^\*\./, ''));
}
}
}
}
const routes = (this.options.smartProxyConfig?.routes || []) as import('../ts_interfaces/data/remoteingress.js').IDcRouterRouteConfig[];
const storedRoutes = this.routeConfigManager?.getStoredRoutes() || new Map();
// Also scan stored/programmatic routes
const storedRoutes = this.routeConfigManager?.getStoredRoutes();
if (storedRoutes) {
for (const [, stored] of storedRoutes) {
if (!stored.enabled) continue;
const dcRoute = stored.route as import('../ts_interfaces/data/remoteingress.js').IDcRouterRouteConfig;
if (!dcRoute.vpn?.enabled) continue;
const { domains, targetIps } = this.targetProfileManager.getClientAccessSpec(
targetProfileIds, routes, storedRoutes,
);
const routeTags = dcRoute.vpn.allowedServerDefinedClientTags;
if (!routeTags?.length || clientTags.some(t => routeTags.includes(t))) {
const domains = (stored.route.match as any)?.domains;
if (Array.isArray(domains)) {
for (const d of domains) {
domainsToResolve.add(d.replace(/^\*\./, ''));
}
}
}
}
// Add target IPs directly
for (const ip of targetIps) {
ips.add(`${ip}/32`);
}
// Resolve DNS A records for matched domains (with caching)
for (const domain of domainsToResolve) {
const resolvedIps = await this.resolveVpnDomainIPs(domain);
for (const domain of domains) {
const stripped = domain.replace(/^\*\./, '');
const resolvedIps = await this.resolveVpnDomainIPs(stripped);
for (const ip of resolvedIps) {
ips.add(`${ip}/32`);
}
@@ -2199,7 +2182,7 @@ export class DcRouter {
await this.vpnManager.start();
// Re-apply routes now that VPN clients are loaded — ensures hardcoded routes
// get correct tag-based ipAllowLists (not possible during setupSmartProxy since
// get correct profile-based ipAllowLists (not possible during setupSmartProxy since
// VPN server wasn't ready yet)
this.routeConfigManager?.applyRoutes();
}

View File

@@ -1,8 +1,8 @@
import * as plugins from '../plugins.js';
import { logger } from '../logger.js';
import { SecurityProfileDoc, NetworkTargetDoc, StoredRouteDoc } from '../db/index.js';
import { SourceProfileDoc, NetworkTargetDoc, StoredRouteDoc } from '../db/index.js';
import type {
ISecurityProfile,
ISourceProfile,
INetworkTarget,
IRouteMetadata,
IStoredRoute,
@@ -12,7 +12,7 @@ import type {
const MAX_INHERITANCE_DEPTH = 5;
export class ReferenceResolver {
private profiles = new Map<string, ISecurityProfile>();
private profiles = new Map<string, ISourceProfile>();
private targets = new Map<string, INetworkTarget>();
// =========================================================================
@@ -38,7 +38,7 @@ export class ReferenceResolver {
const id = plugins.uuid.v4();
const now = Date.now();
const profile: ISecurityProfile = {
const profile: ISourceProfile = {
id,
name: data.name,
description: data.description,
@@ -51,17 +51,17 @@ export class ReferenceResolver {
this.profiles.set(id, profile);
await this.persistProfile(profile);
logger.log('info', `Created security profile '${profile.name}' (${id})`);
logger.log('info', `Created source profile '${profile.name}' (${id})`);
return id;
}
public async updateProfile(
id: string,
patch: Partial<Omit<ISecurityProfile, 'id' | 'createdAt' | 'createdBy'>>,
patch: Partial<Omit<ISourceProfile, 'id' | 'createdAt' | 'createdBy'>>,
): Promise<{ affectedRouteIds: string[] }> {
const profile = this.profiles.get(id);
if (!profile) {
throw new Error(`Security profile '${id}' not found`);
throw new Error(`Source profile '${id}' not found`);
}
if (patch.name !== undefined) profile.name = patch.name;
@@ -71,7 +71,7 @@ export class ReferenceResolver {
profile.updatedAt = Date.now();
await this.persistProfile(profile);
logger.log('info', `Updated security profile '${profile.name}' (${id})`);
logger.log('info', `Updated source profile '${profile.name}' (${id})`);
// Find routes referencing this profile
const affectedRouteIds = await this.findRoutesByProfileRef(id);
@@ -85,7 +85,7 @@ export class ReferenceResolver {
): Promise<{ success: boolean; message?: string }> {
const profile = this.profiles.get(id);
if (!profile) {
return { success: false, message: `Security profile '${id}' not found` };
return { success: false, message: `Source profile '${id}' not found` };
}
// Check usage
@@ -101,7 +101,7 @@ export class ReferenceResolver {
}
// Delete from DB
const doc = await SecurityProfileDoc.findById(id);
const doc = await SourceProfileDoc.findById(id);
if (doc) await doc.delete();
this.profiles.delete(id);
@@ -110,24 +110,24 @@ export class ReferenceResolver {
await this.clearProfileRefsOnRoutes(affectedIds);
logger.log('warn', `Force-deleted profile '${profile.name}'; cleared refs on ${affectedIds.length} route(s)`);
} else {
logger.log('info', `Deleted security profile '${profile.name}' (${id})`);
logger.log('info', `Deleted source profile '${profile.name}' (${id})`);
}
return { success: true };
}
public getProfile(id: string): ISecurityProfile | undefined {
public getProfile(id: string): ISourceProfile | undefined {
return this.profiles.get(id);
}
public getProfileByName(name: string): ISecurityProfile | undefined {
public getProfileByName(name: string): ISourceProfile | undefined {
for (const profile of this.profiles.values()) {
if (profile.name === name) return profile;
}
return undefined;
}
public listProfiles(): ISecurityProfile[] {
public listProfiles(): ISourceProfile[] {
return [...this.profiles.values()];
}
@@ -137,7 +137,7 @@ export class ReferenceResolver {
usage.set(profile.id, []);
}
for (const [routeId, stored] of storedRoutes) {
const ref = stored.metadata?.securityProfileRef;
const ref = stored.metadata?.sourceProfileRef;
if (ref && usage.has(ref)) {
usage.get(ref)!.push({ id: routeId, routeName: stored.route.name || routeId });
}
@@ -151,7 +151,7 @@ export class ReferenceResolver {
): Array<{ id: string; routeName: string }> {
const routes: Array<{ id: string; routeName: string }> = [];
for (const [routeId, stored] of storedRoutes) {
if (stored.metadata?.securityProfileRef === profileId) {
if (stored.metadata?.sourceProfileRef === profileId) {
routes.push({ id: routeId, routeName: stored.route.name || routeId });
}
}
@@ -280,7 +280,7 @@ export class ReferenceResolver {
/**
* Resolve references for a single route.
* Materializes security profile and/or network target into the route's fields.
* Materializes source profile and/or network target into the route's fields.
* Returns the resolved route and updated metadata.
*/
public resolveRoute(
@@ -289,19 +289,19 @@ export class ReferenceResolver {
): { route: plugins.smartproxy.IRouteConfig; metadata: IRouteMetadata } {
const resolvedMetadata: IRouteMetadata = { ...metadata };
if (resolvedMetadata.securityProfileRef) {
const resolvedSecurity = this.resolveSecurityProfile(resolvedMetadata.securityProfileRef);
if (resolvedMetadata.sourceProfileRef) {
const resolvedSecurity = this.resolveSourceProfile(resolvedMetadata.sourceProfileRef);
if (resolvedSecurity) {
const profile = this.profiles.get(resolvedMetadata.securityProfileRef);
const profile = this.profiles.get(resolvedMetadata.sourceProfileRef);
// Merge: profile provides base, route's inline values override
route = {
...route,
security: this.mergeSecurityFields(resolvedSecurity, route.security),
};
resolvedMetadata.securityProfileName = profile?.name;
resolvedMetadata.sourceProfileName = profile?.name;
resolvedMetadata.lastResolvedAt = Date.now();
} else {
logger.log('warn', `Security profile '${resolvedMetadata.securityProfileRef}' not found during resolution`);
logger.log('warn', `Source profile '${resolvedMetadata.sourceProfileRef}' not found during resolution`);
}
}
@@ -335,7 +335,7 @@ export class ReferenceResolver {
public async findRoutesByProfileRef(profileId: string): Promise<string[]> {
const docs = await StoredRouteDoc.findAll();
return docs
.filter((doc) => doc.metadata?.securityProfileRef === profileId)
.filter((doc) => doc.metadata?.sourceProfileRef === profileId)
.map((doc) => doc.id);
}
@@ -349,7 +349,7 @@ export class ReferenceResolver {
public findRoutesByProfileRefSync(profileId: string, storedRoutes: Map<string, IStoredRoute>): string[] {
const ids: string[] = [];
for (const [routeId, stored] of storedRoutes) {
if (stored.metadata?.securityProfileRef === profileId) {
if (stored.metadata?.sourceProfileRef === profileId) {
ids.push(routeId);
}
}
@@ -367,10 +367,10 @@ export class ReferenceResolver {
}
// =========================================================================
// Private: security profile resolution with inheritance
// Private: source profile resolution with inheritance
// =========================================================================
private resolveSecurityProfile(
private resolveSourceProfile(
profileId: string,
visited: Set<string> = new Set(),
depth: number = 0,
@@ -396,7 +396,7 @@ export class ReferenceResolver {
// Resolve parent profiles first (top-down, later overrides earlier)
if (profile.extendsProfiles?.length) {
for (const parentId of profile.extendsProfiles) {
const parentSecurity = this.resolveSecurityProfile(parentId, new Set(visited), depth + 1);
const parentSecurity = this.resolveSourceProfile(parentId, new Set(visited), depth + 1);
if (parentSecurity) {
baseSecurity = this.mergeSecurityFields(baseSecurity, parentSecurity);
}
@@ -453,7 +453,7 @@ export class ReferenceResolver {
// =========================================================================
private async loadProfiles(): Promise<void> {
const docs = await SecurityProfileDoc.findAll();
const docs = await SourceProfileDoc.findAll();
for (const doc of docs) {
if (doc.id) {
this.profiles.set(doc.id, {
@@ -469,7 +469,7 @@ export class ReferenceResolver {
}
}
if (this.profiles.size > 0) {
logger.log('info', `Loaded ${this.profiles.size} security profile(s) from storage`);
logger.log('info', `Loaded ${this.profiles.size} source profile(s) from storage`);
}
}
@@ -494,8 +494,8 @@ export class ReferenceResolver {
}
}
private async persistProfile(profile: ISecurityProfile): Promise<void> {
const existingDoc = await SecurityProfileDoc.findById(profile.id);
private async persistProfile(profile: ISourceProfile): Promise<void> {
const existingDoc = await SourceProfileDoc.findById(profile.id);
if (existingDoc) {
existingDoc.name = profile.name;
existingDoc.description = profile.description;
@@ -504,7 +504,7 @@ export class ReferenceResolver {
existingDoc.updatedAt = profile.updatedAt;
await existingDoc.save();
} else {
const doc = new SecurityProfileDoc();
const doc = new SourceProfileDoc();
doc.id = profile.id;
doc.name = profile.name;
doc.description = profile.description;
@@ -550,8 +550,8 @@ export class ReferenceResolver {
if (doc?.metadata) {
doc.metadata = {
...doc.metadata,
securityProfileRef: undefined,
securityProfileName: undefined,
sourceProfileRef: undefined,
sourceProfileName: undefined,
};
doc.updatedAt = Date.now();
await doc.save();

View File

@@ -21,7 +21,7 @@ export class RouteConfigManager {
private getHardcodedRoutes: () => plugins.smartproxy.IRouteConfig[],
private getSmartProxy: () => plugins.smartproxy.SmartProxy | undefined,
private getHttp3Config?: () => IHttp3Config | undefined,
private getVpnAllowList?: (tags?: string[]) => string[],
private getVpnClientIpsForRoute?: (route: IDcRouterRouteConfig, routeId?: string) => string[],
private referenceResolver?: ReferenceResolver,
private onRoutesApplied?: (routes: plugins.smartproxy.IRouteConfig[]) => void,
) {}
@@ -363,22 +363,19 @@ export class RouteConfigManager {
const enabledRoutes: plugins.smartproxy.IRouteConfig[] = [];
const http3Config = this.getHttp3Config?.();
const vpnAllowList = this.getVpnAllowList;
const vpnCallback = this.getVpnClientIpsForRoute;
// Helper: inject VPN security into a route if vpn.enabled is set
const injectVpn = (route: plugins.smartproxy.IRouteConfig): plugins.smartproxy.IRouteConfig => {
if (!vpnAllowList) return route;
// Helper: inject VPN security into a vpnOnly route
const injectVpn = (route: plugins.smartproxy.IRouteConfig, routeId?: string): plugins.smartproxy.IRouteConfig => {
if (!vpnCallback) return route;
const dcRoute = route as IDcRouterRouteConfig;
if (!dcRoute.vpn?.enabled) return route;
const allowList = vpnAllowList(dcRoute.vpn.allowedServerDefinedClientTags);
const mandatory = dcRoute.vpn.mandatory === true; // defaults to false
if (!dcRoute.vpnOnly) return route;
const allowList = vpnCallback(dcRoute, routeId);
return {
...route,
security: {
...route.security,
ipAllowList: mandatory
? allowList
: [...(route.security?.ipAllowList || []), ...allowList],
ipAllowList: allowList,
},
};
};
@@ -400,7 +397,7 @@ export class RouteConfigManager {
if (http3Config?.enabled !== false) {
route = augmentRouteWithHttp3(route, { enabled: true, ...http3Config });
}
enabledRoutes.push(injectVpn(route));
enabledRoutes.push(injectVpn(route, stored.id));
}
}

View File

@@ -0,0 +1,348 @@
import * as plugins from '../plugins.js';
import { logger } from '../logger.js';
import { TargetProfileDoc, VpnClientDoc } from '../db/index.js';
import type { ITargetProfile, ITargetProfileTarget } from '../../ts_interfaces/data/target-profile.js';
import type { IDcRouterRouteConfig } from '../../ts_interfaces/data/remoteingress.js';
import type { IStoredRoute } from '../../ts_interfaces/data/route-management.js';
/**
* Manages TargetProfiles (target-side: what can be accessed).
* TargetProfiles define what resources a VPN client can reach:
* domains, specific IP:port targets, and/or direct route references.
*/
export class TargetProfileManager {
private profiles = new Map<string, ITargetProfile>();
// =========================================================================
// Lifecycle
// =========================================================================
public async initialize(): Promise<void> {
await this.loadProfiles();
}
// =========================================================================
// CRUD
// =========================================================================
public async createProfile(data: {
name: string;
description?: string;
domains?: string[];
targets?: ITargetProfileTarget[];
routeRefs?: string[];
createdBy: string;
}): Promise<string> {
const id = plugins.uuid.v4();
const now = Date.now();
const profile: ITargetProfile = {
id,
name: data.name,
description: data.description,
domains: data.domains,
targets: data.targets,
routeRefs: data.routeRefs,
createdAt: now,
updatedAt: now,
createdBy: data.createdBy,
};
this.profiles.set(id, profile);
await this.persistProfile(profile);
logger.log('info', `Created target profile '${profile.name}' (${id})`);
return id;
}
public async updateProfile(
id: string,
patch: Partial<Omit<ITargetProfile, 'id' | 'createdAt' | 'createdBy'>>,
): Promise<void> {
const profile = this.profiles.get(id);
if (!profile) {
throw new Error(`Target profile '${id}' not found`);
}
if (patch.name !== undefined) profile.name = patch.name;
if (patch.description !== undefined) profile.description = patch.description;
if (patch.domains !== undefined) profile.domains = patch.domains;
if (patch.targets !== undefined) profile.targets = patch.targets;
if (patch.routeRefs !== undefined) profile.routeRefs = patch.routeRefs;
profile.updatedAt = Date.now();
await this.persistProfile(profile);
logger.log('info', `Updated target profile '${profile.name}' (${id})`);
}
public async deleteProfile(
id: string,
force?: boolean,
): Promise<{ success: boolean; message?: string }> {
const profile = this.profiles.get(id);
if (!profile) {
return { success: false, message: `Target profile '${id}' not found` };
}
// Check if any VPN clients reference this profile
const clients = await VpnClientDoc.findAll();
const referencingClients = clients.filter(
(c) => c.targetProfileIds?.includes(id),
);
if (referencingClients.length > 0 && !force) {
return {
success: false,
message: `Profile '${profile.name}' is in use by ${referencingClients.length} VPN client(s). Use force=true to delete.`,
};
}
// Delete from DB
const doc = await TargetProfileDoc.findById(id);
if (doc) await doc.delete();
this.profiles.delete(id);
if (referencingClients.length > 0) {
// Remove profile ref from clients
for (const client of referencingClients) {
client.targetProfileIds = client.targetProfileIds?.filter((pid) => pid !== id);
client.updatedAt = Date.now();
await client.save();
}
logger.log('warn', `Force-deleted target profile '${profile.name}'; removed refs from ${referencingClients.length} client(s)`);
} else {
logger.log('info', `Deleted target profile '${profile.name}' (${id})`);
}
return { success: true };
}
public getProfile(id: string): ITargetProfile | undefined {
return this.profiles.get(id);
}
public listProfiles(): ITargetProfile[] {
return [...this.profiles.values()];
}
/**
* Get which VPN clients reference a target profile.
*/
public async getProfileUsage(profileId: string): Promise<Array<{ clientId: string; description?: string }>> {
const clients = await VpnClientDoc.findAll();
return clients
.filter((c) => c.targetProfileIds?.includes(profileId))
.map((c) => ({ clientId: c.clientId, description: c.description }));
}
// =========================================================================
// Core matching: route → client IPs
// =========================================================================
/**
* For a vpnOnly route, find all enabled VPN clients whose assigned TargetProfile
* matches the route. Returns their assigned IPs for injection into ipAllowList.
*/
public getMatchingClientIps(
route: IDcRouterRouteConfig,
routeId: string | undefined,
clients: VpnClientDoc[],
): string[] {
const ips: string[] = [];
for (const client of clients) {
if (!client.enabled || !client.assignedIp) continue;
if (!client.targetProfileIds?.length) continue;
// Check if any of the client's profiles match this route
const matches = client.targetProfileIds.some((profileId) => {
const profile = this.profiles.get(profileId);
if (!profile) return false;
return this.routeMatchesProfile(route, routeId, profile);
});
if (matches) {
ips.push(client.assignedIp);
}
}
return ips;
}
/**
* For a given client (by its targetProfileIds), compute the set of
* domains and target IPs it can access. Used for WireGuard AllowedIPs.
*/
public getClientAccessSpec(
targetProfileIds: string[],
allRoutes: IDcRouterRouteConfig[],
storedRoutes: Map<string, IStoredRoute>,
): { domains: string[]; targetIps: string[] } {
const domains = new Set<string>();
const targetIps = new Set<string>();
// Collect all access specifiers from assigned profiles
for (const profileId of targetProfileIds) {
const profile = this.profiles.get(profileId);
if (!profile) continue;
// Direct domain entries
if (profile.domains?.length) {
for (const d of profile.domains) {
domains.add(d);
}
}
// Direct target IP entries
if (profile.targets?.length) {
for (const t of profile.targets) {
targetIps.add(t.host);
}
}
// Route references: scan constructor routes
for (const route of allRoutes) {
if (this.routeMatchesProfile(route as IDcRouterRouteConfig, undefined, profile)) {
const routeDomains = (route.match as any)?.domains;
if (Array.isArray(routeDomains)) {
for (const d of routeDomains) {
domains.add(d);
}
}
}
}
// Route references: scan stored routes
for (const [storedId, stored] of storedRoutes) {
if (!stored.enabled) continue;
if (this.routeMatchesProfile(stored.route as IDcRouterRouteConfig, storedId, profile)) {
const routeDomains = (stored.route.match as any)?.domains;
if (Array.isArray(routeDomains)) {
for (const d of routeDomains) {
domains.add(d);
}
}
}
}
}
return {
domains: [...domains],
targetIps: [...targetIps],
};
}
// =========================================================================
// Private: matching logic
// =========================================================================
/**
* Check if a route matches a profile. A profile matches if ANY condition is true:
* 1. Profile's routeRefs contains the route's name or stored route id
* 2. Profile's domains overlaps with route.match.domains (wildcard matching)
* 3. Profile's targets overlaps with route.action.targets (host + port match)
*/
private routeMatchesProfile(
route: IDcRouterRouteConfig,
routeId: string | undefined,
profile: ITargetProfile,
): boolean {
// 1. Route reference match
if (profile.routeRefs?.length) {
if (routeId && profile.routeRefs.includes(routeId)) return true;
if (route.name && profile.routeRefs.includes(route.name)) return true;
}
// 2. Domain match
if (profile.domains?.length) {
const routeDomains: string[] = (route.match as any)?.domains || [];
for (const profileDomain of profile.domains) {
for (const routeDomain of routeDomains) {
if (this.domainMatchesPattern(routeDomain, profileDomain)) return true;
}
}
}
// 3. Target match (host + port)
if (profile.targets?.length) {
const routeTargets = (route.action as any)?.targets;
if (Array.isArray(routeTargets)) {
for (const profileTarget of profile.targets) {
for (const routeTarget of routeTargets) {
const routeHost = routeTarget.host;
const routePort = routeTarget.port;
if (routeHost === profileTarget.host && routePort === profileTarget.port) {
return true;
}
}
}
}
}
return false;
}
/**
* Check if a domain matches a pattern.
* - '*.example.com' matches 'sub.example.com', 'a.b.example.com'
* - 'example.com' matches only 'example.com'
*/
private domainMatchesPattern(domain: string, pattern: string): boolean {
if (pattern === domain) return true;
if (pattern.startsWith('*.')) {
const suffix = pattern.slice(1); // '.example.com'
return domain.endsWith(suffix) && domain.length > suffix.length;
}
return false;
}
// =========================================================================
// Private: persistence
// =========================================================================
private async loadProfiles(): Promise<void> {
const docs = await TargetProfileDoc.findAll();
for (const doc of docs) {
if (doc.id) {
this.profiles.set(doc.id, {
id: doc.id,
name: doc.name,
description: doc.description,
domains: doc.domains,
targets: doc.targets,
routeRefs: doc.routeRefs,
createdAt: doc.createdAt,
updatedAt: doc.updatedAt,
createdBy: doc.createdBy,
});
}
}
if (this.profiles.size > 0) {
logger.log('info', `Loaded ${this.profiles.size} target profile(s) from storage`);
}
}
private async persistProfile(profile: ITargetProfile): Promise<void> {
const existingDoc = await TargetProfileDoc.findById(profile.id);
if (existingDoc) {
existingDoc.name = profile.name;
existingDoc.description = profile.description;
existingDoc.domains = profile.domains;
existingDoc.targets = profile.targets;
existingDoc.routeRefs = profile.routeRefs;
existingDoc.updatedAt = profile.updatedAt;
await existingDoc.save();
} else {
const doc = new TargetProfileDoc();
doc.id = profile.id;
doc.name = profile.name;
doc.description = profile.description;
doc.domains = profile.domains;
doc.targets = profile.targets;
doc.routeRefs = profile.routeRefs;
doc.createdAt = profile.createdAt;
doc.updatedAt = profile.updatedAt;
doc.createdBy = profile.createdBy;
await doc.save();
}
}
}

View File

@@ -3,4 +3,5 @@ export * from './validator.js';
export { RouteConfigManager } from './classes.route-config-manager.js';
export { ApiTokenManager } from './classes.api-token-manager.js';
export { ReferenceResolver } from './classes.reference-resolver.js';
export { DbSeeder } from './classes.db-seeder.js';
export { DbSeeder } from './classes.db-seeder.js';
export { TargetProfileManager } from './classes.target-profile-manager.js';

View File

@@ -5,7 +5,7 @@ import type { IRouteSecurity } from '../../../ts_interfaces/data/route-managemen
const getDb = () => DcRouterDb.getInstance().getDb();
@plugins.smartdata.Collection(() => getDb())
export class SecurityProfileDoc extends plugins.smartdata.SmartDataDbDoc<SecurityProfileDoc, SecurityProfileDoc> {
export class SourceProfileDoc extends plugins.smartdata.SmartDataDbDoc<SourceProfileDoc, SourceProfileDoc> {
@plugins.smartdata.unI()
@plugins.smartdata.svDb()
public id!: string;
@@ -35,15 +35,15 @@ export class SecurityProfileDoc extends plugins.smartdata.SmartDataDbDoc<Securit
super();
}
public static async findById(id: string): Promise<SecurityProfileDoc | null> {
return await SecurityProfileDoc.getInstance({ id });
public static async findById(id: string): Promise<SourceProfileDoc | null> {
return await SourceProfileDoc.getInstance({ id });
}
public static async findByName(name: string): Promise<SecurityProfileDoc | null> {
return await SecurityProfileDoc.getInstance({ name });
public static async findByName(name: string): Promise<SourceProfileDoc | null> {
return await SourceProfileDoc.getInstance({ name });
}
public static async findAll(): Promise<SecurityProfileDoc[]> {
return await SecurityProfileDoc.getInstances({});
public static async findAll(): Promise<SourceProfileDoc[]> {
return await SourceProfileDoc.getInstances({});
}
}

View File

@@ -0,0 +1,52 @@
import * as plugins from '../../plugins.js';
import { DcRouterDb } from '../classes.dcrouter-db.js';
import type { ITargetProfileTarget } from '../../../ts_interfaces/data/target-profile.js';
const getDb = () => DcRouterDb.getInstance().getDb();
@plugins.smartdata.Collection(() => getDb())
export class TargetProfileDoc extends plugins.smartdata.SmartDataDbDoc<TargetProfileDoc, TargetProfileDoc> {
@plugins.smartdata.unI()
@plugins.smartdata.svDb()
public id!: string;
@plugins.smartdata.svDb()
public name: string = '';
@plugins.smartdata.svDb()
public description?: string;
@plugins.smartdata.svDb()
public domains?: string[];
@plugins.smartdata.svDb()
public targets?: ITargetProfileTarget[];
@plugins.smartdata.svDb()
public routeRefs?: string[];
@plugins.smartdata.svDb()
public createdAt!: number;
@plugins.smartdata.svDb()
public updatedAt!: number;
@plugins.smartdata.svDb()
public createdBy!: string;
constructor() {
super();
}
public static async findById(id: string): Promise<TargetProfileDoc | null> {
return await TargetProfileDoc.getInstance({ id });
}
public static async findByName(name: string): Promise<TargetProfileDoc | null> {
return await TargetProfileDoc.getInstance({ name });
}
public static async findAll(): Promise<TargetProfileDoc[]> {
return await TargetProfileDoc.getInstances({});
}
}

View File

@@ -13,7 +13,7 @@ export class VpnClientDoc extends plugins.smartdata.SmartDataDbDoc<VpnClientDoc,
public enabled!: boolean;
@plugins.smartdata.svDb()
public serverDefinedClientTags?: string[];
public targetProfileIds?: string[];
@plugins.smartdata.svDb()
public description?: string;

View File

@@ -6,7 +6,8 @@ export * from './classes.cached.ip.reputation.js';
export * from './classes.stored-route.doc.js';
export * from './classes.route-override.doc.js';
export * from './classes.api-token.doc.js';
export * from './classes.security-profile.doc.js';
export * from './classes.source-profile.doc.js';
export * from './classes.target-profile.doc.js';
export * from './classes.network-target.doc.js';
// VPN document classes

View File

@@ -29,7 +29,8 @@ export class OpsServer {
private routeManagementHandler!: handlers.RouteManagementHandler;
private apiTokenHandler!: handlers.ApiTokenHandler;
private vpnHandler!: handlers.VpnHandler;
private securityProfileHandler!: handlers.SecurityProfileHandler;
private sourceProfileHandler!: handlers.SourceProfileHandler;
private targetProfileHandler!: handlers.TargetProfileHandler;
private networkTargetHandler!: handlers.NetworkTargetHandler;
constructor(dcRouterRefArg: DcRouter) {
@@ -90,7 +91,8 @@ export class OpsServer {
this.routeManagementHandler = new handlers.RouteManagementHandler(this);
this.apiTokenHandler = new handlers.ApiTokenHandler(this);
this.vpnHandler = new handlers.VpnHandler(this);
this.securityProfileHandler = new handlers.SecurityProfileHandler(this);
this.sourceProfileHandler = new handlers.SourceProfileHandler(this);
this.targetProfileHandler = new handlers.TargetProfileHandler(this);
this.networkTargetHandler = new handlers.NetworkTargetHandler(this);
console.log('✅ OpsServer TypedRequest handlers initialized');

View File

@@ -10,5 +10,6 @@ export * from './remoteingress.handler.js';
export * from './route-management.handler.js';
export * from './api-token.handler.js';
export * from './vpn.handler.js';
export * from './security-profile.handler.js';
export * from './source-profile.handler.js';
export * from './target-profile.handler.js';
export * from './network-target.handler.js';

View File

@@ -2,7 +2,7 @@ import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
export class SecurityProfileHandler {
export class SourceProfileHandler {
public typedrouter = new plugins.typedrequest.TypedRouter();
constructor(private opsServerRef: OpsServer) {
@@ -40,12 +40,12 @@ export class SecurityProfileHandler {
}
private registerHandlers(): void {
// Get all security profiles
// Get all source profiles
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetSecurityProfiles>(
'getSecurityProfiles',
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetSourceProfiles>(
'getSourceProfiles',
async (dataArg) => {
await this.requireAuth(dataArg, 'profiles:read');
await this.requireAuth(dataArg, 'source-profiles:read');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
if (!resolver) {
return { profiles: [] };
@@ -55,12 +55,12 @@ export class SecurityProfileHandler {
),
);
// Get a single security profile
// Get a single source profile
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetSecurityProfile>(
'getSecurityProfile',
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetSourceProfile>(
'getSourceProfile',
async (dataArg) => {
await this.requireAuth(dataArg, 'profiles:read');
await this.requireAuth(dataArg, 'source-profiles:read');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
if (!resolver) {
return { profile: null };
@@ -70,12 +70,12 @@ export class SecurityProfileHandler {
),
);
// Create a security profile
// Create a source profile
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateSecurityProfile>(
'createSecurityProfile',
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateSourceProfile>(
'createSourceProfile',
async (dataArg) => {
const userId = await this.requireAuth(dataArg, 'profiles:write');
const userId = await this.requireAuth(dataArg, 'source-profiles:write');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
if (!resolver) {
return { success: false, message: 'Reference resolver not initialized' };
@@ -92,12 +92,12 @@ export class SecurityProfileHandler {
),
);
// Update a security profile
// Update a source profile
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateSecurityProfile>(
'updateSecurityProfile',
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateSourceProfile>(
'updateSourceProfile',
async (dataArg) => {
await this.requireAuth(dataArg, 'profiles:write');
await this.requireAuth(dataArg, 'source-profiles:write');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
if (!resolver || !manager) {
@@ -121,12 +121,12 @@ export class SecurityProfileHandler {
),
);
// Delete a security profile
// Delete a source profile
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteSecurityProfile>(
'deleteSecurityProfile',
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteSourceProfile>(
'deleteSourceProfile',
async (dataArg) => {
await this.requireAuth(dataArg, 'profiles:write');
await this.requireAuth(dataArg, 'source-profiles:write');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
if (!resolver || !manager) {
@@ -149,12 +149,12 @@ export class SecurityProfileHandler {
),
);
// Get routes using a security profile
// Get routes using a source profile
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetSecurityProfileUsage>(
'getSecurityProfileUsage',
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetSourceProfileUsage>(
'getSourceProfileUsage',
async (dataArg) => {
await this.requireAuth(dataArg, 'profiles:read');
await this.requireAuth(dataArg, 'source-profiles:read');
const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
if (!resolver || !manager) {

View File

@@ -0,0 +1,155 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
export class TargetProfileHandler {
public typedrouter = new plugins.typedrequest.TypedRouter();
constructor(private opsServerRef: OpsServer) {
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
this.registerHandlers();
}
private async requireAuth(
request: { identity?: interfaces.data.IIdentity; apiToken?: string },
requiredScope?: interfaces.data.TApiTokenScope,
): Promise<string> {
if (request.identity?.jwt) {
try {
const isAdmin = await this.opsServerRef.adminHandler.adminIdentityGuard.exec({
identity: request.identity,
});
if (isAdmin) return request.identity.userId;
} catch { /* fall through */ }
}
if (request.apiToken) {
const tokenManager = this.opsServerRef.dcRouterRef.apiTokenManager;
if (tokenManager) {
const token = await tokenManager.validateToken(request.apiToken);
if (token) {
if (!requiredScope || tokenManager.hasScope(token, requiredScope)) {
return token.createdBy;
}
throw new plugins.typedrequest.TypedResponseError('insufficient scope');
}
}
}
throw new plugins.typedrequest.TypedResponseError('unauthorized');
}
private registerHandlers(): void {
// Get all target profiles
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetTargetProfiles>(
'getTargetProfiles',
async (dataArg) => {
await this.requireAuth(dataArg, 'target-profiles:read');
const manager = this.opsServerRef.dcRouterRef.targetProfileManager;
if (!manager) {
return { profiles: [] };
}
return { profiles: manager.listProfiles() };
},
),
);
// Get a single target profile
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetTargetProfile>(
'getTargetProfile',
async (dataArg) => {
await this.requireAuth(dataArg, 'target-profiles:read');
const manager = this.opsServerRef.dcRouterRef.targetProfileManager;
if (!manager) {
return { profile: null };
}
return { profile: manager.getProfile(dataArg.id) || null };
},
),
);
// Create a target profile
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateTargetProfile>(
'createTargetProfile',
async (dataArg) => {
const userId = await this.requireAuth(dataArg, 'target-profiles:write');
const manager = this.opsServerRef.dcRouterRef.targetProfileManager;
if (!manager) {
return { success: false, message: 'Target profile manager not initialized' };
}
const id = await manager.createProfile({
name: dataArg.name,
description: dataArg.description,
domains: dataArg.domains,
targets: dataArg.targets,
routeRefs: dataArg.routeRefs,
createdBy: userId,
});
return { success: true, id };
},
),
);
// Update a target profile
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateTargetProfile>(
'updateTargetProfile',
async (dataArg) => {
await this.requireAuth(dataArg, 'target-profiles:write');
const manager = this.opsServerRef.dcRouterRef.targetProfileManager;
if (!manager) {
return { success: false, message: 'Not initialized' };
}
await manager.updateProfile(dataArg.id, {
name: dataArg.name,
description: dataArg.description,
domains: dataArg.domains,
targets: dataArg.targets,
routeRefs: dataArg.routeRefs,
});
// Re-apply routes to update VPN access
this.opsServerRef.dcRouterRef.routeConfigManager?.applyRoutes();
return { success: true };
},
),
);
// Delete a target profile
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteTargetProfile>(
'deleteTargetProfile',
async (dataArg) => {
await this.requireAuth(dataArg, 'target-profiles:write');
const manager = this.opsServerRef.dcRouterRef.targetProfileManager;
if (!manager) {
return { success: false, message: 'Not initialized' };
}
const result = await manager.deleteProfile(dataArg.id, dataArg.force);
if (result.success) {
// Re-apply routes to update VPN access
this.opsServerRef.dcRouterRef.routeConfigManager?.applyRoutes();
}
return result;
},
),
);
// Get VPN clients using a target profile
this.typedrouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetTargetProfileUsage>(
'getTargetProfileUsage',
async (dataArg) => {
await this.requireAuth(dataArg, 'target-profiles:read');
const manager = this.opsServerRef.dcRouterRef.targetProfileManager;
if (!manager) {
return { clients: [] };
}
return { clients: await manager.getProfileUsage(dataArg.id) };
},
),
);
}
}

View File

@@ -25,7 +25,7 @@ export class VpnHandler {
const clients = manager.listClients().map((c) => ({
clientId: c.clientId,
enabled: c.enabled,
serverDefinedClientTags: c.serverDefinedClientTags,
targetProfileIds: c.targetProfileIds,
description: c.description,
assignedIp: c.assignedIp,
createdAt: c.createdAt,
@@ -120,7 +120,7 @@ export class VpnHandler {
try {
const bundle = await manager.createClient({
clientId: dataArg.clientId,
serverDefinedClientTags: dataArg.serverDefinedClientTags,
targetProfileIds: dataArg.targetProfileIds,
description: dataArg.description,
forceDestinationSmartproxy: dataArg.forceDestinationSmartproxy,
destinationAllowList: dataArg.destinationAllowList,
@@ -142,7 +142,7 @@ export class VpnHandler {
client: {
clientId: bundle.entry.clientId,
enabled: bundle.entry.enabled ?? true,
serverDefinedClientTags: bundle.entry.serverDefinedClientTags,
targetProfileIds: persistedClient?.targetProfileIds,
description: bundle.entry.description,
assignedIp: bundle.entry.assignedIp,
createdAt: Date.now(),
@@ -179,7 +179,7 @@ export class VpnHandler {
try {
await manager.updateClient(dataArg.clientId, {
description: dataArg.description,
serverDefinedClientTags: dataArg.serverDefinedClientTags,
targetProfileIds: dataArg.targetProfileIds,
forceDestinationSmartproxy: dataArg.forceDestinationSmartproxy,
destinationAllowList: dataArg.destinationAllowList,
destinationBlockList: dataArg.destinationBlockList,

View File

@@ -14,7 +14,7 @@ export interface IVpnManagerConfig {
/** Pre-defined VPN clients created on startup (idempotent — skips already-persisted clients) */
initialClients?: Array<{
clientId: string;
serverDefinedClientTags?: string[];
targetProfileIds?: string[];
description?: string;
}>;
/** Called when clients are created/deleted/toggled — triggers route re-application */
@@ -26,10 +26,10 @@ export interface IVpnManagerConfig {
allowList?: string[];
blockList?: string[];
};
/** Compute per-client AllowedIPs based on the client's server-defined tags.
/** Compute per-client AllowedIPs based on the client's target profile IDs.
* Called at config generation time (create/export). Returns CIDRs for WireGuard AllowedIPs.
* When not set, defaults to [subnet]. */
getClientAllowedIPs?: (clientTags: string[]) => Promise<string[]>;
getClientAllowedIPs?: (targetProfileIds: string[]) => Promise<string[]>;
/** Forwarding mode: 'socket' (default, userspace NAT), 'bridge' (L2 bridge to host LAN),
* or 'hybrid' (socket default, bridge for clients with useHostIp=true) */
forwardingMode?: 'socket' | 'bridge' | 'hybrid';
@@ -90,7 +90,6 @@ export class VpnManager {
publicKey: client.noisePublicKey,
wgPublicKey: client.wgPublicKey,
enabled: client.enabled,
serverDefinedClientTags: client.serverDefinedClientTags,
description: client.description,
assignedIp: client.assignedIp,
expiresAt: client.expiresAt,
@@ -163,7 +162,7 @@ export class VpnManager {
if (!this.clients.has(initial.clientId)) {
const bundle = await this.createClient({
clientId: initial.clientId,
serverDefinedClientTags: initial.serverDefinedClientTags,
targetProfileIds: initial.targetProfileIds,
description: initial.description,
});
logger.log('info', `VPN: Created initial client '${initial.clientId}' (IP: ${bundle.entry.assignedIp})`);
@@ -197,7 +196,7 @@ export class VpnManager {
*/
public async createClient(opts: {
clientId: string;
serverDefinedClientTags?: string[];
targetProfileIds?: string[];
description?: string;
forceDestinationSmartproxy?: boolean;
destinationAllowList?: string[];
@@ -214,13 +213,12 @@ export class VpnManager {
const bundle = await this.vpnServer.createClient({
clientId: opts.clientId,
serverDefinedClientTags: opts.serverDefinedClientTags,
description: opts.description,
});
// Override AllowedIPs with per-client values based on tag-matched routes
// Override AllowedIPs with per-client values based on target profiles
if (this.config.getClientAllowedIPs && bundle.wireguardConfig) {
const allowedIPs = await this.config.getClientAllowedIPs(opts.serverDefinedClientTags || []);
const allowedIPs = await this.config.getClientAllowedIPs(opts.targetProfileIds || []);
bundle.wireguardConfig = bundle.wireguardConfig.replace(
/AllowedIPs\s*=\s*.+/,
`AllowedIPs = ${allowedIPs.join(', ')}`,
@@ -231,7 +229,7 @@ export class VpnManager {
const doc = new VpnClientDoc();
doc.clientId = bundle.entry.clientId;
doc.enabled = bundle.entry.enabled ?? true;
doc.serverDefinedClientTags = bundle.entry.serverDefinedClientTags;
doc.targetProfileIds = opts.targetProfileIds;
doc.description = bundle.entry.description;
doc.assignedIp = bundle.entry.assignedIp;
doc.noisePublicKey = bundle.entry.publicKey;
@@ -332,11 +330,11 @@ export class VpnManager {
}
/**
* Update a client's metadata (description, tags) without rotating keys.
* Update a client's metadata (description, target profiles) without rotating keys.
*/
public async updateClient(clientId: string, update: {
description?: string;
serverDefinedClientTags?: string[];
targetProfileIds?: string[];
forceDestinationSmartproxy?: boolean;
destinationAllowList?: string[];
destinationBlockList?: string[];
@@ -349,7 +347,7 @@ export class VpnManager {
const client = this.clients.get(clientId);
if (!client) throw new Error(`Client not found: ${clientId}`);
if (update.description !== undefined) client.description = update.description;
if (update.serverDefinedClientTags !== undefined) client.serverDefinedClientTags = update.serverDefinedClientTags;
if (update.targetProfileIds !== undefined) client.targetProfileIds = update.targetProfileIds;
if (update.forceDestinationSmartproxy !== undefined) client.forceDestinationSmartproxy = update.forceDestinationSmartproxy;
if (update.destinationAllowList !== undefined) client.destinationAllowList = update.destinationAllowList;
if (update.destinationBlockList !== undefined) client.destinationBlockList = update.destinationBlockList;
@@ -409,10 +407,10 @@ export class VpnManager {
);
}
// Override AllowedIPs with per-client values based on tag-matched routes
// Override AllowedIPs with per-client values based on target profiles
if (this.config.getClientAllowedIPs) {
const clientTags = persisted?.serverDefinedClientTags || [];
const allowedIPs = await this.config.getClientAllowedIPs(clientTags);
const profileIds = persisted?.targetProfileIds || [];
const allowedIPs = await this.config.getClientAllowedIPs(profileIds);
config = config.replace(
/AllowedIPs\s*=\s*.+/,
`AllowedIPs = ${allowedIPs.join(', ')}`,
@@ -423,22 +421,6 @@ export class VpnManager {
return config;
}
// ── Tag-based access control ───────────────────────────────────────────
/**
* Get assigned IPs for all enabled clients matching any of the given server-defined tags.
*/
public getClientIpsForServerDefinedTags(tags: string[]): string[] {
const ips: string[] = [];
for (const client of this.clients.values()) {
if (!client.enabled || !client.assignedIp) continue;
if (client.serverDefinedClientTags?.some(t => tags.includes(t))) {
ips.push(client.assignedIp);
}
}
return ips;
}
// ── Status and telemetry ───────────────────────────────────────────────
/**
@@ -548,12 +530,6 @@ export class VpnManager {
private async loadPersistedClients(): Promise<void> {
const docs = await VpnClientDoc.findAll();
for (const doc of docs) {
// Migrate legacy `tags` → `serverDefinedClientTags`
if (!doc.serverDefinedClientTags && (doc as any).tags) {
doc.serverDefinedClientTags = (doc as any).tags;
(doc as any).tags = undefined;
await doc.save();
}
this.clients.set(doc.clientId, doc);
}
if (this.clients.size > 0) {